answer stringlengths 17 10.2M |
|---|
package uk.org.ownage.dmdirc.ui.dialogs;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import uk.org.ownage.dmdirc.actions.Action;
import uk.org.ownage.dmdirc.ui.MainFrame;
import uk.org.ownage.dmdirc.ui.components.StandardDialog;
import static uk.org.ownage.dmdirc.ui.UIUtilities.LARGE_BORDER;
import static uk.org.ownage.dmdirc.ui.UIUtilities.SMALL_BORDER;
import static uk.org.ownage.dmdirc.ui.UIUtilities.layoutGrid;
/**
* Actions editor dialog, used to edit a particular actions.
*/
public final class ActionsEditorDialog extends StandardDialog implements
ActionListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** Actions manager dialog. */
private final ActionsManagerDialog owner;
/** Current settings panel. */
private JPanel settingsPanel;
/** Add settings panel. */
private final JPanel addPanel;
/** Response panel. */
private final JPanel responsePanel;
/** info panel. */
private final JPanel infoPanel;
/** buttons panel. */
private final JPanel buttonsPanel;
/** name field. */
private final JTextField name;
/** event dropdown. */
private final JComboBox event;
/** other event lists. */
private final JList otherEvents;
/** response text area. */
private final JTextArea responses;
/** Delete button. */
private final JButton deleteButton;
/** No settings warning label. */
private final JLabel noCurrentSettingsLabel;
/** new setting value text field. */
private JTextField newSettingField;
/** new type combo box. */
private JComboBox newTypeComboBox;
/** new comparison combo box. */
private JComboBox newComparisonComboBox;
/** channel settings. */
private Properties settings;
/** number of current settings. */
private int numCurrentSettings;
/** Valid option types. */
private enum OPTION_TYPE { TEXTFIELD, CHECKBOX, COMBOBOX, }
/** Action being edited. */
private Action action;
/**
* Creates a new instance of ChannelSettingsPane.
*/
public ActionsEditorDialog(final ActionsManagerDialog parent) {
this(parent, null);
}
/**
* Creates a new instance of ChannelSettingsPane.
* @param newAction parent action
*/
public ActionsEditorDialog(final ActionsManagerDialog parent,
final Action newAction) {
super(MainFrame.getMainFrame(), false);
owner = parent;
action = newAction;
this.setTitle("Action editor");
settingsPanel = new JPanel();
addPanel = new JPanel();
responsePanel = new JPanel();
infoPanel = new JPanel();
buttonsPanel = new JPanel();
name = new JTextField();
event = new JComboBox(new String[]{});
otherEvents = new JList(new DefaultListModel());
otherEvents.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
responses = new JTextArea();
noCurrentSettingsLabel = new JLabel();
orderButtons(new JButton(), new JButton());
deleteButton = new JButton("Delete");
getOkButton().addActionListener(this);
getCancelButton().addActionListener(this);
deleteButton.addActionListener(this);
initSettingsPanel();
this.setMinimumSize(new Dimension(600, 625));
this.setVisible(true);
}
/**
* Initialises the settings panel.
*/
private void initSettingsPanel() {
final SpringLayout layout = new SpringLayout();
initInfoPanel();
initAddPanel();
initCurrentSettingsPanel();
initResponsePanel();
initButtonsPanel();
//this.add(infoLabel);
this.add(infoPanel);
this.add(settingsPanel);
this.add(addPanel);
this.add(responsePanel);
this.add(buttonsPanel);
this.getContentPane().setLayout(layout);
//info label SMALL_BORDER from top, left and right
layout.putConstraint(SpringLayout.NORTH, this.getContentPane(), -SMALL_BORDER,
SpringLayout.NORTH, infoPanel);
layout.putConstraint(SpringLayout.WEST, infoPanel, SMALL_BORDER,
SpringLayout.WEST, this.getContentPane());
layout.putConstraint(SpringLayout.EAST, infoPanel, -SMALL_BORDER,
SpringLayout.EAST, this.getContentPane());
//settings panel SMALL_BORDER from the infoPanel and left
layout.putConstraint(SpringLayout.NORTH, settingsPanel, SMALL_BORDER,
SpringLayout.SOUTH, infoPanel);
layout.putConstraint(SpringLayout.SOUTH, settingsPanel, -SMALL_BORDER,
SpringLayout.NORTH, addPanel);
layout.putConstraint(SpringLayout.WEST, settingsPanel, SMALL_BORDER,
SpringLayout.WEST, this.getContentPane());
layout.putConstraint(SpringLayout.EAST, settingsPanel, -SMALL_BORDER,
SpringLayout.EAST, this.getContentPane());
//add panel SMALL_BORDER from the settingsPanel and left
layout.putConstraint(SpringLayout.SOUTH, addPanel, -SMALL_BORDER,
SpringLayout.NORTH, responsePanel);
layout.putConstraint(SpringLayout.WEST, addPanel, SMALL_BORDER,
SpringLayout.WEST, this.getContentPane());
layout.putConstraint(SpringLayout.EAST, addPanel, -SMALL_BORDER,
SpringLayout.EAST, this.getContentPane());
//response panel SMALL_BORDER from the addPanel and left
layout.putConstraint(SpringLayout.SOUTH, responsePanel, -SMALL_BORDER,
SpringLayout.NORTH, buttonsPanel);
layout.putConstraint(SpringLayout.WEST, responsePanel, SMALL_BORDER,
SpringLayout.WEST, this.getContentPane());
layout.putConstraint(SpringLayout.EAST, responsePanel, -SMALL_BORDER,
SpringLayout.EAST, this.getContentPane());
//buttons panel SMALL_BORDER from the left and bottom
layout.putConstraint(SpringLayout.SOUTH, buttonsPanel, -SMALL_BORDER,
SpringLayout.SOUTH, this.getContentPane());
layout.putConstraint(SpringLayout.WEST, buttonsPanel, SMALL_BORDER,
SpringLayout.WEST, this.getContentPane());
layout.putConstraint(SpringLayout.EAST, buttonsPanel, -SMALL_BORDER,
SpringLayout.EAST, this.getContentPane());
pack();
}
/** Initialises the info panel. */
private void initInfoPanel() {
infoPanel.add(new JLabel("Name: "));
infoPanel.add(name);
infoPanel.add(new JLabel("Event: "));
infoPanel.add(event);
infoPanel.add(new JLabel("Other Events: "));
infoPanel.add(new JScrollPane(otherEvents));
name.setPreferredSize(new Dimension(150,
name.getFont().getSize()));
event.setPreferredSize(new Dimension(150,
event.getFont().getSize()));
infoPanel.setLayout(new SpringLayout());
((SpringLayout) infoPanel.getLayout()).getConstraints(otherEvents)
.setHeight(Spring.constant(100));
layoutGrid(infoPanel, 3,
2, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
}
/** Initialises the current settings panel. */
public void initCurrentSettingsPanel() {
numCurrentSettings = 0;
settingsPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
new EtchedBorder(), "Conditions"),
new EmptyBorder(LARGE_BORDER, LARGE_BORDER, LARGE_BORDER,
LARGE_BORDER)));
settingsPanel.setLayout(new SpringLayout());
noCurrentSettingsLabel.setText("No conditions set.");
noCurrentSettingsLabel.setBorder(new EmptyBorder(0, 0, 0, 0));
settingsPanel.add(noCurrentSettingsLabel);
layoutGrid(settingsPanel, numCurrentSettings,
4, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
}
/** Initialises the add settings panel. */
public void initAddPanel() {
final JButton newSettingButton;
newSettingField = new JTextField();
newSettingButton = new JButton();
newTypeComboBox = new JComboBox(
new DefaultComboBoxModel(
new String[]{}));
newComparisonComboBox = new JComboBox(
new DefaultComboBoxModel(
new String[]{}));
addPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
new EtchedBorder(), "Add new condition"),
new EmptyBorder(LARGE_BORDER, LARGE_BORDER, LARGE_BORDER,
LARGE_BORDER)));
addPanel.setLayout(new SpringLayout());
newTypeComboBox.setPreferredSize(new Dimension(150,
0));
newComparisonComboBox.setPreferredSize(new Dimension(150,
newComparisonComboBox.getFont().getSize() + LARGE_BORDER
+ SMALL_BORDER));
newSettingField.setText("");
newSettingField.setPreferredSize(new Dimension(150,
0));
newSettingButton.setText("Add");
newSettingButton.setMargin(new Insets(0, 0, 0, 0));
newSettingButton.setPreferredSize(new Dimension(45, 0));
newSettingButton.setActionCommand("add");
newSettingButton.addActionListener(this);
addPanel.add(newTypeComboBox);
addPanel.add(newComparisonComboBox);
addPanel.add(newSettingField);
addPanel.add(newSettingButton);
layoutGrid(addPanel, 1, 4, SMALL_BORDER, SMALL_BORDER,
SMALL_BORDER, SMALL_BORDER);
}
/** initliases the response panel. */
private void initResponsePanel() {
final JScrollPane scrollPane = new JScrollPane(responses);
responsePanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
new EtchedBorder(), "Response"),
new EmptyBorder(LARGE_BORDER, LARGE_BORDER, LARGE_BORDER,
LARGE_BORDER)));
responses.setRows(5);
responses.setWrapStyleWord(true);
responses.setLineWrap(true);
responsePanel.setLayout(new BorderLayout());
responsePanel.add(scrollPane, BorderLayout.CENTER);
}
/** Initialises the buttons panel. */
private void initButtonsPanel() {
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.LINE_AXIS));
buttonsPanel.add(deleteButton);
buttonsPanel.add(Box.createHorizontalGlue());
buttonsPanel.add(getLeftButton());
buttonsPanel.add(Box.createHorizontalStrut(SMALL_BORDER));
buttonsPanel.add(getRightButton());
}
/**
* Adds an option to the current options pane.
* @param configName config option name
* @param displayName config option display name
* @param panel parent panel
* @param type Option type
* @param optionValue config option value
*/
private void addCurrentOption(final OPTION_TYPE type1,
final OPTION_TYPE type2, final String optionValue) {
final JButton button = new JButton();
JComboBox type;
JComboBox comparison;
JTextField value;
settingsPanel.setVisible(false);
if (numCurrentSettings == 0) {
settingsPanel.remove(0);
}
numCurrentSettings++;
type = new JComboBox(new OPTION_TYPE[]{});
type.setSelectedItem(type1);
comparison = new JComboBox(new OPTION_TYPE[]{});
comparison.setSelectedItem(type2);
value = new JTextField();
value.setText(optionValue);
type.setPreferredSize(new Dimension(150,
type.getFont().getSize()));
comparison.setPreferredSize(new Dimension(150,
comparison.getFont().getSize()));
value.setPreferredSize(new Dimension(150,
value.getFont().getSize()));
button.setIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource(
"uk/org/ownage/dmdirc/res/close-inactive.png")));
button.setRolloverIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource(
"uk/org/ownage/dmdirc/res/close-active.png")));
button.setPressedIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource(
"uk/org/ownage/dmdirc/res/close-active.png")));
button.setContentAreaFilled(false);
button.setBorder(new EmptyBorder(0, 0, 0, 0));
button.setMargin(new Insets(0, 0, 0, 0));
button.setPreferredSize(new Dimension(16, 0));
button.setActionCommand(String.valueOf(numCurrentSettings));
button.addActionListener(this);
settingsPanel.add(type);
settingsPanel.add(comparison);
settingsPanel.add(value);
settingsPanel.add(button);
settingsPanel.setLayout(new SpringLayout());
layoutGrid(settingsPanel, numCurrentSettings,
4, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
settingsPanel.setVisible(true);
pack();
}
public void removeCurrentOption(int optionNumber) {
int removeItem = (optionNumber - 1) * 4;
settingsPanel.setVisible(false);
settingsPanel.remove(removeItem);
settingsPanel.remove(removeItem);
settingsPanel.remove(removeItem);
settingsPanel.remove(removeItem);
numCurrentSettings
settingsPanel.setLayout(new SpringLayout());
layoutGrid(settingsPanel, numCurrentSettings,
4, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
if (numCurrentSettings == 0) {
settingsPanel.add(noCurrentSettingsLabel);
}
settingsPanel.setVisible(true);
pack();
}
/** {@inheritDoc}. */
public void actionPerformed(final ActionEvent event) {
if (event.getSource() == getOkButton()) {
saveSettings();
this.dispose();
} else if (event.getSource() == getCancelButton()) {
this.dispose();
} else if (event.getSource() == deleteButton) {
//Delete action
saveSettings();
this.dispose();
} else if ("add".equals(event.getActionCommand())) {
addCurrentOption((OPTION_TYPE) newTypeComboBox.getSelectedItem(),
(OPTION_TYPE) newComparisonComboBox.getSelectedItem(),
newSettingField.getText());
} else {
try {
removeCurrentOption(Integer.parseInt(event.getActionCommand()));
} catch (NumberFormatException ex) {
//Ignore
}
}
}
/** Saves the current options. */
public void saveSettings() {
owner.loadGroups();
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nosoop.jsontool;
import bundled.jsontool.org.json.JSONException;
import bundled.jsontool.org.json.JSONObject;
import bundled.jsontool.org.json.JSONTokener;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
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.PrintStream;
import java.util.Enumeration;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultTreeModel;
/**
*
* @author nosoop < nosoop at users.noreply.github.com >
*/
public class Main extends javax.swing.JFrame {
JSONObjectTreeNode jsonRoot;
JSONObjectTreeNode workingJSONObject;
Object[][] dataTable;
/**
* Creates the JFrame form.
*/
public Main() {
try {
jsonRoot = new JSONObjectTreeNode(String.format("root: no file"), new JSONObject());
} catch (JSONException e) {
throw new Error(e);
}
dataTable = new Object[][]{};
initComponents();
FILE_DIALOG = new JFileChooser() {
/**
* Subclass to add a confirm message.
*/
final String CONFIRM_MESSAGE = "The file exists. Overwrite?",
CONFIRM_TITLE = "JSONToolView";
@Override
public void approveSelection() {
File file = getSelectedFile();
if (file.exists()
&& this.getDialogType() == JFileChooser.SAVE_DIALOG) {
int result = JOptionPane.showConfirmDialog(this,
CONFIRM_MESSAGE, CONFIRM_TITLE,
JOptionPane.YES_NO_OPTION);
switch (result) {
case JOptionPane.YES_OPTION:
super.approveSelection();
return;
case JOptionPane.NO_OPTION:
cancelSelection();
return;
case JOptionPane.CLOSED_OPTION:
return;
default:
return;
}
}
// If not the save dialog. then assume it's been approved.
super.approveSelection();
}
};
// TODO add support to drag-and-drop for non-leaf tree nodes.
}
/**
* Loads a file and attempts to parse it as JSON.
*
* @param jsonFile The file to load. Assumed JSON; a message will be
* displayed with the exception message if a JSONException is caught.
*/
void loadFile(final File jsonFile) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
JSONObject jsonData = new JSONObject(new JSONTokener(new FileInputStream(jsonFile)));
// Remove previous JSON object tree and reload GUI.
jsonRoot.removeAllChildren();
// Reload tree.
((DefaultTreeModel) jsonTree.getModel()).reload();
// Generate tree structure.
jsonRoot.buildKeyValues(jsonData);
// Expand root, select root node.
jsonTree.expandRow(0);
jsonTree.setSelectionPath(jsonTree.getPathForRow(0));
} catch (JSONException | FileNotFoundException e) {
JOptionPane.showMessageDialog(Main.this, e.getMessage());
}
}
});
}
/**
* Builds a table of key / type / value objects for a selected JSONReference
* instance.
*
* @param referenceNode The JSONReference instance to build a table from.
*/
void buildTableElements(final JSONObjectTreeNode referenceNode) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
DefaultTableModel jsonTable = ((DefaultTableModel) jsonObjectTable.getModel());
// Fastest way to clear the table.
jsonTable.setNumRows(0);
for (Map.Entry keyValues : referenceNode.keyValues.entrySet()) {
// TODO patch up addrow to support JSONArrays?
Object value = keyValues.getValue();
String textValue, classValue;
if (value != null) {
textValue = value.toString();
classValue = value.getClass().getSimpleName();
} else {
classValue = "Null";
textValue = "";
}
jsonTable.addRow(new Object[]{keyValues.getKey(), classValue, textValue});
}
}
});
}
/**
* Updates the working JSONObjectTreeNode instance with a new key / value
* pair.
*
* @param key
* @param value
*/
void updateWorkingKeyValue(String key, Object value) {
workingJSONObject.keyValues.put(key, value);
// Rebuild table just for the value being changed.
buildTableElements(workingJSONObject);
}
/**
* Saves the current working file as JSON.
*
* @param jsonFile The file to save.
*/
void saveFile(final File jsonFile) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
JSONObject export = exportJSONTree(jsonRoot);
try (FileOutputStream fOut = new FileOutputStream(jsonFile, false);
BufferedOutputStream bOut = new BufferedOutputStream(fOut);
PrintStream pOut = new PrintStream(bOut)) {
pOut.print(export.toString(4));
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
/**
* Recursively exports a tree represented by JSONObjectTreeNode instances
* containing JSONReference objects as a JSONObject.
*
* @param treeNode The node to use as the root to export from.
* @return A JSONObject
* @throws JSONException
*/
JSONObject exportJSONTree(JSONObjectTreeNode treeNode) throws JSONException {
JSONObject rootObject = new JSONObject();
Enumeration<JSONObjectTreeNode> childNodes = treeNode.children();
while (childNodes.hasMoreElements()) {
JSONObjectTreeNode childNode = childNodes.nextElement();
JSONObject innerObject = exportJSONTree(childNode);
rootObject.put(childNode.toString(), innerObject);
}
for (Map.Entry<String, Object> entry : treeNode.keyValues.entrySet()) {
// Wrap values. Mainly for null.
rootObject.put(entry.getKey(), JSONObject.wrap(entry.getValue()));
}
return rootObject;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jsonObjectModify = new javax.swing.JPopupMenu();
jsonKeyDelete = new javax.swing.JMenuItem();
jsonMainPane = new javax.swing.JSplitPane();
jsonTreeScrollPane = new javax.swing.JScrollPane();
jsonTree = new javax.swing.JTree(jsonRoot);
jsonTableScrollPane = new javax.swing.JScrollPane();
jsonObjectTable = new javax.swing.JTable();
menuBar = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuFileOpen = new javax.swing.JMenuItem();
menuFileSave = new javax.swing.JMenuItem();
menuEdit = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jsonKeyDelete.setText("Delete key / value pairs");
jsonKeyDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jsonKeyDeleteActionPerformed(evt);
}
});
jsonObjectModify.add(jsonKeyDelete);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JSONToolView pre-alpha");
jsonMainPane.setDividerLocation(192);
jsonTree.setDragEnabled(true);
jsonTree.setTransferHandler(new JSONObjectTreeTransferHandler());
jsonTree.setDropMode(javax.swing.DropMode.ON_OR_INSERT);
jsonTree.setShowsRootHandles(true);
jsonTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
jsonTreeValueChanged(evt);
}
});
jsonTreeScrollPane.setViewportView(jsonTree);
jsonMainPane.setLeftComponent(jsonTreeScrollPane);
jsonObjectTable.setModel(new javax.swing.table.DefaultTableModel(
dataTable,
new String [] {
"Name", "Type", "Value"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Object.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
@Override
public boolean isCellEditable(int row, int column) {
//Only the third column
return false;
}
});
jsonObjectTable.setFillsViewportHeight(true);
jsonObjectTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jsonObjectTable.setShowHorizontalLines(false);
jsonObjectTable.setShowVerticalLines(false);
jsonObjectTable.getTableHeader().setReorderingAllowed(false);
jsonObjectTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jsonObjectTableMouseReleased(evt);
}
public void mouseClicked(java.awt.event.MouseEvent evt) {
jsonObjectTableMouseClicked(evt);
}
});
jsonObjectTable.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jsonObjectTableKeyPressed(evt);
}
});
jsonTableScrollPane.setViewportView(jsonObjectTable);
jsonMainPane.setRightComponent(jsonTableScrollPane);
menuFile.setText("File");
menuFileOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
menuFileOpen.setText("Open");
menuFileOpen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuFileOpenActionPerformed(evt);
}
});
menuFile.add(menuFileOpen);
menuFileSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
menuFileSave.setText("Save");
menuFileSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuFileSaveActionPerformed(evt);
}
});
menuFile.add(menuFileSave);
menuBar.add(menuFile);
menuEdit.setText("View");
jMenuItem1.setText("View raw JSON text ...");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
menuEdit.add(jMenuItem1);
menuBar.add(menuEdit);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jsonMainPane, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jsonMainPane)
);
pack();
}// </editor-fold>//GEN-END:initComponents
final JFileChooser FILE_DIALOG;
private void menuFileOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileOpenActionPerformed
int fileDialogReturnValue = FILE_DIALOG.showOpenDialog(this);
// Load file.
if (fileDialogReturnValue == JFileChooser.APPROVE_OPTION) {
File file = FILE_DIALOG.getSelectedFile();
loadFile(file);
}
}//GEN-LAST:event_menuFileOpenActionPerformed
private void jsonTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jsonTreeValueChanged
// Switched to a different JSONObject tree node.
JSONObjectTreeNode node = (JSONObjectTreeNode) jsonTree.getLastSelectedPathComponent();
if (node == null) {
return;
}
// Set selected node as working if non-null.
workingJSONObject = node;
// Build the table from the node's key / value pairs.
buildTableElements(node);
}//GEN-LAST:event_jsonTreeValueChanged
private void menuFileSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileSaveActionPerformed
int fileDialogReturnValue = FILE_DIALOG.showSaveDialog(this);
if (fileDialogReturnValue == JFileChooser.APPROVE_OPTION) {
File file = FILE_DIALOG.getSelectedFile();
saveFile(file);
}
}//GEN-LAST:event_menuFileSaveActionPerformed
private void jsonObjectTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jsonObjectTableMouseClicked
int targetRow = jsonObjectTable.getSelectedRow();
if (evt.getClickCount() == 2
&& evt.getButton() == MouseEvent.BUTTON1) {
if (targetRow >= 0) {
// Modify the selected key/value pair.
String key = (String) jsonObjectTable.getModel().getValueAt(targetRow, 0);
// Get the keyvalue from the object and not parsed from the table.
Object object = workingJSONObject.keyValues.get(key);
// Pop-up a modal dialog box to edit the key/value.
JSONValueEditDialog.JSONValueDialogResponse returnValue =
(new JSONValueEditDialog(this, key, object))
.getReturnValue();
String newKey = returnValue.key;
Object newValue = returnValue.value;
/**
* Remove previous key/value pair if the new one does not use
* the same key.
*/
workingJSONObject.keyValues.remove(key);
updateWorkingKeyValue(newKey, newValue);
}
}
}//GEN-LAST:event_jsonObjectTableMouseClicked
private void jsonObjectTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jsonObjectTableMouseReleased
int targetRow = jsonObjectTable.rowAtPoint(evt.getPoint());
// Show exactly which row we're acting on.
if (targetRow >= 0 && targetRow < jsonObjectTable.getRowCount()) {
jsonObjectTable.setRowSelectionInterval(targetRow, targetRow);
} else {
jsonObjectTable.clearSelection();
}
// Show menu for object.
if (evt.getButton() == MouseEvent.BUTTON3 && targetRow >= 0) {
jsonObjectModify.show(jsonObjectTable, evt.getX(), evt.getY());
}
}//GEN-LAST:event_jsonObjectTableMouseReleased
private void jsonKeyDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jsonKeyDeleteActionPerformed
int targetRow = jsonObjectTable.getSelectedRow();
// Delete the selected key/value pair.
if (targetRow >= 0) {
String key = (String) jsonObjectTable.getModel().getValueAt(targetRow, 0);
workingJSONObject.keyValues.remove(key);
buildTableElements(workingJSONObject);
}
}//GEN-LAST:event_jsonKeyDeleteActionPerformed
private void jsonObjectTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jsonObjectTableKeyPressed
// TODO proper implementation
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
int targetRow = jsonObjectTable.getSelectedRow();
if (targetRow >= 0) {
String key = (String) jsonObjectTable.getModel().getValueAt(targetRow, 0);
workingJSONObject.keyValues.remove(key);
buildTableElements(workingJSONObject);
}
}
}//GEN-LAST:event_jsonObjectTableKeyPressed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
try {
JSONRawTextDialog dialog = new JSONRawTextDialog(this,
exportJSONTree(jsonRoot));
dialog.setVisible(true);
} catch (JSONException e) {
}
}//GEN-LAST:event_jMenuItem1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the operating system look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
javax.swing.UIManager.setLookAndFeel(
javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jsonKeyDelete;
private javax.swing.JSplitPane jsonMainPane;
private javax.swing.JPopupMenu jsonObjectModify;
private javax.swing.JTable jsonObjectTable;
private javax.swing.JScrollPane jsonTableScrollPane;
private javax.swing.JTree jsonTree;
private javax.swing.JScrollPane jsonTreeScrollPane;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenu menuEdit;
private javax.swing.JMenu menuFile;
private javax.swing.JMenuItem menuFileOpen;
private javax.swing.JMenuItem menuFileSave;
// End of variables declaration//GEN-END:variables
} |
package me.winspeednl.libz.screen;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import me.winspeednl.libz.core.GameCore;
import me.winspeednl.libz.image.Image;
import me.winspeednl.libz.image.Sprite;
public class Render {
private int width, height;
private int[] pixels, overlayPixels;
private GameCore gc;
private int offsetX, offsetY;
private boolean translate = true;
public Render(GameCore gc) {
this.gc = gc;
this.width = gc.getWidth();
this.height = gc.getHeight();
pixels = ((DataBufferInt) gc.getWindow().getImage().getRaster().getDataBuffer()).getData();
overlayPixels = new int[pixels.length];
}
public void setPixel(int x, int y, int color) {
if (translate) {
x -= offsetX;
y -= offsetY;
}
if ((x < 0 || x >= width || y < 0 || y >= height) || color == gc.getSpriteBGColor())
return;
pixels[x + y * width] = color;
}
public void setOverlayPixel(int x, int y, int color) {
if ((x < 0 || x >= width || y < 0 || y >= height) || color == gc.getSpriteBGColor())
return;
getOverlayPixels()[x + y * width] = color;
}
public void setPixel(int pixel, int color) {
pixels[pixel] = color;
}
public void drawString(String text, int color, int offX, int offY){
drawString(text, color, offX, offY, Font.STANDARD);
}
public void drawString(String text, int color, int offX, int offY, String path){
final int NumberUnicodes = 59;
int[] offsets = new int[NumberUnicodes];
int[] widths = new int[NumberUnicodes];
Image image;
image = new Image(path);
int unicode = -1;
for(int x = 0; x < image.width; x++) {
int Color = image.imagePixels[x];
if(Color == 0xff0000ff) {
unicode++;
offsets[unicode] = x;
}
if(Color == 0xffffff00)
widths[unicode] = x - offsets[unicode];
}
text = text.toUpperCase();
int offset = 0;
for (int i = 0; i < text.length(); i++) {
int Unicode = text.codePointAt(i) - 32;
for (int x = 0; x < widths[Unicode]; x++) {
for (int y = 1; y < image.height; y++) {
if (image.imagePixels[(x + offsets[Unicode]) + y * image.width] == 0xffffffff)
setOverlayPixel(x + offX + offset, y + offY - 1, color);
}
}
offset += widths[Unicode];
}
}
public void drawString(String text, int color, int offX, int offY, Sprite sprite){
final int NumberUnicodes = 59;
int[] offsets = new int[NumberUnicodes];
int[] widths = new int[NumberUnicodes];
int unicode = -1;
for(int x = 0; x < sprite.w; x++) {
int Color = sprite.pixels[x];
if(Color == 0xff0000ff) {
unicode++;
offsets[unicode] = x;
}
if(Color == 0xffffff00)
widths[unicode] = x - offsets[unicode];
}
text = text.toUpperCase();
int offset = 0;
for (int i = 0; i < text.length(); i++) {
int Unicode = text.codePointAt(i) - 32;
for (int x = 0; x < widths[Unicode]; x++) {
for (int y = 1; y < sprite.h; y++) {
if (sprite.pixels[(x + offsets[Unicode]) + y * sprite.w] == 0xffffffff)
setOverlayPixel(x + offX + offset, y + offY - 1, color);
}
}
offset += widths[Unicode];
}
}
public void drawString(String text, int color, int offX, int offY, Font font){
text = text.toUpperCase();
int offset = 0;
for (int i = 0; i < text.length(); i++) {
int unicode = text.codePointAt(i) - 32;
for (int x = 0; x < font.widths[unicode]; x++) {
for (int y = 1; y < font.image.height; y++) {
if (font.image.imagePixels[(x + font.offsets[unicode]) + y * font.image.width] == 0xffffffff)
setOverlayPixel(x + offX + offset, y + offY - 1, color);
}
}
offset += font.widths[unicode];
}
}
public int getStringWidth(String text, Font font) {
text = text.toUpperCase();
int width = 0;
for (int i = 0; i < text.length(); i++) {
int unicode = text.codePointAt(i) - 32;
width += font.widths[unicode];
}
return width;
}
public int getStringWidth(String text, Sprite sprite) {
final int NumberUnicodes = 59;
int[] offsets = new int[NumberUnicodes];
int[] widths = new int[NumberUnicodes];
int unicode = -1;
for(int x = 0; x < sprite.w; x++) {
int Color = sprite.pixels[x];
if(Color == 0xff0000ff) {
unicode++;
offsets[unicode] = x;
}
if(Color == 0xffffff00)
widths[unicode] = x - offsets[unicode];
}
text = text.toUpperCase();
int width = 0;
for (int i = 0; i < text.length(); i++) {
int Unicode = text.codePointAt(i) - 32;
width += widths[Unicode];
}
return width;
}
public void drawRect(int x, int y, int w, int h, int color, int thickness, boolean fill) {
if (fill) {
for (int xi = 0; xi < w; xi++) {
for (int yi = 0; yi < h; yi++) {
setPixel(x + xi, y + yi, color);
}
}
} else {
for (int i = 0; i < thickness; i++) {
for (int xi = 0; xi < w; xi++) {
setPixel(x + xi, y + i, color);
setPixel(x + xi, y + h - i, color);
}
for (int yi = 0; yi < h; yi++) {
setPixel(x + i, y + yi, color);
setPixel(x + w - i, y + yi, color);
}
}
}
}
public void drawOverlayRect(int x, int y, int w, int h, int color, int thickness, boolean fill) {
if (fill) {
for (int xi = 0; xi < w; xi++) {
for (int yi = 0; yi < h; yi++) {
setOverlayPixel(x + xi, y + yi, color);
}
}
} else {
for (int i = 0; i < thickness; i++) {
for (int xi = 0; xi < w; xi++) {
setOverlayPixel(x + xi, y + i, color);
setOverlayPixel(x + xi, y + h - i, color);
}
for (int yi = 0; yi < h; yi++) {
setOverlayPixel(x + i, y + yi, color);
setOverlayPixel(x + w - i, y + yi, color);
}
}
}
}
public void clear() {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
pixels[x + y * width] = 0xFF000000;
getOverlayPixels()[x + y * width] = 0xFF000000;
}
}
}
public BufferedImage rotate(BufferedImage img, double degree) {
AffineTransform tx = new AffineTransform();
tx.rotate(degree,img.getWidth() / 2, img.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_BILINEAR);
BufferedImage image = op.filter(img,null);
return image;
}
public BufferedImage flip(BufferedImage inputImage, boolean horizontal, boolean vertical) {
BufferedImage image = inputImage;
AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
AffineTransformOp op;
if (horizontal && !vertical) {
tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-image.getWidth(null), 0);
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
} else if (!horizontal && vertical) {
tx.translate(0, -image.getHeight(null));
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
} else {
tx = AffineTransform.getScaleInstance(-1, -1);
tx.translate(-image.getWidth(null), -image.getHeight(null));
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
}
return image;
}
public BufferedImage getImageFromArray(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image.setRGB(0, 0, width, height, pixels, 0, width);
return image;
}
public int getOffsetX() {
return offsetX;
}
public void setOffsetX(int offsetX) {
this.offsetX = offsetX;
}
public int getOffsetY() {
return offsetY;
}
public void setOffsetY(int offsetY) {
this.offsetY = offsetY;
}
public int[] getPixels() {
return pixels;
}
public int[] getOverlayPixels() {
return overlayPixels;
}
} |
package org.usergrid.rest;
import static org.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION_ID;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.usergrid.rest.applications.ApplicationResource;
import org.usergrid.rest.exceptions.NoOpException;
import org.usergrid.rest.exceptions.UnauthorizedApiRequestException;
/**
*
* @author ed@anuff.com
*/
@Path("/")
@Component
@Scope("singleton")
@Produces(MediaType.APPLICATION_JSON)
public class RootResource extends AbstractContextResource {
private static final Logger logger = Logger.getLogger(RootResource.class);
long started = System.currentTimeMillis();
public RootResource() {
}
@GET
@Path("applications")
public ApiResponse getAllApplications(@Context UriInfo ui)
throws URISyntaxException {
System.out.println("RootResource.getAllApplications");
ApiResponse response = new ApiResponse(ui);
response.setAction("get applications");
Map<String, UUID> applications = null;
try {
applications = emf.getApplications();
response.setSuccess();
response.setApplications(applications);
} catch (Exception e) {
logger.info("Unable to retrieve applications", e);
response.setError("Unable to retrieve applications");
}
return response;
}
@GET
public Response getRoot(@Context UriInfo ui) throws URISyntaxException {
String redirect_root = properties.getProperty("usergrid.redirect_root");
if (StringUtils.isNotBlank(redirect_root)) {
ResponseBuilder response = Response.temporaryRedirect(new URI(
redirect_root));
return response.build();
} else {
ResponseBuilder response = Response.temporaryRedirect(new URI(
"/status"));
return response.build();
}
}
@GET
@Path("status")
public ApiResponse getStatus() {
ApiResponse response = new ApiResponse();
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("started", started);
node.put("uptime", System.currentTimeMillis() - started);
response.setProperty("status", node);
return response;
}
@Path("{applicationId: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}")
public ApplicationResource getApplicationById(
@PathParam("applicationId") String applicationIdStr)
throws Exception {
if ("options".equalsIgnoreCase(request.getMethod())) {
throw new NoOpException();
}
UUID applicationId = UUID.fromString(applicationIdStr);
if (applicationId == null) {
return null;
}
if (applicationId.equals(MANAGEMENT_APPLICATION_ID)) {
throw new UnauthorizedApiRequestException();
}
return new ApplicationResource(this, applicationId);
}
@Path("applications/{applicationId: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}")
public ApplicationResource getApplicationById2(
@PathParam("applicationId") String applicationId) throws Exception {
return getApplicationById(applicationId);
}
@Path("{applicationName}")
public ApplicationResource getApplicationByName(
@PathParam("applicationName") String applicationName)
throws Exception {
if ("options".equalsIgnoreCase(request.getMethod())) {
throw new NoOpException();
}
UUID applicationId = emf.lookupApplication(applicationName);
if (applicationId == null) {
return null;
}
if (applicationId.equals(MANAGEMENT_APPLICATION_ID)) {
throw new UnauthorizedApiRequestException();
}
return new ApplicationResource(this, applicationId);
}
@Path("applications/{applicationName}")
public ApplicationResource getApplicationByName2(
@PathParam("applicationName") String applicationName)
throws Exception {
return getApplicationByName(applicationName);
}
} |
package com.annimon.stream.operator;
import com.annimon.stream.function.Function;
import java.util.Iterator;
import org.jetbrains.annotations.NotNull;
public class ObjMap<T, R> implements Iterator<R> {
private final Iterator<? extends T> iterator;
private final Function<? super T, ? extends R> mapper;
public ObjMap(
@NotNull Iterator<? extends T> iterator,
@NotNull Function<? super T, ? extends R> mapper) {
this.iterator = iterator;
this.mapper = mapper;
}
@Override
public void remove() {
iterator.remove();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public R next() {
return mapper.apply(iterator.next());
}
} |
@axiomClass
class ArrayList {
@adt
boolean add(Object e);
@adt
Object get(int i);
@adt
Object set(int i, Object e);
@adt
@pure
void ensureCapacity(int n);
@adt
@pure
int size();
axiom Object size(Object ArrayList()) {
return 0;
}
axiom Object size(Object add!(ArrayList a, Object e)) {
return size(a)+1;
}
axiom Object size(Object set!(ArrayList a, int i, Object e)) {
return size(a);
}
axiom Object get(Object add!(ArrayList a, Object e1), int i) {
return size(a) == i-1 ? e1 : get(a, i);
}
axiom Object get(Object set!(ArrayList a, int j, Object e), int i) {
return i==j ? e : get(a, i);
}
axiom Object get(Object ArrayList(), int i) {
return null;
}
} |
package org.cleartk.example.pos;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.jcas.JCas;
import org.cleartk.classifier.Feature;
import org.cleartk.classifier.Instance;
import org.cleartk.classifier.SequentialClassifierAnnotator;
import org.cleartk.classifier.SequentialDataWriterAnnotator;
import org.cleartk.classifier.SequentialInstanceConsumer;
import org.cleartk.classifier.viterbi.ViterbiDataWriterFactory;
import org.cleartk.type.Sentence;
import org.cleartk.type.Token;
import org.cleartk.util.EmptyAnnotator;
import org.cleartk.util.TestsUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.uutuc.factory.AnalysisEngineFactory;
import org.uutuc.factory.TokenFactory;
import org.uutuc.factory.TypeSystemDescriptionFactory;
public class ExamplePOSHandlerTests {
@Test
public void testSimpleSentence() throws Exception {
// create the engine and the cas
AnalysisEngine engine = AnalysisEngineFactory.createAnalysisEngine(
EmptyAnnotator.class,
TypeSystemDescriptionFactory.createTypeSystemDescription(Token.class, Sentence.class));
JCas jCas = engine.newJCas();
// create some tokens, stems and part of speech tags
TokenFactory.createTokens(jCas,
"The Absurdis retreated in 2003.", Token.class, Sentence.class,
"The Absurdis retreated in 2003 .",
"DT NNP VBD IN CD .",
"The Absurdi retreat in 2003 .", "org.cleartk.type.Token:pos", "org.cleartk.type.Token:stem");
List<Instance<String>> instances = TestsUtil.produceInstances(
new ExamplePOSAnnotationHandler(), engine, jCas);
List<String> featureValues;
// check "The"
featureValues = Arrays.asList(new String[]{
"The", // word
"the", // lower case
"INITIAL_UPPERCASE", // capital type
// numeric type
"Th", // first 2 chars
"The", // first 3 chars
"he", // last 2 chars
"The", // last 3 chars
"The", // stem (thrown away if null)
null, null, // left 2 stems
"Absurdi", "retreat", // right 2 stems
null, null, null, // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(0)));
Assert.assertEquals("DT", instances.get(0).getOutcome());
// check "Absurdis"
featureValues = Arrays.asList(new String[]{
"Absurdis", // word
"absurdis", // lower case
"INITIAL_UPPERCASE", // capital type
// numeric type
"Ab", // first 2 chars
"Abs", // first 3 chars
"is", // last 2 chars
"dis", // last 3 chars
"Absurdi", // stem (thrown away if null)
"The", null, // left 2 stems
"retreat", "in", // right 2 stems
"DT", null, null, // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(1)));
Assert.assertEquals("NNP", instances.get(1).getOutcome());
// check "retreated"
featureValues = Arrays.asList(new String[]{
"retreated", // word
"retreated", // lower case
"ALL_LOWERCASE", // capital type
// numeric type
"re", // first 2 chars
"ret", // first 3 chars
"ed", // last 2 chars
"ted", // last 3 chars
"retreat", // stem (thrown away if null)
"Absurdi", "The", // left 2 stems
"in", "2003", // right 2 stems
"NNP", "DT", null, // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(2)));
Assert.assertEquals("VBD", instances.get(2).getOutcome());
// check "in"
featureValues = Arrays.asList(new String[]{
"in", // word
"in", // lower case
"ALL_LOWERCASE", // capital type
// numeric type
"in", // first 2 chars
// first 3 chars
"in", // last 2 chars
// last 3 chars
"in", // stem (thrown away if null)
"retreat", "Absurdi", // left 2 stems
"2003", ".", // right 2 stems
"VBD", "NNP", "DT", // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(3)));
Assert.assertEquals("IN", instances.get(3).getOutcome());
// check "2003"
featureValues = Arrays.asList(new String[]{
"2003", // word
"2003", // lower case
// capital type
"YEAR_DIGITS", // numeric type
"20", // first 2 chars
"200", // first 3 chars
"03", // last 2 chars
"003", // last 3 chars
"2003", // stem (thrown away if null)
"in", "retreat", // left 2 stems
".", null, // right 2 stems
"IN", "VBD", "NNP", // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(4)));
Assert.assertEquals("CD", instances.get(4).getOutcome());
// check "."
featureValues = Arrays.asList(new String[]{
".", // word
".", // lower case
// capital type
// numeric type
// first 2 chars
// first 3 chars
// last 2 chars
// last 3 chars
".", // stem (thrown away if null)
"2003", "in", // left 2 stems
null, null, // right 2 stems
"CD", "IN", "VBD", // left 3 POS tags
});
Assert.assertEquals(featureValues, this.getFeatureValues(instances.get(5)));
Assert.assertEquals(".", instances.get(5).getOutcome());
}
@Test
public void testAnnotatorDescriptor() throws UIMAException, IOException {
AnalysisEngine engine = AnalysisEngineFactory.createAnalysisEngine(
"org.cleartk.example.pos.ExamplePOSAnnotator");
String expectedName = ExamplePOSAnnotationHandler.class.getName();
Object annotationHandler = engine.getConfigParameterValue(
SequentialInstanceConsumer.PARAM_ANNOTATION_HANDLER);
Assert.assertEquals(expectedName, annotationHandler);
Object classifierJar = engine.getConfigParameterValue(
SequentialClassifierAnnotator.PARAM_CLASSIFIER_JAR);
Assert.assertEquals("example/model/model.jar", classifierJar);
engine.collectionProcessComplete();
}
@Test
public void testDataWriterDescriptor() throws UIMAException, IOException {
AnalysisEngine engine = AnalysisEngineFactory.createAnalysisEngine(
"org.cleartk.example.pos.ExamplePOSDataWriter");
String expectedName = ExamplePOSAnnotationHandler.class.getName();
Object annotationHandler = engine.getConfigParameterValue(
SequentialInstanceConsumer.PARAM_ANNOTATION_HANDLER);
Assert.assertEquals(expectedName, annotationHandler);
Object outputDir = engine.getConfigParameterValue(
SequentialDataWriterAnnotator.PARAM_OUTPUT_DIRECTORY);
Assert.assertEquals("example/model", outputDir);
String expectedDataWriterFactory = (
ViterbiDataWriterFactory.class.getName());
Object dataWriter = engine.getConfigParameterValue(
SequentialDataWriterAnnotator.PARAM_DATAWRITER_FACTORY_CLASS);
Assert.assertEquals(expectedDataWriterFactory, dataWriter);
engine.collectionProcessComplete();
}
@After
public void tearDown() throws Exception {
for (File file: new File("example/model").listFiles()) {
if (!file.getName().equals("model.jar")) {
file.delete();
}
}
}
private List<String> getFeatureValues(Instance<String> instance) {
List<String> values = new ArrayList<String>();
for (Feature feature: instance.getFeatures()) {
Object value = feature == null ? null : feature.getValue();
values.add(value == null ? null : value.toString());
}
return values;
}
} |
package org.voltdb.regressionsuites;
import java.io.IOException;
import org.voltdb.BackendTarget;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.client.Client;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.NullCallback;
import org.voltdb.client.ProcCallException;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.elt.ELTestClient;
import org.voltdb.regressionsuites.sqltypesprocs.Delete;
import org.voltdb.regressionsuites.sqltypesprocs.Insert;
import org.voltdb.regressionsuites.sqltypesprocs.RollbackInsert;
import org.voltdb.regressionsuites.sqltypesprocs.Update_ELT;
/**
* End to end ELT tests using the RawProcessor and the ELSinkServer.
*
* Note, this test reuses the TestSQLTypesSuite schema and procedures.
* Each table in that schema, to the extent the DDL is supported by the
* DB, really needs an ELT round trip test.
*/
public class TestELTSuite extends RegressionSuite {
private ELTestClient m_tester;
/** Shove a table name and pkey in front of row data */
private Object[] convertValsToParams(String tableName, final int i,
final Object[] rowdata)
{
final Object[] params = new Object[rowdata.length + 2];
params[0] = tableName;
params[1] = i;
for (int ii=0; ii < rowdata.length; ++ii)
params[ii+2] = rowdata[ii];
return params;
}
/** Push pkey into expected row data */
private Object[] convertValsToRow(final int i, final Object[] rowdata) {
final Object[] row = new Object[rowdata.length + 1];
row[0] = i;
for (int ii=0; ii < rowdata.length; ++ii)
row[ii+1] = rowdata[ii];
return row;
}
private void quiesce(final Client client)
throws ProcCallException, NoConnectionsException, IOException
{
client.drain();
client.callProcedure("@Quiesce");
}
private void quiesceAndVerify(final Client client, ELTestClient tester)
throws ProcCallException, IOException
{
quiesce(client);
tester.work();
assertTrue(tester.allRowsVerified());
assertTrue(tester.verifyEltOffsets());
}
private void quiesceAndVerifyFalse(final Client client, ELTestClient tester)
throws ProcCallException, IOException
{
quiesce(client);
tester.work();
assertFalse(tester.allRowsVerified());
}
public void setUp()
{
super.setUp();
m_tester = new ELTestClient(getServerConfig().getNodeCount());
m_tester.connectToELServers();
}
/**
* Verify safe startup (we can connect clients and poll empty tables)
*/
public void testELTSafeStartup() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
quiesceAndVerify(client, m_tester);
}
/**
* Sends ten tuples to an EL enabled VoltServer and verifies the receipt
* of those tuples after a quiesce (shutdown). Base case.
*/
public void testELTRoundTripPersistentTable() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerify(client, m_tester);
}
public void testELTLocalServerTooMany() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerifyFalse(client, m_tester);
}
public void testELTLocalServerTooMany2() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
// register only even rows with tester
if ((i % 2) == 0)
{
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
}
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerifyFalse(client, m_tester);
}
/** Verify test infrastructure fails a test that sends too few rows */
public void testELTLocalServerTooFew() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
// Only do the first 7 inserts
if (i < 7)
{
client.callProcedure("Insert", params);
}
}
quiesceAndVerifyFalse(client, m_tester);
}
/** Verify test infrastructure fails a test that sends mismatched data */
public void testELTLocalServerBadData() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
// add wrong pkeys on purpose!
m_tester.addRow("ALLOW_NULLS", i + 10, convertValsToRow(i+10, rowdata));
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerifyFalse(client, m_tester);
}
/**
* Sends ten tuples to an EL enabled VoltServer and verifies the receipt
* of those tuples after a quiesce (shutdown). Base case.
*/
public void testELTRoundTripStreamedTable() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("NO_NULLS", i, convertValsToRow(i, rowdata));
final Object[] params = convertValsToParams("NO_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerify(client, m_tester);
}
/** Test that a table w/o ELT enabled does not produce ELT content */
public void testThatTablesOptIn() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
Object params[] = new Object[TestSQLTypesSuite.COLS + 2];
params[0] = "WITH_DEFAULTS"; // this table should not produce ELT output
// populate the row data
for (int i=0; i < TestSQLTypesSuite.COLS; ++i) {
params[i+2] = TestSQLTypesSuite.m_midValues[i];
}
for (int i=0; i < 10; i++) {
params[1] = i; // pkey
// do NOT add row to TupleVerfier as none should be produced
client.callProcedure("Insert", params);
}
quiesceAndVerify(client, m_tester);
}
class RollbackCallback implements ProcedureCallback {
@Override
public void clientCallback(ClientResponse clientResponse) {
if (clientResponse.getStatus() != ClientResponse.USER_ABORT) {
fail();
}
}
}
/*
* Sends many tuples to an EL enabled VoltServer and verifies the receipt
* of each in the EL stream. Some procedures rollback (after a real insert).
* Tests that streams are correct in the face of rollback.
*/
public void testELTRollback() throws IOException, ProcCallException, InterruptedException {
final Client client = getClient();
double rollbackPerc = 0.15;
double random = Math.random(); // initializes the generator
// eltxxx: should pick more random data
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
// roughly 10k rows is a full buffer it seems
for (int pkey=0; pkey < 175000; pkey++) {
if ((pkey % 1000) == 0) {
System.out.println("Rollback test added " + pkey + " rows");
}
final Object[] params = convertValsToParams("ALLOW_NULLS", pkey, rowdata);
random = Math.random();
if (random <= rollbackPerc) {
// note - do not update the el verifier as this rollsback
boolean done;
do {
done = client.callProcedure(new RollbackCallback(), "RollbackInsert", params);
if (done == false) {
client.backpressureBarrier();
}
} while (!done);
}
else {
m_tester.addRow("ALLOW_NULLS", pkey, convertValsToRow(pkey, rowdata));
// the sync call back isn't synchronous if it isn't explicitly blocked on...
boolean done;
do {
done = client.callProcedure(new NullCallback(), "Insert", params);
if (done == false) {
client.backpressureBarrier();
}
} while (!done);
}
}
client.drain();
quiesceAndVerify(client, m_tester);
}
private VoltTable createLoadTableTable(boolean addToVerifier, ELTestClient tester) {
VoltTable loadTable = new VoltTable(new ColumnInfo("PKEY", VoltType.INTEGER),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[0], TestSQLTypesSuite.m_types[0]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[1], TestSQLTypesSuite.m_types[1]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[2], TestSQLTypesSuite.m_types[2]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[3], TestSQLTypesSuite.m_types[3]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[4], TestSQLTypesSuite.m_types[4]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[5], TestSQLTypesSuite.m_types[5]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[6], TestSQLTypesSuite.m_types[6]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[7], TestSQLTypesSuite.m_types[7]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[8], TestSQLTypesSuite.m_types[8]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[9], TestSQLTypesSuite.m_types[9]),
new ColumnInfo(TestSQLTypesSuite.m_columnNames[10], TestSQLTypesSuite.m_types[10]));
for (int i=0; i < 100; i++) {
if (addToVerifier) {
tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, TestSQLTypesSuite.m_midValues));
}
loadTable.addRow(convertValsToRow(i, TestSQLTypesSuite.m_midValues));
}
return loadTable;
}
/*
* Verify that allowELT = no is obeyed for @LoadMultipartitionTable
*/
public void testLoadMultiPartitionTableELTOff() throws IOException, ProcCallException
{
// allow ELT is off. no rows added to the verifier
VoltTable loadTable = createLoadTableTable(false, m_tester);
Client client = getClient();
client.callProcedure("@LoadMultipartitionTable", "ALLOW_NULLS", loadTable, 0);
quiesceAndVerify(client, m_tester);
}
/*
* Verify that allowELT = yes is obeyed for @LoadMultipartitionTable
*/
public void testLoadMultiPartitionTableELTOn() throws IOException, ProcCallException
{
// allow ELT is on. rows added to the verifier
VoltTable loadTable = createLoadTableTable(true, m_tester);
Client client = getClient();
client.callProcedure("@LoadMultipartitionTable", "ALLOW_NULLS", loadTable, 1);
quiesceAndVerify(client, m_tester);
}
/*
* Verify that allowELT = yes is obeyed for @LoadMultipartitionTable
*/
public void testLoadMultiPartitionTableELTOn2() throws IOException, ProcCallException
{
// allow ELT is on but table is not opted in to ELT.
VoltTable loadTable = createLoadTableTable(false, m_tester);
Client client = getClient();
client.callProcedure("@LoadMultipartitionTable", "WITH_DEFAULTS", loadTable, 1);
quiesceAndVerify(client, m_tester);
}
/*
* Verify that planner rejects updates to append-only tables
*/
public void testELTUpdateAppendOnly() throws IOException {
final Client client = getClient();
boolean passed = false;
try {
client.callProcedure("@AdHoc", "Update NO_NULLS SET A_TINYINT=0 WHERE PKEY=0;");
}
catch (ProcCallException e) {
if (e.getMessage().contains("Illegal to update an export-only table.")) {
passed = true;
}
}
assertTrue(passed);
}
/*
* Verify that planner rejects reads of append-only tables.
*/
public void testELTSelectAppendOnly() throws IOException {
final Client client = getClient();
boolean passed = false;
try {
client.callProcedure("@AdHoc", "Select PKEY from NO_NULLS WHERE PKEY=0;");
}
catch (ProcCallException e) {
if (e.getMessage().contains("Illegal to read an export-only table.")) {
passed = true;
}
}
assertTrue(passed);
}
/*
* Verify that planner rejects deletes of append-only tables
*/
public void testELTDeleteAppendOnly() throws IOException {
final Client client = getClient();
boolean passed = false;
try {
client.callProcedure("@AdHoc", "DELETE from NO_NULLS WHERE PKEY=0;");
}
catch (ProcCallException e) {
if (e.getMessage().contains("Illegal to delete from an export-only table.")) {
passed = true;
}
}
assertTrue(passed);
}
/**
* Verify round trips of updates to a persistent table.
*/
public void testELTDeletes() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
// insert
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
for (int i=0; i < 10; i++) {
// add the full 'D' row
Object[] rowdata_d = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata_d));
// perform the delete
client.callProcedure("Delete", "ALLOW_NULLS", i);
}
quiesceAndVerify(client, m_tester);
}
/**
* Verify round trips of updates to a persistent table.
*/
public void testELTUpdates() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
// insert
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
// update
for (int i=0; i < 10; i++) {
// add the 'D' row
Object[] rowdata_d = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata_d));
// calculate the update and add that to the m_tester
Object[] rowdata_i = TestSQLTypesSuite.m_defaultValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i,rowdata_i));
// perform the update
final Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata_i);
client.callProcedure("Update_ELT", params);
}
// delete
for (int i=0; i < 10; i++) {
// add the full 'D' row
Object[] rowdata_d = TestSQLTypesSuite.m_defaultValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata_d));
// perform the delete
client.callProcedure("Delete", "ALLOW_NULLS", i);
}
quiesceAndVerify(client, m_tester);
}
/**
* Multi-table test
*/
/**
* Verify round trips of updates to a persistent table.
*/
public void testELTMultiTable() throws IOException, ProcCallException, InterruptedException
{
final Client client = getClient();
for (int i=0; i < 10; i++) {
// add data to a first (persistent) table
Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow("ALLOW_NULLS", i, convertValsToRow(i, rowdata));
Object[] params = convertValsToParams("ALLOW_NULLS", i, rowdata);
client.callProcedure("Insert", params);
// add data to a second (streaming) table.
rowdata = TestSQLTypesSuite.m_defaultValues;
m_tester.addRow("NO_NULLS", i, convertValsToRow(i, rowdata));
params = convertValsToParams("NO_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
quiesceAndVerify(client, m_tester);
}
/*
* Test suite boilerplate
*/
static final Class<?>[] PROCEDURES = {
Insert.class,
RollbackInsert.class,
Update_ELT.class,
Delete.class
};
public TestELTSuite(final String name) {
super(name);
}
public static void main(final String args[]) {
org.junit.runner.JUnitCore.runClasses(TestOrderBySuite.class);
}
static public junit.framework.Test suite()
{
final MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestELTSuite.class);
final VoltProjectBuilder project = new VoltProjectBuilder();
project.addSchema(TestELTSuite.class.getResource("sqltypessuite-ddl.sql"));
// add the connector/processor (name, host, port)
// and the exportable tables (name, export-only)
project.addELT("org.voltdb.elt.processors.RawProcessor", true /*enabled*/);
// "WITH_DEFAULTS" is a non-elt'd persistent table
project.addELTTable("ALLOW_NULLS", false); // persistent table
project.addELTTable("NO_NULLS", true); // streamed table
// and then project builder as normal
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES);
VoltServerConfig config;
// JNI, single server
config = new LocalSingleProcessServer("elt-ddl.jar", 2,
BackendTarget.NATIVE_EE_JNI);
config.compile(project);
builder.addServerConfig(config);
// three host, two site-per-host, k=1 replication config
config = new LocalCluster("elt-ddl-cluster-rep.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, true);
config.compile(project);
builder.addServerConfig(config);
return builder;
}
} |
package org.webrtc;
import org.webrtc.CameraEnumerationAndroid.CaptureFormat;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Surface;
import android.view.WindowManager;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
// Android specific implementation of VideoCapturer.
// VideoCapturerAndroid.create();
// This class extends VideoCapturer with a method to easily switch between the
// front and back camera. It also provides methods for enumerating valid device
// names.
// Threading notes: this class is called from C++ code, Android Camera callbacks, and possibly
// arbitrary Java threads. All public entry points are thread safe, and delegate the work to the
// camera thread. The internal *OnCameraThread() methods must check |camera| for null to check if
// the camera has been stopped.
// TODO(magjed): This class name is now confusing - rename to Camera1VideoCapturer.
@SuppressWarnings("deprecation")
public class VideoCapturerAndroid implements
CameraVideoCapturer,
android.hardware.Camera.PreviewCallback,
SurfaceTextureHelper.OnTextureFrameAvailableListener {
private final static String TAG = "VideoCapturerAndroid";
private static final int CAMERA_STOP_TIMEOUT_MS = 7000;
private android.hardware.Camera camera; // Only non-null while capturing.
private final Object handlerLock = new Object();
// |cameraThreadHandler| must be synchronized on |handlerLock| when not on the camera thread,
// or when modifying the reference. Use maybePostOnCameraThread() instead of posting directly to
// the handler - this way all callbacks with a specifed token can be removed at once.
private Handler cameraThreadHandler;
private Context applicationContext;
// Synchronization lock for |id|.
private final Object cameraIdLock = new Object();
private int id;
private android.hardware.Camera.CameraInfo info;
private CameraStatistics cameraStatistics;
// Remember the requested format in case we want to switch cameras.
private int requestedWidth;
private int requestedHeight;
private int requestedFramerate;
// The capture format will be the closest supported format to the requested format.
private CaptureFormat captureFormat;
private final Object pendingCameraSwitchLock = new Object();
private volatile boolean pendingCameraSwitch;
private CapturerObserver frameObserver = null;
private final CameraEventsHandler eventsHandler;
private boolean firstFrameReported;
// Arbitrary queue depth. Higher number means more memory allocated & held,
// lower number means more sensitivity to processing time in the client (and
// potentially stalling the capturer if it runs out of buffers to write to).
private static final int NUMBER_OF_CAPTURE_BUFFERS = 3;
private final Set<byte[]> queuedBuffers = new HashSet<byte[]>();
private final boolean isCapturingToTexture;
private SurfaceTextureHelper surfaceHelper;
private final static int MAX_OPEN_CAMERA_ATTEMPTS = 3;
private final static int OPEN_CAMERA_DELAY_MS = 500;
private int openCameraAttempts;
// Camera error callback.
private final android.hardware.Camera.ErrorCallback cameraErrorCallback =
new android.hardware.Camera.ErrorCallback() {
@Override
public void onError(int error, android.hardware.Camera camera) {
String errorMessage;
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
errorMessage = "Camera server died!";
} else {
errorMessage = "Camera error: " + error;
}
Logging.e(TAG, errorMessage);
if (eventsHandler != null) {
eventsHandler.onCameraError(errorMessage);
}
}
};
public static VideoCapturerAndroid create(String name,
CameraEventsHandler eventsHandler) {
return VideoCapturerAndroid.create(name, eventsHandler, false /* captureToTexture */);
}
// Use ctor directly instead.
@Deprecated
public static VideoCapturerAndroid create(String name,
CameraEventsHandler eventsHandler, boolean captureToTexture) {
try {
return new VideoCapturerAndroid(name, eventsHandler, captureToTexture);
} catch (RuntimeException e) {
Logging.e(TAG, "Couldn't create camera.", e);
return null;
}
}
public void printStackTrace() {
Thread cameraThread = null;
synchronized (handlerLock) {
if (cameraThreadHandler != null) {
cameraThread = cameraThreadHandler.getLooper().getThread();
}
}
if (cameraThread != null) {
StackTraceElement[] cameraStackTraces = cameraThread.getStackTrace();
if (cameraStackTraces.length > 0) {
Logging.d(TAG, "VideoCapturerAndroid stacks trace:");
for (StackTraceElement stackTrace : cameraStackTraces) {
Logging.d(TAG, stackTrace.toString());
}
}
}
}
// Switch camera to the next valid camera id. This can only be called while
// the camera is running.
@Override
public void switchCamera(final CameraSwitchHandler switchEventsHandler) {
if (android.hardware.Camera.getNumberOfCameras() < 2) {
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("No camera to switch to.");
}
return;
}
synchronized (pendingCameraSwitchLock) {
if (pendingCameraSwitch) {
// Do not handle multiple camera switch request to avoid blocking
// camera thread by handling too many switch request from a queue.
Logging.w(TAG, "Ignoring camera switch request.");
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("Pending camera switch already in progress.");
}
return;
}
pendingCameraSwitch = true;
}
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
switchCameraOnCameraThread();
synchronized (pendingCameraSwitchLock) {
pendingCameraSwitch = false;
}
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchDone(
info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
}
}
});
if (!didPost && switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("Camera is stopped.");
}
}
// Requests a new output format from the video capturer. Captured frames
// by the camera will be scaled/or dropped by the video capturer.
// It does not matter if width and height are flipped. I.E, |width| = 640, |height| = 480 produce
// the same result as |width| = 480, |height| = 640.
// TODO(magjed/perkj): Document what this function does. Change name?
@Override
public void onOutputFormatRequest(final int width, final int height, final int framerate) {
maybePostOnCameraThread(new Runnable() {
@Override public void run() {
onOutputFormatRequestOnCameraThread(width, height, framerate);
}
});
}
// Reconfigure the camera to capture in a new format. This should only be called while the camera
// is running.
@Override
public void changeCaptureFormat(final int width, final int height, final int framerate) {
maybePostOnCameraThread(new Runnable() {
@Override public void run() {
startPreviewOnCameraThread(width, height, framerate);
}
});
}
// Helper function to retrieve the current camera id synchronously. Note that the camera id might
// change at any point by switchCamera() calls.
private int getCurrentCameraId() {
synchronized (cameraIdLock) {
return id;
}
}
@Override
public List<CaptureFormat> getSupportedFormats() {
return Camera1Enumerator.getSupportedFormats(getCurrentCameraId());
}
// Returns true if this VideoCapturer is setup to capture video frames to a SurfaceTexture.
public boolean isCapturingToTexture() {
return isCapturingToTexture;
}
public VideoCapturerAndroid(String cameraName, CameraEventsHandler eventsHandler,
boolean captureToTexture) {
if (android.hardware.Camera.getNumberOfCameras() == 0) {
throw new RuntimeException("No cameras available");
}
if (cameraName == null || cameraName.equals("")) {
this.id = 0;
} else {
this.id = Camera1Enumerator.getCameraIndex(cameraName);
}
this.eventsHandler = eventsHandler;
isCapturingToTexture = captureToTexture;
Logging.d(TAG, "VideoCapturerAndroid isCapturingToTexture : " + isCapturingToTexture);
}
private void checkIsOnCameraThread() {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "Camera is stopped - can't check thread.");
} else if (Thread.currentThread() != cameraThreadHandler.getLooper().getThread()) {
throw new IllegalStateException("Wrong thread");
}
}
}
private boolean maybePostOnCameraThread(Runnable runnable) {
return maybePostDelayedOnCameraThread(0 /* delayMs */, runnable);
}
private boolean maybePostDelayedOnCameraThread(int delayMs, Runnable runnable) {
synchronized (handlerLock) {
return cameraThreadHandler != null
&& cameraThreadHandler.postAtTime(
runnable, this /* token */, SystemClock.uptimeMillis() + delayMs);
}
}
@Override
public void dispose() {
Logging.d(TAG, "dispose");
}
// Note that this actually opens the camera, and Camera callbacks run on the
// thread that calls open(), so this is done on the CameraThread.
@Override
public void startCapture(
final int width, final int height, final int framerate,
final SurfaceTextureHelper surfaceTextureHelper, final Context applicationContext,
final CapturerObserver frameObserver) {
Logging.d(TAG, "startCapture requested: " + width + "x" + height + "@" + framerate);
if (surfaceTextureHelper == null) {
frameObserver.onCapturerStarted(false /* success */);
if (eventsHandler != null) {
eventsHandler.onCameraError("No SurfaceTexture created.");
}
return;
}
if (applicationContext == null) {
throw new IllegalArgumentException("applicationContext not set.");
}
if (frameObserver == null) {
throw new IllegalArgumentException("frameObserver not set.");
}
synchronized (handlerLock) {
if (this.cameraThreadHandler != null) {
throw new RuntimeException("Camera has already been started.");
}
this.cameraThreadHandler = surfaceTextureHelper.getHandler();
this.surfaceHelper = surfaceTextureHelper;
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
openCameraAttempts = 0;
startCaptureOnCameraThread(width, height, framerate, frameObserver,
applicationContext);
}
});
if (!didPost) {
frameObserver.onCapturerStarted(false);
if (eventsHandler != null) {
eventsHandler.onCameraError("Could not post task to camera thread.");
}
}
}
}
private void startCaptureOnCameraThread(
final int width, final int height, final int framerate, final CapturerObserver frameObserver,
final Context applicationContext) {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "startCaptureOnCameraThread: Camera is stopped");
return;
} else {
checkIsOnCameraThread();
}
}
if (camera != null) {
Logging.e(TAG, "startCaptureOnCameraThread: Camera has already been started.");
return;
}
this.applicationContext = applicationContext;
this.frameObserver = frameObserver;
this.firstFrameReported = false;
try {
try {
synchronized (cameraIdLock) {
Logging.d(TAG, "Opening camera " + id);
if (eventsHandler != null) {
eventsHandler.onCameraOpening(id);
}
camera = android.hardware.Camera.open(id);
info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(id, info);
}
} catch (RuntimeException e) {
openCameraAttempts++;
if (openCameraAttempts < MAX_OPEN_CAMERA_ATTEMPTS) {
Logging.e(TAG, "Camera.open failed, retrying", e);
maybePostDelayedOnCameraThread(OPEN_CAMERA_DELAY_MS, new Runnable() {
@Override public void run() {
startCaptureOnCameraThread(width, height, framerate, frameObserver,
applicationContext);
}
});
return;
}
throw e;
}
camera.setPreviewTexture(surfaceHelper.getSurfaceTexture());
Logging.d(TAG, "Camera orientation: " + info.orientation +
" .Device orientation: " + getDeviceOrientation());
camera.setErrorCallback(cameraErrorCallback);
startPreviewOnCameraThread(width, height, framerate);
frameObserver.onCapturerStarted(true);
if (isCapturingToTexture) {
surfaceHelper.startListening(this);
}
// Start camera observer.
cameraStatistics = new CameraStatistics(surfaceHelper, eventsHandler);
} catch (IOException|RuntimeException e) {
Logging.e(TAG, "startCapture failed", e);
// Make sure the camera is released.
stopCaptureOnCameraThread(true /* stopHandler */);
frameObserver.onCapturerStarted(false);
if (eventsHandler != null) {
eventsHandler.onCameraError("Camera can not be started.");
}
}
}
// (Re)start preview with the closest supported format to |width| x |height| @ |framerate|.
private void startPreviewOnCameraThread(int width, int height, int framerate) {
synchronized (handlerLock) {
if (cameraThreadHandler == null || camera == null) {
Logging.e(TAG, "startPreviewOnCameraThread: Camera is stopped");
return;
} else {
checkIsOnCameraThread();
}
}
Logging.d(
TAG, "startPreviewOnCameraThread requested: " + width + "x" + height + "@" + framerate);
requestedWidth = width;
requestedHeight = height;
requestedFramerate = framerate;
// Find closest supported format for |width| x |height| @ |framerate|.
final android.hardware.Camera.Parameters parameters = camera.getParameters();
final List<CaptureFormat.FramerateRange> supportedFramerates =
Camera1Enumerator.convertFramerates(parameters.getSupportedPreviewFpsRange());
Logging.d(TAG, "Available fps ranges: " + supportedFramerates);
final CaptureFormat.FramerateRange fpsRange =
CameraEnumerationAndroid.getClosestSupportedFramerateRange(supportedFramerates, framerate);
final Size previewSize = CameraEnumerationAndroid.getClosestSupportedSize(
Camera1Enumerator.convertSizes(parameters.getSupportedPreviewSizes()), width, height);
final CaptureFormat captureFormat =
new CaptureFormat(previewSize.width, previewSize.height, fpsRange);
// Check if we are already using this capture format, then we don't need to do anything.
if (captureFormat.equals(this.captureFormat)) {
return;
}
// Update camera parameters.
Logging.d(TAG, "isVideoStabilizationSupported: " +
parameters.isVideoStabilizationSupported());
if (parameters.isVideoStabilizationSupported()) {
parameters.setVideoStabilization(true);
}
// Note: setRecordingHint(true) actually decrease frame rate on N5.
// parameters.setRecordingHint(true);
if (captureFormat.framerate.max > 0) {
parameters.setPreviewFpsRange(captureFormat.framerate.min, captureFormat.framerate.max);
}
parameters.setPreviewSize(previewSize.width, previewSize.height);
if (!isCapturingToTexture) {
parameters.setPreviewFormat(captureFormat.imageFormat);
}
// Picture size is for taking pictures and not for preview/video, but we need to set it anyway
// as a workaround for an aspect ratio problem on Nexus 7.
final Size pictureSize = CameraEnumerationAndroid.getClosestSupportedSize(
Camera1Enumerator.convertSizes(parameters.getSupportedPictureSizes()), width, height);
parameters.setPictureSize(pictureSize.width, pictureSize.height);
// Temporarily stop preview if it's already running.
if (this.captureFormat != null) {
camera.stopPreview();
// Calling |setPreviewCallbackWithBuffer| with null should clear the internal camera buffer
// queue, but sometimes we receive a frame with the old resolution after this call anyway.
camera.setPreviewCallbackWithBuffer(null);
}
// (Re)start preview.
Logging.d(TAG, "Start capturing: " + captureFormat);
this.captureFormat = captureFormat;
List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
// Calculate orientation manually and send it as CVO instead.
camera.setDisplayOrientation(0 /* degrees */);
if (!isCapturingToTexture) {
queuedBuffers.clear();
final int frameSize = captureFormat.frameSize();
for (int i = 0; i < NUMBER_OF_CAPTURE_BUFFERS; ++i) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(frameSize);
queuedBuffers.add(buffer.array());
camera.addCallbackBuffer(buffer.array());
}
camera.setPreviewCallbackWithBuffer(this);
}
camera.startPreview();
}
// Blocks until camera is known to be stopped.
@Override
public void stopCapture() throws InterruptedException {
Logging.d(TAG, "stopCapture");
final CountDownLatch barrier = new CountDownLatch(1);
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override public void run() {
stopCaptureOnCameraThread(true /* stopHandler */);
barrier.countDown();
}
});
if (!didPost) {
Logging.e(TAG, "Calling stopCapture() for already stopped camera.");
return;
}
if (!barrier.await(CAMERA_STOP_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
Logging.e(TAG, "Camera stop timeout");
printStackTrace();
if (eventsHandler != null) {
eventsHandler.onCameraError("Camera stop timeout");
}
}
Logging.d(TAG, "stopCapture done");
}
private void stopCaptureOnCameraThread(boolean stopHandler) {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "stopCaptureOnCameraThread: Camera is stopped");
} else {
checkIsOnCameraThread();
}
}
Logging.d(TAG, "stopCaptureOnCameraThread");
// Note that the camera might still not be started here if startCaptureOnCameraThread failed
// and we posted a retry.
// Make sure onTextureFrameAvailable() is not called anymore.
if (surfaceHelper != null) {
surfaceHelper.stopListening();
}
if (stopHandler) {
synchronized (handlerLock) {
// Clear the cameraThreadHandler first, in case stopPreview or
// other driver code deadlocks. Deadlock in
// android.hardware.Camera._stopPreview(Native Method) has
// been observed on Nexus 5 (hammerhead), OS version LMY48I.
// The camera might post another one or two preview frames
// before stopped, so we have to check for a null
// cameraThreadHandler in our handler. Remove all pending
// Runnables posted from |this|.
if (cameraThreadHandler != null) {
cameraThreadHandler.removeCallbacksAndMessages(this /* token */);
cameraThreadHandler = null;
}
surfaceHelper = null;
}
}
if (cameraStatistics != null) {
cameraStatistics.release();
cameraStatistics = null;
}
Logging.d(TAG, "Stop preview.");
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallbackWithBuffer(null);
}
queuedBuffers.clear();
captureFormat = null;
Logging.d(TAG, "Release camera.");
if (camera != null) {
camera.release();
camera = null;
}
if (eventsHandler != null) {
eventsHandler.onCameraClosed();
}
Logging.d(TAG, "stopCaptureOnCameraThread done");
}
private void switchCameraOnCameraThread() {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "switchCameraOnCameraThread: Camera is stopped");
return;
} else {
checkIsOnCameraThread();
}
}
Logging.d(TAG, "switchCameraOnCameraThread");
stopCaptureOnCameraThread(false /* stopHandler */);
synchronized (cameraIdLock) {
id = (id + 1) % android.hardware.Camera.getNumberOfCameras();
}
startCaptureOnCameraThread(requestedWidth, requestedHeight, requestedFramerate, frameObserver,
applicationContext);
Logging.d(TAG, "switchCameraOnCameraThread done");
}
private void onOutputFormatRequestOnCameraThread(int width, int height, int framerate) {
synchronized (handlerLock) {
if (cameraThreadHandler == null || camera == null) {
Logging.e(TAG, "onOutputFormatRequestOnCameraThread: Camera is stopped");
return;
} else {
checkIsOnCameraThread();
}
}
Logging.d(TAG, "onOutputFormatRequestOnCameraThread: " + width + "x" + height +
"@" + framerate);
frameObserver.onOutputFormatRequest(width, height, framerate);
}
private int getDeviceOrientation() {
int orientation = 0;
WindowManager wm = (WindowManager) applicationContext.getSystemService(
Context.WINDOW_SERVICE);
switch(wm.getDefaultDisplay().getRotation()) {
case Surface.ROTATION_90:
orientation = 90;
break;
case Surface.ROTATION_180:
orientation = 180;
break;
case Surface.ROTATION_270:
orientation = 270;
break;
case Surface.ROTATION_0:
default:
orientation = 0;
break;
}
return orientation;
}
private int getFrameOrientation() {
int rotation = getDeviceOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK) {
rotation = 360 - rotation;
}
return (info.orientation + rotation) % 360;
}
// Called on cameraThread so must not "synchronized".
@Override
public void onPreviewFrame(byte[] data, android.hardware.Camera callbackCamera) {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "onPreviewFrame: Camera is stopped");
return;
} else {
checkIsOnCameraThread();
}
}
if (!queuedBuffers.contains(data)) {
// |data| is an old invalid buffer.
return;
}
if (camera != callbackCamera) {
throw new RuntimeException("Unexpected camera in callback!");
}
final long captureTimeNs =
TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());
if (eventsHandler != null && !firstFrameReported) {
eventsHandler.onFirstFrameAvailable();
firstFrameReported = true;
}
cameraStatistics.addFrame();
frameObserver.onByteBufferFrameCaptured(data, captureFormat.width, captureFormat.height,
getFrameOrientation(), captureTimeNs);
camera.addCallbackBuffer(data);
}
@Override
public void onTextureFrameAvailable(
int oesTextureId, float[] transformMatrix, long timestampNs) {
synchronized (handlerLock) {
if (cameraThreadHandler == null) {
Logging.e(TAG, "onTextureFrameAvailable: Camera is stopped");
surfaceHelper.returnTextureFrame();
return;
} else {
checkIsOnCameraThread();
}
}
if (eventsHandler != null && !firstFrameReported) {
eventsHandler.onFirstFrameAvailable();
firstFrameReported = true;
}
int rotation = getFrameOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT) {
// Undo the mirror that the OS "helps" us with.
// http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)
transformMatrix =
RendererCommon.multiplyMatrices(transformMatrix, RendererCommon.horizontalFlipMatrix());
}
cameraStatistics.addFrame();
frameObserver.onTextureFrameCaptured(captureFormat.width, captureFormat.height, oesTextureId,
transformMatrix, rotation, timestampNs);
}
} |
// public class HashMap<K,V> extends Map {
public class HashMap<K,V> {
static final int DEFAULT_INITIAL_CAPACITY;// = 1 << 4; // aka 16
Node[] elementData;
int numPairs;
int capacity;
class Node<K,V> extends Object {
K key;
V value;
int hash;
public Node(K key, V value, int hash) {
this.key = key;
this.value = value;
this.hash = hash;
}
}
public HashMap() {
this.DEFAULT_INITIAL_CAPACITY = 16;
this.elementData = new Node[DEFAULT_INITIAL_CAPACITY];
this.numPairs = 0;
this.capacity = DEFAULT_INITIAL_CAPACITY;
}
public int size() {
return numPairs;
}
public boolean isEmpty() {
return numPairs == 0;
}
public void resize(int newSize) {
int i,h, hashMod;
Node<K, V> n;
Node[] oldElementData = elementData;
Node[] newElementData = new Node[newSize];
//this.elementData = new Node[newSize];
K k;
V v;
for (i = 0; i < capacity; i++) {
// putVal call gives Sketch Not Resolved Error
if (oldElementData[i] != null) {
h = oldElementData[i].hash;
k = oldElementData[i].key;
v = oldElementData[i].value;
//putValNoResize(h, k, v);
hashMod = h % newSize;
if (hashMod < 0) {
hashMod += newSize;
}
newElementData[hashMod] = new Node<K,V>(k, v, h);
}
}
this.elementData = newElementData;
this.capacity = newSize;
}
public boolean containsValue(V value) {
int i;
for (i = 0; i < capacity; i++) {
if (elementData[i] != null) {
V v = elementData[i].value;
if (value.equals(v)) {
return true;
}
}
}
return false;
}
public boolean containsKey(K key) {
return get(key) != null;
}
public V get(K key) {
int hashMod = key.hashCode() % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
Node<K,V> node = elementData[hashMod];
if (node != null) {
if (key.equals(node.key)) {
return node.value;
}
}
return null;
}
public K[] keySet() {
K[] keys = new K[size()];
int j = 0;
for (int i = 0; i < capacity; i++) {
if (elementData[i] != null) {
keys[j++] = elementData[i].key;
}
}
return keys;
}
public void clear() {
elementData = new Node[DEFAULT_INITIAL_CAPACITY];
this.capacity = DEFAULT_INITIAL_CAPACITY;
this.numPairs = 0;
}
public V remove(K key) {
V val = get(key);
int hashMod = key.hashCode() % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
elementData[hashMod] = null;
if (val != null) {
numPairs
}
return val;
}
public V put(K key, V value) {
int h = key.hashCode();
return putVal(h, key, value);
}
public V replace(K key, V newVal) {
int hashMod = key.hashCode() % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
Node<K,V> node = elementData[hashMod];
if (node != null) {
if (key.equals(node.key)) {
node.value = newVal;
return node.value;
}
}
return null;
}
private V putVal(int hash, K key, V value) {
int hashMod = hash % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
Node<K,V> node = elementData[hashMod];
while (node != null && (node.hash != hash || !key.equals(node.key))) {
resize(capacity + 4);
hashMod = hash % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
node = elementData[hashMod];
}
elementData[hashMod] = new Node<K,V>(key, value, hash);
if (node != null) {
return node.value;
} else {
numPairs ++;
return null;
}
}
private void putValNoResize(int hash, K key, V value) {
int hashMod = hash % capacity;
if (hashMod < 0) {
hashMod += capacity;
}
elementData[hashMod] = new Node<K,V>(key, value, hash);
}
} |
/*
* @author max
*/
package com.intellij.lang.html;
import com.intellij.codeInsight.completion.CompletionUtilCore;
import com.intellij.codeInsight.daemon.XmlErrorMessages;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.tree.ICustomParsingType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ILazyParseableElementType;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.containers.Stack;
import com.intellij.xml.util.HtmlUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public class HtmlParsing {
@NonNls private static final String TR_TAG = "tr";
@NonNls private static final String TD_TAG = "td";
@NonNls private static final String TH_TAG = "th";
@NonNls private static final String TABLE_TAG = "table";
private final PsiBuilder myBuilder;
private final Stack<String> myTagNamesStack = new Stack<>();
private final Stack<String> myOriginalTagNamesStack = new Stack<>();
private final Stack<PsiBuilder.Marker> myTagMarkersStack = new Stack<>();
@NonNls private static final String COMPLETION_NAME = StringUtil.toLowerCase(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED);
public HtmlParsing(final PsiBuilder builder) {
myBuilder = builder;
}
public void parseDocument() {
final PsiBuilder.Marker document = mark();
while (token() == XmlTokenType.XML_COMMENT_START) {
parseComment();
}
parseProlog();
PsiBuilder.Marker error = null;
while (!eof()) {
final IElementType tt = token();
if (tt == XmlTokenType.XML_START_TAG_START) {
error = flushError(error);
parseTag();
myTagMarkersStack.clear();
myTagNamesStack.clear();
}
else if (tt == XmlTokenType.XML_COMMENT_START) {
error = flushError(error);
parseComment();
}
else if (tt == XmlTokenType.XML_PI_START) {
error = flushError(error);
parseProcessingInstruction();
}
else if (tt == XmlTokenType.XML_CHAR_ENTITY_REF || tt == XmlTokenType.XML_ENTITY_REF_TOKEN) {
parseReference();
}
else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE || tt == XmlTokenType.XML_DATA_CHARACTERS) {
error = flushError(error);
advance();
} else if (tt == XmlTokenType.XML_END_TAG_START) {
final PsiBuilder.Marker tagEndError = myBuilder.mark();
advance();
if (token() == XmlTokenType.XML_NAME) {
advance();
if (token() == XmlTokenType.XML_TAG_END) {
advance();
}
}
tagEndError.error(XmlErrorMessages.message("xml.parsing.closing.tag.matches.nothing"));
}
else if (hasCustomTopLevelContent()) {
error = parseCustomTopLevelContent(error);
} else {
if (error == null) error = mark();
advance();
}
}
if (error != null) {
error.error(XmlErrorMessages.message("top.level.element.is.not.completed"));
}
document.done(XmlElementType.HTML_DOCUMENT);
}
protected boolean hasCustomTopLevelContent() {
return false;
}
protected PsiBuilder.Marker parseCustomTopLevelContent(PsiBuilder.Marker error) {
return error;
}
protected boolean hasCustomTagContent() {
return false;
}
protected PsiBuilder.Marker parseCustomTagContent(PsiBuilder.Marker xmlText) {
return xmlText;
}
@Nullable
protected static PsiBuilder.Marker flushError(PsiBuilder.Marker error) {
if (error != null) {
error.error(XmlErrorMessages.message("xml.parsing.unexpected.tokens"));
}
return null;
}
private void parseDoctype() {
assert token() == XmlTokenType.XML_DOCTYPE_START : "Doctype start expected";
final PsiBuilder.Marker doctype = mark();
advance();
while (token() != XmlTokenType.XML_DOCTYPE_END && !eof()) advance();
if (eof()) {
error(XmlErrorMessages.message("xml.parsing.unexpected.end.of.file"));
}
else {
advance();
}
doctype.done(XmlElementType.XML_DOCTYPE);
}
public void parseTag() {
assert token() == XmlTokenType.XML_START_TAG_START : "Tag start expected";
String originalTagName;
PsiBuilder.Marker xmlText = null;
while (!eof()) {
final IElementType tt = token();
if (tt == XmlTokenType.XML_START_TAG_START) {
xmlText = terminateText(xmlText);
final PsiBuilder.Marker tag = mark();
// Start tag header
advance();
if (token() != XmlTokenType.XML_NAME) {
error(XmlErrorMessages.message("xml.parsing.tag.name.expected"));
originalTagName = "";
}
else {
originalTagName = Objects.requireNonNull(myBuilder.getTokenText());
advance();
}
String tagName = StringUtil.toLowerCase(originalTagName);
while (childTerminatesParentInStack(tagName)) {
PsiBuilder.Marker top = closeTag();
top.doneBefore(XmlElementType.HTML_TAG, tag);
}
myTagMarkersStack.push(tag);
myTagNamesStack.push(tagName);
myOriginalTagNamesStack.push(originalTagName);
parseHeader(tagName);
if (token() == XmlTokenType.XML_EMPTY_ELEMENT_END) {
advance();
doneTag(tag);
continue;
}
if (token() == XmlTokenType.XML_TAG_END) {
advance();
}
else {
error(XmlErrorMessages.message("tag.start.is.not.closed"));
doneTag(tag);
continue;
}
if (isSingleTag(tagName, originalTagName)) {
final PsiBuilder.Marker footer = mark();
while (token() == XmlTokenType.XML_REAL_WHITE_SPACE) {
advance();
}
if (token() == XmlTokenType.XML_END_TAG_START) {
advance();
if (token() == XmlTokenType.XML_NAME) {
if (tagName.equalsIgnoreCase(myBuilder.getTokenText())) {
advance();
footer.drop();
if (token() == XmlTokenType.XML_TAG_END) {
advance();
}
doneTag(tag);
continue;
}
}
}
footer.rollbackTo();
doneTag(tag);
}
}
else if (tt == XmlTokenType.XML_PI_START) {
xmlText = terminateText(xmlText);
parseProcessingInstruction();
}
else if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN || tt == XmlTokenType.XML_CHAR_ENTITY_REF) {
xmlText = startText(xmlText);
parseReference();
}
else if (tt == XmlTokenType.XML_CDATA_START) {
xmlText = startText(xmlText);
parseCData();
}
else if (tt == XmlTokenType.XML_COMMENT_START) {
xmlText = startText(xmlText);
parseComment();
}
else if (tt == XmlTokenType.XML_BAD_CHARACTER) {
xmlText = startText(xmlText);
final PsiBuilder.Marker error = mark();
advance();
error.error(XmlErrorMessages.message("unescaped.ampersand.or.nonterminated.character.entity.reference"));
}
else if (tt instanceof ICustomParsingType || tt instanceof ILazyParseableElementType) {
xmlText = terminateText(xmlText);
advance();
}
else if (token() == XmlTokenType.XML_END_TAG_START) {
xmlText = terminateText(xmlText);
final PsiBuilder.Marker footer = mark();
advance();
if (token() == XmlTokenType.XML_NAME) {
String endName = StringUtil.toLowerCase(Objects.requireNonNull(myBuilder.getTokenText()));
final String parentTagName = !myTagNamesStack.isEmpty() ? myTagNamesStack.peek() : "";
if (!parentTagName.equals(endName) && !endName.endsWith(COMPLETION_NAME)) {
final boolean isOptionalTagEnd = HtmlUtil.isOptionalEndForHtmlTagL(parentTagName);
final boolean hasChancesToMatch = HtmlUtil.isOptionalEndForHtmlTagL(endName) ? childTerminatesParentInStack(endName) : myTagNamesStack.contains(endName);
if (hasChancesToMatch) {
footer.rollbackTo();
if (!isOptionalTagEnd) {
error(XmlErrorMessages.message("named.element.is.not.closed", myOriginalTagNamesStack.peek()));
}
doneTag(myTagMarkersStack.peek());
}
else {
advance();
if (token() == XmlTokenType.XML_TAG_END) advance();
footer.error(XmlErrorMessages.message("xml.parsing.closing.tag.matches.nothing"));
}
continue;
}
advance();
while (token() != XmlTokenType.XML_TAG_END && token() != XmlTokenType.XML_START_TAG_START && token() != XmlTokenType.XML_END_TAG_START && !eof()) {
error(XmlErrorMessages.message("xml.parsing.unexpected.token"));
advance();
}
}
else {
error(XmlErrorMessages.message("xml.parsing.closing.tag.name.missing"));
}
footer.drop();
if (token() == XmlTokenType.XML_TAG_END) {
advance();
}
else {
error(XmlErrorMessages.message("xml.parsing.closing.tag.is.not.done"));
}
if (hasTags()) doneTag(myTagMarkersStack.peek());
} else if ((token() == XmlTokenType.XML_REAL_WHITE_SPACE || token() == XmlTokenType.XML_DATA_CHARACTERS) && !hasTags()) {
xmlText = terminateText(xmlText);
advance();
} else if (hasCustomTagContent()) {
xmlText = parseCustomTagContent(xmlText);
} else {
xmlText = startText(xmlText);
advance();
}
}
terminateText(xmlText);
while (hasTags()) {
final String tagName = myTagNamesStack.peek();
if (!HtmlUtil.isOptionalEndForHtmlTagL(tagName) && !"html".equals(tagName) && !"body".equals(tagName)) {
error(XmlErrorMessages.message("named.element.is.not.closed", myOriginalTagNamesStack.peek()));
}
doneTag(myTagMarkersStack.peek());
}
}
protected boolean isSingleTag(@NotNull String tagName, @NotNull String originalTagName) {
return HtmlUtil.isSingleHtmlTagL(tagName);
}
protected boolean hasTags() {
return !myTagNamesStack.isEmpty();
}
protected PsiBuilder.Marker closeTag() {
myTagNamesStack.pop();
myOriginalTagNamesStack.pop();
return myTagMarkersStack.pop();
}
protected String peekTagName() {
return myTagNamesStack.peek();
}
protected PsiBuilder.Marker peekTagMarker() {
return myTagMarkersStack.peek();
}
private void doneTag(PsiBuilder.Marker tag) {
tag.done(XmlElementType.HTML_TAG);
final String tagName = myTagNamesStack.peek();
closeTag();
final String parentTagName = hasTags() ? myTagNamesStack.peek() : "";
boolean isInlineTagContainer = HtmlUtil.isInlineTagContainerL(parentTagName);
boolean isOptionalTagEnd = HtmlUtil.isOptionalEndForHtmlTagL(parentTagName);
if (isInlineTagContainer && HtmlUtil.isHtmlBlockTagL(tagName) && isOptionalTagEnd && !HtmlUtil.isPossiblyInlineTag(tagName)) {
PsiBuilder.Marker top = closeTag();
top.doneBefore(XmlElementType.HTML_TAG, tag);
}
}
private void parseHeader(String tagName) {
boolean freeMakerTag = !tagName.isEmpty() && '#' == tagName.charAt(0);
do {
final IElementType tt = token();
if (freeMakerTag) {
if (tt == XmlTokenType.XML_EMPTY_ELEMENT_END ||
tt == XmlTokenType.XML_TAG_END ||
tt == XmlTokenType.XML_END_TAG_START ||
tt == XmlTokenType.XML_START_TAG_START) break;
advance();
}
else {
if (tt == XmlTokenType.XML_NAME) {
parseAttribute();
}
else if (tt == XmlTokenType.XML_CHAR_ENTITY_REF || tt == XmlTokenType.XML_ENTITY_REF_TOKEN) {
parseReference();
}
else {
break;
}
}
}
while (!eof());
}
private boolean childTerminatesParentInStack(final String childName) {
boolean isCell = TD_TAG.equals(childName) || TH_TAG.equals(childName);
boolean isRow = TR_TAG.equals(childName);
boolean isStructure = isStructure(childName);
for (int i = myTagNamesStack.size() - 1; i >= 0; i
String parentName = myTagNamesStack.get(i);
final boolean isParentTable = TABLE_TAG.equals(parentName);
final boolean isParentStructure = isStructure(parentName);
if (isCell && (TR_TAG.equals(parentName) || isParentStructure || isParentTable) ||
isRow && (isParentStructure || isParentTable) ||
isStructure && isParentTable) {
return false;
}
if ("li".equals(childName) && ("ul".equals(parentName) || "ol".equals(parentName))) {
return false;
}
if ("dl".equals(parentName) && ("dd".equals(childName) || "dt".equals(childName))) {
return false;
}
if (HtmlUtil.canTerminate(childName, parentName)) {
return true;
}
}
return false;
}
private static boolean isStructure(String childName) {
return "thead".equals(childName) || "tbody".equals(childName) || "tfoot".equals(childName);
}
@NotNull
protected PsiBuilder.Marker startText(@Nullable PsiBuilder.Marker xmlText) {
if (xmlText == null) {
xmlText = mark();
}
return xmlText;
}
protected final PsiBuilder getBuilder() {
return myBuilder;
}
protected final PsiBuilder.Marker mark() {
return myBuilder.mark();
}
@Nullable
protected static PsiBuilder.Marker terminateText(@Nullable PsiBuilder.Marker xmlText) {
if (xmlText != null) {
xmlText.done(XmlElementType.XML_TEXT);
xmlText = null;
}
return xmlText;
}
protected void parseCData() {
assert token() == XmlTokenType.XML_CDATA_START;
final PsiBuilder.Marker cdata = mark();
while (token() != XmlTokenType.XML_CDATA_END && !eof()) {
advance();
}
if (!eof()) {
advance();
}
cdata.done(XmlElementType.XML_CDATA);
}
protected void parseComment() {
final PsiBuilder.Marker comment = mark();
advance();
while (true) {
final IElementType tt = token();
if (tt == XmlTokenType.XML_COMMENT_CHARACTERS || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START
|| tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START_END || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END_START
|| tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END) {
advance();
continue;
}
if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN || tt == XmlTokenType.XML_CHAR_ENTITY_REF) {
parseReference();
continue;
}
if (tt == XmlTokenType.XML_BAD_CHARACTER) {
final PsiBuilder.Marker error = mark();
advance();
error.error(XmlErrorMessages.message("xml.parsing.bad.character"));
continue;
}
if (tt == XmlTokenType.XML_COMMENT_END) {
advance();
}
break;
}
comment.done(XmlElementType.XML_COMMENT);
}
protected void parseReference() {
if (token() == XmlTokenType.XML_CHAR_ENTITY_REF) {
advance();
}
else if (token() == XmlTokenType.XML_ENTITY_REF_TOKEN) {
final PsiBuilder.Marker ref = mark();
advance();
ref.done(XmlElementType.XML_ENTITY_REF);
}
else {
assert false : "Unexpected token";
}
}
protected void parseAttribute() {
assert token() == XmlTokenType.XML_NAME;
final PsiBuilder.Marker att = mark();
advance();
if (token() == XmlTokenType.XML_EQ) {
advance();
parseAttributeValue();
}
att.done(XmlElementType.XML_ATTRIBUTE);
}
protected void parseAttributeValue() {
final PsiBuilder.Marker attValue = mark();
if (token() == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER) {
while (true) {
final IElementType tt = token();
if (tt == null || tt == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || tt == XmlTokenType.XML_END_TAG_START || tt == XmlTokenType
.XML_EMPTY_ELEMENT_END ||
tt == XmlTokenType.XML_START_TAG_START) {
break;
}
if (tt == XmlTokenType.XML_BAD_CHARACTER) {
final PsiBuilder.Marker error = mark();
advance();
error.error(XmlErrorMessages.message("unescaped.ampersand.or.nonterminated.character.entity.reference"));
}
else if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN) {
parseReference();
}
else {
advance();
}
}
if (token() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER) {
advance();
}
else {
error(XmlErrorMessages.message("xml.parsing.unclosed.attribute.value"));
}
}
else {
if (token() != XmlTokenType.XML_TAG_END && token() != XmlTokenType.XML_EMPTY_ELEMENT_END) {
advance(); // Single token att value
}
}
attValue.done(XmlElementType.XML_ATTRIBUTE_VALUE);
}
private void parseProlog() {
while (true) {
final IElementType tt = token();
if (tt == XmlTokenType.XML_COMMENT_START) {
parseComment();
}
else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE) {
advance();
}
else {
break;
}
}
final PsiBuilder.Marker prolog = mark();
while (true) {
final IElementType tt = token();
if (tt == XmlTokenType.XML_PI_START) {
parseProcessingInstruction();
}
else if (tt == XmlTokenType.XML_DOCTYPE_START) {
parseDoctype();
}
else if (tt == XmlTokenType.XML_COMMENT_START) {
parseComment();
}
else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE) {
advance();
}
else {
break;
}
}
prolog.done(XmlElementType.XML_PROLOG);
}
protected void parseProcessingInstruction() {
assert token() == XmlTokenType.XML_PI_START;
final PsiBuilder.Marker pi = mark();
advance();
if (token() == XmlTokenType.XML_NAME || token() == XmlTokenType.XML_PI_TARGET) {
advance();
}
while (token() == XmlTokenType.XML_NAME) {
advance();
if (token() == XmlTokenType.XML_EQ) {
advance();
}
else {
error(XmlErrorMessages.message("expected.attribute.eq.sign"));
}
parseAttributeValue();
}
if (token() == XmlTokenType.XML_PI_END) {
advance();
}
else {
error(XmlErrorMessages.message("xml.parsing.unterminated.processing.instruction"));
}
pi.done(XmlElementType.XML_PROCESSING_INSTRUCTION);
}
protected final IElementType token() {
return myBuilder.getTokenType();
}
protected final boolean eof() {
return myBuilder.eof();
}
protected final void advance() {
myBuilder.advanceLexer();
}
protected void error(@NotNull String message) {
myBuilder.error(message);
}
} |
package com.thoughtworks.acceptance;
public class ArraysTest extends AbstractAcceptanceTest {
public void testStringArray() {
String[] array = new String[]{"a", "b", "c"};
String expected = "" +
"<string-array>\n" +
" <string>a</string>\n" +
" <string>b</string>\n" +
" <string>c</string>\n" +
"</string-array>";
assertBothWays(array, expected);
}
public void testPrimitiveArray() {
int[] array = new int[]{1, 2};
String expected = "" +
"<int-array>\n" +
" <int>1</int>\n" +
" <int>2</int>\n" +
"</int-array>";
assertBothWays(array, expected);
}
public void testBoxedTypeArray() {
Integer[] array = new Integer[]{new Integer(1), new Integer(2)};
String expected = "" +
"<java.lang.Integer-array>\n" +
" <int>1</int>\n" +
" <int>2</int>\n" +
"</java.lang.Integer-array>";
assertBothWays(array, expected);
}
public static class X extends StandardObject {
String s = "hi";
}
public void testCustomObjectArray() {
X[] array = new X[]{new X(), new X()};
String expected = "" +
"<com.thoughtworks.acceptance.ArraysTest_-X-array>\n" +
" <com.thoughtworks.acceptance.ArraysTest_-X>\n" +
" <s>hi</s>\n" +
" </com.thoughtworks.acceptance.ArraysTest_-X>\n" +
" <com.thoughtworks.acceptance.ArraysTest_-X>\n" +
" <s>hi</s>\n" +
" </com.thoughtworks.acceptance.ArraysTest_-X>\n" +
"</com.thoughtworks.acceptance.ArraysTest_-X-array>";
assertBothWays(array, expected);
}
public void testArrayOfMixedTypes() {
Object[] array = new Number[]{new Long(2), new Integer(3)};
String expected = "" +
"<number-array>\n" +
" <long>2</long>\n" +
" <int>3</int>\n" +
"</number-array>";
assertBothWays(array, expected);
}
public void testEmptyArray() {
int[] array = new int[]{};
String expected = "<int-array/>";
assertBothWays(array, expected);
}
public void testUninitializedArray() {
String[] array = new String[4];
array[0] = "zero";
array[2] = "two";
String expected = "" +
"<string-array>\n" +
" <string>zero</string>\n" +
" <null/>\n" +
" <string>two</string>\n" +
" <null/>\n" +
"</string-array>";
assertBothWays(array, expected);
}
public void testArrayInCustomObject() {
ObjWithArray objWithArray = new ObjWithArray();
objWithArray.strings = new String[]{"hi", "bye"};
xstream.alias("owa", ObjWithArray.class);
String expected = "" +
"<owa>\n" +
" <strings>\n" +
" <string>hi</string>\n" +
" <string>bye</string>\n" +
" </strings>\n" +
"</owa>";
assertBothWays(objWithArray, expected);
}
public void testNullArrayInCustomObject() {
ObjWithArray objWithArray = new ObjWithArray();
xstream.alias("owa", ObjWithArray.class);
String expected = "<owa/>";
assertBothWays(objWithArray, expected);
}
public static class ObjWithArray extends StandardObject {
String[] strings;
}
public void testDeserializingObjectWhichContainsAPrimitiveLongArray() {
String xml =
"<owla>" +
" <bits class=\"long-array\">" +
" <long>0</long>" +
" <long>1</long>" +
" <long>2</long>" +
" </bits>" +
"</owla>";
xstream.alias("owla", ObjectWithLongArray.class);
ObjectWithLongArray o = (ObjectWithLongArray) xstream.fromXML(xml);
assertEquals(o.bits[0], 0);
assertEquals(o.bits[1], 1);
assertEquals(o.bits[2], 2);
}
public static class ObjectWithLongArray {
long[] bits;
}
public void testMultidimensionalArray() {
int[][] array = new int[3][2];
array[0][0] = 2;
array[0][1] = 4;
array[1][0] = 8;
array[1][1] = 16;
array[2] = new int[3];
array[2][0] = 33;
array[2][1] = 66;
array[2][2] = 99;
String expectedXml = "" +
"<int-array-array>\n" +
" <int-array>\n" +
" <int>2</int>\n" +
" <int>4</int>\n" +
" </int-array>\n" +
" <int-array>\n" +
" <int>8</int>\n" +
" <int>16</int>\n" +
" </int-array>\n" +
" <int-array>\n" +
" <int>33</int>\n" +
" <int>66</int>\n" +
" <int>99</int>\n" +
" </int-array>\n" +
"</int-array-array>";
String actualXml = xstream.toXML(array);
assertEquals(expectedXml, actualXml);
int[][] result = (int[][]) xstream.fromXML(actualXml);
assertEquals(2, result[0][0]);
assertEquals(4, result[0][1]);
assertEquals(8, result[1][0]);
assertEquals(16, result[1][1]);
assertEquals(99, result[2][2]);
assertEquals(3, result.length);
assertEquals(2, result[0].length);
assertEquals(2, result[1].length);
assertEquals(3, result[2].length);
}
public static class Thing {
}
public static class SpecialThing extends Thing {
}
public void testMultidimensionalArrayOfMixedTypes() {
xstream.alias("thing", Thing.class);
xstream.alias("special-thing", SpecialThing.class);
Object[][] array = new Object[2][2];
array[0][0] = new Object();
array[0][1] = "a string";
array[1] = new Thing[2];
array[1][0] = new Thing();
array[1][1] = new SpecialThing();
String expectedXml = "" +
"<object-array-array>\n" +
" <object-array>\n" +
" <object/>\n" +
" <string>a string</string>\n" +
" </object-array>\n" +
" <thing-array>\n" +
" <thing/>\n" +
" <special-thing/>\n" +
" </thing-array>\n" +
"</object-array-array>";
String actualXml = xstream.toXML(array);
assertEquals(expectedXml, actualXml);
Object[][] result = (Object[][]) xstream.fromXML(actualXml);
assertEquals(Object.class, result[0][0].getClass());
assertEquals("a string", result[0][1]);
assertEquals(Thing.class, result[1][0].getClass());
assertEquals(SpecialThing.class, result[1][1].getClass());
}
public static class NoOneLikesMe extends StandardObject {
private int name;
public NoOneLikesMe(int name) {
this.name = name;
}
}
public void testHandlesArrayClassesThatHaveNotYetBeenLoaded() {
// Catch weirdness in classloader.
// Resolved by using Class.forName(x, false, classLoader), instead of classLoader.loadClass(x);
String xml = ""
+ "<com.thoughtworks.acceptance.ArraysTest_-NoOneLikesMe-array>\n"
+ " <com.thoughtworks.acceptance.ArraysTest_-NoOneLikesMe>\n"
+ " <name>99</name>\n"
+ " </com.thoughtworks.acceptance.ArraysTest_-NoOneLikesMe>\n"
+ "</com.thoughtworks.acceptance.ArraysTest_-NoOneLikesMe-array>";
NoOneLikesMe[] result = (NoOneLikesMe[]) xstream.fromXML(xml);
assertEquals(1, result.length);
assertEquals(99, result[0].name);
}
} |
package com.thoughtworks.acceptance;
public class ArraysTest extends AbstractAcceptanceTest {
public void testStringArray() {
String[] array = new String[]{"a", "b", "c"};
String expected = "" +
"<string-array>\n" +
" <string>a</string>\n" +
" <string>b</string>\n" +
" <string>c</string>\n" +
"</string-array>";
assertBothWays(array, expected);
}
public void testPrimitiveArray() {
int[] array = new int[]{1, 2};
String expected = "" +
"<int-array>\n" +
" <int>1</int>\n" +
" <int>2</int>\n" +
"</int-array>";
assertBothWays(array, expected);
}
class X extends StandardObject {
String s = "hi";
}
public void testCustomObjectArray() {
X[] array = new X[]{new X(), new X()};
String expected = "" +
"<com.thoughtworks.acceptance.ArraysTest-X-array>\n" +
" <com.thoughtworks.acceptance.ArraysTest-X>\n" +
" <s>hi</s>\n" +
" </com.thoughtworks.acceptance.ArraysTest-X>\n" +
" <com.thoughtworks.acceptance.ArraysTest-X>\n" +
" <s>hi</s>\n" +
" </com.thoughtworks.acceptance.ArraysTest-X>\n" +
"</com.thoughtworks.acceptance.ArraysTest-X-array>";
assertBothWays(array, expected);
}
public void testArrayOfMixedTypes() {
Object[] array = new Number[]{new Long(2), new Integer(3)};
String expected = "" +
"<number-array>\n" +
" <long>2</long>\n" +
" <int>3</int>\n" +
"</number-array>";
assertBothWays(array, expected);
}
public void testEmptyArray() {
int[] array = new int[]{};
String expected = "<int-array/>";
assertBothWays(array, expected);
}
public void testUninitializedArray() {
String[] array = new String[4];
array[0] = "zero";
array[2] = "two";
String expected = "" +
"<string-array>\n" +
" <string>zero</string>\n" +
" <null/>\n" +
" <string>two</string>\n" +
" <null/>\n" +
"</string-array>";
assertBothWays(array, expected);
}
public void testArrayInCustomObject() {
ObjWithArray objWithArray = new ObjWithArray();
objWithArray.strings = new String[]{"hi", "bye"};
xstream.alias("owa", ObjWithArray.class);
String expected = "" +
"<owa>\n" +
" <strings class=\"string-array\">\n" +
" <string>hi</string>\n" +
" <string>bye</string>\n" +
" </strings>\n" +
"</owa>";
assertBothWays(objWithArray, expected);
}
class ObjWithArray extends StandardObject {
String[] strings;
}
public void testDeserializingObjectWhichContainsAPrimitiveLongArray() {
String xml =
"<owla>" +
" <bits class=\"long-array\">" +
" <long>0</long>" +
" <long>1</long>" +
" <long>2</long>" +
" </bits>" +
"</owla>";
xstream.alias( "owla", ObjectWithLongArray.class );
ObjectWithLongArray o = (ObjectWithLongArray) xstream.fromXML( xml );
assertEquals( o.bits[0], 0 );
assertEquals( o.bits[1], 1 );
assertEquals( o.bits[2], 2 );
}
class ObjectWithLongArray {
long[] bits;
}
} |
package org.yamcs.parameter;
import java.util.Arrays;
import org.yamcs.protobuf.Yamcs.Value.Type;
/**
* Multidimensional value array. All the elements of the array have to have the same type.
*
* The number of dimensions and the size of each dimension are fixed in the constructor.
*
* The array is internally stored into a flat java array. The {@link #flatIndex(int[])} can be used to convert from the
* multi dimensional index to the flat index.
*
* @author nm
*
*/
public class ArrayValue extends Value {
final Value[] elements;
final int[] dim;
final Type elementType;
/**
* Create a new value array of size dim[0]*dim[1]*...*dim[n]
*
* @param dim
* @param elementType
*/
public ArrayValue(int[] dim, Type elementType) {
if (dim.length == 0) {
throw new IllegalArgumentException("The array has to be at least ");
}
this.elementType = elementType;
int fs = flatSize(dim);
this.dim = dim;
this.elements = new Value[fs];
}
@Override
public Type getType() {
return Type.ARRAY;
}
/**
* Get the value of the element at the given index
*
* @param idx
* - multidimensional index
* @return - the value
*
* @throws ArrayIndexOutOfBoundsException
* if the index is outside of the array
*/
public Value getElementValue(int[] idx) {
if (dim.length != idx.length) {
throw new IllegalArgumentException("number of dimensions should be " + dim.length);
}
return elements[flatIndex(idx)];
}
/**
* Return true of the idx is the same dimensions with this array and if the element exists (i.e. idx is not out of bounds)
*
* @param idx
* @return
*/
public boolean hasElement(int[] idx) {
if (dim.length != idx.length) {
return false;
}
return flatIndex(idx) < elements.length;
}
public void setElementValue(int[] idx, Value v) {
if (dim.length != idx.length) {
throw new IllegalArgumentException("number of dimensions should be " + dim.length);
}
if (v.getType() != elementType) {
throw new IllegalArgumentException("Element type should be " + elementType);
}
elements[flatIndex(idx)] = v;
}
public static int flatIndex(int[] dim, int[] idx) {
if (idx.length == 1) {
return idx[0];
}
int n = idx[0];
for (int i = 1; i < dim.length; i++) {
n = n * dim[i] + idx[i];
}
return n;
}
public int flatIndex(int[] idx) {
return flatIndex(dim, idx);
}
static public int flatSize(int[] dim) {
if (dim.length == 1) {
return dim[0];
}
int n = dim[0];
for (int i = 1; i < dim.length; i++) {
n *= dim[i];
}
return n;
}
/**
* unflatten the flatIndex into the idx array
*/
public void unFlattenIndex(int flatIndex, int[] idx) {
if(idx.length!=dim.length) {
throw new IllegalArgumentException("idx length is not the expected one");
}
if (dim.length == 1) {
idx[0] = flatIndex;
return;
}
}
/**
* Set the value of an element using the flat index
*
* @param flatIdx
* - flat index of the element to be set
* @param v
* - the value to be set
* @throws ArrayIndexOutOfBoundsException
* if the index is outside of the array
*/
public void setElementValue(int flatIdx, Value v) {
elements[flatIdx] = v;
}
/**
* Get the element value using the flat index;
*
* @param flatIdx
* - flat index of the element to be set
* @return the value
*/
public Value getElementValue(int flatIdx) {
return elements[flatIdx];
}
/**
* Return the length of the flat array
* This is the product of the size of the individual dimensions.
*
* @return
*/
public int flatLength() {
return elements.length;
}
/**
*
* @return the type of the array elements
*/
public Type getElementType() {
return elementType;
}
/**
* returns the dimensions of the array
*
* @return
*/
public int[] getDimensions() {
return dim;
}
public String toString() {
return Arrays.toString(elements);
}
} |
package org.pentaho.di.ui.spoon.job;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.LineAttributes;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.dnd.DragAndDropContainer;
import org.pentaho.di.core.dnd.XMLTransfer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleJobException;
import org.pentaho.di.core.gui.GUIPositionInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.Redrawable;
import org.pentaho.di.core.gui.SnapAllignDistribute;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobHopMeta;
import org.pentaho.di.job.JobListener;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.job.JobEntryJob;
import org.pentaho.di.job.entries.trans.JobEntryTrans;
import org.pentaho.di.job.entry.JobEntryCopy;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.XulHelper;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.spoon.job.Messages;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.TabMapEntry;
import org.pentaho.di.ui.spoon.TransPainter;
import org.pentaho.di.ui.spoon.XulMessages;
import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox;
import org.pentaho.xul.menu.XulMenu;
import org.pentaho.xul.menu.XulMenuChoice;
import org.pentaho.xul.menu.XulPopupMenu;
import org.pentaho.xul.swt.tab.TabItem;
import org.pentaho.xul.toolbar.XulToolbar;
import org.pentaho.xul.toolbar.XulToolbarButton;
public class JobGraph extends Composite implements Redrawable, TabItemInterface {
private static final String XUL_FILE_JOB_TOOLBAR = "ui/job-toolbar.xul";
public static final String XUL_FILE_JOB_TOOLBAR_PROPERTIES = "ui/job-toolbar.properties";
public final static String START_TEXT = Messages.getString("JobLog.Button.Start"); //$NON-NLS-1$
// public final static String PAUSE_TEXT = Messages.getString("JobLog.Button.PauseJob"); //$NON-NLS-1$ TODO
// public final static String RESUME_TEXT = Messages.getString("JobLog.Button.ResumeJob"); //$NON-NLS-1$ TODO
public final static String STOP_TEXT = Messages.getString("JobLog.Button.Stop"); //$NON-NLS-1$
private final static String STRING_PARALLEL_WARNING_PARAMETER = "ParallelJobEntriesWarning";
private static final int HOP_SEL_MARGIN = 9;
protected Shell shell;
protected Canvas canvas;
protected LogWriter log;
protected JobMeta jobMeta;
private Job job;
// protected Props props;
protected int iconsize;
protected int linewidth;
protected Point lastclick;
protected JobEntryCopy selected_entries[];
protected JobEntryCopy selected_icon;
protected Point prev_locations[];
protected NotePadMeta selected_note;
protected Point previous_note_location;
protected Point lastMove;
protected JobHopMeta hop_candidate;
protected Point drop_candidate;
protected Spoon spoon;
protected Point offset, iconoffset, noteoffset;
protected ScrollBar hori;
protected ScrollBar vert;
// public boolean shift, control;
protected boolean split_hop;
protected int last_button;
protected JobHopMeta last_hop_split;
protected Rectangle selrect;
protected static final double theta = Math.toRadians(10); // arrowhead sharpness
protected static final int size = 30; // arrowhead length
protected int shadowsize;
protected Map<String, org.pentaho.xul.swt.menu.Menu> menuMap = new HashMap<String, org.pentaho.xul.swt.menu.Menu>();
protected int currentMouseX = 0;
protected int currentMouseY = 0;
protected JobEntryCopy jobEntry;
protected NotePadMeta ni = null;
protected JobHopMeta currentHop;
// private Text filenameLabel;
private SashForm sashForm;
public Composite extraViewComposite;
public CTabFolder extraViewTabFolder;
private XulToolbar toolbar;
private float magnification = 1.0f;
public JobLogDelegate jobLogDelegate;
public JobHistoryDelegate jobHistoryDelegate;
public JobGridDelegate jobGridDelegate;
private boolean running;
private Composite mainComposite;
private List<RefreshListener> refreshListeners;
private Label closeButton;
private Label minMaxButton;
private Combo zoomLabel;
private int gridSize;
private float translationX;
private float translationY;
private boolean shadow;
public JobGraph(Composite par, final Spoon spoon, final JobMeta jobMeta) {
super(par, SWT.NONE);
shell = par.getShell();
this.log = LogWriter.getInstance();
this.spoon = spoon;
this.jobMeta = jobMeta;
// this.props = Props.getInstance();
jobLogDelegate = new JobLogDelegate(spoon, this);
jobHistoryDelegate = new JobHistoryDelegate(spoon, this);
jobGridDelegate = new JobGridDelegate(spoon, this);
refreshListeners = new ArrayList<RefreshListener>();
setLayout(new FormLayout());
// Add a tool-bar at the top of the tab
// The form-data is set on the native widget automatically
addToolBar();
// The main composite contains the graph view, but if needed also
// a view with an extra tab containing log, etc.
mainComposite = new Composite(this, SWT.NONE);
mainComposite.setLayout(new FillLayout());
FormData fdMainComposite = new FormData();
fdMainComposite.left = new FormAttachment(0, 0);
fdMainComposite.top = new FormAttachment((Control) toolbar.getNativeObject(), 0);
fdMainComposite.right = new FormAttachment(100, 0);
fdMainComposite.bottom = new FormAttachment(100, 0);
mainComposite.setLayoutData(fdMainComposite);
// To allow for a splitter later on, we will add the splitter here...
sashForm = new SashForm(mainComposite, SWT.VERTICAL);
// Add a canvas below it, use up all space initially
canvas = new Canvas(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER);
sashForm.setWeights(new int[] { 100, });
try {
menuMap = XulHelper.createPopupMenus(SpoonInterface.XUL_FILE_MENUS, shell,
new org.pentaho.di.ui.spoon.job.XulMessages(), "job-graph-hop", "job-graph-note", "job-graph-background",
"job-graph-entry");
} catch (Throwable t) {
log.logError(toString(), Const.getStackTracker(t));
new ErrorDialog(shell, Messages.getString("JobGraph.Exception.ErrorReadingXULFile.Title"),
Messages.getString("JobGraph.Exception.ErrorReadingXULFile.Message", Spoon.XUL_FILE_MENUS), new Exception(t));
}
newProps();
selrect = null;
hop_candidate = null;
last_hop_split = null;
selected_entries = null;
selected_note = null;
hori = canvas.getHorizontalBar();
vert = canvas.getVerticalBar();
hori.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
vert.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
hori.setThumb(100);
vert.setThumb(100);
hori.setVisible(true);
vert.setVisible(true);
setVisible(true);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
JobGraph.this.paintControl(e);
}
});
canvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseScrolled(MouseEvent e) {
if (e.count == 3) {
// scroll up
zoomIn();
} else if (e.count == -3) {
// scroll down
zoomOut();
}
}
});
selected_entries = null;
lastclick = null;
canvas.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
clearSettings();
Point real = screen2real(e.x, e.y);
JobEntryCopy jobentry = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (jobentry != null) {
if (e.button == 1) {
editEntry(jobentry);
} else // open tab in Spoon
{
launchStuff(jobentry);
}
} else {
// Check if point lies on one of the many hop-lines...
JobHopMeta online = findJobHop(real.x, real.y);
if (online != null) {
// editJobHop(online);
} else {
NotePadMeta ni = jobMeta.getNote(real.x, real.y);
if (ni != null) {
editNote(ni);
}
}
}
}
public void mouseDown(MouseEvent e) {
clearSettings();
last_button = e.button;
Point real = screen2real(e.x, e.y);
lastclick = new Point(real.x, real.y);
// Clear the tooltip!
if (spoon.getProperties().showToolTips())
setToolTipText(null);
// Set the pop-up menu
if (e.button == 3) {
setMenu(real.x, real.y);
return;
}
JobEntryCopy je = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (je != null) {
selected_entries = jobMeta.getSelectedEntries();
selected_icon = je;
// make sure this is correct!!!
// When an icon is moved that is not selected, it gets selected too late.
// It is not captured here, but in the mouseMoveListener...
prev_locations = jobMeta.getSelectedLocations();
Point p = je.getLocation();
iconoffset = new Point(real.x - p.x, real.y - p.y);
} else {
// Dit we hit a note?
NotePadMeta ni = jobMeta.getNote(real.x, real.y);
if (ni != null && last_button == 1) {
selected_note = ni;
Point loc = ni.getLocation();
previous_note_location = new Point(loc.x, loc.y);
noteoffset = new Point(real.x - loc.x, real.y - loc.y);
// System.out.println("We hit a note!!");
} else {
selrect = new Rectangle(real.x, real.y, 0, 0);
}
}
redraw();
}
public void mouseUp(MouseEvent e) {
boolean control = (e.stateMask & SWT.CONTROL) != 0;
if (iconoffset == null)
iconoffset = new Point(0, 0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
// See if we need to add a hop...
if (hop_candidate != null) {
// hop doesn't already exist
if (jobMeta.findJobHop(hop_candidate.from_entry, hop_candidate.to_entry) == null) {
if (!hop_candidate.from_entry.evaluates() && hop_candidate.from_entry.isUnconditional()) {
hop_candidate.setUnconditional();
} else {
hop_candidate.setConditional();
int nr = jobMeta.findNrNextJobEntries(hop_candidate.from_entry);
// If there is one green link: make this one red! (or vice-versa)
if (nr == 1) {
JobEntryCopy jge = jobMeta.findNextJobEntry(hop_candidate.from_entry, 0);
JobHopMeta other = jobMeta.findJobHop(hop_candidate.from_entry, jge);
if (other != null) {
hop_candidate.setEvaluation(!other.getEvaluation());
}
}
}
jobMeta.addJobHop(hop_candidate);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { hop_candidate }, new int[] { jobMeta
.indexOfJobHop(hop_candidate) });
spoon.refreshTree();
}
hop_candidate = null;
selected_entries = null;
last_button = 0;
redraw();
}
// Did we select a region on the screen?
else if (selrect != null) {
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
jobMeta.unselectAll();
selectInRect(jobMeta, selrect);
selrect = null;
redraw();
}
// Clicked on an icon?
else if (selected_icon != null) {
if (e.button == 1) {
if (lastclick.x == real.x && lastclick.y == real.y) {
// Flip selection when control is pressed!
if (control) {
selected_icon.flipSelected();
} else {
// Otherwise, select only the icon clicked on!
jobMeta.unselectAll();
selected_icon.setSelected(true);
}
} else // We moved around some items: store undo info...
if (selected_entries != null && prev_locations != null) {
int indexes[] = jobMeta.getEntryIndexes(selected_entries);
spoon.addUndoPosition(jobMeta, selected_entries, indexes, prev_locations, jobMeta.getSelectedLocations());
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if (split_hop) {
JobHopMeta hi = findJobHop(icon.x + iconsize / 2, icon.y + iconsize / 2);
if (hi != null) {
int id = 0;
if (!spoon.props.getAutoSplit()) {
MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages
.getString("JobGraph.Dialog.SplitHop.Title"), null, Messages
.getString("JobGraph.Dialog.SplitHop.Message")
+ Const.CR + hi.from_entry.getName() + " --> " + hi.to_entry.getName(), MessageDialog.QUESTION,
new String[] { Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") },
0, Messages.getString("JobGraph.Dialog.SplitHop.Toggle"), spoon.props.getAutoSplit());
MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
id = md.open();
spoon.props.setAutoSplit(md.getToggleState());
}
if ((id & 0xFF) == 0) {
JobHopMeta newhop1 = new JobHopMeta(hi.from_entry, selected_icon);
jobMeta.addJobHop(newhop1);
JobHopMeta newhop2 = new JobHopMeta(selected_icon, hi.to_entry);
jobMeta.addJobHop(newhop2);
if (!selected_icon.evaluates())
newhop2.setUnconditional();
spoon.addUndoNew(jobMeta,
new JobHopMeta[] { (JobHopMeta) newhop1.clone(), (JobHopMeta) newhop2.clone() }, new int[] {
jobMeta.indexOfJobHop(newhop1), jobMeta.indexOfJobHop(newhop2) });
int idx = jobMeta.indexOfJobHop(hi);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { (JobHopMeta) hi.clone() }, new int[] { idx });
jobMeta.removeJobHop(idx);
spoon.refreshTree();
}
}
split_hop = false;
}
selected_entries = null;
redraw();
}
// Notes?
else if (selected_note != null) {
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
if (last_button == 1) {
if (lastclick.x != real.x || lastclick.y != real.y) {
int indexes[] = new int[] { jobMeta.indexOfNote(selected_note) };
spoon.addUndoPosition(jobMeta, new NotePadMeta[] { selected_note }, indexes,
new Point[] { previous_note_location }, new Point[] { note });
}
}
selected_note = null;
}
}
});
canvas.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent e) {
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
// Remember the last position of the mouse for paste with keyboard
lastMove = new Point(e.x, e.y);
if (iconoffset == null)
iconoffset = new Point(0, 0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
setToolTip(real.x, real.y, e.x, e.y);
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should unselect all other icons,
// selected and move only the one icon
if (selected_icon != null && !selected_icon.isSelected()) {
jobMeta.unselectAll();
selected_icon.setSelected(true);
selected_entries = new JobEntryCopy[] { selected_icon };
prev_locations = new Point[] { selected_icon.getLocation() };
}
// Did we select a region...?
if (selrect != null) {
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
redraw();
} else
// Or just one entry on the screen?
if (selected_entries != null) {
if (last_button == 1 && !shift) {
/*
* One or more icons are selected and moved around...
*
* new : new position of the ICON (not the mouse pointer)
* dx : difference with previous position
*/
int dx = icon.x - selected_icon.getLocation().x;
int dy = icon.y - selected_icon.getLocation().y;
JobHopMeta hi = findJobHop(icon.x + iconsize / 2, icon.y + iconsize / 2);
if (hi != null) {
//log.logBasic("MouseMove", "Split hop candidate B!");
if (!jobMeta.isEntryUsedInHops(selected_icon)) {
//log.logBasic("MouseMove", "Split hop candidate A!");
split_hop = true;
last_hop_split = hi;
hi.setSplit(true);
}
} else {
if (last_hop_split != null) {
last_hop_split.setSplit(false);
last_hop_split = null;
split_hop = false;
}
}
// One or more job entries are being moved around!
for (int i = 0; i < jobMeta.nrJobEntries(); i++) {
JobEntryCopy je = jobMeta.getJobEntry(i);
if (je.isSelected()) {
PropsUI.setLocation(je, je.getLocation().x + dx, je.getLocation().y + dy);
}
}
redraw();
} else
// The middle button perhaps?
if (last_button == 2 || (last_button == 1 && shift)) {
JobEntryCopy si = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (si != null && !selected_icon.equals(si)) {
if (hop_candidate == null) {
hop_candidate = new JobHopMeta(selected_icon, si);
redraw();
}
} else {
if (hop_candidate != null) {
hop_candidate = null;
redraw();
}
}
}
} else
// are we moving a note around?
if (selected_note != null) {
if (last_button == 1) {
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
PropsUI.setLocation(selected_note, note.x, note.y);
redraw();
//spoon.refreshGraph(); removed in 2.4.1 (SB: defect #4862)
}
}
}
});
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void dragLeave(DropTargetEvent event) {
drop_candidate = null;
redraw();
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void drop(DropTargetEvent event) {
// no data to copy, indicate failure in event.detail
if (event.data == null) {
event.detail = DND.DROP_NONE;
return;
}
Point p = getRealPosition(canvas, event.x, event.y);
try {
DragAndDropContainer container = (DragAndDropContainer) event.data;
String entry = container.getData();
switch (container.getType()) {
case DragAndDropContainer.TYPE_BASE_JOB_ENTRY: // Create a new Job Entry on the canvas
{
JobEntryCopy jge = spoon.newJobEntry(jobMeta, entry, false);
if (jge != null) {
PropsUI.setLocation(jge, p.x, p.y);
jge.setDrawn();
redraw();
}
}
break;
case DragAndDropContainer.TYPE_JOB_ENTRY: // Drag existing one onto the canvas
{
JobEntryCopy jge = jobMeta.findJobEntry(entry, 0, true);
if (jge != null) // Create duplicate of existing entry
{
// There can be only 1 start!
if (jge.isStart() && jge.isDrawn()) {
showOnlyStartOnceMessage(shell);
return;
}
boolean jge_changed = false;
// For undo :
JobEntryCopy before = (JobEntryCopy) jge.clone_deep();
JobEntryCopy newjge = jge;
if (jge.isDrawn()) {
newjge = (JobEntryCopy) jge.clone();
if (newjge != null) {
// newjge.setEntry(jge.getEntry());
if(log.isDebug()) log.logDebug(toString(), "entry aft = " + ((Object) jge.getEntry()).toString()); //$NON-NLS-1$
newjge.setNr(jobMeta.findUnusedNr(newjge.getName()));
jobMeta.addJobEntry(newjge);
spoon.addUndoNew(jobMeta, new JobEntryCopy[] { newjge }, new int[] { jobMeta
.indexOfJobEntry(newjge) });
} else {
if(log.isDebug()) log.logDebug(toString(), "jge is not cloned!"); //$NON-NLS-1$
}
} else {
if(log.isDebug()) log.logDebug(toString(), jge.toString() + " is not drawn"); //$NON-NLS-1$
jge_changed = true;
}
PropsUI.setLocation(newjge, p.x, p.y);
newjge.setDrawn();
if (jge_changed) {
spoon.addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { newjge },
new int[] { jobMeta.indexOfJobEntry(newjge) });
}
redraw();
spoon.refreshTree();
log.logBasic("DropTargetEvent", "DROP " + newjge.toString() + "!, type="
+ JobEntryCopy.getTypeDesc(newjge.getEntry()));
} else {
log.logError(toString(), "Unknown job entry dropped onto the canvas.");
}
}
break;
default:
break;
}
} catch (Exception e) {
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorDroppingObject.Message"), Messages.getString("JobGraph.Dialog.ErrorDroppingObject.Title"), e);
}
}
public void dropAccept(DropTargetEvent event) {
drop_candidate = null;
}
});
addKeyListener(canvas);
// addKeyListener(filenameLabel);
// filenameLabel.addKeyListener(spoon.defKeys);
canvas.addKeyListener(spoon.defKeys);
setBackground(GUIResource.getInstance().getColorBackground());
setControlStates();
}
private void addToolBar() {
try {
toolbar = XulHelper.createToolbar(XUL_FILE_JOB_TOOLBAR, JobGraph.this, JobGraph.this, new XulMessages());
ToolBar toolBar = (ToolBar) toolbar.getNativeObject();
toolBar.pack();
// int h = toolBar.getBounds().height;
// Hack alert : more XUL limitations...
ToolItem sep = new ToolItem(toolBar, SWT.SEPARATOR);
zoomLabel = new Combo(toolBar, SWT.DROP_DOWN);
zoomLabel.setItems(TransPainter.magnificationDescriptions);
zoomLabel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
readMagnification();
}
});
zoomLabel.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.character == SWT.CR) {
readMagnification();
}
}
});
setZoomLabel();
zoomLabel.pack();
sep.setWidth(80);
sep.setControl(zoomLabel);
toolBar.pack();
// Add a few default key listeners
toolBar.addKeyListener(spoon.defKeys);
addToolBarListeners();
} catch (Throwable t) {
log.logError(toString(), Const.getStackTracker(t));
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"),
Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_JOB_TOOLBAR), new Exception(t));
}
}
private void setZoomLabel() {
zoomLabel.setText(Integer.toString(Math.round(magnification * 100)) + "%");
}
/**
* Allows for magnifying to any percentage entered by the user...
*/
private void readMagnification(){
String possibleText = zoomLabel.getText();
possibleText = possibleText.replace("%", "");
float possibleFloatMagnification;
try {
possibleFloatMagnification = Float.parseFloat(possibleText) / 100;
magnification = possibleFloatMagnification;
if (zoomLabel.getText().indexOf('%') < 0) {
zoomLabel.setText(zoomLabel.getText().concat("%"));
}
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("TransGraph.Dialog.InvalidZoomMeasurement.Message", zoomLabel.getText())); //$NON-NLS-1$
mb.setText(Messages.getString("TransGraph.Dialog.InvalidZoomMeasurement.Title")); //$NON-NLS-1$
mb.open();
}
redraw();
}
public void addToolBarListeners() {
try {
// first get the XML document
URL url = XulHelper.getAndValidate(XUL_FILE_JOB_TOOLBAR_PROPERTIES);
Properties props = new Properties();
props.load(url.openStream());
String ids[] = toolbar.getMenuItemIds();
for (int i = 0; i < ids.length; i++) {
String methodName = (String) props.get(ids[i]);
if (methodName != null) {
toolbar.addMenuListener(ids[i], this, methodName);
}
}
} catch (Throwable t) {
t.printStackTrace();
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"),
Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_JOB_TOOLBAR_PROPERTIES), new Exception(t));
}
}
private void addKeyListener(Control control) {
// Keyboard shortcuts...
control.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// F2 --> rename Job entry
if (e.keyCode == SWT.F2) {
renameJobEntry();
}
// Delete
if (e.keyCode == SWT.DEL) {
JobEntryCopy copies[] = jobMeta.getSelectedEntries();
if (copies != null && copies.length > 0) {
delSelected();
}
}
// CTRL-UP : allignTop();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0) {
alligntop();
}
// CTRL-DOWN : allignBottom();
if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0) {
allignbottom();
}
// CTRL-LEFT : allignleft();
if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0) {
allignleft();
}
// CTRL-RIGHT : allignRight();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0) {
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0) {
distributehorizontal();
}
// ALT-UP : distributeVertical();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0) {
distributevertical();
}
// ALT-HOME : snap to grid
if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0) {
snaptogrid(ConstUI.GRID_SIZE);
}
}
});
}
public void selectInRect(JobMeta jobMeta, Rectangle rect) {
int i;
for (i = 0; i < jobMeta.nrJobEntries(); i++) {
JobEntryCopy je = jobMeta.getJobEntry(i);
Point p = je.getLocation();
if (((p.x >= rect.x && p.x <= rect.x + rect.width) || (p.x >= rect.x + rect.width && p.x <= rect.x))
&& ((p.y >= rect.y && p.y <= rect.y + rect.height) || (p.y >= rect.y + rect.height && p.y <= rect.y)))
je.setSelected(true);
}
}
public void redraw() {
canvas.redraw();
setZoomLabel();
}
public boolean forceFocus() {
return canvas.forceFocus();
}
public boolean setFocus() {
return canvas.setFocus();
}
public void renameJobEntry() {
JobEntryCopy[] selection = jobMeta.getSelectedEntries();
if (selection != null && selection.length == 1) {
final JobEntryCopy jobEntryMeta = selection[0];
// What is the location of the step?
final String name = jobEntryMeta.getName();
Point stepLocation = jobEntryMeta.getLocation();
Point realStepLocation = real2screen(stepLocation.x, stepLocation.y);
// The location of the step name?
GC gc = new GC(shell.getDisplay());
gc.setFont(GUIResource.getInstance().getFontGraph());
Point namePosition = TransPainter.getNamePosition(gc, name, realStepLocation, iconsize);
int width = gc.textExtent(name).x + 30;
gc.dispose();
// at this very point, create a new text widget...
final Text text = new Text(this, SWT.SINGLE | SWT.BORDER);
text.setText(name);
FormData fdText = new FormData();
fdText.left = new FormAttachment(0, namePosition.x);
fdText.right = new FormAttachment(0, namePosition.x + width);
fdText.top = new FormAttachment(0, namePosition.y);
text.setLayoutData(fdText);
// Add a listener!
// Catch the keys pressed when editing a Text-field...
KeyListener lsKeyText = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// "ENTER": close the text editor and copy the data over
if (e.character == SWT.CR) {
String newName = text.getText();
text.dispose();
if (!name.equals(newName))
renameJobEntry(jobEntryMeta, newName);
}
if (e.keyCode == SWT.ESC) {
text.dispose();
}
}
};
text.addKeyListener(lsKeyText);
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
String newName = text.getText();
text.dispose();
if (!name.equals(newName))
renameJobEntry(jobEntryMeta, newName);
}
});
this.layout(true, true);
text.setFocus();
text.setSelection(0, name.length());
}
}
/**
* Method gets called, when the user wants to change a job entries name and he indeed entered
* a different name then the old one. Make sure that no other job entry matches this name
* and rename in case of uniqueness.
*
* @param jobEntry
* @param newName
*/
public void renameJobEntry(JobEntryCopy jobEntry, String newName) {
JobEntryCopy[] jobs = jobMeta.getAllJobGraphEntries(newName);
if (jobs != null && jobs.length > 0) {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryNameExists.Message", newName));
mb.setText(Messages.getString("Spoon.Dialog.JobEntryNameExists.Title"));
mb.open();
} else {
jobEntry.setName(newName);
jobEntry.setChanged();
spoon.refreshTree(); // to reflect the new name
spoon.refreshGraph();
}
}
public static void showOnlyStartOnceMessage(Shell shell) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("JobGraph.Dialog.OnlyUseStartOnce.Message"));
mb.setText(Messages.getString("JobGraph.Dialog.OnlyUseStartOnce.Title"));
mb.open();
}
public void delSelected() {
JobEntryCopy[] copies = jobMeta.getSelectedEntries();
int nrsels = copies.length;
if (nrsels == 0)
return;
// Load the list of steps
List<String> stepList = new ArrayList<String>();
for (int i = 0; i < copies.length; ++i) {
stepList.add(copies[i].toString());
}
// Display the delete confirmation message box
MessageBox mb = new DeleteMessageBox(shell, Messages.getString("Spoon.Dialog.DeletionConfirm.Message"), //$NON-NLS-1$
stepList);
int answer = mb.open();
if (answer == SWT.YES) {
// Perform the delete
for (int i = 0; i < copies.length; i++) {
spoon.deleteJobEntryCopies(jobMeta, copies[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
}
public void clearSettings() {
selected_icon = null;
selected_note = null;
selected_entries = null;
selrect = null;
hop_candidate = null;
last_hop_split = null;
last_button = 0;
iconoffset = null;
for (int i = 0; i < jobMeta.nrJobHops(); i++)
jobMeta.getJobHop(i).setSplit(false);
}
public Point screen2real(int x, int y) {
getOffset();
Point real;
if (offset != null) {
real = new Point(Math.round((x / magnification - offset.x)), Math.round((y / magnification - offset.y)));
} else {
real = new Point(x, y);
}
return real;
}
public Point real2screen(int x, int y) {
getOffset();
Point screen = new Point(x + offset.x, y + offset.y);
return screen;
}
public Point getRealPosition(Composite canvas, int x, int y) {
Point p = new Point(0, 0);
Composite follow = canvas;
while (follow != null) {
Point xy = new Point(follow.getLocation().x, follow.getLocation().y);
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
p.x = x - p.x - 8;
p.y = y - p.y - 48;
return screen2real(p.x, p.y);
}
// See if location (x,y) is on a line between two steps: the hop!
// return the HopInfo if so, otherwise: null
protected JobHopMeta findJobHop(int x, int y) {
int i;
JobHopMeta online = null;
for (i = 0; i < jobMeta.nrJobHops(); i++) {
JobHopMeta hi = jobMeta.getJobHop(i);
int line[] = getLine(hi.from_entry, hi.to_entry);
if (line != null && pointOnLine(x, y, line))
online = hi;
}
return online;
}
protected int[] getLine(JobEntryCopy fs, JobEntryCopy ts) {
if (fs == null || ts == null)
return null;
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
public void setJobEntry(JobEntryCopy jobEntry) {
this.jobEntry = jobEntry;
}
public JobEntryCopy getJobEntry() {
return jobEntry;
}
public void openTransformation() {
final JobEntryInterface entry = getJobEntry().getEntry();
openTransformation((JobEntryTrans) entry);
}
public void launchChef() {
final JobEntryInterface entry = getJobEntry().getEntry();
launchChef((JobEntryJob) entry);
}
public void newHopClick() {
selected_entries = null;
newHop();
}
public void editEntryClick() {
selected_entries = null;
editEntry(getJobEntry());
}
public void editEntryDescription() {
String title = Messages.getString("JobGraph.Dialog.EditDescription.Title"); //$NON-NLS-1$
String message = Messages.getString("JobGraph.Dialog.EditDescription.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, getJobEntry().getDescription());
String des = dd.open();
if (des != null)
jobEntry.setDescription(des);
}
/**
* Go from serial to parallel to serial execution
*/
public void editEntryParallel() {
getJobEntry().setLaunchingInParallel(!getJobEntry().isLaunchingInParallel());
if (getJobEntry().isLaunchingInParallel()) {
// Show a warning (optional)
if ("Y".equalsIgnoreCase(spoon.props.getCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, "Y"))) //$NON-NLS-1$ //$NON-NLS-2$
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages
.getString("JobGraph.ParallelJobEntriesWarning.DialogTitle"), //$NON-NLS-1$
null, Messages.getString("JobGraph.ParallelJobEntriesWarning.DialogMessage", Const.CR) + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.WARNING, new String[] { Messages.getString("JobGraph.ParallelJobEntriesWarning.Option1") }, //$NON-NLS-1$
0, Messages.getString("JobGraph.ParallelJobEntriesWarning.Option2"), //$NON-NLS-1$
"N".equalsIgnoreCase(spoon.props.getCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, "Y")) //$NON-NLS-1$ //$NON-NLS-2$
);
MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
md.open();
spoon.props.setCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, md.getToggleState() ? "N" : "Y"); //$NON-NLS-1$ //$NON-NLS-2$
spoon.props.saveProps();
}
}
redraw();
}
public void duplicateEntry() throws KettleException {
if (!canDup(jobEntry)) {
JobGraph.showOnlyStartOnceMessage(spoon.getShell());
}
spoon.delegates.jobs.dupeJobEntry(jobMeta, jobEntry);
}
public void copyEntry() {
JobEntryCopy[] entries = jobMeta.getSelectedEntries();
for (int i = 0; i < entries.length; i++) {
if (!canDup(entries[i]))
entries[i] = null;
}
spoon.delegates.jobs.copyJobEntries(jobMeta, entries);
}
private boolean canDup(JobEntryCopy entry) {
return !entry.isStart();
}
public void detatchEntry() {
detach(getJobEntry());
jobMeta.unselectAll();
}
public void hideEntry() {
getJobEntry().setDrawn(false);
// nr > 1: delete
if (jobEntry.getNr() > 0) {
int ind = jobMeta.indexOfJobEntry(jobEntry);
jobMeta.removeJobEntry(ind);
spoon.addUndoDelete(jobMeta, new JobEntryCopy[] { getJobEntry() }, new int[] { ind });
}
redraw();
}
public void deleteEntry() {
spoon.deleteJobEntryCopies(jobMeta, getJobEntry());
redraw();
}
protected synchronized void setMenu(int x, int y) {
currentMouseX = x;
currentMouseY = y;
final JobEntryCopy jobEntry = jobMeta.getJobEntryCopy(x, y, iconsize);
setJobEntry(jobEntry);
if (jobEntry != null) // We clicked on a Job Entry!
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get("job-graph-entry"); //$NON-NLS-1$
if (menu != null) {
int sels = jobMeta.nrSelected();
XulMenuChoice item = menu.getMenuItemById("job-graph-entry-newhop"); //$NON-NLS-1$
menu.addMenuListener("job-graph-entry-newhop", this, JobGraph.class, "newHopClick"); //$NON-NLS-1$ //$NON-NLS-2$
item.setEnabled(sels == 2);
item = menu.getMenuItemById("job-graph-entry-launch"); //$NON-NLS-1$
switch (jobEntry.getJobEntryType()) {
case TRANS: {
item.setEnabled(true);
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.LaunchSpoon"));
menu.addMenuListener("job-graph-entry-launch", this, "openTransformation"); //$NON-NLS-1$ //$NON-NLS-2$
break;
}
case JOB: {
item.setEnabled(true);
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.LaunchChef"));
menu.addMenuListener("job-graph-entry-launch", this, "launchChef"); //$NON-NLS-1$ //$NON-NLS-2$
}
break;
default: {
item.setEnabled(false);
}
break;
}
item = menu.getMenuItemById("job-graph-entry-align-snap"); //$NON-NLS-1$
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.AllignDistribute.SnapToGrid") + ConstUI.GRID_SIZE
+ ")\tALT-HOME");
XulMenu aMenu = menu.getMenuById("job-graph-entry-align"); //$NON-NLS-1$
if (aMenu != null) {
aMenu.setEnabled(sels > 1);
}
item = menu.getMenuItemById("job-graph-entry-detach"); //$NON-NLS-1$
if (item != null) {
item.setEnabled(jobMeta.isEntryUsedInHops(jobEntry));
}
item = menu.getMenuItemById("job-graph-entry-hide"); //$NON-NLS-1$
if (item != null) {
item.setEnabled(jobEntry.isDrawn() && !jobMeta.isEntryUsedInHops(jobEntry));
}
item = menu.getMenuItemById("job-graph-entry-delete"); //$NON-NLS-1$
if (item != null) {
item.setEnabled(jobEntry.isDrawn());
}
item = menu.getMenuItemById("job-graph-entry-parallel"); // $NON-NLS-1$
if (item != null) {
item.setChecked(jobEntry.isLaunchingInParallel());
}
menu.addMenuListener("job-graph-entry-align-left", this, "allignleft"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-right", this, "allignright"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-top", this, "alligntop"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-bottom", this, "allignbottom"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-horz", this, "distributehorizontal"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-vert", this, "distributevertical"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-align-snap", this, "snaptogrid"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-edit", this, "editEntryClick"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-edit-description", this, "editEntryDescription"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-parallel", this, "editEntryParallel"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-duplicate", this, "duplicateEntry"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-copy", this, "copyEntry"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-detach", this, "detatchEntry"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-hide", this, "hideEntry"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-entry-delete", this, "deleteEntry"); //$NON-NLS-1$ //$NON-NLS-2$
ConstUI.displayMenu((Menu)menu.getNativeObject(), canvas);
}
} else // Clear the menu
{
final JobHopMeta hi = findJobHop(x, y);
setCurrentHop(hi);
if (hi != null) // We clicked on a HOP!
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get("job-graph-hop"); //$NON-NLS-1$
if (menu != null) {
XulMenuChoice miPopEvalUncond = menu.getMenuItemById("job-graph-hop-evaluation-uncond"); //$NON-NLS-1$
XulMenuChoice miPopEvalTrue = menu.getMenuItemById("job-graph-hop-evaluation-true"); //$NON-NLS-1$
XulMenuChoice miPopEvalFalse = menu.getMenuItemById("job-graph-hop-evaluation-false"); //$NON-NLS-1$
XulMenuChoice miDisHop = menu.getMenuItemById("job-graph-hop-enabled"); //$NON-NLS-1$
menu.addMenuListener("job-graph-hop-evaluation-uncond", this, "setHopConditional"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-hop-evaluation-true", this, "setHopConditional"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-hop-evaluation-false", this, "setHopConditional"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-hop-flip", this, "flipHop"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-hop-enabled", this, "disableHop"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-hop-delete", this, "deleteHop"); //$NON-NLS-1$ //$NON-NLS-2$
if (hi.isUnconditional()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setChecked(true);
if (miPopEvalTrue != null)
miPopEvalTrue.setChecked(false);
if (miPopEvalFalse != null)
miPopEvalFalse.setChecked(false);
} else {
if (hi.getEvaluation()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setChecked(false);
if (miPopEvalTrue != null)
miPopEvalTrue.setChecked(true);
if (miPopEvalFalse != null)
miPopEvalFalse.setChecked(false);
} else {
if (miPopEvalUncond != null)
miPopEvalUncond.setChecked(false);
if (miPopEvalTrue != null)
miPopEvalTrue.setChecked(false);
if (miPopEvalFalse != null)
miPopEvalFalse.setChecked(true);
}
}
if (!hi.from_entry.evaluates()) {
if (miPopEvalTrue != null)
miPopEvalTrue.setEnabled(false);
if (miPopEvalFalse != null)
miPopEvalFalse.setEnabled(false);
}
if (!hi.from_entry.isUnconditional()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setEnabled(false);
}
if (miDisHop != null) {
if (hi.isEnabled())
miDisHop.setText(Messages.getString("JobGraph.PopupMenu.Hop.Disable")); //$NON-NLS-1$
else
miDisHop.setText(Messages.getString("JobGraph.PopupMenu.Hop.Enable")); //$NON-NLS-1$
}
ConstUI.displayMenu((Menu)menu.getNativeObject(), canvas);
}
} else {
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = jobMeta.getNote(x, y);
setCurrentNote(ni);
if (ni != null) {
XulPopupMenu menu = (XulPopupMenu) menuMap.get("job-graph-note"); //$NON-NLS-1$
if (menu != null) {
menu.addMenuListener("job-graph-note-edit", this, "editNote"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-note-delete", this, "deleteNote"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-note-raise", this, "raiseNote"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-note-lower", this, "lowerNote"); //$NON-NLS-1$ //$NON-NLS-2$
ConstUI.displayMenu((Menu)menu.getNativeObject(), canvas);
}
} else {
XulPopupMenu menu = (XulPopupMenu) menuMap.get("job-graph-background"); //$NON-NLS-1$
if (menu != null) {
menu.addMenuListener("job-graph-note-new", this, "newNote"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-note-paste", this, "pasteNote"); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener("job-graph-background-settings", this, "editJobProperties"); //$NON-NLS-1$ //$NON-NLS-2$
final String clipcontent = spoon.fromClipboard();
XulMenuChoice item = menu.getMenuItemById("job-graph-note-paste"); //$NON-NLS-1$
if (item != null) {
item.setEnabled(clipcontent != null);
}
ConstUI.displayMenu((Menu)menu.getNativeObject(), canvas);
}
}
}
}
}
public void editJobProperties() {
editProperties(jobMeta, spoon, spoon.getRepository(), true);
}
public void pasteNote() {
final String clipcontent = spoon.fromClipboard();
Point loc = new Point(currentMouseX, currentMouseY);
spoon.pasteXML(jobMeta, clipcontent, loc);
}
public void newNote() {
selrect = null;
String title = Messages.getString("JobGraph.Dialog.EditNote.Title");
String message = Messages.getString("JobGraph.Dialog.EditNote.Message");
EnterTextDialog dd = new EnterTextDialog(shell, title, message, "");
String n = dd.open();
if (n != null) {
NotePadMeta npi = new NotePadMeta(n, lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE);
jobMeta.addNote(npi);
spoon.addUndoNew(jobMeta, new NotePadMeta[] { npi }, new int[] { jobMeta.indexOfNote(npi) });
redraw();
}
}
public void setCurrentNote(NotePadMeta ni) {
this.ni = ni;
}
public NotePadMeta getCurrentNote() {
return ni;
}
public void editNote() {
selrect = null;
editNote(getCurrentNote());
}
public void deleteNote() {
selrect = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.removeNote(idx);
spoon.addUndoDelete(jobMeta, new NotePadMeta[] { getCurrentNote() }, new int[] { idx });
}
redraw();
}
public void raiseNote() {
selrect = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.raiseNote(idx);
//spoon.addUndoRaise(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void lowerNote() {
selrect = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.lowerNote(idx);
//spoon.addUndoLower(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void flipHop() {
selrect = null;
JobEntryCopy dummy = currentHop.from_entry;
currentHop.from_entry = currentHop.to_entry;
currentHop.to_entry = dummy;
if (jobMeta.hasLoop(currentHop.from_entry)) {
spoon.refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("JobGraph.Dialog.HopFlipCausesLoop.Message"));
mb.setText(Messages.getString("JobGraph.Dialog.HopFlipCausesLoop.Title"));
mb.open();
dummy = currentHop.from_entry;
currentHop.from_entry = currentHop.to_entry;
currentHop.to_entry = dummy;
spoon.refreshGraph();
} else {
currentHop.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void disableHop() {
selrect = null;
currentHop.setEnabled(!currentHop.isEnabled());
spoon.refreshGraph();
spoon.refreshTree();
}
public void deleteHop() {
selrect = null;
int idx = jobMeta.indexOfJobHop(currentHop);
jobMeta.removeJobHop(idx);
spoon.refreshTree();
spoon.refreshGraph();
}
public void setHopConditional(String id) {
if ("job-graph-hop-evaluation-uncond".equals(id)) { //$NON-NLS-1$
currentHop.setUnconditional();
spoon.refreshGraph();
} else if ("job-graph-hop-evaluation-true".equals(id)) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(true);
spoon.refreshGraph();
} else if ("job-graph-hop-evaluation-false".equals(id)) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(false);
spoon.refreshGraph();
}
}
protected void setCurrentHop(JobHopMeta hop) {
currentHop = hop;
}
protected JobHopMeta getCurrentHop() {
return currentHop;
}
protected void setToolTip(int x, int y, int screenX, int screenY) {
if (!spoon.getProperties().showToolTips())
return;
canvas.setToolTipText("-"); // Some stupid bug in GTK+ causes a phantom tool tip to pop up, even if the tip is null
canvas.setToolTipText(null);
String newTip = null;
final JobEntryCopy je = jobMeta.getJobEntryCopy(x, y, iconsize);
if (je != null && je.isDrawn()) // We hover above a Step!
{
// Set the tooltip!
String desc = je.getDescription();
if (desc != null) {
int le = desc.length() >= 200 ? 200 : desc.length();
newTip = desc.substring(0, le);
} else {
newTip = je.toString();
}
} else {
offset = getOffset();
JobHopMeta hi = findJobHop(x + offset.x, y + offset.x);
if (hi != null) {
newTip = hi.toString();
} else {
newTip = null;
}
}
if (newTip == null || !newTip.equalsIgnoreCase(getToolTipText())) {
canvas.setToolTipText(newTip);
}
}
public void launchStuff(JobEntryCopy jobentry) {
if (jobentry.getJobEntryType() == JobEntryType.JOB) {
final JobEntryJob entry = (JobEntryJob) jobentry.getEntry();
if ((entry != null && entry.getFilename() != null && spoon.rep == null)
|| (entry != null && entry.getName() != null && spoon.rep != null)) {
launchChef(entry);
}
} else if (jobentry.getJobEntryType() == JobEntryType.TRANS) {
final JobEntryTrans entry = (JobEntryTrans) jobentry.getEntry();
if ((entry != null && entry.getFilename() != null && spoon.rep == null)
|| (entry != null && entry.getName() != null && spoon.rep != null)) {
openTransformation(entry);
}
}
}
protected void openTransformation(JobEntryTrans entry) {
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename());
String exactTransname = jobMeta.environmentSubstitute(entry.getTransname());
// check, whether a tab of this name is already opened
TabItem tab = spoon.delegates.tabs.findTabItem(exactFilename, TabMapEntry.OBJECT_TYPE_TRANSFORMATION_GRAPH);
if (tab == null) {
tab = spoon.delegates.tabs.findTabItem(Const.filenameOnly(exactFilename),
TabMapEntry.OBJECT_TYPE_TRANSFORMATION_GRAPH);
}
if (tab != null) {
spoon.tabfolder.setSelected(tab);
return;
}
// Load from repository?
if (TransMeta.isRepReference(exactFilename, exactTransname)) {
try {
// New transformation?
long id = spoon.rep.getTransformationID(exactTransname, spoon.rep.getDirectoryTree().findDirectory(entry.getDirectory()).getID());
TransMeta newTrans;
if (id < 0) // New
{
newTrans = new TransMeta(null, exactTransname, entry.arguments);
} else {
newTrans = new TransMeta(spoon.rep, exactTransname, spoon.rep.getDirectoryTree().findDirectory(entry.getDirectory()));
}
copyInternalJobVariables(jobMeta, newTrans);
spoon.addTransGraph(newTrans);
newTrans.clearChanged();
spoon.open();
} catch (Throwable e) {
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Title"),
Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Message"), (Exception) e);
}
} else {
try {
// only try to load if the file exists...
if (Const.isEmpty(exactFilename)) {
throw new Exception(Messages.getString("JobGraph.Exception.NoFilenameSpecified"));
}
TransMeta launchTransMeta = null;
if (KettleVFS.fileExists(exactFilename)) {
launchTransMeta = new TransMeta(exactFilename);
} else {
launchTransMeta = new TransMeta();
}
launchTransMeta.clearChanged();
launchTransMeta.setFilename(exactFilename);
copyInternalJobVariables(jobMeta, launchTransMeta);
spoon.addTransGraph(launchTransMeta);
spoon.open();
} catch (Throwable e) {
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Title"),
Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Message"), (Exception) e);
}
}
spoon.applyVariables();
}
public static void copyInternalJobVariables(JobMeta sourceJobMeta, TransMeta targetTransMeta) {
// Also set some internal JOB variables...
String[] internalVariables = Const.INTERNAL_JOB_VARIABLES;
for (String variableName : internalVariables) {
targetTransMeta.setVariable(variableName, sourceJobMeta.getVariable(variableName));
}
}
public void launchChef(JobEntryJob entry) {
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename());
String exactJobname = jobMeta.environmentSubstitute(entry.getJobName());
// Load from repository?
if (Const.isEmpty(exactFilename) && !Const.isEmpty(exactJobname)) {
try {
JobMeta newJobMeta = new JobMeta(log, spoon.rep, exactJobname, spoon.rep.getDirectoryTree().findDirectory(entry.getDirectory()));
newJobMeta.clearChanged();
spoon.delegates.jobs.addJobGraph(newJobMeta);
} catch (Throwable e) {
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Title"),
Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Message"), e);
}
} else {
try {
if (Const.isEmpty(exactFilename)) {
throw new Exception(Messages.getString("JobGraph.Exception.NoFilenameSpecified"));
}
JobMeta newJobMeta;
if (KettleVFS.fileExists(exactFilename)) {
newJobMeta = new JobMeta(log, exactFilename, spoon.rep, spoon);
} else {
newJobMeta = new JobMeta(log);
}
newJobMeta.setFilename(exactFilename);
newJobMeta.clearChanged();
spoon.delegates.jobs.addJobGraph(newJobMeta);
} catch (Throwable e) {
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Title"),
Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Message"), e);
}
}
spoon.applyVariables();
}
public void paintControl(PaintEvent e) {
Point area = getArea();
if (area.x == 0 || area.y == 0)
return; // nothing to do!
Display disp = shell.getDisplay();
if (disp.isDisposed())
return; // Nothing to do!
Image img = new Image(disp, area.x, area.y);
GC gc = new GC(img);
drawJob(disp, gc, PropsUI.getInstance().isBrandingActive());
e.gc.drawImage(img, 0, 0);
gc.dispose();
img.dispose();
// spoon.setShellText();
}
public void drawJob(Device device, GC gc, boolean branded) {
if (spoon.props.isAntiAliasingEnabled())
gc.setAntialias(SWT.ON);
shadowsize = spoon.props.getShadowSize();
gridSize = spoon.props.getCanvasGridSize();
Point area = getArea();
Point max = jobMeta.getMaximum();
Point thumb = getThumb(area, max);
offset = getOffset(thumb, area);
gc.setBackground(GUIResource.getInstance().getColorBackground());
hori.setThumb(thumb.x);
vert.setThumb(thumb.y);
if (branded) {
Image gradient = GUIResource.getInstance().getImageBanner();
gc.drawImage(gradient, 0, 0);
Image logo = GUIResource.getInstance().getImageKettleLogo();
org.eclipse.swt.graphics.Rectangle logoBounds = logo.getBounds();
gc.drawImage(logo, 20, area.y - logoBounds.height);
}
// If there is a shadow, we draw the transformation first with an alpha setting
if (shadowsize > 0) {
Transform transform = new Transform(device);
transform.scale(magnification, magnification);
transform.translate(translationX + shadowsize * magnification, translationY + shadowsize * magnification);
gc.setAlpha(20);
gc.setTransform(transform);
shadow = true;
drawJobElements(gc);
}
// Draw the transformation onto the image
Transform transform = new Transform(device);
transform.scale(magnification, magnification);
transform.translate(translationX, translationY);
gc.setAlpha(255);
gc.setTransform(transform);
shadow = false;
drawJobElements(gc);
}
private void drawJobElements(GC gc) {
if (!shadow && gridSize > 1) {
drawGrid(gc);
}
// First draw the notes...
gc.setFont(GUIResource.getInstance().getFontNote());
for (int i = 0; i < jobMeta.nrNotes(); i++) {
NotePadMeta ni = jobMeta.getNote(i);
drawNote(gc, ni);
}
gc.setFont(GUIResource.getInstance().getFontGraph());
// ... and then the rest on top of it...
for (int i = 0; i < jobMeta.nrJobHops(); i++) {
JobHopMeta hi = jobMeta.getJobHop(i);
drawJobHop(gc, hi, false);
}
if (hop_candidate != null) {
drawJobHop(gc, hop_candidate, true);
}
for (int j = 0; j < jobMeta.nrJobEntries(); j++) {
JobEntryCopy je = jobMeta.getJobEntry(j);
drawJobEntryCopy(gc, je);
}
if (drop_candidate != null) {
gc.setLineStyle(SWT.LINE_SOLID);
gc.setForeground(GUIResource.getInstance().getColorBlack());
Point screen = real2screen(drop_candidate.x, drop_candidate.y);
gc.drawRectangle(screen.x, screen.y, iconsize, iconsize);
}
if (!shadow) {
drawRect(gc, selrect);
}
}
private void drawGrid(GC gc) {
int gridSize = spoon.props.getCanvasGridSize();
Rectangle bounds = gc.getDevice().getBounds();
for (int x = 0; x < bounds.width; x += gridSize) {
for (int y = 0; y < bounds.height; y += gridSize) {
gc.drawPoint(x + (offset.x % gridSize), y + (offset.y % gridSize));
}
}
}
protected void drawJobHop(GC gc, JobHopMeta hop, boolean candidate) {
if (hop == null || hop.from_entry == null || hop.to_entry == null)
return;
if (!hop.from_entry.isDrawn() || !hop.to_entry.isDrawn())
return;
drawLine(gc, hop, candidate);
}
public Image getIcon(JobEntryCopy je) {
Image im = null;
if (je == null)
return null;
switch (je.getJobEntryType()) {
case SPECIAL:
if (je.isStart())
im = GUIResource.getInstance().getImageStart();
if (je.isDummy())
im = GUIResource.getInstance().getImageDummy();
break;
default:
String configId = je.getEntry().getConfigId();
if (configId != null) {
im = (Image) GUIResource.getInstance().getImagesJobentries().get(configId);
}
}
return im;
}
protected void drawJobEntryCopy(GC gc, JobEntryCopy je) {
if (!je.isDrawn())
return;
Point pt = je.getLocation();
int x, y;
if (pt != null) {
x = pt.x;
y = pt.y;
} else {
x = 50;
y = 50;
}
String name = je.getName();
if (je.isSelected())
gc.setLineWidth(3);
else
gc.setLineWidth(1);
Image im = getIcon(je);
if (im != null) // Draw the icon!
{
Rectangle bounds = new Rectangle(im.getBounds().x, im.getBounds().y, im.getBounds().width, im.getBounds().height);
gc.drawImage(im, 0, 0, bounds.width, bounds.height, offset.x + x, offset.y + y, iconsize, iconsize);
}
gc.setBackground(GUIResource.getInstance().getColorWhite());
gc.drawRectangle(offset.x + x - 1, offset.y + y - 1, iconsize + 1, iconsize + 1);
//gc.setXORMode(true);
Point textsize = new Point(gc.textExtent("" + name).x, gc.textExtent("" + name).y);
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setLineWidth(1);
int xpos = offset.x + x + (iconsize / 2) - (textsize.x / 2);
int ypos = offset.y + y + iconsize + 5;
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(name, xpos, ypos, true);
}
protected void drawNote(GC gc, NotePadMeta ni) {
int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT;
org.eclipse.swt.graphics.Point ext = gc.textExtent(ni.getNote(), flags);
Point p = new Point(ext.x, ext.y);
Point loc = ni.getLocation();
Point note = real2screen(loc.x, loc.y);
int margin = Const.NOTE_MARGIN;
p.x += 2 * margin;
p.y += 2 * margin;
int width = ni.width;
int height = ni.height;
if (p.x > width)
width = p.x;
if (p.y > height)
height = p.y;
int noteshape[] = new int[] { note.x, note.y, // Top left
note.x + width + 2 * margin, note.y, // Top right
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x + width, note.y + height, // bottom right 3
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x, note.y + height + 2 * margin // bottom left
};
gc.setForeground(GUIResource.getInstance().getColorDarkGray());
gc.setBackground(GUIResource.getInstance().getColorYellow());
gc.fillPolygon(noteshape);
gc.drawPolygon(noteshape);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(ni.getNote(), note.x + margin, note.y + margin, flags);
ni.width = width; // Save for the "mouse" later on...
ni.height = height;
}
protected void drawLine(GC gc, JobHopMeta hop, boolean is_candidate) {
int line[] = getLine(hop.from_entry, hop.to_entry);
gc.setLineWidth(linewidth);
Color col;
if (hop.from_entry.isLaunchingInParallel()) {
gc.setLineAttributes(new LineAttributes((float) linewidth, SWT.CAP_FLAT, SWT.JOIN_MITER, SWT.LINE_CUSTOM,
new float[] { 5, 3, }, 0, 10));
} else {
gc.setLineStyle(SWT.LINE_SOLID);
}
if (is_candidate) {
col = GUIResource.getInstance().getColorBlue();
} else if (hop.isEnabled()) {
if (hop.isUnconditional()) {
col = GUIResource.getInstance().getColorBlack();
} else {
if (hop.getEvaluation()) {
col = GUIResource.getInstance().getColorGreen();
} else {
col = GUIResource.getInstance().getColorRed();
}
}
} else {
col = GUIResource.getInstance().getColorDarkGray();
}
gc.setForeground(col);
if (hop.isSplit())
gc.setLineWidth(linewidth + 2);
drawArrow(gc, line);
if (hop.isSplit())
gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setLineStyle(SWT.LINE_SOLID);
}
protected Point getArea() {
org.eclipse.swt.graphics.Rectangle rect = canvas.getClientArea();
Point area = new Point(rect.width, rect.height);
return area;
}
private Point magnifyPoint(Point p) {
return new Point(Math.round(p.x * magnification), Math.round(p.y * magnification));
}
private Point getThumb(Point area, Point transMax) {
Point resizedMax = magnifyPoint(transMax);
Point thumb = new Point(0, 0);
if (resizedMax.x <= area.x)
thumb.x = 100;
else
thumb.x = 100 * area.x / resizedMax.x;
if (resizedMax.y <= area.y)
thumb.y = 100;
else
thumb.y = 100 * area.y / resizedMax.y;
return thumb;
}
protected Point getOffset() {
Point area = getArea();
Point max = jobMeta.getMaximum();
Point thumb = getThumb(area, max);
return getOffset(thumb, area);
}
protected Point getOffset(Point thumb, Point area) {
Point p = new Point(0, 0);
Point sel = new Point(hori.getSelection(), vert.getSelection());
if (thumb.x == 0 || thumb.y == 0)
return p;
p.x = -sel.x * area.x / thumb.x;
p.y = -sel.y * area.y / thumb.y;
return p;
}
public int sign(int n) {
return n < 0 ? -1 : (n > 0 ? 1 : 1);
}
protected void newHop() {
JobEntryCopy fr = jobMeta.getSelected(0);
JobEntryCopy to = jobMeta.getSelected(1);
spoon.newJobHop(jobMeta, fr, to);
}
protected void editEntry(JobEntryCopy je) {
spoon.editJobEntry(jobMeta, je);
}
protected void editNote(NotePadMeta ni) {
NotePadMeta before = (NotePadMeta) ni.clone();
String title = Messages.getString("JobGraph.Dialog.EditNote.Title");
String message = Messages.getString("JobGraph.Dialog.EditNote.Message");
EnterTextDialog dd = new EnterTextDialog(shell, title, message, ni.getNote());
String n = dd.open();
if (n != null) {
spoon.addUndoChange(jobMeta, new NotePadMeta[] { before }, new NotePadMeta[] { ni }, new int[] { jobMeta
.indexOfNote(ni) });
ni.setChanged();
ni.setNote(n);
ni.width = ConstUI.NOTE_MIN_SIZE;
ni.height = ConstUI.NOTE_MIN_SIZE;
spoon.refreshGraph();
}
}
protected void drawArrow(GC gc, int line[]) {
int mx, my;
int x1 = line[0] + offset.x;
int y1 = line[1] + offset.y;
int x2 = line[2] + offset.x;
int y2 = line[3] + offset.y;
int x3;
int y3;
int x4;
int y4;
int a, b, dist;
double factor;
double angle;
//gc.setLineWidth(1);
//WuLine(gc, black, x1, y1, x2, y2);
gc.drawLine(x1, y1, x2, y2);
// What's the distance between the 2 points?
a = Math.abs(x2 - x1);
b = Math.abs(y2 - y1);
dist = (int) Math.sqrt(a * a + b * b);
// determine factor (position of arrow to left side or right side 0-->100%)
if (dist >= 2 * iconsize)
factor = 1.5;
else
factor = 1.2;
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2);
my = (int) (y1 + factor * (y2 - y1) / 2);
// calculate points for arrowhead
angle = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
x3 = (int) (mx + Math.cos(angle - theta) * size);
y3 = (int) (my + Math.sin(angle - theta) * size);
x4 = (int) (mx + Math.cos(angle + theta) * size);
y4 = (int) (my + Math.sin(angle + theta) * size);
// draw arrowhead
//gc.drawLine(mx, my, x3, y3);
//gc.drawLine(mx, my, x4, y4);
//gc.drawLine( x3, y3, x4, y4 );
Color fore = gc.getForeground();
Color back = gc.getBackground();
gc.setBackground(fore);
gc.fillPolygon(new int[] { mx, my, x3, y3, x4, y4 });
gc.setBackground(back);
}
protected boolean pointOnLine(int x, int y, int line[]) {
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for (dx = -pm; dx <= pm && !retval; dx++) {
for (dy = -pm; dy <= pm && !retval; dy++) {
retval = pointOnThinLine(x + dx, y + dy, line);
}
}
return retval;
}
protected boolean pointOnThinLine(int x, int y, int line[]) {
int x1 = line[0];
int y1 = line[1];
int x2 = line[2];
int y2 = line[3];
// Not in the square formed by these 2 points: ignore!
if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))))
return false;
double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
double angle_point = Math.atan2(y - y1, x - x1) + Math.PI;
// Same angle, or close enough?
if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01)
return true;
return false;
}
protected SnapAllignDistribute createSnapAllignDistribute() {
List<GUIPositionInterface> elements = jobMeta.getSelectedDrawnJobEntryList();
int[] indices = jobMeta.getEntryIndexes(elements.toArray(new JobEntryCopy[elements.size()]));
return new SnapAllignDistribute(jobMeta, elements, indices, spoon, this);
}
public void snaptogrid() {
snaptogrid(ConstUI.GRID_SIZE);
}
protected void snaptogrid(int size) {
createSnapAllignDistribute().snaptogrid(size);
}
public void allignleft() {
createSnapAllignDistribute().allignleft();
}
public void allignright() {
createSnapAllignDistribute().allignright();
}
public void alligntop() {
createSnapAllignDistribute().alligntop();
}
public void allignbottom() {
createSnapAllignDistribute().allignbottom();
}
public void distributehorizontal() {
createSnapAllignDistribute().distributehorizontal();
}
public void distributevertical() {
createSnapAllignDistribute().distributevertical();
}
public void zoomIn() {
/* if (magnificationIndex+1<TransPainter.magnifications.length) {
magnification = TransPainter.magnifications[++magnificationIndex];
}
*/
magnification += .1f;
redraw();
}
public void zoomOut() {
/* if (magnificationIndex>0) {
magnification = TransPainter.magnifications[--magnificationIndex];
}
*/
magnification -= .1f;
redraw();
}
public void zoom100Percent() {
//magnificationIndex=TransPainter.MAGNIFICATION_100_PERCENT_INDEX;
//magnification = TransPainter.magnifications[magnificationIndex];
magnification = 1.0f;
redraw();
}
protected void drawRect(GC gc, Rectangle rect) {
if (rect == null)
return;
gc.setLineStyle(SWT.LINE_DASHDOT);
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorDarkGray());
gc.drawRectangle(rect.x + offset.x, rect.y + offset.y, rect.width, rect.height);
gc.setLineStyle(SWT.LINE_SOLID);
}
protected void detach(JobEntryCopy je) {
JobHopMeta hfrom = jobMeta.findJobHopTo(je);
JobHopMeta hto = jobMeta.findJobHopFrom(je);
if (hfrom != null && hto != null) {
if (jobMeta.findJobHop(hfrom.from_entry, hto.to_entry) == null) {
JobHopMeta hnew = new JobHopMeta(hfrom.from_entry, hto.to_entry);
jobMeta.addJobHop(hnew);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { (JobHopMeta) hnew.clone() }, new int[] { jobMeta
.indexOfJobHop(hnew) });
}
}
if (hfrom != null) {
int fromidx = jobMeta.indexOfJobHop(hfrom);
if (fromidx >= 0) {
jobMeta.removeJobHop(fromidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { hfrom }, new int[] { fromidx });
}
}
if (hto != null) {
int toidx = jobMeta.indexOfJobHop(hto);
if (toidx >= 0) {
jobMeta.removeJobHop(toidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { hto }, new int[] { toidx });
}
}
spoon.refreshTree();
redraw();
}
public void newProps() {
iconsize = spoon.props.getIconSize();
linewidth = spoon.props.getLineWidth();
}
public String toString() {
return Spoon.APP_NAME;
}
public EngineMetaInterface getMeta() {
return jobMeta;
}
/**
* @param jobMeta the jobMeta to set
*/
public void setJobMeta(JobMeta jobMeta) {
this.jobMeta = jobMeta;
}
public boolean applyChanges() {
return spoon.saveToFile(jobMeta);
}
public boolean canBeClosed() {
return !jobMeta.hasChanged();
}
public JobMeta getManagedObject() {
return jobMeta;
}
public boolean hasContentChanged() {
return jobMeta.hasChanged();
}
public int showChangedWarning() {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.FileChangedSaveFirst.Message", spoon.delegates.tabs
.makeJobGraphTabName(jobMeta)));//"This model has changed. Do you want to save it?"
mb.setText(Messages.getString("Spoon.Dialog.FileChangedSaveFirst.Title"));
return mb.open();
}
public static int showChangedWarning(Shell shell, String name) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("JobGraph.Dialog.PromptSave.Message", name));
mb.setText(Messages.getString("JobGraph.Dialog.PromptSave.Title"));
return mb.open();
}
public static boolean editProperties(JobMeta jobMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange) {
if (jobMeta == null)
return false;
JobDialog jd = new JobDialog(spoon.getShell(), SWT.NONE, jobMeta, rep);
jd.setDirectoryChangeAllowed(allowDirectoryChange);
JobMeta ji = jd.open();
// In this case, load shared objects
if (jd.isSharedObjectsFileChanged()) {
try {
SharedObjects sharedObjects = jobMeta.readSharedObjects(rep);
spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects);
} catch (Exception e) {
new ErrorDialog(spoon.getShell(), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"),
Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.delegates.tabs
.makeJobGraphTabName(jobMeta)), e);
}
}
if (jd.isSharedObjectsFileChanged() || ji != null) {
spoon.refreshTree();
spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway
}
spoon.setShellText();
return ji != null;
}
/**
* @return the lastMove
*/
public Point getLastMove() {
return lastMove;
}
/**
* @param lastMove the lastMove to set
*/
public void setLastMove(Point lastMove) {
this.lastMove = lastMove;
}
/**
* Add an extra view to the main composite SashForm
*/
public void addExtraView() {
extraViewComposite = new Composite(sashForm, SWT.NONE);
FormLayout extraCompositeFormLayout = new FormLayout();
extraCompositeFormLayout.marginWidth = 2;
extraCompositeFormLayout.marginHeight = 2;
extraViewComposite.setLayout(extraCompositeFormLayout);
// Put a close and max button to the upper right corner...
closeButton = new Label(extraViewComposite, SWT.NONE);
closeButton.setImage(GUIResource.getInstance().getImageClosePanel());
closeButton.setToolTipText(Messages.getString("JobGraph.ExecutionResultsPanel.CloseButton.Tooltip"));
FormData fdClose = new FormData();
fdClose.right = new FormAttachment(100, 0);
fdClose.top = new FormAttachment(0, 0);
closeButton.setLayoutData(fdClose);
closeButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
disposeExtraView();
}
});
minMaxButton = new Label(extraViewComposite, SWT.NONE);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(Messages.getString("JobGraph.ExecutionResultsPanel.MaxButton.Tooltip"));
FormData fdMinMax = new FormData();
fdMinMax.right = new FormAttachment(closeButton, -Const.MARGIN);
fdMinMax.top = new FormAttachment(0, 0);
minMaxButton.setLayoutData(fdMinMax);
minMaxButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
minMaxExtraView();
}
});
// Add a label at the top: Results
Label wResultsLabel = new Label(extraViewComposite, SWT.LEFT);
wResultsLabel.setFont(GUIResource.getInstance().getFontMediumBold());
wResultsLabel.setBackground(GUIResource.getInstance().getColorLightGray());
wResultsLabel.setText(Messages.getString("JobLog.ResultsPanel.NameLabel"));
FormData fdResultsLabel = new FormData();
fdResultsLabel.left = new FormAttachment(0, 0);
fdResultsLabel.right = new FormAttachment(100, 0);
fdResultsLabel.top = new FormAttachment(0, 0);
wResultsLabel.setLayoutData(fdResultsLabel);
// Add a tab folder ...
extraViewTabFolder = new CTabFolder(extraViewComposite, SWT.MULTI);
spoon.props.setLook(extraViewTabFolder, Props.WIDGET_STYLE_TAB);
extraViewTabFolder.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent arg0) {
if (sashForm.getMaximizedControl() == null) {
sashForm.setMaximizedControl(extraViewComposite);
} else {
sashForm.setMaximizedControl(null);
}
}
});
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(wResultsLabel, Const.MARGIN);
fdTabFolder.bottom = new FormAttachment(100, 0);
extraViewTabFolder.setLayoutData(fdTabFolder);
sashForm.setWeights(new int[] { 60, 40, });
}
/**
* If the extra tab view at the bottom is empty, we close it.
*/
public void checkEmptyExtraView() {
if (extraViewTabFolder.getItemCount() == 0) {
disposeExtraView();
}
}
private void disposeExtraView() {
extraViewComposite.dispose();
sashForm.layout();
sashForm.setWeights(new int[] { 100, });
XulToolbarButton button = toolbar.getButtonById("job-show-results");
button.setImage(GUIResource.getInstance().getImageShowResults());
button.setHint(Messages.getString("Spoon.Tooltip.ShowExecutionResults"));
}
private void minMaxExtraView() {
// What is the state?
boolean maximized = sashForm.getMaximizedControl() != null;
if (maximized) {
// Minimize
sashForm.setMaximizedControl(null);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(Messages.getString("JobGraph.ExecutionResultsPanel.MaxButton.Tooltip"));
} else {
// Maximize
sashForm.setMaximizedControl(extraViewComposite);
minMaxButton.setImage(GUIResource.getInstance().getImageMinimizePanel());
minMaxButton.setToolTipText(Messages.getString("JobGraph.ExecutionResultsPanel.MinButton.Tooltip"));
}
}
public void showExecutionResults() {
if (extraViewComposite == null || extraViewComposite.isDisposed()) {
addAllTabs();
} else {
disposeExtraView();
}
}
public void addAllTabs() {
jobHistoryDelegate.addJobHistory();
jobLogDelegate.addJobLog();
jobGridDelegate.addJobGrid();
extraViewTabFolder.setSelection(jobGridDelegate.getJobGridTab()); // TODO: remember last selected?
XulToolbarButton button = toolbar.getButtonById("job-show-results");
button.setImage(GUIResource.getInstance().getImageHideResults());
button.setHint(Messages.getString("Spoon.Tooltip.HideExecutionResults"));
}
public void newFileDropDown() {
spoon.newFileDropDown(toolbar);
}
public void openFile() {
spoon.openFile();
}
public void saveFile() {
spoon.saveFile();
}
public void saveFileAs() {
spoon.saveFileAs();
}
public void saveXMLFileToVfs() {
spoon.saveXMLFileToVfs();
}
public void printFile() {
spoon.printFile();
}
public void runJob() {
spoon.runFile();
}
public void getSQL() {
spoon.getSQL();
}
public void exploreDatabase() {
spoon.exploreDatabase();
}
public synchronized void startJob(Date replayDate) {
if (job == null) // Not running, start the transformation...
{
// Auto save feature...
if (jobMeta.hasChanged()) {
if (spoon.props.getAutoSave()) {
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobLog.Log.AutoSaveFileBeforeRunning")); //$NON-NLS-1$
System.out.println(Messages.getString("JobLog.Log.AutoSaveFileBeforeRunning2")); //$NON-NLS-1$
spoon.saveToFile(jobMeta);
} else {
MessageDialogWithToggle md = new MessageDialogWithToggle(
shell,
Messages.getString("JobLog.Dialog.SaveChangedFile.Title"), //$NON-NLS-1$
null,
Messages.getString("JobLog.Dialog.SaveChangedFile.Message") + Const.CR + Messages.getString("JobLog.Dialog.SaveChangedFile.Message2") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.QUESTION, new String[] {
Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$
0, Messages.getString("JobLog.Dialog.SaveChangedFile.Toggle"), //$NON-NLS-1$
spoon.props.getAutoSave());
int answer = md.open();
if ((answer & 0xFF) == 0) {
spoon.saveToFile(jobMeta);
}
spoon.props.setAutoSave(md.getToggleState());
}
}
if (((jobMeta.getName() != null && spoon.rep != null) || // Repository available & name set
(jobMeta.getFilename() != null && spoon.rep == null) // No repository & filename set
)
&& !jobMeta.hasChanged() // Didn't change
) {
if (job == null || (job != null && !job.isActive())) {
try {
// TODO: clean up this awful mess...
job = new Job(log, jobMeta.getName(), jobMeta.getFilename(), null);
job.open(spoon.rep, jobMeta.getFilename(), jobMeta.getName(), jobMeta.getDirectory().getPath(), spoon);
job.getJobMeta().setArguments(jobMeta.getArguments());
job.shareVariablesWith(jobMeta);
log.logMinimal(Spoon.APP_NAME, Messages.getString("JobLog.Log.StartingJob")); //$NON-NLS-1$
job.start();
jobGridDelegate.previousNrItems = -1;
// Link to the new jobTracker!
jobGridDelegate.jobTracker = job.getJobTracker();
running = true;
// Attach a listener to notify us that the transformation has finished.
job.addJobListener(new JobListener() {
public void JobFinished(Job job) {
jobFinished();
}
});
// Show the execution results views
addAllTabs();
} catch (KettleException e) {
new ErrorDialog(
shell,
Messages.getString("JobLog.Dialog.CanNotOpenJob.Title"), Messages.getString("JobLog.Dialog.CanNotOpenJob.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
job = null;
}
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("JobLog.Dialog.JobIsAlreadyRunning.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("JobLog.Dialog.JobIsAlreadyRunning.Message")); //$NON-NLS-1$
m.open();
}
} else {
if (jobMeta.hasChanged()) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("JobLog.Dialog.JobHasChangedSave.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("JobLog.Dialog.JobHasChangedSave.Message")); //$NON-NLS-1$
m.open();
} else if (spoon.rep != null && jobMeta.getName() == null) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("JobLog.Dialog.PleaseGiveThisJobAName.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("JobLog.Dialog.PleaseGiveThisJobAName.Message")); //$NON-NLS-1$
m.open();
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("JobLog.Dialog.NoFilenameSaveYourJobFirst.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("JobLog.Dialog.NoFilenameSaveYourJobFirst.Message")); //$NON-NLS-1$
m.open();
}
}
setControlStates();
}
}
/**
* This gets called at the very end, when everything is done.
*/
private void jobFinished() {
// Do a final check to see if it all ended...
if (running && job != null && job.isInitialized() && job.isFinished()) {
job = null;
running = false;
for (RefreshListener listener : refreshListeners)
listener.refreshNeeded();
log.logMinimal(Spoon.APP_NAME, Messages.getString("JobLog.Log.JobHasEnded")); //$NON-NLS-1$
}
setControlStates();
}
public synchronized void stopJob() {
try {
if (job != null && running && job.isInitialized()) {
job.stopAll();
job.endProcessing("stop", new Result()); //$NON-NLS-1$
job.waitUntilFinished(5000); // wait until everything is stopped, maximum 5 seconds...
job = null;
running = false;
log.logMinimal(Spoon.APP_NAME, Messages.getString("JobLog.Log.JobWasStopped")); //$NON-NLS-1$
}
} catch (KettleJobException je) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("JobLog.Dialog.UnableToSaveStopLineInLoggingTable.Title")); //$NON-NLS-1$
m
.setMessage(Messages.getString("JobLog.Dialog.UnableToSaveStopLineInLoggingTable.Message") + Const.CR + je.toString()); //$NON-NLS-1$
m.open();
} finally {
setControlStates();
}
}
private void setControlStates() {
getDisplay().asyncExec(new Runnable() {
public void run() {
// Start/Run button...
XulToolbarButton runButton = toolbar.getButtonById("job-run");
if (runButton != null) {
runButton.setEnable(!running);
}
/* TODO add pause button
*
// Pause button...
//
XulToolbarButton pauseButton = toolbar.getButtonById("trans-pause");
if (pauseButton!=null)
{
pauseButton.setEnable(running);
pauseButton.setText( pausing ? RESUME_TEXT : PAUSE_TEXT );
pauseButton.setHint( pausing ? Messages.getString("Spoon.Tooltip.ResumeTranformation") : Messages.getString("Spoon.Tooltip.PauseTranformation"));
}
*/
// Stop button...
XulToolbarButton stopButton = toolbar.getButtonById("job-stop");
if (stopButton != null) {
stopButton.setEnable(running);
}
// TODO: enable/disable Job menu entries too
}
});
}
/**
* @return the refresh listeners
*/
public List<RefreshListener> getRefreshListeners() {
return refreshListeners;
}
/**
* @param refreshListeners the refresh listeners to set
*/
public void setRefreshListeners(List<RefreshListener> refreshListeners) {
this.refreshListeners = refreshListeners;
}
/**
* @param refreshListener the job refresh listener to add
*/
public void addRefreshListener(RefreshListener refreshListener) {
refreshListeners.add(refreshListener);
}
} |
package cmabreu.sagitarii.teapot;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import cmabreu.sagitarii.teapot.comm.Communicator;
import cmabreu.sagitarii.teapot.console.CommandLoader;
public class Main {
private static Logger logger = LogManager.getLogger( "cmabreu.sagitarii.teapot.Main" );
private static CommandLoader cm;
private static long totalInstancesProcessed = 0;
private static boolean paused = false;
private static List<TaskRunner> runners = new ArrayList<TaskRunner>();
private static boolean restarting = false;
private static boolean reloading = false;
private static boolean quiting = false;
private static boolean cleaning = false;
private static Communicator communicator;
private static Configurator configurator;
public static void pause() {
paused = true;
}
public static long getTotalInstancesProcessed() {
return totalInstancesProcessed;
}
public static Communicator getCommunicator() {
return communicator;
}
public static Configurator getConfigurator() {
return configurator;
}
public static void resume() {
paused = false;
}
/**
* Remover o diretorio raiz do namespace
* Chamado antes de iniciar os trabalhos para sempre ter um namespace limpo.
*/
private static void cleanUp() {
cleaning = true;
if ( getRunners().size() > 0 ) {
logger.warn("will not clean workspace. " + getRunners().size() + " tasks still runnig");
} else {
try {
FileUtils.deleteDirectory( new File( "namespaces" ) );
} catch ( IOException e ) {
logger.error( e.getMessage() );
}
logger.warn("workspace cleaned");
cleaning = false;
}
}
/**
* Teapot entry point
*
* EX UNITATE VIRES !
*/
public static void main( String[] args ) {
boolean wrappersDownloaded = false;
try {
System.out.println("");
System.out.println("Sagitarii Teapot Node v1.0.125 23/04/2015");
System.out.println("Carlos Magno Abreu magno.mabreu@gmail.com");
System.out.println("
System.out.println("");
logger.debug("Loading Repository Manager ...");
configurator = new Configurator("config.xml");
configurator.loadMainConfig();
RepositoryManager rm = new RepositoryManager( configurator );
logger.debug("Loading Task Manager ...");
logger.debug("Cores : " + configurator.getSystemProperties().getAvailableProcessors() + " cores." );
logger.debug("SO Name : " + configurator.getSystemProperties().getSoName() );
logger.debug("Machine : " + configurator.getSystemProperties().getMachineName() );
logger.debug("Free Space: " + configurator.getSystemProperties().getFreeDiskSpace() );
logger.debug("SO family : " + configurator.getSystemProperties().getOsType() );
logger.debug("IP/MAC : " + configurator.getSystemProperties().getLocalIpAddress() + " / " + configurator.getSystemProperties().getMacAddress() );
logger.debug("Java : " + configurator.getSystemProperties().getJavaVersion() );
logger.debug("Announce : " + configurator.getPoolIntervalMilliSeconds() +"ms." );
logger.debug("Sagitarii : " + configurator.getHostURL() );
logger.debug("Classpath : " + configurator.getSystemProperties().getClassPath() );
logger.debug("R Home : " + configurator.getSystemProperties().getrHome() );
logger.debug("JRI : " + configurator.getSystemProperties().getJriPath() );
logger.debug("Path : " + configurator.getSystemProperties().getPath() );
logger.debug("cleaning workspace...");
cleanUp();
if ( configurator.useProxy() ) {
logger.debug("Proxy: " + configurator.getProxyInfo().getHost() );
}
if ( !configurator.getShowConsole() ) {
logger.debug("No activations console.");
}
logger.debug("Searching for wrappers...");
try {
rm.downloadWrappers( );
wrappersDownloaded = true;
} catch ( ConnectException e ) {
logger.error("Cannot download wrappers. Will interrupt startup until Sagitarii is up.");
}
logger.debug("Staring communicator...");
communicator = new Communicator( configurator );
if ( wrappersDownloaded ) {
logger.debug("Teapot started.");
}
if ( args.length > 0) {
if( args[0].equalsIgnoreCase("interactive") ) {
logger.debug("Stating interactive mode...");
cm = new CommandLoader();
cm.start();
LogManager.disableLoggers();
}
if( ( args.length > 1) && args[1].equalsIgnoreCase("norun") ) {
return;
}
}
while (true) {
clearRunners();
logger.debug( "init new cycle: " + runners.size() + " of " + configurator.getActivationsMaxLimit() + " tasks running:" );
for ( TaskRunner tr : getRunners() ) {
if ( tr.getCurrentTask() != null ) {
String time = tr.getStartTime() + " (" + tr.getTime() + ")";
logger.debug( " > " + tr.getCurrentTask().getTaskId() + " (" + tr.getCurrentActivation().getExecutor() + ") : " + time);
}
}
SpeedEqualizer.equalize( configurator, runners.size() );
if ( !wrappersDownloaded ) {
try {
logger.debug("Searching for wrappers...");
rm.downloadWrappers();
wrappersDownloaded = true;
logger.debug("Done. Teapot Started.");
} catch ( ConnectException e ) {
logger.error("Cannot download wrappers. Skipping.");
}
} else {
if ( !paused ) {
String response = "NO_DATA";
try {
if ( runners.size() < configurator.getActivationsMaxLimit() ) {
if ( !havePendentCommand() ) {
logger.debug( "asking Sagitarii for tasks to process...");
response = communicator.announceAndRequestTask( configurator.getSystemProperties().getCpuLoad(),
configurator.getSystemProperties().getFreeMemory(), configurator.getSystemProperties().getTotalMemory() );
if ( response.length() > 0 ) {
logger.debug("Sagitarii answered " + response.length() + " bytes");
if ( response.equals("COMM_ERROR") ) {
logger.error("Sagitarii is offline");
} else {
if ( !specialCommand( response ) ) {
logger.debug("starting new process");
TaskRunner tr = new TaskRunner( response, communicator, configurator);
runners.add(tr);
tr.start();
totalInstancesProcessed++;
logger.debug("new process started");
}
}
} else {
logger.debug("nothing to do for now");
}
} else {
logger.debug("cannot request new tasks: flushing buffers...");
}
}
} catch ( Exception e ) {
logger.error( "process error: " + e.getMessage() );
logger.error( " > " + response );
}
}
sendRunners();
}
try {
Thread.sleep( configurator.getPoolIntervalMilliSeconds() );
} catch( InterruptedException ex ) {
}
}
} catch (Exception e) {
logger.debug("Critical error. Cannot start Teapot Node.");
logger.debug("Error details:");
e.printStackTrace();
}
}
private static String generateJsonPair(String paramName, String paramValue) {
return "\"" + paramName + "\":\"" + paramValue + "\"";
}
private static String addArray(String paramName, String arrayValue) {
return "\"" + paramName + "\":" + arrayValue ;
}
private static void sendRunners() {
logger.debug("sending " + getRunners().size() + " Task Runners to Sagitarii ");
StringBuilder sb = new StringBuilder();
String dataPrefix = "";
sb.append("[");
for ( TaskRunner tr : getRunners() ) {
if ( tr.getCurrentActivation() != null ) {
logger.debug( " > " + tr.getCurrentActivation().getTaskId() + " sent" );
sb.append( dataPrefix + "{");
sb.append( generateJsonPair( "workflow" , tr.getCurrentActivation().getWorkflow() ) + "," );
sb.append( generateJsonPair( "experiment" , tr.getCurrentActivation().getExperiment() ) + "," );
sb.append( generateJsonPair( "taskId" , tr.getCurrentActivation().getTaskId() ) + "," );
sb.append( generateJsonPair( "executor" , tr.getCurrentActivation().getExecutor() ) + "," );
sb.append( generateJsonPair( "startTime" , tr.getStartTime() ) + "," );
sb.append( generateJsonPair( "elapsedTime" , tr.getTime() ) );
dataPrefix = ",";
sb.append("}");
} else {
sb.append( dataPrefix + "{");
sb.append( generateJsonPair( "workflow" , "UNKNOWN" ) + "," );
sb.append( generateJsonPair( "experiment" , "UNKNOWN" ) + "," );
sb.append( generateJsonPair( "taskId" , "UNKNOWN" ) + "," );
sb.append( generateJsonPair( "executor" , "UNKNOWN" ) + "," );
sb.append( generateJsonPair( "startTime" , "00:00:00" ) + "," );
sb.append( generateJsonPair( "elapsedTime" , "00:00:00" ) );
dataPrefix = ",";
sb.append("}");
}
}
sb.append("]");
StringBuilder data = new StringBuilder();
data.append("{");
data.append( generateJsonPair( "nodeId" , configurator.getSystemProperties().getMacAddress() ) + "," );
data.append( generateJsonPair( "cpuLoad" , String.valueOf( configurator.getSystemProperties().getCpuLoad() ) ) + "," );
data.append( generateJsonPair( "freeMemory" , String.valueOf( configurator.getSystemProperties().getFreeMemory() ) ) + "," );
data.append( generateJsonPair( "totalMemory" , String.valueOf( configurator.getSystemProperties().getTotalMemory() ) ) + "," );
data.append( generateJsonPair( "totalDiskSpace" , String.valueOf( configurator.getSystemProperties().getTotalDiskSpace() ) ) + "," );
data.append( generateJsonPair( "freeDiskSpace" , String.valueOf( configurator.getSystemProperties().getFreeDiskSpace() ) ) + "," );
data.append( addArray("data", sb.toString() ) );
data.append("}");
logger.debug(" done sending Task Runners: " + data.toString() );
communicator.doPost("receiveNodeTasks", "tasks", data.toString() );
}
/**
* Check if there is a command waiting for task buffer is flushed
*/
private static boolean havePendentCommand() {
if ( quiting ) {
logger.debug("Teapot is quiting... do not process tasks anymore");
quit();
return true;
}
if ( restarting ) {
logger.debug("Teapot is restarting... do not process tasks anymore");
restart();
return true;
}
if ( reloading ) {
logger.debug("Teapot is reloading wrappers... do not process tasks for now");
reloadWrappers();
return true;
}
if ( cleaning ) {
logger.debug("Teapot is cleaning workspace... do not process tasks for now");
cleanUp();
return true;
}
// No command is in process. Can free Teapot now...
return false;
}
/**
* Will check if Sagitarii sent a special command to this node
* Returning TRUE will deny to run tasks ( may be a command or in flushing process )
*
* WARNING: By returning FALSE ensure this "response" is a valid XML instance
* or the XML parser will throw an error.
*
*/
private static boolean specialCommand( String response ) {
logger.debug("checking preprocess");
// RESULT:
// FALSE = A valid XML instance. Will run a new task.
// TRUE = A Sagitarii command or we don't want to run new tasks
// even "response" is a valid XML instance
if ( ( !response.equals( "NO_ANSWER" ) ) && ( !response.equals( "COMM_ERROR" ) ) && ( !response.equals( "" ) ) ) {
if ( response.equals( "COMM_RESTART" ) ) {
logger.warn("get restart command from Sagitarii");
restart();
return true;
}
if ( response.equals( "RELOAD_WRAPPERS" ) ) {
logger.warn("get reload wrappers command from Sagitarii");
reloadWrappers();
return true;
}
if ( response.equals( "COMM_QUIT" ) ) {
logger.warn("get quit command from Sagitarii");
quit();
return true;
}
if ( response.contains( "INFORM" ) ) {
String[] data = response.split("
logger.warn("Sagitarii is asking for Instance " + data[1] );
inform( data[1] );
// No need to stop Teapot or flush buffers... just an information request
// Avoid consider this response as a valid XML instance by returning "TRUE"
return true;
}
if ( response.equals( "COMM_CLEAN_WORKSPACE" ) ) {
logger.warn("get clean workspace command from Sagitarii");
cleanUp();
return true;
}
} else {
logger.debug("invalid response from Sagitarii: " + response);
return true;
}
return false;
}
/**
* Will restart Teapot
* It is a Sagitarii command
*/
public static void restartApplication() {
try {
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File ( Teapot.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if( !currentJar.getName().endsWith(".jar") ) {
return;
}
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add( javaBin );
command.add( "-jar" );
command.add( currentJar.getPath() );
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
} catch ( Exception e ) {
e.printStackTrace();
}
}
/**
* Restart Teapot
*/
private static void restart() {
restarting = true;
if ( getRunners().size() > 0 ) {
logger.debug("cannot restart now. " + getRunners().size() + " tasks still runnig");
} else {
logger.debug("restart now.");
restartApplication();
}
}
private static void inform( String instanceSerial ) {
boolean found = false;
for ( TaskRunner tr : getRunners() ) {
if ( tr.getCurrentTask() != null ) {
if ( tr.getCurrentActivation().getInstanceSerial().equals( instanceSerial ) ) {
found = true;
break;
}
}
}
String status = "";
if ( found ) {
status = "RUNNING";
logger.debug("Instance "+instanceSerial+" is running");
} else {
status = "NOT_FOUND";
logger.debug("Instance "+instanceSerial+" not found");
}
String parameters = "macAddress=" + configurator.getSystemProperties().getMacAddress() +
"&instance=" + instanceSerial + "&status=" + status;
communicator.send("taskStatusReport", parameters);
}
/**
* Close Teapot
*/
private static void quit() {
quiting = true;
if ( getRunners().size() > 0 ) {
logger.debug("cannot quit now. " + getRunners().size() + " tasks still runnig");
} else {
logger.debug("quit now.");
System.exit(0);
}
}
/**
* Download all wrappers from Sagitarii again
*/
private static void reloadWrappers() {
if( reloading ) {
logger.debug("already reloading... will wait.");
return;
}
reloading = true;
if ( getRunners().size() > 0 ) {
logger.debug("cannot reload wrappers now. " + getRunners().size() + " tasks still runnig");
} else {
logger.debug("reload all wrappers now.");
try {
RepositoryManager rm = new RepositoryManager( configurator );
rm.downloadWrappers();
logger.debug("all wrappers reloaded.");
} catch ( Exception e ) {
logger.error("cannot reload wrappers: " + e.getMessage() );
}
reloading = false;
}
}
public static List<TaskRunner> getRunners() {
return new ArrayList<TaskRunner>( runners );
}
/**
* Remove all finished task threads from buffer
*
*/
private static void clearRunners() {
logger.debug("cleaning task runners...");
int total = 0;
Iterator<TaskRunner> i = runners.iterator();
while ( i.hasNext() ) {
TaskRunner req = i.next();
if ( !req.isActive() ) {
try {
logger.debug(" > killing task runner " + req.getCurrentActivation().getExecutor() + " " + req.getSerial() + " (" + req.getCurrentTask().getTaskId() + ")" );
} catch ( Exception e ) {
logger.debug(" > killing null task runner");
}
i.remove();
total++;
}
}
logger.debug( total + " task runners deleted" );
}
} |
package com.ace.cache.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@Slf4j
public class CacheUtil {
private static ThreadLocal<Boolean> FORCE_REFRESH = new ThreadLocal<>();
private static ThreadLocal<String> LOCK_STACK = new ThreadLocal<>();
public static void setForceRefreshCache(){
FORCE_REFRESH.set(true);
}
public static boolean isForceRefreshCache(){
Boolean isForceRefresh = FORCE_REFRESH.get();
boolean result = null != isForceRefresh && isForceRefresh;
if (result && StringUtils.isBlank(LOCK_STACK.get()))
{
String stack = getInvokeStackStr(2);
LOCK_STACK.set(stack);
}
return result;
}
public static void clear(){
clear(false);
}
public static void clear(boolean isForce){
if (isForce){
FORCE_REFRESH.remove();
LOCK_STACK.remove();
}
else{
String thisLockStack = LOCK_STACK.get();
if (StringUtils.isBlank(thisLockStack) ) {
FORCE_REFRESH.remove();
LOCK_STACK.remove();
}
else {
String stack = getInvokeStackStr(2);
if(stack.startsWith("com.ace.cache.utils.CacheUtil.clear<-")){ //clear()
stack = stack.replaceFirst("com.ace.cache.utils.CacheUtil.clear<-","");
}
if(thisLockStack.equals(stack)){
FORCE_REFRESH.remove();
LOCK_STACK.remove();
}
else{
return;
}
}
}
}
public static void main(String[] args) {
String china = "2";
System.out.println(china.substring(0,3));
CacheUtil.setForceRefreshCache();
CacheUtil.setForceRefreshCache();
System.out.println(CacheUtil.isForceRefreshCache());
test2();
System.out.println(CacheUtil.isForceRefreshCache());
CacheUtil.clear(false);
System.out.println(CacheUtil.isForceRefreshCache());
CacheUtil.clear(true);
System.out.println(CacheUtil.isForceRefreshCache());
}
private static void test(){
System.out.println(getInvokeStackStr(0));
}
private static void test2(){
CacheUtil.clear(false);
}
private static String getInvokeStackStr(int before){
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StringBuilder sb= new StringBuilder();
if (stackTraceElements.length> before +1) {
for (int i = 1 + before; i < stackTraceElements.length; i++) {
sb.append(stackTraceElements[i].getClassName() + "." + stackTraceElements[i].getMethodName() + "<-");
}
}
return sb.toString();
}
} |
package io.druid.indexing.overlord.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
public class ForkingTaskRunnerConfig
{
@JsonProperty
@NotNull
private String taskDir = "/tmp/persistent";
@JsonProperty
@NotNull
private String javaCommand = "java";
/**
* This is intended for setting -X parameters on the underlying java. It is used by first splitting on whitespace,
* so it cannot handle properties that have whitespace in the value. Those properties should be set via a
* druid.indexer.fork.property. property instead.
*/
@JsonProperty
@NotNull
private String javaOpts = "";
@JsonProperty
@NotNull
private String classpath = System.getProperty("java.class.path");
@JsonProperty
@Min(1024)
@Max(65535)
private int startPort = 8080;
@JsonProperty
@NotNull
List<String> allowedPrefixes = Lists.newArrayList(
"com.metamx",
"druid",
"io.druid",
"user.timezone",
"file.encoding",
"java.io.tmpdir"
);
public String getTaskDir()
{
return taskDir;
}
public String getJavaCommand()
{
return javaCommand;
}
public String getJavaOpts()
{
return javaOpts;
}
public String getClasspath()
{
return classpath;
}
public int getStartPort()
{
return startPort;
}
public List<String> getAllowedPrefixes()
{
return allowedPrefixes;
}
} |
package com.akiban.sql.aisddl;
import com.akiban.server.api.DDLFunctions;
import com.akiban.server.error.*;
import com.akiban.server.service.session.Session;
import com.akiban.sql.optimizer.AISBinderContext;
import com.akiban.sql.optimizer.AISViewDefinition;
import com.akiban.sql.parser.CreateViewNode;
import com.akiban.sql.parser.DropViewNode;
import com.akiban.sql.parser.ExistenceCheck;
import com.akiban.sql.parser.ResultColumn;
import com.akiban.sql.types.DataTypeDescriptor;
import com.akiban.sql.types.TypeId;
import com.akiban.ais.model.AISBuilder;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.Columnar;
import com.akiban.ais.model.Type;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.Types;
import com.akiban.ais.model.View;
import java.util.Collection;
import java.util.Map;
/** DDL operations on Views */
public class ViewDDL
{
private ViewDDL() {
}
public static void createView(DDLFunctions ddlFunctions,
Session session,
String defaultSchemaName,
CreateViewNode createView,
AISBinderContext binderContext) {
com.akiban.sql.parser.TableName parserName = createView.getObjectName();
String schemaName = parserName.hasSchema() ? parserName.getSchemaName() : defaultSchemaName;
String viewName = parserName.getTableName();
ExistenceCheck condition = createView.getExistenceCheck();
if (ddlFunctions.getAIS(session).getView(schemaName, viewName) != null) {
switch(condition) {
case IF_NOT_EXISTS:
// view already exists. does nothing
return;
case NO_CONDITION:
throw new DuplicateViewException(schemaName, viewName);
default:
throw new IllegalStateException("Unexpected condition: " + condition);
}
}
AISViewDefinition viewdef = binderContext.getViewDefinition(createView);
Map<Columnar,Collection<Column>> tableColumnReferences = viewdef.getTableColumnReferences();
AISBuilder builder = new AISBuilder();
builder.view(schemaName, viewName, viewdef.getQueryExpression(),
binderContext.getParserProperties(schemaName), tableColumnReferences);
int colpos = 0;
for (ResultColumn rc : viewdef.getResultColumns()) {
TableDDL.addColumn(builder, schemaName, viewName, rc.getName(), colpos++,
rc.getType(), false);
}
View view = builder.akibanInformationSchema().getView(schemaName, viewName);
ddlFunctions.createView(session, view);
}
public static void dropView (DDLFunctions ddlFunctions,
Session session,
String defaultSchemaName,
DropViewNode dropView,
AISBinderContext binderContext) {
com.akiban.sql.parser.TableName parserName = dropView.getObjectName();
String schemaName = parserName.hasSchema() ? parserName.getSchemaName() : defaultSchemaName;
TableName viewName = TableName.create(schemaName, parserName.getTableName());
ExistenceCheck existenceCheck = dropView.getExistenceCheck();
if (ddlFunctions.getAIS(session).getView(viewName) == null) {
if (existenceCheck == ExistenceCheck.IF_EXISTS)
return;
throw new UndefinedViewException(viewName);
}
ddlFunctions.dropView(session, viewName);
}
} |
package info.nightscout.androidaps.plugins.pump.insight;
import static info.nightscout.androidaps.extensions.PumpStateExtensionKt.convertedToAbsolute;
import static info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.InsightBolusID;
import info.nightscout.androidaps.db.InsightHistoryOffset;
import info.nightscout.androidaps.db.InsightPumpID;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.insight.R;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Config;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.Constraints;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.Pump;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.interfaces.PumpSync.PumpState.TemporaryBasal;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.Service;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.HistoryReadingDirection;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.ReadHistoryEventsMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.StartReadingHistoryMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.StopReadingHistoryMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.BolusDeliveredEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.BolusProgrammedEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.CannulaFilledEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.DateTimeChangedEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.DefaultDateTimeSetEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.EndOfTBREvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.HistoryEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.OccurrenceOfAlertEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.OperatingModeChangedEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.PowerUpEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.SniffingDoneEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.StartOfTBREvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.TotalDailyDoseEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.TubeFilledEvent;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.ActiveBRProfileBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfile1Block;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfileBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.FactoryMinBasalAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.FactoryMinBolusAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBasalAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBolusAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.CancelBolusMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.CancelTBRMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.ChangeTBRMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.ConfirmAlertMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.DeliverBolusMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.SetDateTimeMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.SetOperatingModeMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.SetTBRMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetActiveAlertMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetActiveBasalRateMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetActiveBolusesMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetActiveTBRMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetBatteryStatusMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetCartridgeStatusMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetDateTimeMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetOperatingModeMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetPumpStatusRegisterMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetTotalDailyDoseMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.ResetPumpStatusRegisterMessage;
import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertType;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.BasalProfile;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.BasalProfileBlock;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.BatteryStatus;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.BolusType;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.CartridgeStatus;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.OperatingMode;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.PumpTime;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose;
import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightException;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException;
import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator;
import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton
public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constraints, InsightConnectionService.StateCallback {
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final SP sp;
private final CommandQueueProvider commandQueue;
private final ProfileFunction profileFunction;
private final Context context;
private final DateUtil dateUtil;
private final DatabaseHelperInterface databaseHelper;
private final PumpSync pumpSync;
public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert";
private final PumpDescription pumpDescription;
private InsightAlertService alertService;
private InsightConnectionService connectionService;
private long timeOffset;
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
if (binder instanceof InsightConnectionService.LocalBinder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService();
connectionService.registerStateCallback(LocalInsightPlugin.this);
} else if (binder instanceof InsightAlertService.LocalBinder) {
alertService = ((InsightAlertService.LocalBinder) binder).getService();
}
if (connectionService != null && alertService != null) {
rxBus.send(new EventInitializationChanged());
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
connectionService = null;
}
};
private final Object $bolusLock = new Object[0];
private int bolusID;
private boolean bolusCancelled;
private BasalProfile activeBasalProfile;
private List<BasalProfileBlock> profileBlocks;
private boolean limitsFetched;
private double maximumBolusAmount;
private double minimumBolusAmount;
private OperatingMode operatingMode;
private BatteryStatus batteryStatus;
private CartridgeStatus cartridgeStatus;
private TotalDailyDose totalDailyDose;
private ActiveBasalRate activeBasalRate;
private ActiveTBR activeTBR;
private List<ActiveBolus> activeBoluses;
private boolean statusLoaded;
private TBROverNotificationBlock tbrOverNotificationBlock;
@Inject
public LocalInsightPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
ResourceHelper resourceHelper,
SP sp,
CommandQueueProvider commandQueue,
ProfileFunction profileFunction,
Context context,
Config config,
DateUtil dateUtil,
DatabaseHelperInterface databaseHelper,
PumpSync pumpSync
) {
super(new PluginDescription()
.pluginIcon(R.drawable.ic_insight_128)
.pluginName(R.string.insight_local)
.shortName(R.string.insightpump_shortname)
.mainType(PluginType.PUMP)
.description(R.string.description_pump_insight_local)
.fragmentClass(LocalInsightFragment.class.getName())
.preferencesId(config.getAPS() ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol),
injector, aapsLogger, resourceHelper, commandQueue
);
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
this.resourceHelper = resourceHelper;
this.sp = sp;
this.commandQueue = commandQueue;
this.profileFunction = profileFunction;
this.context = context;
this.dateUtil = dateUtil;
this.databaseHelper = databaseHelper;
this.pumpSync = pumpSync;
pumpDescription = new PumpDescription();
pumpDescription.fillFor(PumpType.ACCU_CHEK_INSIGHT);
}
public TBROverNotificationBlock getTBROverNotificationBlock() {
return tbrOverNotificationBlock;
}
public InsightConnectionService getConnectionService() {
return connectionService;
}
public OperatingMode getOperatingMode() {
return operatingMode;
}
public BatteryStatus getBatteryStatus() {
return batteryStatus;
}
public CartridgeStatus getCartridgeStatus() {
return cartridgeStatus;
}
public TotalDailyDose getTotalDailyDose() {
return totalDailyDose;
}
public ActiveBasalRate getActiveBasalRate() {
return activeBasalRate;
}
public ActiveTBR getActiveTBR() {
return activeTBR;
}
public List<ActiveBolus> getActiveBoluses() {
return activeBoluses;
}
@Override
protected void onStart() {
super.onStart();
context.bindService(new Intent(context, InsightConnectionService.class), serviceConnection, Context.BIND_AUTO_CREATE);
context.bindService(new Intent(context, InsightAlertService.class), serviceConnection, Context.BIND_AUTO_CREATE);
createNotificationChannel();
}
private void createNotificationChannel() {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, resourceHelper.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH);
channel.setSound(null, null);
notificationManager.createNotificationChannel(channel);
}
@Override
protected void onStop() {
super.onStop();
context.unbindService(serviceConnection);
}
@Override
public boolean isInitialized() {
return connectionService != null && alertService != null && connectionService.isPaired();
}
@Override
public boolean isSuspended() {
return operatingMode != null && operatingMode != OperatingMode.STARTED;
}
@Override
public boolean isBusy() {
return false;
}
@Override
public boolean isConnected() {
return connectionService != null
&& alertService != null
&& connectionService.hasRequestedConnection(this)
&& connectionService.getState() == InsightState.CONNECTED;
}
@Override
public boolean isConnecting() {
if (connectionService == null || alertService == null || !connectionService.hasRequestedConnection(this))
return false;
InsightState state = connectionService.getState();
return state == InsightState.CONNECTING
|| state == InsightState.APP_CONNECT_MESSAGE
|| state == InsightState.RECOVERING;
}
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void connect(@NonNull String reason) {
if (connectionService != null && alertService != null)
connectionService.requestConnection(this);
}
@Override
public void disconnect(@NonNull String reason) {
if (connectionService != null && alertService != null)
connectionService.withdrawConnectionRequest(this);
}
@Override
public void stopConnecting() {
if (connectionService != null && alertService != null)
connectionService.withdrawConnectionRequest(this);
}
@Override
public void getPumpStatus(@NonNull String reason) {
try {
tbrOverNotificationBlock = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, TBROverNotificationBlock.class);
readHistory();
fetchBasalProfile();
fetchLimitations();
updatePumpTimeIfNeeded();
fetchStatus();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while fetching status: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while fetching status: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception while fetching status", e);
}
}
private void updatePumpTimeIfNeeded() throws Exception {
PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, pumpTime.getYear());
calendar.set(Calendar.MONTH, pumpTime.getMonth() - 1);
calendar.set(Calendar.DAY_OF_MONTH, pumpTime.getDay());
calendar.set(Calendar.HOUR_OF_DAY, pumpTime.getHour());
calendar.set(Calendar.MINUTE, pumpTime.getMinute());
calendar.set(Calendar.SECOND, pumpTime.getSecond());
if (calendar.get(Calendar.HOUR_OF_DAY) != pumpTime.getHour() || Math.abs(calendar.getTimeInMillis() - dateUtil.now()) > 10000) {
calendar.setTime(new Date());
pumpTime.setYear(calendar.get(Calendar.YEAR));
pumpTime.setMonth(calendar.get(Calendar.MONTH) + 1);
pumpTime.setDay(calendar.get(Calendar.DAY_OF_MONTH));
pumpTime.setHour(calendar.get(Calendar.HOUR_OF_DAY));
pumpTime.setMinute(calendar.get(Calendar.MINUTE));
pumpTime.setSecond(calendar.get(Calendar.SECOND));
SetDateTimeMessage setDateTimeMessage = new SetDateTimeMessage();
setDateTimeMessage.setPumpTime(pumpTime);
connectionService.requestMessage(setDateTimeMessage).await();
Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, resourceHelper.gs(R.string.pump_time_updated), Notification.INFO, 60);
rxBus.send(new EventNewNotification(notification));
}
}
private void fetchBasalProfile() throws Exception {
activeBasalProfile = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, ActiveBRProfileBlock.class).getActiveBasalProfile();
profileBlocks = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, BRProfile1Block.class).getProfileBlocks();
}
private void fetchStatus() throws Exception {
if (statusLoaded) {
GetPumpStatusRegisterMessage registerMessage = connectionService.requestMessage(new GetPumpStatusRegisterMessage()).await();
ResetPumpStatusRegisterMessage resetMessage = new ResetPumpStatusRegisterMessage();
resetMessage.setOperatingModeChanged(registerMessage.isOperatingModeChanged());
resetMessage.setBatteryStatusChanged(registerMessage.isBatteryStatusChanged());
resetMessage.setCartridgeStatusChanged(registerMessage.isCartridgeStatusChanged());
resetMessage.setTotalDailyDoseChanged(registerMessage.isTotalDailyDoseChanged());
resetMessage.setActiveTBRChanged(registerMessage.isActiveTBRChanged());
resetMessage.setActiveBolusesChanged(registerMessage.isActiveBolusesChanged());
connectionService.requestMessage(resetMessage).await();
if (registerMessage.isOperatingModeChanged())
operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode();
if (registerMessage.isBatteryStatusChanged())
batteryStatus = connectionService.requestMessage(new GetBatteryStatusMessage()).await().getBatteryStatus();
if (registerMessage.isCartridgeStatusChanged())
cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await().getCartridgeStatus();
if (registerMessage.isTotalDailyDoseChanged())
totalDailyDose = connectionService.requestMessage(new GetTotalDailyDoseMessage()).await().getTDD();
if (operatingMode == OperatingMode.STARTED) {
if (registerMessage.isActiveBasalRateChanged())
activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await().getActiveBasalRate();
if (registerMessage.isActiveTBRChanged())
activeTBR = connectionService.requestMessage(new GetActiveTBRMessage()).await().getActiveTBR();
if (registerMessage.isActiveBolusesChanged())
activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses();
} else {
activeBasalRate = null;
activeTBR = null;
activeBoluses = null;
}
} else {
ResetPumpStatusRegisterMessage resetMessage = new ResetPumpStatusRegisterMessage();
resetMessage.setOperatingModeChanged(true);
resetMessage.setBatteryStatusChanged(true);
resetMessage.setCartridgeStatusChanged(true);
resetMessage.setTotalDailyDoseChanged(true);
resetMessage.setActiveBasalRateChanged(true);
resetMessage.setActiveTBRChanged(true);
resetMessage.setActiveBolusesChanged(true);
connectionService.requestMessage(resetMessage).await();
operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode();
batteryStatus = connectionService.requestMessage(new GetBatteryStatusMessage()).await().getBatteryStatus();
cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await().getCartridgeStatus();
totalDailyDose = connectionService.requestMessage(new GetTotalDailyDoseMessage()).await().getTDD();
if (operatingMode == OperatingMode.STARTED) {
activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await().getActiveBasalRate();
activeTBR = connectionService.requestMessage(new GetActiveTBRMessage()).await().getActiveTBR();
activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses();
} else {
activeBasalRate = null;
activeTBR = null;
activeBoluses = null;
}
statusLoaded = true;
}
new Handler(Looper.getMainLooper()).post(() -> {
rxBus.send(new EventLocalInsightUpdateGUI());
rxBus.send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus", false));
});
}
private void fetchLimitations() throws Exception {
maximumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBolusAmountBlock.class).getAmountLimitation();
double maximumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBasalAmountBlock.class).getAmountLimitation();
minimumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBolusAmountBlock.class).getAmountLimitation();
double minimumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBasalAmountBlock.class).getAmountLimitation();
this.pumpDescription.setBasalMaximumRate(maximumBasalAmount);
this.pumpDescription.setBasalMinimumRate(minimumBasalAmount);
limitsFetched = true;
}
@NonNull @Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult(getInjector());
rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
List<BasalProfileBlock> profileBlocks = new ArrayList<>();
for (int i = 0; i < profile.getBasalValues().length; i++) {
Profile.ProfileValue basalValue = profile.getBasalValues()[i];
Profile.ProfileValue nextValue = null;
if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1];
BasalProfileBlock profileBlock = new BasalProfileBlock();
profileBlock.setBasalAmount(basalValue.getValue() > 5 ? Math.round(basalValue.getValue() / 0.1) * 0.1 : Math.round(basalValue.getValue() / 0.01) * 0.01);
profileBlock.setDuration((((nextValue != null ? nextValue.getTimeAsSeconds() : 24 * 60 * 60) - basalValue.getTimeAsSeconds()) / 60));
profileBlocks.add(profileBlock);
}
try {
ActiveBRProfileBlock activeBRProfileBlock = new ActiveBRProfileBlock();
activeBRProfileBlock.setActiveBasalProfile(BasalProfile.PROFILE_1);
ParameterBlockUtil.writeConfigurationBlock(connectionService, activeBRProfileBlock);
activeBasalProfile = BasalProfile.PROFILE_1;
BRProfileBlock profileBlock = new BRProfile1Block();
profileBlock.setProfileBlocks(profileBlocks);
ParameterBlockUtil.writeConfigurationBlock(connectionService, profileBlock);
rxBus.send(new EventDismissNotification(Notification.FAILED_UPDATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60);
rxBus.send(new EventNewNotification(notification));
result.success(true)
.enacted(true)
.comment(R.string.virtualpump_resultok);
this.profileBlocks = profileBlocks;
try {
fetchStatus();
} catch (Exception ignored) {
}
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName());
Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while setting profile", e);
Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
@Override
public boolean isThisProfileSet(@NonNull Profile profile) {
if (!isInitialized() || profileBlocks == null) return true;
if (profile.getBasalValues().length != profileBlocks.size()) return false;
if (activeBasalProfile != BasalProfile.PROFILE_1) return false;
for (int i = 0; i < profileBlocks.size(); i++) {
BasalProfileBlock profileBlock = profileBlocks.get(i);
Profile.ProfileValue basalValue = profile.getBasalValues()[i];
Profile.ProfileValue nextValue = null;
if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1];
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.getTimeAsSeconds() : 24 * 60 * 60) - basalValue.getTimeAsSeconds())
return false;
if (Math.abs(profileBlock.getBasalAmount() - basalValue.getValue()) > (basalValue.getValue() > 5 ? 0.051 : 0.0051))
return false;
}
return true;
}
@Override
public long lastDataTime() {
if (connectionService == null || alertService == null) return dateUtil.now();
return connectionService.getLastDataTime();
}
@Override
public double getBaseBasalRate() {
if (connectionService == null || alertService == null) return 0;
if (activeBasalRate != null) return activeBasalRate.getActiveBasalRate();
else return 0;
}
@Override
public double getReservoirLevel() {
if (cartridgeStatus == null) return 0;
return cartridgeStatus.getRemainingAmount();
}
@Override
public int getBatteryLevel() {
if (batteryStatus == null) return 0;
return batteryStatus.getBatteryAmount();
}
@NonNull @Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
if (detailedBolusInfo.insulin == 0 || detailedBolusInfo.carbs > 0) {
throw new IllegalArgumentException(detailedBolusInfo.toString(), new Exception());
}
PumpEnactResult result = new PumpEnactResult(getInjector());
double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01;
if (insulin > 0) {
try {
synchronized ($bolusLock) {
DeliverBolusMessage bolusMessage = new DeliverBolusMessage();
bolusMessage.setBolusType(BolusType.STANDARD);
bolusMessage.setDuration(0);
bolusMessage.setExtendedAmount(0);
bolusMessage.setImmediateAmount(insulin);
bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? R.string.key_insight_disable_vibration_auto : R.string.key_insight_disable_vibration, false));
bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId();
bolusCancelled = false;
}
result.success(true).enacted(true);
EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB);
final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
bolusingEvent.setT(t);
bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, 0d, insulin));
bolusingEvent.setPercent(0);
rxBus.send(bolusingEvent);
int trials = 0;
// Move to Insight room database
InsightBolusID insightBolusID = new InsightBolusID();
insightBolusID.bolusID = bolusID;
insightBolusID.timestamp = dateUtil.now();
insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber();
databaseHelper.createOrUpdate(insightBolusID);
aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin);
pumpSync.syncBolusWithPumpId(
insightBolusID.timestamp,
detailedBolusInfo.insulin,
detailedBolusInfo.getBolusType(),
insightBolusID.id,
PumpType.ACCU_CHEK_INSIGHT,
serialNumber());
while (true) {
synchronized ($bolusLock) {
if (bolusCancelled) break;
}
OperatingMode operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode();
if (operatingMode != OperatingMode.STARTED) break;
List<ActiveBolus> activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses();
ActiveBolus activeBolus = null;
for (ActiveBolus bolus : activeBoluses) {
if (bolus.getBolusID() == bolusID) {
activeBolus = bolus;
break;
}
}
if (activeBolus != null) {
trials = -1;
int percentBefore = bolusingEvent.getPercent();
bolusingEvent.setPercent((int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount())));
bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount()));
if (percentBefore != bolusingEvent.getPercent())
rxBus.send(bolusingEvent);
} else {
synchronized ($bolusLock) {
if (bolusCancelled || trials == -1 || trials++ >= 5) {
if (!bolusCancelled) {
bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, insulin, insulin));
bolusingEvent.setPercent(100);
rxBus.send(bolusingEvent);
}
break;
}
}
}
SystemClock.sleep(200);
}
readHistory();
fetchStatus();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while delivering bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while delivering bolus: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while delivering bolus", e);
result.comment(ExceptionTranslator.getString(context, e));
}
result.bolusDelivered(insulin);
}
return result;
}
@Override
public void stopBolusDelivering() {
new Thread(() -> {
try {
synchronized ($bolusLock) {
alertService.ignore(AlertType.WARNING_38);
CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
cancelBolusMessage.setBolusID(bolusID);
connectionService.requestMessage(cancelBolusMessage).await();
bolusCancelled = true;
confirmAlert(AlertType.WARNING_38);
alertService.ignore(null);
aapsLogger.debug(LTag.PUMP, "XXXX Stop Bolus : " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()));
}
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception while canceling bolus", e);
}
}).start();
}
@NonNull @Override
public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
if (activeBasalRate == null) return result;
if (activeBasalRate.getActiveBasalRate() == 0) return result;
double percent = 100D / activeBasalRate.getActiveBasalRate() * absoluteRate;
if (isFakingTempsByExtendedBoluses()) {
PumpEnactResult cancelEBResult = cancelExtendedBolusOnly();
if (cancelEBResult.getSuccess()) {
if (percent > 250) {
PumpEnactResult cancelTBRResult = cancelTempBasalOnly();
if (cancelTBRResult.getSuccess()) {
PumpEnactResult ebResult = setExtendedBolusOnly((absoluteRate - getBaseBasalRate()) / 60D
* ((double) durationInMinutes), durationInMinutes,
sp.getBoolean(R.string.key_insight_disable_vibration_auto, false));
if (ebResult.getSuccess()) {
result.success(true)
.enacted(true)
.isPercent(false)
.absolute(absoluteRate)
.duration(durationInMinutes)
.comment(R.string.virtualpump_resultok);
} else {
result.comment(ebResult.getComment());
}
} else {
result.comment(cancelTBRResult.getComment());
}
} else {
return setTempBasalPercent((int) Math.round(percent), durationInMinutes, profile, enforceNew, tbrType);
}
} else {
result.comment(cancelEBResult.getComment());
}
} else {
return setTempBasalPercent((int) Math.round(percent), durationInMinutes, profile, enforceNew, tbrType);
}
try {
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception after setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception after setting TBR: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception after setting TBR", e);
}
return result;
}
@NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
percent = (int) Math.round(((double) percent) / 10d) * 10;
if (percent == 100) return cancelTempBasal(true);
else if (percent > 250) percent = 250;
try {
if (activeTBR != null) {
ChangeTBRMessage message = new ChangeTBRMessage();
message.setDuration(durationInMinutes);
message.setPercentage(percent);
connectionService.requestMessage(message);
} else {
SetTBRMessage message = new SetTBRMessage();
message.setDuration(durationInMinutes);
message.setPercentage(percent);
connectionService.requestMessage(message);
}
result.isPercent(true)
.percent(percent)
.duration(durationInMinutes)
.success(true)
.enacted(true)
.comment(R.string.virtualpump_resultok);
aapsLogger.debug(LTag.PUMP, "XXXX Set Temp Basal timestamp: " + dateUtil.now() + " rate: " + percent + " duration: " + durationInMinutes);
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while setting TBR", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
@NonNull @Override
public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) {
PumpEnactResult result = cancelExtendedBolusOnly();
if (result.getSuccess())
result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_insight_disable_vibration, false));
try {
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception after delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception after delivering extended bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception after delivering extended bolus", e);
}
return result;
}
public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes, boolean disableVibration) {
PumpEnactResult result = new PumpEnactResult(getInjector());
try {
DeliverBolusMessage bolusMessage = new DeliverBolusMessage();
bolusMessage.setBolusType(BolusType.EXTENDED);
bolusMessage.setDuration(durationInMinutes);
bolusMessage.setExtendedAmount(insulin);
bolusMessage.setImmediateAmount(0);
bolusMessage.setVibration(disableVibration);
int bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId();
InsightBolusID insightBolusID = new InsightBolusID();
insightBolusID.bolusID = bolusID;
insightBolusID.timestamp = System.currentTimeMillis();
insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber();
databaseHelper.createOrUpdate(insightBolusID);
aapsLogger.debug(LTag.PUMP, "XXXX Set Extended timestamp: " + dateUtil.now() + " amount: " + insulin + "U duration: " + durationInMinutes + "BolusId: " + bolusID);
result.success(true).enacted(true).comment(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while delivering extended bolus", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
@NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult cancelEBResult = null;
if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly();
PumpEnactResult cancelTBRResult = cancelTempBasalOnly();
result.success((cancelEBResult == null || (cancelEBResult != null && cancelEBResult.getSuccess())) && cancelTBRResult.getSuccess()); //Fix a bug when Fake TBR is disabled and click on Cancel TBR button
result.enacted((cancelEBResult != null && cancelEBResult.getEnacted()) || cancelTBRResult.getEnacted());
result.comment(cancelEBResult != null ? cancelEBResult.getComment() : cancelTBRResult.getComment());
try {
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception after canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception after canceling TBR: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception after canceling TBR", e);
}
return result;
}
private PumpEnactResult cancelTempBasalOnly() {
PumpEnactResult result = new PumpEnactResult(getInjector());
try {
alertService.ignore(AlertType.WARNING_36);
connectionService.requestMessage(new CancelTBRMessage()).await();
result.success(true)
.enacted(true)
.isTempCancel(true);
confirmAlert(AlertType.WARNING_36);
alertService.ignore(null);
result.comment(R.string.virtualpump_resultok);
aapsLogger.debug(LTag.PUMP, "XXXX cancel Temp Basal time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()));
} catch (NoActiveTBRToCanceLException e) {
result.success(true);
result.comment(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling TBR: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while canceling TBR", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
@NonNull @Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = cancelExtendedBolusOnly();
try {
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception after canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception after canceling extended bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception after canceling extended bolus", e);
}
return result;
}
private PumpEnactResult cancelExtendedBolusOnly() {
PumpEnactResult result = new PumpEnactResult(getInjector());
try {
for (ActiveBolus activeBolus : activeBoluses) {
if (activeBolus.getBolusType() == BolusType.EXTENDED || activeBolus.getBolusType() == BolusType.MULTIWAVE) {
alertService.ignore(AlertType.WARNING_38);
CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
cancelBolusMessage.setBolusID(activeBolus.getBolusID());
connectionService.requestMessage(cancelBolusMessage).await();
confirmAlert(AlertType.WARNING_38);
alertService.ignore(null);
InsightBolusID insightBolusID = databaseHelper.getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(),
activeBolus.getBolusID(), System.currentTimeMillis());
if (insightBolusID != null) {
/* Search in Insight room database
PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id);
if (extendedBolus != null) {
extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000);
if (extendedBolus.durationInMinutes <= 0) {
final String _id = extendedBolus._id;
databaseHelper.delete(extendedBolus);
} else
treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
}
*/
aapsLogger.debug(LTag.PUMP, "XXXX cancel Extended Bolus time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " BolusId: " + activeBolus.getBolusID());
result.enacted(true).success(true);
}
}
}
result.success(true).comment(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while canceling extended bolus: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while canceling extended bolus", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
private void confirmAlert(AlertType alertType) {
try {
long started = dateUtil.now();
while (dateUtil.now() - started < 10000) {
GetActiveAlertMessage activeAlertMessage = connectionService.requestMessage(new GetActiveAlertMessage()).await();
if (activeAlertMessage.getAlert() != null) {
if (activeAlertMessage.getAlert().getAlertType() == alertType) {
ConfirmAlertMessage confirmMessage = new ConfirmAlertMessage();
confirmMessage.setAlertID(activeAlertMessage.getAlert().getAlertId());
connectionService.requestMessage(confirmMessage).await();
} else break;
}
}
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while confirming alert: " + e.getClass().getCanonicalName());
} catch (Exception e) {
aapsLogger.error("Exception while confirming alert", e);
}
}
@NonNull @Override
public JSONObject getJSONStatus(@NonNull Profile profile, @NonNull String profileName, @NonNull String version) {
long now = dateUtil.now();
if (connectionService == null) return new JSONObject();
if (dateUtil.now() - connectionService.getLastConnected() > (60 * 60 * 1000)) {
return new JSONObject();
}
final JSONObject pump = new JSONObject();
final JSONObject battery = new JSONObject();
final JSONObject status = new JSONObject();
final JSONObject extended = new JSONObject();
try {
status.put("timestamp", dateUtil.toISOString(connectionService.getLastConnected()));
extended.put("Version", version);
try {
extended.put("ActiveProfile", profileFunction.getProfileName());
} catch (Exception e) {
e.printStackTrace();
}
PumpSync.PumpState.TemporaryBasal tb = pumpSync.expectedPumpState().getTemporaryBasal();
if (tb != null) {
extended.put("TempBasalAbsoluteRate", convertedToAbsolute(tb, now, profile));
extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.getTimestamp()));
extended.put("TempBasalRemaining", getPlannedRemainingMinutes(tb));
}
PumpSync.PumpState.ExtendedBolus eb = pumpSync.expectedPumpState().getExtendedBolus();
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.getRate());
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.getTimestamp()));
extended.put("ExtendedBolusRemaining", getPlannedRemainingMinutes(eb));
}
extended.put("BaseBasalRate", getBaseBasalRate());
status.put("timestamp", dateUtil.toISOString(now));
pump.put("extended", extended);
if (statusLoaded) {
status.put("status", operatingMode != OperatingMode.STARTED ? "suspended" : "normal");
pump.put("status", status);
battery.put("percent", batteryStatus.getBatteryAmount());
pump.put("battery", battery);
pump.put("reservoir", cartridgeStatus.getRemainingAmount());
}
pump.put("clock", dateUtil.toISOString(now));
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return pump;
}
@NonNull @Override
public ManufacturerType manufacturer() {
return ManufacturerType.Roche;
}
@NonNull @Override
public PumpType model() {
return PumpType.ACCU_CHEK_INSIGHT;
}
@NonNull @Override
public String serialNumber() {
if (connectionService == null || alertService == null) return "Unknown";
return connectionService.getPumpSystemIdentification().getSerialNumber();
}
public PumpEnactResult stopPump() {
PumpEnactResult result = new PumpEnactResult(getInjector());
try {
SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage();
operatingModeMessage.setOperatingMode(OperatingMode.STOPPED);
connectionService.requestMessage(operatingModeMessage).await();
result.success(true).enacted(true);
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while stopping pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while stopping pump: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while stopping pump", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
public PumpEnactResult startPump() {
PumpEnactResult result = new PumpEnactResult(getInjector());
try {
SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage();
operatingModeMessage.setOperatingMode(OperatingMode.STARTED);
connectionService.requestMessage(operatingModeMessage).await();
result.success(true).enacted(true);
fetchStatus();
readHistory();
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while starting pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while starting pump: " + e.getClass().getCanonicalName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
aapsLogger.error("Exception while starting pump", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
public PumpEnactResult setTBROverNotification(boolean enabled) {
PumpEnactResult result = new PumpEnactResult(getInjector());
boolean valueBefore = tbrOverNotificationBlock.isEnabled();
tbrOverNotificationBlock.setEnabled(enabled);
try {
ParameterBlockUtil.writeConfigurationBlock(connectionService, tbrOverNotificationBlock);
result.success(true).enacted(true);
} catch (AppLayerErrorException e) {
tbrOverNotificationBlock.setEnabled(valueBefore);
aapsLogger.info(LTag.PUMP, "Exception while updating TBR notification block: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment(ExceptionTranslator.getString(context, e));
} catch (InsightException e) {
tbrOverNotificationBlock.setEnabled(valueBefore);
aapsLogger.info(LTag.PUMP, "Exception while updating TBR notification block: " + e.getClass().getSimpleName());
result.comment(ExceptionTranslator.getString(context, e));
} catch (Exception e) {
tbrOverNotificationBlock.setEnabled(valueBefore);
aapsLogger.error("Exception while updating TBR notification block", e);
result.comment(ExceptionTranslator.getString(context, e));
}
return result;
}
@NonNull @Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@NonNull @Override
public String shortStatus(boolean veryShort) {
StringBuilder ret = new StringBuilder();
if (connectionService.getLastConnected() != 0) {
long agoMsec = dateUtil.now() - connectionService.getLastConnected();
int agoMin = (int) (agoMsec / 60d / 1000d);
ret.append(resourceHelper.gs(R.string.short_status_last_connected, agoMin)).append("\n");
}
if (activeTBR != null) {
ret.append(resourceHelper.gs(R.string.short_status_tbr, activeTBR.getPercentage(),
activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration())).append("\n");
}
if (activeBoluses != null) for (ActiveBolus activeBolus : activeBoluses) {
if (activeBolus.getBolusType() == BolusType.STANDARD) continue;
ret.append(resourceHelper.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended,
activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration())).append("\n");
}
if (!veryShort && totalDailyDose != null) {
ret.append(resourceHelper.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal())).append("\n");
}
if (cartridgeStatus != null) {
ret.append(resourceHelper.gs(R.string.short_status_reservoir, cartridgeStatus.getRemainingAmount())).append("\n");
}
if (batteryStatus != null) {
ret.append(resourceHelper.gs(R.string.short_status_battery, batteryStatus.getBatteryAmount())).append("\n");
}
return ret.toString();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return sp.getBoolean(R.string.key_insight_enable_tbr_emulation, false);
}
@NonNull @Override
public PumpEnactResult loadTDDs() {
return new PumpEnactResult(getInjector()).success(true);
}
private void readHistory() {
try {
PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime();
String pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber();
timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(),
pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond());
// Move to Insight room database
InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial);
try {
List<HistoryEvent> historyEvents = new ArrayList<>();
if (historyOffset == null) {
StartReadingHistoryMessage startMessage = new StartReadingHistoryMessage();
startMessage.setDirection(HistoryReadingDirection.BACKWARD);
startMessage.setOffset(0xFFFFFFFF);
connectionService.requestMessage(startMessage).await();
historyEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents();
} else {
StartReadingHistoryMessage startMessage = new StartReadingHistoryMessage();
startMessage.setDirection(HistoryReadingDirection.FORWARD);
startMessage.setOffset(historyOffset.offset + 1);
connectionService.requestMessage(startMessage).await();
while (true) {
List<HistoryEvent> newEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents();
if (newEvents.size() == 0) break;
historyEvents.addAll(newEvents);
}
}
Collections.sort(historyEvents);
Collections.reverse(historyEvents);
if (historyOffset != null) processHistoryEvents(pumpSerial, historyEvents);
if (historyEvents.size() > 0) {
// Move to Insight room database
historyOffset = new InsightHistoryOffset();
historyOffset.pumpSerial = pumpSerial;
historyOffset.offset = historyEvents.get(0).getEventPosition();
databaseHelper.createOrUpdate(historyOffset);
}
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getSimpleName());
} catch (Exception e) {
aapsLogger.error("Exception while reading history", e);
} finally {
try {
connectionService.requestMessage(new StopReadingHistoryMessage()).await();
} catch (Exception ignored) {
}
}
} catch (AppLayerErrorException e) {
aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getSimpleName());
} catch (Exception e) {
aapsLogger.error("Exception while reading history", e);
}
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::readHistory", false)));
}
private void processHistoryEvents(String serial, List<HistoryEvent> historyEvents) {
List<TemporaryBasal> temporaryBasals = new ArrayList<>();
List<InsightPumpID> pumpStartedEvents = new ArrayList<>();
for (HistoryEvent historyEvent : historyEvents)
if (!processHistoryEvent(serial, temporaryBasals, pumpStartedEvents, historyEvent))
break;
Collections.reverse(temporaryBasals);
for (InsightPumpID pumpID : pumpStartedEvents) {
InsightPumpID stoppedEvent = databaseHelper.getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp);
if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue;
long tbrStart = stoppedEvent.timestamp + 10000;
TemporaryBasal temporaryBasal = new TemporaryBasal(
tbrStart,
pumpID.timestamp - tbrStart,
0,
false,
PumpSync.TemporaryBasalType.NORMAL,
pumpID.id,
pumpID.id);
temporaryBasals.add(temporaryBasal);
}
temporaryBasals.sort((o1, o2) -> (int) (o1.getTimestamp() - o2.getTimestamp()));
for (TemporaryBasal temporaryBasal : temporaryBasals) {
if (temporaryBasal.getRate() == 100.0) { // for Stop TBR event rate = 100.0
pumpSync.syncStopTemporaryBasalWithPumpId(
temporaryBasal.getTimestamp(),
temporaryBasal.getPumpId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
if (temporaryBasal.getRate() != 100.0){
Boolean resultdb = pumpSync.syncTemporaryBasalWithPumpId(
temporaryBasal.getTimestamp(),
temporaryBasal.getRate(),
temporaryBasal.getDuration(),
temporaryBasal.isAbsolute(),
temporaryBasal.getType(),
temporaryBasal.getPumpId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
}
}
private boolean processHistoryEvent(String serial, List<TemporaryBasal> temporaryBasals, List<InsightPumpID> pumpStartedEvents, HistoryEvent event) {
if (event instanceof DefaultDateTimeSetEvent) return false;
else if (event instanceof DateTimeChangedEvent)
processDateTimeChangedEvent((DateTimeChangedEvent) event);
else if (event instanceof CannulaFilledEvent)
processCannulaFilledEvent(serial, (CannulaFilledEvent) event);
else if (event instanceof TotalDailyDoseEvent)
processTotalDailyDoseEvent(serial, (TotalDailyDoseEvent) event);
else if (event instanceof TubeFilledEvent) processTubeFilledEvent(serial, (TubeFilledEvent) event);
else if (event instanceof SniffingDoneEvent)
processSniffingDoneEvent(serial, (SniffingDoneEvent) event);
else if (event instanceof PowerUpEvent) processPowerUpEvent(serial, (PowerUpEvent) event);
else if (event instanceof OperatingModeChangedEvent)
processOperatingModeChangedEvent(serial, pumpStartedEvents, (OperatingModeChangedEvent) event);
else if (event instanceof StartOfTBREvent)
processStartOfTBREvent(serial, temporaryBasals, (StartOfTBREvent) event);
else if (event instanceof EndOfTBREvent)
processEndOfTBREvent(serial, temporaryBasals, (EndOfTBREvent) event);
else if (event instanceof BolusProgrammedEvent)
processBolusProgrammedEvent(serial, (BolusProgrammedEvent) event);
else if (event instanceof BolusDeliveredEvent)
processBolusDeliveredEvent(serial, (BolusDeliveredEvent) event);
else if (event instanceof OccurrenceOfAlertEvent)
processOccurrenceOfAlertEvent((OccurrenceOfAlertEvent) event);
return true;
}
private void processDateTimeChangedEvent(DateTimeChangedEvent event) {
long timeAfter = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond());
long timeBefore = parseDate(event.getBeforeYear(), event.getBeforeMonth(), event.getBeforeDay(), event.getBeforeHour(), event.getBeforeMinute(), event.getBeforeSecond());
timeOffset -= timeAfter - timeBefore;
}
private void processCannulaFilledEvent(String serial, CannulaFilledEvent event) {
if (!sp.getBoolean(R.string.key_insight_log_site_changes, false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE);
aapsLogger.debug(LTag.PUMP, "XXXX event Site Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp,
DetailedBolusInfo.EventType.CANNULA_CHANGE,
"",
event.getEventPosition(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
private void processTotalDailyDoseEvent(String serial, TotalDailyDoseEvent event) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(0));
calendar.set(Calendar.YEAR, event.getTotalYear());
calendar.set(Calendar.MONTH, event.getTotalMonth() - 1);
calendar.set(Calendar.DAY_OF_MONTH, event.getTotalDay());
aapsLogger.debug(LTag.PUMP, "XXXX event Daily Dose event day: " + event.getTotalYear() + "/" + (event.getTotalMonth() - 1) + "/" + event.getTotalDay() + " Basal: " + event.getBasalTotal() + " Bolus: " + event.getBolusTotal());
pumpSync.createOrUpdateTotalDailyDose(
calendar.getTimeInMillis(),
event.getBolusTotal(),
event.getBasalTotal(),
0.0, // will be calculated automatically
null,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
private void processTubeFilledEvent(String serial, TubeFilledEvent event) {
if (!sp.getBoolean(R.string.key_insight_log_tube_changes, false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
logNote(timestamp, resourceHelper.gs(R.string.tube_changed));
aapsLogger.debug(LTag.PUMP, "XXXX event Tube Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp,
DetailedBolusInfo.EventType.INSULIN_CHANGE,
"",
event.getEventPosition(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
private void processSniffingDoneEvent(String serial, SniffingDoneEvent event) {
if (!sp.getBoolean(R.string.key_insight_log_reservoir_changes, false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE);
aapsLogger.debug(LTag.PUMP, "XXXX event Reservoir Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp,
DetailedBolusInfo.EventType.INSULIN_CHANGE,
"",
event.getEventPosition(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
private void processPowerUpEvent(String serial, PowerUpEvent event) {
if (!sp.getBoolean(R.string.key_insight_log_battery_changes, false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE);
aapsLogger.debug(LTag.PUMP, "XXXX event Battery Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp,
DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE,
"",
null,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
private void processOperatingModeChangedEvent(String serial, List<InsightPumpID> pumpStartedEvents, OperatingModeChangedEvent event) {
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
InsightPumpID pumpID = new InsightPumpID();
pumpID.eventID = event.getEventPosition();
pumpID.pumpSerial = serial;
pumpID.timestamp = timestamp;
switch (event.getNewValue()) {
case STARTED:
pumpID.eventType = "PumpStarted";
pumpStartedEvents.add(pumpID);
if (sp.getBoolean("insight_log_operating_mode_changes", false))
logNote(timestamp, resourceHelper.gs(R.string.pump_started));
aapsLogger.debug(LTag.PUMP, "XXXX event START Event TimeStamp: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
break;
case STOPPED:
pumpID.eventType = "PumpStopped";
if (sp.getBoolean("insight_log_operating_mode_changes", false))
logNote(timestamp, resourceHelper.gs(R.string.pump_stopped));
aapsLogger.debug(LTag.PUMP, "XXXX event STOP: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
break;
case PAUSED:
pumpID.eventType = "PumpPaused";
if (sp.getBoolean("insight_log_operating_mode_changes", false))
logNote(timestamp, resourceHelper.gs(R.string.pump_paused));
aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp));
break;
}
// Move to Insight room database
databaseHelper.createOrUpdate(pumpID);
}
private void processStartOfTBREvent(String serial, List<TemporaryBasal> temporaryBasals, StartOfTBREvent event) {
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
// Move to Insight room database
InsightPumpID pumpID = new InsightPumpID();
pumpID.eventID = event.getEventPosition();
pumpID.pumpSerial = serial;
pumpID.timestamp = timestamp;
pumpID.eventType = "StartOfTBR";
databaseHelper.createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new TemporaryBasal(
timestamp,
T.mins(event.getDuration()).msecs(),
event.getAmount(),
false,
PumpSync.TemporaryBasalType.NORMAL,
pumpID.id,
pumpID.eventID); // margin added because on several reeadHistory, timestamp could vary
temporaryBasals.add(temporaryBasal);
}
private void processEndOfTBREvent(String serial, List<TemporaryBasal> temporaryBasals, EndOfTBREvent event) {
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
// Move to Insight room database
InsightPumpID pumpID = new InsightPumpID();
pumpID.eventID = event.getEventPosition();
pumpID.pumpSerial = serial;
pumpID.eventType = "EndOfTBR";
pumpID.timestamp = timestamp;
databaseHelper.createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new PumpSync.PumpState.TemporaryBasal(
timestamp - 1500L,
0L,
100.0,
false,
PumpSync.TemporaryBasalType.NORMAL,
pumpID.id,
pumpID.eventID);
temporaryBasals.add(temporaryBasal);
}
private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) {
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
// Move to Insight room database
InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp);
if (bolusID != null && bolusID.endID != null) {
bolusID.startID = event.getEventPosition();
databaseHelper.createOrUpdate(bolusID);
return;
}
if (bolusID == null || bolusID.startID != null) {
bolusID = new InsightBolusID();
bolusID.timestamp = timestamp;
bolusID.bolusID = event.getBolusID();
bolusID.pumpSerial = serial;
}
bolusID.startID = event.getEventPosition();
databaseHelper.createOrUpdate(bolusID);
if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) {
pumpSync.syncBolusWithPumpId(
bolusID.timestamp,
event.getImmediateAmount(),
null,
bolusID.id,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) {
if (profileFunction.getProfile(bolusID.timestamp) != null)
pumpSync.syncExtendedBolusWithPumpId(
bolusID.timestamp,
event.getExtendedAmount(),
T.mins(event.getDuration()).msecs(),
isFakingTempsByExtendedBoluses(),
bolusID.id,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
}
private void processBolusDeliveredEvent(String serial, BolusDeliveredEvent event) {
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(),
event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset;
// Move to Insight room database
InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp);
if (bolusID == null || bolusID.endID != null) {
bolusID = new InsightBolusID();
bolusID.timestamp = startTimestamp;
bolusID.bolusID = event.getBolusID();
bolusID.pumpSerial = serial;
}
bolusID.endID = event.getEventPosition();
databaseHelper.createOrUpdate(bolusID);
if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) {
pumpSync.syncBolusWithPumpId(
bolusID.timestamp,
event.getImmediateAmount(),
null,
bolusID.id,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) {
if (event.getDuration() == 0) {
/*
ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(bolusID.id);
if (extendedBolus != null) {
final String _id = extendedBolus._id;
// if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id);
// else uploadQueue.removeByMongoId("dbAdd", _id);
databaseHelper.delete(extendedBolus);
}
*/
} else {
if (profileFunction.getProfile(bolusID.timestamp) != null)
pumpSync.syncExtendedBolusWithPumpId(
bolusID.timestamp,
event.getExtendedAmount(),
T.mins(event.getDuration()).msecs(),
isFakingTempsByExtendedBoluses(),
bolusID.id,
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
}
}
private void processOccurrenceOfAlertEvent(OccurrenceOfAlertEvent event) {
if (!sp.getBoolean(R.string.key_insight_log_alerts, false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
Integer code = null;
Integer title = null;
switch (event.getAlertType()) {
case ERROR_6:
code = R.string.alert_e6_code;
title = R.string.alert_e6_title;
break;
case ERROR_10:
code = R.string.alert_e10_code;
title = R.string.alert_e10_title;
break;
case ERROR_13:
code = R.string.alert_e13_code;
title = R.string.alert_e13_title;
break;
case MAINTENANCE_20:
code = R.string.alert_m20_code;
title = R.string.alert_m20_title;
break;
case MAINTENANCE_21:
code = R.string.alert_m21_code;
title = R.string.alert_m21_title;
break;
case MAINTENANCE_22:
code = R.string.alert_m22_code;
title = R.string.alert_m22_title;
break;
case MAINTENANCE_23:
code = R.string.alert_m23_code;
title = R.string.alert_m23_title;
break;
case MAINTENANCE_24:
code = R.string.alert_m24_code;
title = R.string.alert_m24_title;
break;
case MAINTENANCE_25:
code = R.string.alert_m25_code;
title = R.string.alert_m25_title;
break;
case MAINTENANCE_26:
code = R.string.alert_m26_code;
title = R.string.alert_m26_title;
break;
case MAINTENANCE_27:
code = R.string.alert_m27_code;
title = R.string.alert_m27_title;
break;
case MAINTENANCE_28:
code = R.string.alert_m28_code;
title = R.string.alert_m28_title;
break;
case MAINTENANCE_29:
code = R.string.alert_m29_code;
title = R.string.alert_m29_title;
break;
case MAINTENANCE_30:
code = R.string.alert_m30_code;
title = R.string.alert_m30_title;
break;
case WARNING_31:
code = R.string.alert_w31_code;
title = R.string.alert_w31_title;
break;
case WARNING_32:
code = R.string.alert_w32_code;
title = R.string.alert_w32_title;
break;
case WARNING_33:
code = R.string.alert_w33_code;
title = R.string.alert_w33_title;
break;
case WARNING_34:
code = R.string.alert_w34_code;
title = R.string.alert_w34_title;
break;
case WARNING_39:
code = R.string.alert_w39_code;
title = R.string.alert_w39_title;
break;
}
if (code != null)
logNote(timestamp, resourceHelper.gs(R.string.insight_alert_formatter, resourceHelper.gs(code), resourceHelper.gs(title)));
}
private long parseDate(int year, int month, int day, int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
return calendar.getTimeInMillis();
}
private void logNote(long date, String note) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber());
}
private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, int relativeMinute, int relativeSecond) {
if (relativeHour * 60 * 60 + relativeMinute * 60 + relativeSecond >= hour * 60 * 60 * minute * 60 + second)
day
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, relativeHour);
calendar.set(Calendar.MINUTE, relativeMinute);
calendar.set(Calendar.SECOND, relativeSecond);
return calendar.getTimeInMillis();
}
private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber());
}
@NonNull @Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, @NonNull Profile profile) {
percentRate.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().getMaxTempPercent(), resourceHelper.gs(R.string.pumplimit)), this);
return percentRate;
}
@NonNull @Override
public Constraint<Double> applyBolusConstraints(@NonNull Constraint<Double> insulin) {
if (!limitsFetched) return insulin;
insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this);
if (insulin.value() < minimumBolusAmount) {
//TODO: Add function to Constraints or use different approach
// This only works if the interface of the InsightPlugin is called last.
// If not, another constraint could theoretically set the value between 0 and minimumBolusAmount
insulin.set(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbolus), minimumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this);
}
return insulin;
}
@NonNull @Override
public Constraint<Double> applyExtendedBolusConstraints(@NonNull Constraint<Double> insulin) {
return applyBolusConstraints(insulin);
}
@Override
public void onStateChanged(InsightState state) {
if (state == InsightState.CONNECTED) {
statusLoaded = false;
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE)));
} else if (state == InsightState.NOT_PAIRED) {
connectionService.withdrawConnectionRequest(this);
statusLoaded = false;
profileBlocks = null;
operatingMode = null;
batteryStatus = null;
cartridgeStatus = null;
totalDailyDose = null;
activeBasalRate = null;
activeTBR = null;
activeBoluses = null;
tbrOverNotificationBlock = null;
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged", false)));
}
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventLocalInsightUpdateGUI()));
}
@Override
public void onPumpPaired() {
commandQueue.readStatus("Pump paired", null);
}
@Override
public void onTimeoutDuringHandshake() {
Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, resourceHelper.gs(R.string.timeout_during_handshake), Notification.URGENT);
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventNewNotification(notification)));
}
@Override
public boolean canHandleDST() {
return true;
}
} |
package com.alexrnl.commons.time;
import java.io.Serializable;
import java.sql.Date;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.alexrnl.commons.CommonsConstants;
import com.alexrnl.commons.utils.object.AutoCompare;
import com.alexrnl.commons.utils.object.AutoHashCode;
import com.alexrnl.commons.utils.object.Field;
/**
* Class representing a time (hours and minutes).<br />
* This time has <em>no limit</em>, which means that the number of hours may be anything (negative,
* more than 23, etc.). However, the number of minutes is kept between 0 and 60.<br />
* This class is immutable.
* @author Alex
*/
public class Time implements Serializable, Comparable<Time> {
/** Logger */
private static Logger lg = Logger.getLogger(Time.class.getName());
/** Serial Version UID */
private static final long serialVersionUID = -8846707527438298774L;
/** Number of minutes per hour */
private static final int MINUTES_PER_HOURS = 60;
/** The number of hours */
private final int hours;
/** The number of minutes */
private final int minutes;
/**
* Constructor #1.<br />
* Default constructor, set time to midnight.
*/
public Time () {
this(0);
}
/**
* Constructor #2.<br />
* Number of minutes will be set to 0.
* @param hours
* the number of hours.
*/
public Time (final int hours) {
this(hours, 0);
}
/**
* Constructor #3.<br />
* @param hours
* the number of hours.
* @param minutes
* the number of minutes.
*/
public Time (final int hours, final int minutes) {
super();
int cHours = hours;
int cMinutes = minutes;
// Correcting if minutes are below zero
while (cMinutes < 0) {
--cHours;
cMinutes += MINUTES_PER_HOURS;
}
this.hours = cHours + cMinutes / MINUTES_PER_HOURS;
this.minutes = cMinutes % MINUTES_PER_HOURS;
if (lg.isLoggable(Level.FINE)) {
lg.fine("Created time: " + this.hours + " h, " + this.minutes + " min");
}
}
/**
* Constructor #4.<br />
* @param timeStamp the number of seconds since January 1st, 1970.
*/
public Time (final long timeStamp) {
this(new Date(timeStamp));
}
/**
* Constructor #5.<br />
* Build the time from the date.
* @param date
* the date to use.
*/
public Time (final Date date) {
final Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTime(date);
hours = cal.get(Calendar.HOUR);
minutes = cal.get(Calendar.MINUTE);
}
/**
* Build a time based on a string.<br />
* The time format must be hours minutes (in that order) separated using any
* non-numerical character.<br />
* @param time
* the time set.
* @return the time matching the string.
*/
public static Time get (final String time) {
if (lg.isLoggable(Level.FINE)) {
lg.fine("Parsing time " + time);
}
final String[] hm = time.split(CommonsConstants.NON_DECIMAL_CHARACTER);
boolean first = true;
int hours = 0;
int minutes = 0;
for (final String s : hm) {
if (s.isEmpty()) {
continue;
}
if (first) {
hours = Integer.parseInt(s);
first = false;
continue;
}
minutes = Integer.parseInt(s);
break;
}
return new Time(hours, minutes);
}
/**
* Return the current time.
* @return a {@link Time} object matching the current time.
*/
public static Time getCurrent () {
return new Time(System.currentTimeMillis());
}
/**
* Return the attribute hours.
* @return the attribute hours.
*/
@Field
public int getHours () {
return hours;
}
/**
* Return the attribute minutes.
* @return the attribute minutes.
*/
@Field
public int getMinutes () {
return minutes;
}
/**
* Add the amount of time specified to the current time.<br />
* There is no maximum, so you may reach 25:48.
* @param time
* the time to add.
* @return the new time.
*/
public Time add (final Time time) {
return new Time(hours + time.hours, minutes + time.minutes);
}
/**
* Add the amount of time specified to the current time.<br />
* There is no maximum, so you may reach 25:48.
* @param time
* the time to add.
* @return the new time.
*/
public Time sub (final Time time) {
return new Time(hours - time.hours, minutes - time.minutes);
}
/*
* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo (final Time o) {
if (o == null) {
return 1;
}
if (hours > o.hours) {
return 1;
} else if (hours < o.hours) {
return -1;
}
if (minutes > o.minutes) {
return 1;
} else if (minutes < o.minutes) {
return -1;
}
assert equals(o);
return 0;
}
/**
* Check if the current time is after the specified time.<br />
* @param time
* the time used for reference.
* @return <code>true</code> if this time is after the reference time provided.
* @see #compareTo(Time)
*/
public boolean after (final Time time) {
return compareTo(time) > 0;
}
/**
* Check if the current time is before the specified time.<br />
* @param time
* the time used for reference.
* @return <code>true</code> if this time is before the reference time provided.
* @see #compareTo(Time)
*/
public boolean before (final Time time) {
return compareTo(time) < 0;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString () {
String h = Integer.toString(hours);
String m = Integer.toString(minutes);
if (h.length() < 2) {
h = Integer.valueOf(0) + h;
}
if (m.length() < 2) {
m = Integer.valueOf(0) + m;
}
return h + CommonsConstants.TIME_SEPARATOR + m;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode () {
return AutoHashCode.getInstance().hashCode(this);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals (final Object obj) {
if (!(obj instanceof Time)) {
return false;
}
return AutoCompare.getInstance().compare(this, (Time) obj);
}
} |
package com.alibaba.fastjson;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ASMJavaBeanDeserializer;
import com.alibaba.fastjson.parser.deserializer.FieldDeserializer;
import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.ASMJavaBeanSerializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.JavaBeanSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.util.IOUtils;
/**
* @author wenshao[szujobs@hotmail.com]
* @since 1.2.0
*/
public class JSONPath implements ObjectSerializer {
private static int CACHE_SIZE = 1024;
private static ConcurrentMap<String, JSONPath> pathCache = new ConcurrentHashMap<String, JSONPath>(128, 0.75f, 1);
private final String path;
private Segement[] segments;
private SerializeConfig serializeConfig;
private ParserConfig parserConfig;
public JSONPath(String path){
this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance());
}
public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig){
if (path == null || path.isEmpty()) {
throw new IllegalArgumentException();
}
this.path = path;
this.serializeConfig = serializeConfig;
this.parserConfig = parserConfig;
}
protected void init() {
if (segments != null) {
return;
}
if ("*".equals(path)) {
this.segments = new Segement[] { WildCardSegement.instance };
} else {
JSONPathParser parser = new JSONPathParser(path);
this.segments = parser.explain();
}
}
public Object eval(Object rootObject) {
if (rootObject == null) {
return null;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
currentObject = segments[i].eval(this, rootObject, currentObject);
}
return currentObject;
}
public boolean contains(Object rootObject) {
if (rootObject == null) {
return false;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
currentObject = segments[i].eval(this, rootObject, currentObject);
if (currentObject == null) {
return false;
}
}
return true;
}
@SuppressWarnings("rawtypes")
public boolean containsValue(Object rootObject, Object value) {
Object currentObject = eval(rootObject);
if (currentObject == value) {
return true;
}
if (currentObject == null) {
return false;
}
if (currentObject instanceof Iterable) {
Iterator it = ((Iterable) currentObject).iterator();
while (it.hasNext()) {
Object item = it.next();
if (eq(item, value)) {
return true;
}
}
return false;
}
return eq(currentObject, value);
}
public int size(Object rootObject) {
if (rootObject == null) {
return -1;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
currentObject = segments[i].eval(this, rootObject, currentObject);
}
return evalSize(currentObject);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void arrayAdd(Object rootObject, Object... values) {
if (values == null || values.length == 0) {
return;
}
if (rootObject == null) {
return;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
for (int i = 0; i < segments.length; ++i) {
if (i == segments.length - 1) {
parentObject = currentObject;
}
currentObject = segments[i].eval(this, rootObject, currentObject);
}
Object result = currentObject;
if (result == null) {
throw new JSONPathException("value not found in path " + path);
}
if (result instanceof Collection) {
Collection collection = (Collection) result;
for (Object value : values) {
collection.add(value);
}
return;
}
Class<?> resultClass = result.getClass();
Object newResult;
if (resultClass.isArray()) {
int length = Array.getLength(result);
Object descArray = Array.newInstance(resultClass.getComponentType(), length + values.length);
System.arraycopy(result, 0, descArray, 0, length);
for (int i = 0; i < values.length; ++i) {
Array.set(descArray, length + i, values[i]);
}
newResult = descArray;
} else {
throw new UnsupportedOperationException();
}
Segement lastSegement = segments[segments.length - 1];
if (lastSegement instanceof PropertySegement) {
PropertySegement propertySegement = (PropertySegement) lastSegement;
propertySegement.setValue(this, parentObject, newResult);
return;
}
if (lastSegement instanceof ArrayAccessSegement) {
((ArrayAccessSegement) lastSegement).setValue(this, parentObject, newResult);
return;
}
throw new UnsupportedOperationException();
}
public boolean set(Object rootObject, Object value) {
if (rootObject == null) {
return false;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
for (int i = 0; i < segments.length; ++i) {
if (i == segments.length - 1) {
parentObject = currentObject;
break;
}
currentObject = segments[i].eval(this, rootObject, currentObject);
if (currentObject == null) {
break;
}
}
if (parentObject == null) {
return false;
}
Segement lastSegement = segments[segments.length - 1];
if (lastSegement instanceof PropertySegement) {
PropertySegement propertySegement = (PropertySegement) lastSegement;
propertySegement.setValue(this, parentObject, value);
return true;
}
if (lastSegement instanceof ArrayAccessSegement) {
return ((ArrayAccessSegement) lastSegement).setValue(this, parentObject, value);
}
throw new UnsupportedOperationException();
}
public static Object eval(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
return jsonpath.eval(rootObject);
}
public static int size(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
Object result = jsonpath.eval(rootObject);
return jsonpath.evalSize(result);
}
public static boolean contains(Object rootObject, String path) {
if (rootObject == null) {
return false;
}
JSONPath jsonpath = compile(path);
return jsonpath.contains(rootObject);
}
public static boolean containsValue(Object rootObject, String path, Object value) {
JSONPath jsonpath = compile(path);
return jsonpath.containsValue(rootObject, value);
}
public static void arrayAdd(Object rootObject, String path, Object... values) {
JSONPath jsonpath = compile(path);
jsonpath.arrayAdd(rootObject, values);
}
public static void set(Object rootObject, String path, Object value) {
JSONPath jsonpath = compile(path);
jsonpath.set(rootObject, value);
}
public static JSONPath compile(String path) {
JSONPath jsonpath = pathCache.get(path);
if (jsonpath == null) {
jsonpath = new JSONPath(path);
if (pathCache.size() < CACHE_SIZE) {
pathCache.putIfAbsent(path, jsonpath);
jsonpath = pathCache.get(path);
}
}
return jsonpath;
}
public String getPath() {
return path;
}
static class JSONPathParser {
private final String path;
private int pos;
private char ch;
private int level;
public JSONPathParser(String path){
this.path = path;
next();
}
void next() {
ch = path.charAt(pos++);
}
boolean isEOF() {
return pos >= path.length();
}
Segement readSegement() {
while (!isEOF()) {
skipWhitespace();
if (ch == '@') {
next();
return SelfSegement.instance;
}
if (ch == '$') {
next();
continue;
}
if (ch == '.') {
next();
if (ch == '*') {
if (!isEOF()) {
next();
}
return WildCardSegement.instance;
}
String propertyName = readName();
if (ch == '(') {
next();
if (ch == ')') {
if (!isEOF()) {
next();
}
if ("size".equals(propertyName)) {
return SizeSegement.instance;
}
throw new UnsupportedOperationException();
}
throw new UnsupportedOperationException();
}
return new PropertySegement(propertyName);
}
if (ch == '[') {
return parseArrayAccess();
}
if (level == 0) {
String propertyName = readName();
return new PropertySegement(propertyName);
}
throw new UnsupportedOperationException();
}
return null;
}
public final void skipWhitespace() {
for (;;) {
if (ch < IOUtils.whitespaceFlags.length && IOUtils.whitespaceFlags[ch]) {
next();
continue;
} else {
break;
}
}
}
Segement parseArrayAccess() {
accept('[');
boolean predicateFlag = false;
if (ch == '?') {
next();
accept('(');
if (ch == '@') {
next();
accept('.');
}
predicateFlag = true;
}
if (predicateFlag || IOUtils.firstIdentifier(ch)) {
String propertyName = readName();
skipWhitespace();
if (predicateFlag && ch == ')') {
next();
accept(']');
return new FilterSegement(new NotNullSegement(propertyName));
}
if (ch == ']') {
next();
return new FilterSegement(new NotNullSegement(propertyName));
}
Operator op = readOp();
skipWhitespace();
if (op == Operator.BETWEEN || op == Operator.NOT_BETWEEN) {
final boolean not = (op == Operator.NOT_BETWEEN);
Object startValue = readValue();
String name = readName();
if (!"and".equalsIgnoreCase(name)) {
throw new JSONPathException(path);
}
Object endValue = readValue();
if (startValue == null || endValue == null) {
throw new JSONPathException(path);
}
if (isInt(startValue.getClass()) && isInt(endValue.getClass())) {
Filter filter = new IntBetweenSegement(propertyName, ((Number) startValue).longValue(),
((Number) endValue).longValue(), not);
return new FilterSegement(filter);
}
throw new JSONPathException(path);
}
if (op == Operator.IN || op == Operator.NOT_IN) {
final boolean not = (op == Operator.NOT_IN);
accept('(');
List<Object> valueList = new ArrayList<Object>();
{
Object value = readValue();
valueList.add(value);
for (;;) {
skipWhitespace();
if (ch != ',') {
break;
}
next();
value = readValue();
valueList.add(value);
}
accept(')');
if (predicateFlag) {
accept(')');
}
accept(']');
}
boolean isInt = true;
boolean isIntObj = true;
boolean isString = true;
for (Object item : valueList) {
if (item == null) {
if (isInt) {
isInt = false;
}
continue;
}
Class<?> clazz = item.getClass();
if (isInt
&& !(clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class)) {
isInt = false;
isIntObj = false;
}
if (isString && clazz != String.class) {
isString = false;
}
}
if (valueList.size() == 1 && valueList.get(0) == null) {
if (not) {
return new FilterSegement(new NotNullSegement(propertyName));
} else {
return new FilterSegement(new NullSegement(propertyName));
}
}
if (isInt) {
if (valueList.size() == 1) {
long value = ((Number) valueList.get(0)).longValue();
Operator intOp = not ? Operator.NE : Operator.EQ;
return new FilterSegement(new IntOpSegement(propertyName, value, intOp));
}
long[] values = new long[valueList.size()];
for (int i = 0; i < values.length; ++i) {
values[i] = ((Number) valueList.get(i)).longValue();
}
return new FilterSegement(new IntInSegement(propertyName, values, not));
}
if (isString) {
if (valueList.size() == 1) {
String value = (String) valueList.get(0);
Operator intOp = not ? Operator.NE : Operator.EQ;
return new FilterSegement(new StringOpSegement(propertyName, value, intOp));
}
String[] values = new String[valueList.size()];
valueList.toArray(values);
return new FilterSegement(new StringInSegement(propertyName, values, not));
}
if (isIntObj) {
Long[] values = new Long[valueList.size()];
for (int i = 0; i < values.length; ++i) {
Number item = (Number) valueList.get(i);
if (item != null) {
values[i] = item.longValue();
}
}
return new FilterSegement(new IntObjInSegement(propertyName, values, not));
}
throw new UnsupportedOperationException();
}
if (ch == '\'' || ch == '"') {
String strValue = readString();
if (predicateFlag) {
accept(')');
}
accept(']');
if (op == Operator.RLIKE) {
return new FilterSegement(new RlikeSegement(propertyName, strValue, false));
}
if (op == Operator.NOT_RLIKE) {
return new FilterSegement(new RlikeSegement(propertyName, strValue, true));
}
if (op == Operator.LIKE || op == Operator.NOT_LIKE) {
while (strValue.indexOf("%%") != -1) {
strValue = strValue.replaceAll("%%", "%");
}
final boolean not = (op == Operator.NOT_LIKE);
int p0 = strValue.indexOf('%');
if (p0 == -1) {
if (op == Operator.LIKE) {
op = Operator.EQ;
} else {
op = Operator.NE;
}
} else {
String[] items = strValue.split("%");
String startsWithValue = null;
String endsWithValue = null;
String[] containsValues = null;
if (p0 == 0) {
if (strValue.charAt(strValue.length() - 1) == '%') {
containsValues = new String[items.length - 1];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
} else {
endsWithValue = items[items.length - 1];
if (items.length > 2) {
containsValues = new String[items.length - 2];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
}
}
} else if (strValue.charAt(strValue.length() - 1) == '%') {
containsValues = items;
} else {
if (items.length == 1) {
startsWithValue = items[0];
} else if (items.length == 2) {
startsWithValue = items[0];
endsWithValue = items[1];
} else {
startsWithValue = items[0];
endsWithValue = items[items.length - 1];
containsValues = new String[items.length - 2];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
}
}
return new FilterSegement(new MatchSegement(propertyName, startsWithValue, endsWithValue,
containsValues, not));
}
}
return new FilterSegement(new StringOpSegement(propertyName, strValue, op));
}
if (isDigitFirst(ch)) {
long value = readLongValue();
if (predicateFlag) {
accept(')');
}
accept(']');
return new FilterSegement(new IntOpSegement(propertyName, value, op));
}
if (ch == 'n') {
String name = readName();
if ("null".equals(name)) {
if (predicateFlag) {
accept(')');
}
accept(']');
if (op == Operator.EQ) {
return new FilterSegement(new NullSegement(propertyName));
}
if (op == Operator.NE) {
return new FilterSegement(new NotNullSegement(propertyName));
}
throw new UnsupportedOperationException();
}
}
throw new UnsupportedOperationException();
// accept(')');
}
int start = pos - 1;
while (ch != ']' && !isEOF()) {
next();
}
String text = path.substring(start, pos - 1);
if (!isEOF()) {
accept(']');
}
return buildArraySegement(text);
}
protected long readLongValue() {
int beginIndex = pos - 1;
if (ch == '+' || ch == '-') {
next();
}
while (ch >= '0' && ch <= '9') {
next();
}
int endIndex = pos - 1;
String text = path.substring(beginIndex, endIndex);
long value = Long.parseLong(text);
return value;
}
protected Object readValue() {
skipWhitespace();
if (isDigitFirst(ch)) {
return readLongValue();
}
if (ch == '"' || ch == '\'') {
return readString();
}
if (ch == 'n') {
String name = readName();
if ("null".equals(name)) {
return null;
} else {
throw new JSONPathException(path);
}
}
throw new UnsupportedOperationException();
}
static boolean isDigitFirst(char ch) {
return ch == '-' || ch == '+' || (ch >= '0' && ch <= '9');
}
protected Operator readOp() {
Operator op = null;
if (ch == '=') {
next();
op = Operator.EQ;
} else if (ch == '!') {
next();
accept('=');
op = Operator.NE;
} else if (ch == '<') {
next();
if (ch == '=') {
next();
op = Operator.LE;
} else {
op = Operator.LT;
}
} else if (ch == '>') {
next();
if (ch == '=') {
next();
op = Operator.GE;
} else {
op = Operator.GT;
}
}
if (op == null) {
String name = readName();
if ("not".equalsIgnoreCase(name)) {
skipWhitespace();
name = readName();
if ("like".equalsIgnoreCase(name)) {
op = Operator.NOT_LIKE;
} else if ("rlike".equalsIgnoreCase(name)) {
op = Operator.NOT_RLIKE;
} else if ("in".equalsIgnoreCase(name)) {
op = Operator.NOT_IN;
} else if ("between".equalsIgnoreCase(name)) {
op = Operator.NOT_BETWEEN;
} else {
throw new UnsupportedOperationException();
}
} else {
if ("like".equalsIgnoreCase(name)) {
op = Operator.LIKE;
} else if ("rlike".equalsIgnoreCase(name)) {
op = Operator.RLIKE;
} else if ("in".equalsIgnoreCase(name)) {
op = Operator.IN;
} else if ("between".equalsIgnoreCase(name)) {
op = Operator.BETWEEN;
} else {
throw new UnsupportedOperationException();
}
}
}
return op;
}
String readName() {
skipWhitespace();
if (!IOUtils.firstIdentifier(ch)) {
throw new JSONPathException("illeal jsonpath syntax. " + path);
}
StringBuffer buf = new StringBuffer();
while (!isEOF()) {
if (ch == '\\') {
next();
buf.append(ch);
next();
continue;
}
boolean identifierFlag = IOUtils.isIdent(ch);
if (!identifierFlag) {
break;
}
buf.append(ch);
next();
}
if (isEOF() && IOUtils.isIdent(ch)) {
buf.append(ch);
}
String propertyName = buf.toString();
return propertyName;
}
String readString() {
char quoate = ch;
next();
int beginIndex = pos - 1;
while (ch != quoate && !isEOF()) {
next();
}
String strValue = path.substring(beginIndex, isEOF() ? pos : pos - 1);
accept(quoate);
return strValue;
}
void accept(char expect) {
if (ch != expect) {
throw new JSONPathException("expect '" + expect + ", but '" + ch + "'");
}
if (!isEOF()) {
next();
}
}
public Segement[] explain() {
if (path == null || path.isEmpty()) {
throw new IllegalArgumentException();
}
Segement[] segements = new Segement[8];
for (;;) {
Segement segment = readSegement();
if (segment == null) {
break;
}
segements[level++] = segment;
}
if (level == segements.length) {
return segements;
}
Segement[] result = new Segement[level];
System.arraycopy(segements, 0, result, 0, level);
return result;
}
Segement buildArraySegement(String indexText) {
final int indexTextLen = indexText.length();
final char firstChar = indexText.charAt(0);
final char lastChar = indexText.charAt(indexTextLen - 1);
int commaIndex = indexText.indexOf(',');
if (indexText.length() > 2 && firstChar == '\'' && lastChar == '\'') {
if (commaIndex == -1) {
String propertyName = indexText.substring(1, indexTextLen - 1);
return new PropertySegement(propertyName);
}
String[] indexesText = indexText.split(",");
String[] propertyNames = new String[indexesText.length];
for (int i = 0; i < indexesText.length; ++i) {
String indexesTextItem = indexesText[i];
propertyNames[i] = indexesTextItem.substring(1, indexesTextItem.length() - 1);
}
return new MultiPropertySegement(propertyNames);
}
int colonIndex = indexText.indexOf(':');
if (commaIndex == -1 && colonIndex == -1) {
int index = Integer.parseInt(indexText);
return new ArrayAccessSegement(index);
}
if (commaIndex != -1) {
String[] indexesText = indexText.split(",");
int[] indexes = new int[indexesText.length];
for (int i = 0; i < indexesText.length; ++i) {
indexes[i] = Integer.parseInt(indexesText[i]);
}
return new MultiIndexSegement(indexes);
}
if (colonIndex != -1) {
String[] indexesText = indexText.split(":");
int[] indexes = new int[indexesText.length];
for (int i = 0; i < indexesText.length; ++i) {
String str = indexesText[i];
if (str.isEmpty()) {
if (i == 0) {
indexes[i] = 0;
} else {
throw new UnsupportedOperationException();
}
} else {
indexes[i] = Integer.parseInt(str);
}
}
int start = indexes[0];
int end;
if (indexes.length > 1) {
end = indexes[1];
} else {
end = -1;
}
int step;
if (indexes.length == 3) {
step = indexes[2];
} else {
step = 1;
}
if (end >= 0 && end < start) {
throw new UnsupportedOperationException("end must greater than or equals start. start " + start
+ ", end " + end);
}
if (step <= 0) {
throw new UnsupportedOperationException("step must greater than zero : " + step);
}
return new RangeSegement(start, end, step);
}
throw new UnsupportedOperationException();
}
}
static interface Segement {
Object eval(JSONPath path, Object rootObject, Object currentObject);
}
// static class RootSegement implements Segement {
// public final static RootSegement instance = new RootSegement();
// public Object eval(JSONPath path, Object rootObject, Object currentObject) {
// return rootObject;
static class SelfSegement implements Segement {
public final static SelfSegement instance = new SelfSegement();
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
return currentObject;
}
}
static class SizeSegement implements Segement {
public final static SizeSegement instance = new SizeSegement();
public Integer eval(JSONPath path, Object rootObject, Object currentObject) {
return path.evalSize(currentObject);
}
}
static class PropertySegement implements Segement {
private final String propertyName;
public PropertySegement(String propertyName){
this.propertyName = propertyName;
}
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
return path.getPropertyValue(currentObject, propertyName, true);
}
public void setValue(JSONPath path, Object parent, Object value) {
path.setPropertyValue(parent, propertyName, value);
}
}
static class MultiPropertySegement implements Segement {
private final String[] propertyNames;
public MultiPropertySegement(String[] propertyNames){
this.propertyNames = propertyNames;
}
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
List<Object> fieldValues = new ArrayList<Object>(propertyNames.length);
for (String propertyName : propertyNames) {
Object fieldValue = path.getPropertyValue(currentObject, propertyName, true);
fieldValues.add(fieldValue);
}
return fieldValues;
}
}
static class WildCardSegement implements Segement {
public static WildCardSegement instance = new WildCardSegement();
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
return path.getPropertyValues(currentObject);
}
}
static class ArrayAccessSegement implements Segement {
private final int index;
public ArrayAccessSegement(int index){
this.index = index;
}
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
return path.getArrayItem(currentObject, index);
}
public boolean setValue(JSONPath path, Object currentObject, Object value) {
return path.setArrayItem(path, currentObject, index, value);
}
}
static class MultiIndexSegement implements Segement {
private final int[] indexes;
public MultiIndexSegement(int[] indexes){
this.indexes = indexes;
}
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
List<Object> items = new ArrayList<Object>(indexes.length);
for (int i = 0; i < indexes.length; ++i) {
Object item = path.getArrayItem(currentObject, indexes[i]);
items.add(item);
}
return items;
}
}
static class RangeSegement implements Segement {
private final int start;
private final int end;
private final int step;
public RangeSegement(int start, int end, int step){
this.start = start;
this.end = end;
this.step = step;
}
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
int size = SizeSegement.instance.eval(path, rootObject, currentObject);
int start = this.start >= 0 ? this.start : this.start + size;
int end = this.end >= 0 ? this.end : this.end + size;
List<Object> items = new ArrayList<Object>((end - start) / step + 1);
for (int i = start; i <= end && i < size; i += step) {
Object item = path.getArrayItem(currentObject, i);
items.add(item);
}
return items;
}
}
static class NotNullSegement implements Filter {
private final String propertyName;
public NotNullSegement(String propertyName){
this.propertyName = propertyName;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
return propertyValue != null;
}
}
static class NullSegement implements Filter {
private final String propertyName;
public NullSegement(String propertyName){
this.propertyName = propertyName;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
return propertyValue == null;
}
}
static class IntInSegement implements Filter {
private final String propertyName;
private final long[] values;
private final boolean not;
public IntInSegement(String propertyName, long[] values, boolean not){
this.propertyName = propertyName;
this.values = values;
this.not = not;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
return false;
}
if (propertyValue instanceof Number) {
long longPropertyValue = ((Number) propertyValue).longValue();
for (long value : values) {
if (value == longPropertyValue) {
return !not;
}
}
}
return not;
}
}
static class IntBetweenSegement implements Filter {
private final String propertyName;
private final long startValue;
private final long endValue;
private final boolean not;
public IntBetweenSegement(String propertyName, long startValue, long endValue, boolean not){
this.propertyName = propertyName;
this.startValue = startValue;
this.endValue = endValue;
this.not = not;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
return false;
}
if (propertyValue instanceof Number) {
long longPropertyValue = ((Number) propertyValue).longValue();
if (longPropertyValue >= startValue && longPropertyValue <= endValue) {
return !not;
}
}
return not;
}
}
static class IntObjInSegement implements Filter {
private final String propertyName;
private final Long[] values;
private final boolean not;
public IntObjInSegement(String propertyName, Long[] values, boolean not){
this.propertyName = propertyName;
this.values = values;
this.not = not;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
for (Long value : values) {
if (value == null) {
return !not;
}
}
return not;
}
if (propertyValue instanceof Number) {
long longPropertyValue = ((Number) propertyValue).longValue();
for (Long value : values) {
if (value == null) {
continue;
}
if (value.longValue() == longPropertyValue) {
return !not;
}
}
}
return not;
}
}
static class StringInSegement implements Filter {
private final String propertyName;
private final String[] values;
private final boolean not;
public StringInSegement(String propertyName, String[] values, boolean not){
this.propertyName = propertyName;
this.values = values;
this.not = not;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
for (String value : values) {
if (value == propertyValue) {
return !not;
} else if (value != null && value.equals(propertyValue)) {
return !not;
}
}
return not;
}
}
static class IntOpSegement implements Filter {
private final String propertyName;
private final long value;
private final Operator op;
public IntOpSegement(String propertyName, long value, Operator op){
this.propertyName = propertyName;
this.value = value;
this.op = op;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
return false;
}
if (!(propertyValue instanceof Number)) {
return false;
}
long longValue = ((Number) propertyValue).longValue();
if (op == Operator.EQ) {
return longValue == value;
} else if (op == Operator.NE) {
return longValue != value;
} else if (op == Operator.GE) {
return longValue >= value;
} else if (op == Operator.GT) {
return longValue > value;
} else if (op == Operator.LE) {
return longValue <= value;
} else if (op == Operator.LT) {
return longValue < value;
}
return false;
}
}
static class MatchSegement implements Filter {
private final String propertyName;
private final String startsWithValue;
private final String endsWithValue;
private final String[] containsValues;
private final int minLength;
private final boolean not;
public MatchSegement(String propertyName, String startsWithValue, String endsWithValue,
String[] containsValues, boolean not){
this.propertyName = propertyName;
this.startsWithValue = startsWithValue;
this.endsWithValue = endsWithValue;
this.containsValues = containsValues;
this.not = not;
int len = 0;
if (startsWithValue != null) {
len += startsWithValue.length();
}
if (endsWithValue != null) {
len += endsWithValue.length();
}
if (containsValues != null) {
for (String item : containsValues) {
len += item.length();
}
}
this.minLength = len;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
return false;
}
final String strPropertyValue = propertyValue.toString();
if (strPropertyValue.length() < minLength) {
return not;
}
int start = 0;
if (startsWithValue != null) {
if (!strPropertyValue.startsWith(startsWithValue)) {
return not;
}
start += startsWithValue.length();
}
if (containsValues != null) {
for (String containsValue : containsValues) {
int index = strPropertyValue.indexOf(containsValue, start);
if (index == -1) {
return not;
}
start = index + containsValue.length();
}
}
if (endsWithValue != null) {
if (!strPropertyValue.endsWith(endsWithValue)) {
return not;
}
}
return !not;
}
}
static class RlikeSegement implements Filter {
private final String propertyName;
private final Pattern pattern;
private final boolean not;
public RlikeSegement(String propertyName, String pattern, boolean not){
this.propertyName = propertyName;
this.pattern = Pattern.compile(pattern);
this.not = not;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (propertyValue == null) {
return false;
}
String strPropertyValue = propertyValue.toString();
Matcher m = pattern.matcher(strPropertyValue);
boolean match = m.matches();
if (not) {
match = !match;
}
return match;
}
}
static class StringOpSegement implements Filter {
private final String propertyName;
private final String value;
private final Operator op;
public StringOpSegement(String propertyName, String value, Operator op){
this.propertyName = propertyName;
this.value = value;
this.op = op;
}
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
Object propertyValue = path.getPropertyValue(item, propertyName, false);
if (op == Operator.EQ) {
return value.equals(propertyValue);
} else if (op == Operator.NE) {
return !value.equals(propertyValue);
}
if (propertyValue == null) {
return false;
}
int compareResult = value.compareTo(propertyValue.toString());
if (op == Operator.GE) {
return compareResult <= 0;
} else if (op == Operator.GT) {
return compareResult < 0;
} else if (op == Operator.LE) {
return compareResult >= 0;
} else if (op == Operator.LT) {
return compareResult > 0;
}
return false;
}
}
static enum Operator {
EQ, NE, GT, GE, LT, LE, LIKE, NOT_LIKE, RLIKE, NOT_RLIKE, IN, NOT_IN, BETWEEN, NOT_BETWEEN
}
static public class FilterSegement implements Segement {
private final Filter filter;
public FilterSegement(Filter filter){
super();
this.filter = filter;
}
@SuppressWarnings("rawtypes")
public Object eval(JSONPath path, Object rootObject, Object currentObject) {
if (currentObject == null) {
return null;
}
List<Object> items = new ArrayList<Object>();
if (currentObject instanceof Iterable) {
Iterator it = ((Iterable) currentObject).iterator();
while (it.hasNext()) {
Object item = it.next();
if (filter.apply(path, rootObject, currentObject, item)) {
items.add(item);
}
}
return items;
}
if (filter.apply(path, rootObject, currentObject, currentObject)) {
return currentObject;
}
return null;
}
}
static interface Filter {
boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item);
}
@SuppressWarnings("rawtypes")
protected Object getArrayItem(final Object currentObject, int index) {
if (currentObject == null) {
return null;
}
if (currentObject instanceof List) {
List list = (List) currentObject;
if (index >= 0) {
if (index < list.size()) {
return list.get(index);
}
return null;
} else {
if (Math.abs(index) <= list.size()) {
return list.get(list.size() + index);
}
return null;
}
}
if (currentObject.getClass().isArray()) {
int arrayLenth = Array.getLength(currentObject);
if (index >= 0) {
if (index < arrayLenth) {
return Array.get(currentObject, index);
}
return null;
} else {
if (Math.abs(index) <= arrayLenth) {
return Array.get(currentObject, arrayLenth + index);
}
return null;
}
}
throw new UnsupportedOperationException();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean setArrayItem(JSONPath path, Object currentObject, int index, Object value) {
if (currentObject instanceof List) {
List list = (List) currentObject;
if (index >= 0) {
list.set(index, value);
} else {
list.set(list.size() + index, value);
}
return true;
}
if (currentObject.getClass().isArray()) {
int arrayLenth = Array.getLength(currentObject);
if (index >= 0) {
if (index < arrayLenth) {
Array.set(currentObject, index, value);
}
} else {
if (Math.abs(index) <= arrayLenth) {
Array.set(currentObject, arrayLenth + index, value);
}
}
return true;
}
throw new UnsupportedOperationException();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Collection<Object> getPropertyValues(final Object currentObject) {
final Class<?> currentClass = currentObject.getClass();
JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass);
if (beanSerializer != null) {
try {
return beanSerializer.getFieldValues(currentObject);
} catch (Exception e) {
throw new JSONPathException("jsonpath error, path " + path, e);
}
}
if (currentObject instanceof Map) {
Map map = (Map) currentObject;
return map.values();
}
throw new UnsupportedOperationException();
}
static boolean eq(Object a, Object b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.getClass() == b.getClass()) {
return a.equals(b);
}
if (a instanceof Number) {
if (b instanceof Number) {
return eqNotNull((Number) a, (Number) b);
}
return false;
}
return a.equals(b);
}
@SuppressWarnings("rawtypes")
static boolean eqNotNull(Number a, Number b) {
Class clazzA = a.getClass();
boolean isIntA = isInt(clazzA);
Class clazzB = a.getClass();
boolean isIntB = isInt(clazzB);
if (isIntA && isIntB) {
return a.longValue() == b.longValue();
}
boolean isDoubleA = isDouble(clazzA);
boolean isDoubleB = isDouble(clazzB);
if ((isDoubleA && isDoubleB) || (isDoubleA && isIntA) || (isDoubleB && isIntA)) {
return a.doubleValue() == b.doubleValue();
}
return false;
}
protected static boolean isDouble(Class<?> clazzA) {
return clazzA == Float.class || clazzA == Double.class;
}
protected static boolean isInt(Class<?> clazzA) {
return clazzA == Byte.class || clazzA == Short.class || clazzA == Integer.class || clazzA == Long.class;
}
@SuppressWarnings("rawtypes")
protected Object getPropertyValue(final Object currentObject, final String propertyName, boolean strictMode) {
if (currentObject == null) {
return null;
}
if (currentObject instanceof Map) {
Map map = (Map) currentObject;
return map.get(propertyName);
}
final Class<?> currentClass = currentObject.getClass();
JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass);
if (beanSerializer != null) {
try {
return beanSerializer.getFieldValue(currentObject, propertyName);
} catch (Exception e) {
throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e);
}
}
if (currentObject instanceof List) {
List list = (List) currentObject;
List<Object> fieldValues = new ArrayList<Object>(list.size());
for (int i = 0; i < list.size(); ++i) {
Object obj = list.get(i);
Object itemValue = getPropertyValue(obj, propertyName, strictMode);
fieldValues.add(itemValue);
}
return fieldValues;
}
throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected boolean setPropertyValue(Object parent, String name, Object value) {
if (parent instanceof Map) {
((Map) parent).put(name, value);
return true;
}
if (parent instanceof List) {
for (Object element : (List) parent) {
if (element == null) {
continue;
}
setPropertyValue(element, name, value);
}
return true;
}
ObjectDeserializer derializer = parserConfig.getDeserializer(parent.getClass());
JavaBeanDeserializer beanDerializer = null;
if (derializer instanceof JavaBeanDeserializer) {
beanDerializer = (JavaBeanDeserializer) derializer;
} else if (derializer instanceof ASMJavaBeanDeserializer) {
beanDerializer = ((ASMJavaBeanDeserializer) derializer).getInnterSerializer();
}
if (beanDerializer != null) {
FieldDeserializer fieldDeserializer = beanDerializer.getFieldDeserializer(name);
if (fieldDeserializer == null) {
return false;
}
fieldDeserializer.setValue(parent, value);
return true;
}
throw new UnsupportedOperationException();
}
protected JavaBeanSerializer getJavaBeanSerializer(final Class<?> currentClass) {
JavaBeanSerializer beanSerializer = null;
{
ObjectSerializer serializer = serializeConfig.getObjectWriter(currentClass);
if (serializer instanceof JavaBeanSerializer) {
beanSerializer = (JavaBeanSerializer) serializer;
} else if (serializer instanceof ASMJavaBeanSerializer) {
beanSerializer = ((ASMJavaBeanSerializer) serializer).getJavaBeanSerializer();
}
}
return beanSerializer;
}
@SuppressWarnings("rawtypes")
int evalSize(Object currentObject) {
if (currentObject == null) {
return -1;
}
if (currentObject instanceof Collection) {
return ((Collection) currentObject).size();
}
if (currentObject instanceof Object[]) {
return ((Object[]) currentObject).length;
}
if (currentObject.getClass().isArray()) {
return Array.getLength(currentObject);
}
if (currentObject instanceof Map) {
int count = 0;
for (Object value : ((Map) currentObject).values()) {
if (value != null) {
count++;
}
}
return count;
}
JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentObject.getClass());
if (beanSerializer == null) {
return -1;
}
try {
List<Object> values = beanSerializer.getFieldValues(currentObject);
int count = 0;
for (int i = 0; i < values.size(); ++i) {
if (values.get(i) != null) {
count++;
}
}
return count;
} catch (Exception e) {
throw new JSONException("evalSize error : " + path, e);
}
}
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
throws IOException {
serializer.write(path);
}
} |
package org.openqa.selenium.qtwebkit.visualizer_tests;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.qtwebkit.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.NeedsLocalEnvironment;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.Callable;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.openqa.selenium.TestWaiter.waitFor;
import static org.openqa.selenium.WaitingConditions.*;
public class QtWebDriverVisualizerTest extends JUnit4TestBase {
protected WebDriver driver2;
private String wdIP = "http://localhost:9517";
private String wd2IP = "http://localhost:9520";
@Before
public void createDriver() throws Exception {
DesiredCapabilities capabilities = DesiredCapabilities.qtwebkit();
System.setProperty(QtWebDriverService.QT_DRIVER_EXE_PROPERTY, wdIP);
QtWebDriverExecutor webDriverExecutor = QtWebKitDriver.createDefaultExecutor();
driver = new QtWebKitDriver(webDriverExecutor, capabilities);
System.setProperty(QtWebDriverService.QT_DRIVER_EXE_PROPERTY, wd2IP);
QtWebDriverExecutor webDriver2Executor = QtWebKitDriver.createDefaultExecutor();
driver2 = new QtWebKitDriver(webDriver2Executor, capabilities);
}
@After
public void theerDown() throws Exception {
driver.quit();
driver2.quit();
}
@NeedsLocalEnvironment
@Test
public void canOpenLinkAndTypeText() {
driver.get(wd2IP + "/WebDriverJsDemo.html");
WebElement webDriverUrlPort = driver.findElement(By.name("webDriverUrlPort"));
webDriverUrlPort.clear();
webDriverUrlPort.sendKeys(wd2IP);
WebElement webPage = driver.findElement(By.name("webPage"));
webPage.clear();
webPage.sendKeys(pages.clicksPage);
String currentHandle = driver.getWindowHandle();
Set<String> currentWindowHandles = driver.getWindowHandles();
driver.findElement(By.xpath("//input[@value='Source']")).click();
waitFor(newWindowIsOpened(driver, currentWindowHandles));
driver2.findElement(By.id("normal")).click();
waitFor(pageTitleToBe(driver2, "XHTML Test Page"));
driver.findElement(By.xpath("//input[@value='Source']")).click();
waitFor(windowHandleCountToBe(driver, 2));
Set<String> allWindowHandles = driver.getWindowHandles();
assertEquals(2, allWindowHandles.size());
String handle = (String) allWindowHandles.toArray()[1];
if (currentHandle.equalsIgnoreCase(handle)) {
handle = (String) allWindowHandles.toArray()[0];
}
driver.switchTo().window(handle);
waitFor(windowToBeSwitchedToWithName(driver, handle));
String typingText = "TheTypingText";
String expectedText = "change" + typingText;
waitFor(elementToExist(driver, "username"));
WebElement inputField = driver.findElement(By.id("username"));
inputField.click();
waitFor(activeElementToBe(driver, inputField));
inputField.sendKeys(typingText);
inputField.click();
WebElement inputField2 = driver2.findElement(By.id("username"));
waitFor(elementValueToEqual(inputField2, expectedText));
assertThat(inputField2.getAttribute("value"), equalTo(expectedText));
}
public static Callable<WebElement> activeElementToBe(
final WebDriver driver, final WebElement expectedActiveElement) {
return new Callable<WebElement>() {
public WebElement call() throws Exception {
WebElement activeElement = driver.switchTo().activeElement();
if (expectedActiveElement.equals(activeElement)) {
return activeElement;
}
return null;
}
@Override
public String toString() {
return "active element to be: " + expectedActiveElement;
}
};
}
} |
package com.aragaer.yama;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
public class EditActivity extends Activity {
EditText memo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
memo = (EditText) findViewById(R.id.memo_edit);
memo.setText(getIntent().getStringExtra("memo"));
}
MenuItem.OnMenuItemClickListener cancelListener = new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
EditActivity.this.setResult(Activity.RESULT_CANCELED);
EditActivity.this.finish();
return true;
}
};
MenuItem.OnMenuItemClickListener doneListener = new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
EditActivity.this.saveMemo(memo.getText().toString());
EditActivity.this.finish();
return true;
}
};
MenuItem.OnMenuItemClickListener deleteListener = new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
EditActivity.this.saveMemo("");
EditActivity.this.finish();
return true;
}
};
private void saveMemo(String memo) {
Intent result = new Intent().putExtra("edited", memo);
Toast.makeText(this, memo.isEmpty() ? "Deleted" : "Saved", Toast.LENGTH_SHORT).show();
setResult(RESULT_OK, result);
}
@Override public void onBackPressed() {
saveMemo(memo.getText().toString());
finish();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem done = menu.add("Done");
MenuItem cancel = menu.add("Cancel");
MenuItem delete = menu.add("Delete");
done.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
done.setOnMenuItemClickListener(doneListener);
cancel.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
cancel.setOnMenuItemClickListener(cancelListener);
delete.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
delete.setOnMenuItemClickListener(deleteListener);
return true;
}
} |
package ly.snmp.core.monitor;
import ly.snmp.core.model.DataSet;
import ly.snmp.core.model.Oid;
import ly.snmp.core.model.TableColumnOid;
import ly.snmp.core.model.TableOid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Network implements Monitor {
private Map<String, Interface> interfaces;
private Map<String, Interface> sample;
private static final long UINT_MAX_VALUE = 4294967295l;
private static final String IF_INDEX = "1.3.6.1.2.1.2.2.1.1";// ifTable.ifIndex
private static final String IF_TYPE = "1.3.6.1.2.1.2.2.1.3";// ifTable.ifType
protected static final String IF_DESCR = "1.3.6.1.2.1.2.2.1.2";// ifTable.ifDescr
private static final String IF_MTU = "1.3.6.1.2.1.2.2.1.4";// ifTable.ifMtu
private static final String IF_SPEED = "1.3.6.1.2.1.2.2.1.5";// ifTable.ifSpeed
private static final String IF_PHY_ADDRESS = "1.3.6.1.2.1.2.2.1.6";// ifTable.ifPhysAddress
private static final String IF_LAST_CHANGE = "1.3.6.1.2.1.2.2.1.9";// ifTable.ifLastChange
private static final String IF_IN_OCTETS = "1.3.6.1.2.1.2.2.1.10"; // ifTable.ifInOctets
private static final String IF_OUT_OCTETS = "1.3.6.1.2.1.2.2.1.16"; // ifTable.ifOutOctets
private static final String IP_AD_ENT_ADDR = "1.3.6.1.2.1.4.20.1.1";
private static final String IP_AD_ENT_IF_INDEX = "1.3.6.1.2.1.4.20.1.2";// ipAddrTable.ipAdEntIfIndex
private Map<String, TableColumnOid> tableColumnOidMap;
private Set<Oid> oids;
private DataSet<Double> inRate, outRate;
public Network() {
oids = new HashSet<Oid>(Arrays.asList(new TableOid("1.3.6.1.2.1.2.2", IF_INDEX, IF_TYPE, IF_DESCR, IF_MTU, IF_SPEED, IF_PHY_ADDRESS, IF_LAST_CHANGE, IF_IN_OCTETS, IF_OUT_OCTETS),
new TableOid("1.3.6.1.2.1.4.20", IP_AD_ENT_ADDR, IP_AD_ENT_IF_INDEX)));
for (Oid oid : oids) {
for (TableColumnOid column : ((TableOid) oid).getColumns()) {
tableColumnOidMap.put(column.getOidString(), column);
}
}
interfaces = new HashMap<String, Interface>();
sample = new HashMap<String, Interface>();
}
@Override
public Set<Oid> getOIDs() {
return oids;
}
@Override
public void build(Long time) {
for (String index : tableColumnOidMap.get(IF_DESCR).getIndex()) {
String des = tableColumnOidMap.get(IF_DESCR).getValue(index);
Double inOcts = tableColumnOidMap.get(IF_IN_OCTETS).getValue(index);
Double outOcts = tableColumnOidMap.get(IF_OUT_OCTETS).getValue(index);
Double speed = tableColumnOidMap.get(IF_SPEED).getValue(index);
Double mtu = tableColumnOidMap.get(IF_MTU).getValue(index);
String phy = tableColumnOidMap.get(IF_PHY_ADDRESS).getValue(index);
Long change = tableColumnOidMap.get(IF_LAST_CHANGE).getValue(index);
Interface anInterface = sample.get(index);
if (anInterface != null && (anInterface.change != null && !anInterface.change.equals(change))) {
Interface instance = interfaces.get(index);
if (instance == null) {
instance = anInterface;
interfaces.put(index, anInterface);
}
long mill = System.currentTimeMillis() - anInterface.mill;
instance.inRate.appendData(time, calculateRateWithOverflowCheck(inOcts, anInterface.inOcts, mill, 1000d * 1000d, true));
instance.outRate.appendData(time, calculateRateWithOverflowCheck(outOcts, anInterface.outOcts, mill, 1000d * 1000d, true));
instance.phyAddress = phy;
instance.mtu = mtu;
instance.speed = speed;
instance.desc = des;
instance.ip = getIP(index);
} else {
anInterface = new Interface();
sample.put(index, anInterface);
}
anInterface.change = change;
anInterface.inOcts = inOcts;
anInterface.outOcts = outOcts;
anInterface.mill = System.currentTimeMillis();
}
}
private String getIP(String index) {
String ipIndex = "";
for (String key : tableColumnOidMap.get(IP_AD_ENT_IF_INDEX).getIndex()) {
if (index.equals(tableColumnOidMap.get(IP_AD_ENT_IF_INDEX).getValue(key))) {
ipIndex = key;
break;
}
}
return tableColumnOidMap.get(IP_AD_ENT_ADDR).getValue(ipIndex);
}
private Double calculateRateWithOverflowCheck(Double current, Double previous, Long mill, Double unit, boolean doNotGuess) {
Long seconds = mill / 1000;
if (current == null || previous == null || current == Double.MAX_VALUE || previous == Double.MAX_VALUE) {
return 0d;
}
double duration = 0;
if (doNotGuess) {
duration = current >= previous ? (current - previous) : 0d;
} else {
if (current < UINT_MAX_VALUE && previous < UINT_MAX_VALUE) {
current = (double) ((previous.longValue() & 0xFFFFFFFF00000000l) | current.longValue());
} else if (current > UINT_MAX_VALUE && previous < UINT_MAX_VALUE && (current - previous) > UINT_MAX_VALUE) {
previous = (double) ((current.longValue() & 0xFFFFFFFF00000000l) | previous.longValue());
} else if (current < previous && current < UINT_MAX_VALUE && previous < UINT_MAX_VALUE) {
current = current + UINT_MAX_VALUE;
}
if (current >= previous) {
duration = current - previous;
}
}
return duration / (seconds * unit);
}
public class Interface {
private double inOcts;
private double outOcts;
private double mtu;
private double speed;
private String desc;
private Long change;
private String ip;
private String phyAddress;
private DataSet<Double> inRate, outRate;
private Long mill;
public Interface() {
inRate = new DataSet<Double>("In Rate");
outRate = new DataSet<Double>("Out Rate");
}
public double getMtu() {
return mtu;
}
public double getSpeed() {
return speed;
}
public String getDesc() {
return desc;
}
public DataSet<Double> getInRate() {
return inRate;
}
public DataSet<Double> getOutRate() {
return outRate;
}
public String getPhyAddress() {
return phyAddress;
}
public String getIp() {
return ip;
}
}
} |
package com.intellij.codeInspection.bytecodeAnalysis;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class HardCodedPurity {
static final boolean AGGRESSIVE_HARDCODED_PURITY = Registry.is("java.annotations.inference.aggressive.hardcoded.purity", true);
private static final Set<Member> thisChangingMethods = ContainerUtil.set(
new Member("java/lang/Throwable", "fillInStackTrace", "()Ljava/lang/Throwable;")
);
// Assumed that all these methods are not only pure, but return object which could be safely modified
private static final Set<Member> pureMethods = ContainerUtil.set(
// Maybe overloaded and be not pure, but this would be definitely bad code style
// Used in Throwable(Throwable) ctor, so this helps to infer purity of many exception constructors
new Member("java/lang/Throwable", "toString", "()Ljava/lang/String;"),
// Cycle in AbstractStringBuilder ctor and this method disallows to infer the purity
new Member("java/lang/StringUTF16", "newBytesFor", "(I)[B"),
// Declared in final class StringBuilder
new Member("java/lang/StringBuilder", "toString", "()Ljava/lang/String;"),
new Member("java/lang/StringBuffer", "toString", "()Ljava/lang/String;"),
// Often used in generated code since Java 9; to avoid too many equations
new Member("java/util/Objects", "requireNonNull", "(Ljava/lang/Object;)Ljava/lang/Object;"),
// Caches hashCode, but it's better to suppose it's pure
new Member("java/lang/String", "hashCode", "()I"),
// Native
new Member("java/lang/Object", "getClass", "()Ljava/lang/Class;"),
new Member("java/lang/Class", "getComponentType", "()Ljava/lang/Class;"),
new Member("java/lang/reflect/Array", "newInstance", "(Ljava/lang/Class;I)Ljava/lang/Object;"),
new Member("java/lang/reflect/Array", "newInstance", "(Ljava/lang/Class;[I)Ljava/lang/Object;"),
new Member("java/lang/Float", "floatToRawIntBits", "(F)I"),
new Member("java/lang/Float", "intBitsToFloat", "(I)F"),
new Member("java/lang/Double", "doubleToRawLongBits", "(D)J"),
new Member("java/lang/Double", "longBitsToDouble", "(J)D")
);
private static final Map<Member, Set<EffectQuantum>> solutions = new HashMap<>();
private static final Set<EffectQuantum> thisChange = Set.of(EffectQuantum.ThisChangeQuantum);
static {
// Native
solutions.put(new Member("java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V"),
Set.of(new EffectQuantum.ParamChangeQuantum(2)));
solutions.put(new Member("java/lang/Object", "hashCode", "()I"), Set.of());
}
static HardCodedPurity getInstance() {
return Holder.INSTANCE;
}
Effects getHardCodedSolution(Member method) {
if (isThisChangingMethod(method)) {
return new Effects(isBuilderChainCall(method) ? DataValue.ThisDataValue : DataValue.UnknownDataValue1, thisChange);
}
else if (isPureMethod(method)) {
return new Effects(getReturnValueForPureMethod(method), Collections.emptySet());
}
else {
Set<EffectQuantum> effects = solutions.get(method);
return effects == null ? null : new Effects(DataValue.UnknownDataValue1, effects);
}
}
boolean isThisChangingMethod(Member method) {
return isBuilderChainCall(method) || thisChangingMethods.contains(method);
}
boolean isBuilderChainCall(Member method) {
// Those methods are virtual, thus contracts cannot be inferred automatically,
// but all possible implementations are controlled
// (only final classes j.l.StringBuilder and j.l.StringBuffer extend package-private j.l.AbstractStringBuilder)
return (method.internalClassName.equals("java/lang/StringBuilder") || method.internalClassName.equals("java/lang/StringBuffer")) &&
method.methodName.startsWith("append");
}
DataValue getReturnValueForPureMethod(Member method) {
String type = StringUtil.substringAfter(method.methodDesc, ")");
if (type != null && (type.length() == 1 || type.equals("Ljava/lang/String;") || type.equals("Ljava/lang/Class;"))) {
return DataValue.UnknownDataValue1;
}
return DataValue.LocalDataValue;
}
boolean isPureMethod(Member method) {
if (pureMethods.contains(method)) {
return true;
}
// Array clone() method is a special beast: it's qualifier class is array itself
if (method.internalClassName.startsWith("[") && method.methodName.equals("clone") && method.methodDesc.equals("()Ljava/lang/Object;")) {
return true;
}
return false;
}
boolean isOwnedField(FieldInsnNode fieldInsn) {
return fieldInsn.owner.equals("java/lang/AbstractStringBuilder") && fieldInsn.name.equals("value");
}
static class AggressiveHardCodedPurity extends HardCodedPurity {
static final Set<String> ITERABLES = ContainerUtil.set("java/lang/Iterable", "java/util/Collection",
"java/util/List", "java/util/Set", "java/util/ArrayList",
"java/util/HashSet", "java/util/AbstractList",
"java/util/AbstractSet", "java/util/TreeSet");
@Override
boolean isThisChangingMethod(Member method) {
if (method.methodName.equals("next") && method.methodDesc.startsWith("()") && method.internalClassName.equals("java/util/Iterator")) {
return true;
}
if (method.methodName.equals("initCause") && method.methodDesc.equals("(Ljava/lang/Throwable;)Ljava/lang/Throwable;") &&
method.internalClassName.startsWith("java/")) {
// Throwable.initCause is overridable. For Java classes, we assume that its contract is fixed
return true;
}
return super.isThisChangingMethod(method);
}
@Override
boolean isPureMethod(Member method) {
if (method.methodName.equals("toString") && method.methodDesc.equals("()Ljava/lang/String;")) return true;
if (method.methodName.equals("iterator") && method.methodDesc.equals("()Ljava/util/Iterator;") &&
ITERABLES.contains(method.internalClassName)) {
return true;
}
if (method.methodName.equals("hasNext") && method.methodDesc.equals("()Z") && method.internalClassName.equals("java/util/Iterator")) {
return true;
}
return super.isPureMethod(method);
}
}
private static final class Holder {
static final HardCodedPurity INSTANCE = AGGRESSIVE_HARDCODED_PURITY ? new AggressiveHardCodedPurity() : new HardCodedPurity();
}
} |
package com.google.appengine.tools.mapreduce.impl.shardedjob;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* Contains all logic to manage and run sharded jobs.
*
* This is a helper class for {@link ShardedJobServiceImpl} that implements
* all the functionality but assumes fixed types for {@code <T>} and
* {@code <R>}.
*
* @author ohler@google.com (Christian Ohler)
*
* @param <T> type of tasks that the job being processed consists of
* @param <R> type of intermediate and final results of the job being processed
*/
class ShardedJobRunner<T extends IncrementalTask<T, R>, R extends Serializable> {
// High-level overview:
// A sharded job is started with a given number of tasks, and every task
// has zero or one follow-up task; so the total number of tasks never
// increases. We assign each follow-up task the same taskId as its
// predecessor and reuse the same datastore entity to store it. So, each
// taskId really represents an entire chain of tasks, and the set of such task
// chains is known at startup.
// Each task chain is its own entity group to avoid contention.
// (We could extend the API later to allow more than one follow-up task, but
// that either leads to datastore contention, or makes finding the set of all
// task entities harder; so, since we don't need more than one follow-up task
// for now, we use a single entity for each chain of follow-up tasks.)
// There is also a single entity (in its own entity group) that holds the
// overall job state. It is updated only during initialization and from the
// controller.
// Partial results of each task and its chain of follow-up tasks are combined
// incrementally as the tasks complete. Partial results across chains are
// combined only when the job completes, or when getJobState() is called. (We
// could have the controller store the overall combined result, but there's a
// risk that it doesn't fit in a single entity, so we don't.
// ShardedJobStateImpl has a field for it and the Serializer supports it
// for completeness, but the value in the datastore is always null.)
// Worker and controller tasks and entities carry a strictly monotonic
// "sequence number" that allows each task to detect if its work has already
// been done (useful in case the task queue runs it twice). We schedule each
// task in the same datastore transaction that updates the sequence number in
// the entity.
// Each task also checks the job state entity to detect if the job has been
// aborted or deleted, and terminates if so.
// We make job startup idempotent by letting the caller specify the job id
// (rather than generating one randomly), and deriving task ids from it in a
// deterministic fashion. This makes it possible to schedule sharded jobs
// from Pipeline jobs with no danger of scheduling a duplicate sharded job if
// Pipeline or the task queue runs a job twice. (For example, a caller could
// derive the job id for the sharded job from the Pipeline job id.)
private static final Logger log = Logger.getLogger(ShardedJobRunner.class.getName());
static final String JOB_ID_PARAM = "job";
static final String TASK_ID_PARAM = "task";
static final String SEQUENCE_NUMBER_PARAM = "seq";
private static final DatastoreService DATASTORE = DatastoreServiceFactory.getDatastoreService();
ShardedJobRunner() {
}
private ShardedJobStateImpl<T, R> lookupJobState(Transaction tx, String jobId) {
try {
Entity entity = DATASTORE.get(tx, ShardedJobStateImpl.ShardedJobSerializer.makeKey(jobId));
return ShardedJobStateImpl.ShardedJobSerializer.<T, R>fromEntity(entity);
} catch (EntityNotFoundException e) {
return null;
}
}
private IncrementalTaskState<T, R> lookupTaskState(Transaction tx, String taskId) {
try {
Entity entity = DATASTORE.get(tx, IncrementalTaskState.Serializer.makeKey(taskId));
return IncrementalTaskState.Serializer.<T, R>fromEntity(entity);
} catch (EntityNotFoundException e) {
return null;
}
}
private static Iterator<Entity> lookupTasks(ShardedJobState<?, ?> jobState) {
final String jobId = jobState.getJobId();
final int taskCount = jobState.getTotalTaskCount();
return new AbstractIterator<Entity>() {
private int lastCount;
private Iterator<Map.Entry<Key, Entity>> lastBatch = Iterators.emptyIterator();
@Override protected Entity computeNext() {
if (lastBatch.hasNext()) {
Map.Entry<Key, Entity> entry = lastBatch.next();
Entity entity = entry.getValue();
Preconditions.checkState(entity != null, "%s: Missing task: %s", jobId, entry.getKey());
return entity;
} else if (lastCount >= taskCount) {
return endOfData();
}
int toRead = Math.min(20, taskCount - lastCount);
List<Key> keys = new ArrayList<>(toRead);
for (int i = 0; i < toRead; i++, lastCount++) {
Key key = IncrementalTaskState.Serializer.makeKey(getTaskId(jobId, lastCount));
keys.add(key);
}
lastBatch = DATASTORE.get(keys).entrySet().iterator();
return computeNext();
}
};
}
private static int countActiveTasks(ShardedJobState<?, ?> jobState) {
int count = 0;
for (Iterator<Entity> iter = lookupTasks(jobState); iter.hasNext(); ) {
Entity entity = iter.next();
if (IncrementalTaskState.Serializer.hasNextTask(entity)) {
count++;
}
}
return count;
}
private R aggregateState(ShardedJobController<T, R> controller, ShardedJobState<?, ?> jobState) {
ImmutableList.Builder<R> results = ImmutableList.builder();
for (Iterator<Entity> iter = lookupTasks(jobState); iter.hasNext(); ) {
Entity entity = iter.next();
IncrementalTaskState<T, R> state = IncrementalTaskState.Serializer.<T, R>fromEntity(entity);
results.add(state.getPartialResult());
}
return controller.combineResults(results.build());
}
private void scheduleControllerTask(Transaction tx, ShardedJobStateImpl<T, R> state) {
ShardedJobSettings settings = state.getSettings();
TaskOptions taskOptions = TaskOptions.Builder.withMethod(TaskOptions.Method.POST)
.url(settings.getControllerPath())
.param(JOB_ID_PARAM, state.getJobId())
.param(SEQUENCE_NUMBER_PARAM, String.valueOf(state.getNextSequenceNumber()))
.countdownMillis(settings.getMillisBetweenPolls());
if (settings.getControllerBackend() != null) {
taskOptions.header("Host",
BackendServiceFactory.getBackendService().getBackendAddress(
settings.getControllerBackend()));
}
QueueFactory.getQueue(settings.getControllerQueueName()).add(tx, taskOptions);
}
private void scheduleWorkerTask(Transaction tx,
ShardedJobSettings settings, IncrementalTaskState<T, R> state) {
TaskOptions taskOptions = TaskOptions.Builder.withMethod(TaskOptions.Method.POST)
.url(settings.getWorkerPath())
.param(TASK_ID_PARAM, state.getTaskId())
.param(JOB_ID_PARAM, state.getJobId())
.param(SEQUENCE_NUMBER_PARAM, String.valueOf(state.getNextSequenceNumber()));
if (settings.getWorkerBackend() != null) {
taskOptions.header("Host",
BackendServiceFactory.getBackendService().getBackendAddress(settings.getWorkerBackend()));
}
QueueFactory.getQueue(settings.getWorkerQueueName()).add(tx, taskOptions);
}
void pollTaskStates(String jobId, int sequenceNumber) {
ShardedJobStateImpl<T, R> jobState = lookupJobState(null, jobId);
if (jobState == null) {
log.info(jobId + ": Job gone");
return;
}
log.info("Polling task states for job " + jobId + ", sequence number " + sequenceNumber);
Preconditions.checkState(jobState.getStatus() != Status.INITIALIZING,
"Should be done initializing: %s", jobState);
if (!jobState.getStatus().isActive()) {
log.info(jobId + ": Job no longer active: " + jobState);
return;
}
if (jobState.getNextSequenceNumber() != sequenceNumber) {
Preconditions.checkState(jobState.getNextSequenceNumber() > sequenceNumber,
"%s: Job state is from the past: %s", jobId, jobState);
log.info(jobId + ": Poll sequence number " + sequenceNumber
+ " already completed: " + jobState);
return;
}
long currentPollTimeMillis = System.currentTimeMillis();
int activeTasks = countActiveTasks(jobState);
jobState.setMostRecentUpdateTimeMillis(currentPollTimeMillis);
jobState.setActiveTaskCount(activeTasks);
if (activeTasks == 0) {
jobState.setStatus(Status.DONE);
R aggregateResult = aggregateState(jobState.getController(), jobState);
jobState.getController().completed(aggregateResult);
} else {
jobState.setNextSequenceNumber(sequenceNumber + 1);
}
log.fine(jobId + ": Writing " + jobState);
Transaction tx = DATASTORE.beginTransaction();
try {
ShardedJobStateImpl<T, R> existing = lookupJobState(tx, jobId);
if (existing == null) {
log.info(jobId + ": Job gone after poll");
return;
}
if (existing.getNextSequenceNumber() != sequenceNumber) {
log.info(jobId + ": Job processed concurrently; was sequence number " + sequenceNumber
+ ", now " + existing.getNextSequenceNumber());
return;
}
DATASTORE.put(tx, ShardedJobStateImpl.ShardedJobSerializer.toEntity(jobState));
if (jobState.getStatus().isActive()) {
scheduleControllerTask(tx, jobState);
}
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
void runTask(String taskId, String jobId, int sequenceNumber) {
ShardedJobState<T, R> jobState = lookupJobState(null, jobId);
if (jobState == null) {
log.info(taskId + ": Job gone");
return;
}
if (!jobState.getStatus().isActive()) {
log.info(taskId + ": Job no longer active: " + jobState);
return;
}
IncrementalTaskState<T, R> taskState = lookupTaskState(null, taskId);
if (taskState == null) {
log.info(taskId + ": Task gone");
return;
}
log.info("Running task " + taskId + " (job " + jobId + "), sequence number " + sequenceNumber);
if (taskState.getNextSequenceNumber() != sequenceNumber) {
Preconditions.checkState(taskState.getNextSequenceNumber() > sequenceNumber,
"%s: Task state is from the past: %s", taskId, taskState);
log.info(taskId + ": Task sequence number " + sequenceNumber
+ " already completed: " + taskState);
return;
}
Preconditions.checkState(taskState.getNextTask() != null, "%s: Next task is null",
taskState);
log.fine("About to run task: " + taskState);
IncrementalTask.RunResult<T, R> result = taskState.getNextTask().run();
taskState.setPartialResult(
jobState.getController().combineResults(
ImmutableList.of(taskState.getPartialResult(), result.getPartialResult())));
taskState.setNextTask(result.getFollowupTask());
taskState.setMostRecentUpdateMillis(System.currentTimeMillis());
taskState.setNextSequenceNumber(sequenceNumber + 1);
// TOOD: retries. we should only have one writer, so should have no
// concurrency exceptions, but we should guard against other RPC failures.
Transaction tx = DATASTORE.beginTransaction();
Entity entity = null;
try {
IncrementalTaskState<?, ?> existing = lookupTaskState(tx, taskId);
if (existing == null) {
log.info(taskId + ": Task disappeared while processing");
return;
}
if (existing.getNextSequenceNumber() != sequenceNumber) {
log.info(taskId + ": Task processed concurrently; was sequence number " + sequenceNumber
+ ", now " + existing.getNextSequenceNumber());
return;
}
entity = IncrementalTaskState.Serializer.toEntity(taskState);
DATASTORE.put(tx, entity);
if (result.getFollowupTask() != null) {
scheduleWorkerTask(tx, jobState.getSettings(), taskState);
}
tx.commit();
} catch (Exception e) {
throw new RuntimeException("Failed to write end of slice. Serialzing next task: "
+ taskState.getNextTask() + " Result: " + taskState.getPartialResult()
+ "Serializing entity: " + entity, e);
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
private static String getTaskId(String jobId, int taskNumber) {
return jobId + "-task" + taskNumber;
}
private void createTasks(ShardedJobController<T, R> controller,
ShardedJobSettings settings, String jobId,
List<? extends T> initialTasks,
long startTimeMillis) {
log.info(jobId + ": Creating " + initialTasks.size() + " tasks");
// It's tempting to try to do a large batch put and a large batch enqueue,
// but I don't see a way to make the batch put idempotent; we don't want to
// clobber entities that record progress that has already been made.
for (int i = 0; i < initialTasks.size(); i++) {
String taskId = getTaskId(jobId, i);
Transaction tx = DATASTORE.beginTransaction();
try {
IncrementalTaskState<T, R> existing = lookupTaskState(tx, taskId);
if (existing != null) {
log.info(jobId + ": Task already exists: " + existing);
continue;
}
IncrementalTaskState<T, R> taskState =
new IncrementalTaskState<T, R>(taskId, jobId, startTimeMillis,
initialTasks.get(i), controller.combineResults(ImmutableList.<R>of()));
DATASTORE.put(tx, IncrementalTaskState.Serializer.toEntity(taskState));
scheduleWorkerTask(tx, settings, taskState);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
}
// Returns true on success, false if the job is already finished according to
// the datastore.
private boolean writeInitialJobState(ShardedJobStateImpl<T, R> jobState) {
String jobId = jobState.getJobId();
log.fine(jobId + ": Writing initial job state");
Transaction tx = DATASTORE.beginTransaction();
try {
ShardedJobState<T, R> existing = lookupJobState(tx, jobId);
if (existing == null) {
DATASTORE.put(tx, ShardedJobStateImpl.ShardedJobSerializer.toEntity(jobState));
tx.commit();
} else {
if (!existing.getStatus().isActive()) {
// Maybe a concurrent initialization finished before us, and the
// job was very quick and has already completed as well.
log.info(jobId + ": Attempt to reinitialize inactive job: " + existing);
return false;
}
log.info(jobId + ": Reinitializing job: " + existing);
}
return true;
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
private void scheduleControllerAndMarkActive(ShardedJobStateImpl<T, R> jobState) {
String jobId = jobState.getJobId();
log.fine(jobId + ": Scheduling controller and marking active");
Transaction tx = DATASTORE.beginTransaction();
try {
ShardedJobStateImpl<T, R> existing = lookupJobState(tx, jobId);
if (existing == null) {
// Someone cleaned it up while we were still initializing.
log.warning(jobId + ": Job disappeared while initializing");
return;
}
if (existing.getStatus() != Status.INITIALIZING) {
// Maybe a concurrent initialization finished first, or someone
// cancelled it while we were initializing.
log.info(jobId + ": Job changed status while initializing: " + jobState);
return;
}
DATASTORE.put(tx, ShardedJobStateImpl.ShardedJobSerializer.toEntity(jobState));
scheduleControllerTask(tx, jobState);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
log.info(jobId + ": Started");
}
void startJob(String jobId,
List<? extends T> rawInitialTasks,
ShardedJobController<T, R> controller,
ShardedJobSettings settings) {
long startTimeMillis = System.currentTimeMillis();
// ImmutableList.copyOf() checks for null elements.
List<? extends T> initialTasks = ImmutableList.copyOf(rawInitialTasks);
ShardedJobStateImpl<T, R> jobState = new ShardedJobStateImpl<T, R>(
jobId, controller, settings, initialTasks.size(), startTimeMillis, Status.INITIALIZING,
null);
if (initialTasks.isEmpty()) {
log.info(jobId + ": No tasks, immediately complete: " + controller);
jobState.setStatus(Status.DONE);
DATASTORE.put(ShardedJobStateImpl.ShardedJobSerializer.toEntity(jobState));
controller.completed(controller.combineResults(ImmutableList.<R>of()));
return;
}
if (!writeInitialJobState(jobState)) {
return;
}
createTasks(controller, settings, jobId, initialTasks, startTimeMillis);
jobState.setStatus(Status.RUNNING);
scheduleControllerAndMarkActive(jobState);
}
ShardedJobState<T, R> getJobState(String jobId) {
ShardedJobStateImpl<T, R> jobState = lookupJobState(null, jobId);
if (jobState == null) {
return null;
}
// We don't pre-aggregate the result across all tasks since it might not fit
// in one entity. The stored value is always null.
Preconditions.checkState(jobState.getAggregateResult() == null,
"%s: Non-null aggregate result: %s", jobState, jobState.getAggregateResult());
R aggregateResult = aggregateState(jobState.getController(), jobState);
jobState.setAggregateResult(aggregateResult);
return jobState;
}
void abortJob(String jobId) {
log.info(jobId + ": Aborting");
Transaction tx = DATASTORE.beginTransaction();
try {
ShardedJobStateImpl<T, R> jobState = lookupJobState(tx, jobId);
if (jobState == null || !jobState.getStatus().isActive()) {
log.info(jobId + ": Job not active, not aborting: " + jobState);
return;
}
jobState.setStatus(Status.ABORTED);
DATASTORE.put(tx, ShardedJobStateImpl.ShardedJobSerializer.toEntity(jobState));
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
} |
package com.e16din.lightutils.utils;
import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Build;
public class U extends SdkUtils {
private U() {
}
// public static boolean checkGooglePlayServiceAvailability(Context context) {
// GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
// int result = googleAPI.isGooglePlayServicesAvailable(context);
// return result == ConnectionResult.SUCCESS;
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| "google_sdk".equals(Build.PRODUCT);
}
public static boolean isGpsEnabled(Context context) {
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public static boolean isOnline(Context context) {
if (context == null)
return false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
public static boolean runIfOnline(boolean isOnline, Context context, Runnable callback) {
boolean result = isOnline(context);
if (result == isOnline)
callback.run();
return result;
}
} |
package com.fishercoder.solutions;
import java.util.Stack;
/**
* 20. Valid Parentheses
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
*
* An input string is valid if:
*
* 1. Open brackets must be closed by the same type of brackets.
* 2. Open brackets must be closed in the correct order.
*
* Note that an empty string is also considered valid.
*
* Example 1:
* Input: "()"
* Output: true
*
* Example 2:
* Input: "()[]{}"
* Output: true
*
* Example 3:
* Input: "(]"
* Output: false
*
* Example 4:
* Input: "([)]"
* Output: false
*
* Example 5:
* Input: "{[]}"
* Output: true
* */
public class _20 {
public static class Solution1 {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty()) {
return false;
} else {
if (stack.peek() == '(' && s.charAt(i) != ')') {
return false;
} else if (stack.peek() == '{' && s.charAt(i) != '}') {
return false;
} else if (stack.peek() == '[' && s.charAt(i) != ']') {
return false;
}
stack.pop();
}
}
}
return stack.isEmpty();
}
}
} |
package com.modthemod.modthemod;
import java.util.logging.Logger;
import com.modthemod.api.Game;
import com.modthemod.api.platform.Platform;
import com.modthemod.modthemod.entity.MEntityManager;
import com.modthemod.modthemod.event.MEventManager;
import com.modthemod.modthemod.property.MTypeManager;
/**
* Represents the game.
*/
public class MGame implements Game {
/**
* The platform of the game.
*/
private final Platform platform;
private final MEntityManager entityManager;
private final MEventManager eventManager;
private final MTypeManager typeManager;
public MGame(Platform platform) {
this.platform = platform;
this.entityManager = new MEntityManager(this);
this.eventManager = new MEventManager(this);
this.typeManager = new MTypeManager(this);
}
@Override
public Platform getPlatform() {
return platform;
}
@Override
public MEntityManager getEntityManager() {
return entityManager;
}
@Override
public MEventManager getEventManager() {
return eventManager;
}
@Override
public MTypeManager getTypeManager() {
return typeManager;
}
@Override
public Logger getLogger() {
return platform.getLogger();
}
} |
package com.qriosity.config;
import java.util.ArrayList;
import java.util.List;
import com.qriosity.servlet.filter.JsonpFilter;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.JacksonObjectMapperFactoryBean;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author yoandy
* @since 10/5/13
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.qriosity.mvc.controller","com.qriosity.service"})
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { |
package com.restOne.hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.restOne.configurationExample.AnnotationConfiguration;
import com.restOne.configurationExample.TypeSafeConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ComponentScan(basePackages = { "com.restOne.hello", "com.restOne.greeting", "com.restOne.configurationExample" })
@SpringBootApplication
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
final TypeSafeConfiguration typeSafeConfiguration = ctx.getBean(TypeSafeConfiguration.class);
final AnnotationConfiguration annotationConfiguration = ctx.getBean(AnnotationConfiguration.class);
info("Application initialized with the following configuration:");
info(typeSafeConfiguration.toString());
info(annotationConfiguration.toString());
System.out.println();
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx, RecipeRepository repository) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
LOG.debug("inspected the beans");
};
}
private static void info(String text) {
System.out.println(String.format("Application.java: %s", text));
}
} |
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public final class MainPanel extends JPanel {
private MainPanel() {
super();
UIManager.put("CheckBoxMenuItem.doNotCloseOnMouseClick", true); // Java 9
JPopupMenu popup = new JPopupMenu();
popup.addMouseWheelListener(InputEvent::consume);
popup.add(Box.createHorizontalStrut(200));
addCheckBoxAndSlider(popup);
addCheckBoxAndToggleSlider(popup);
addCheckBoxMenuItemAndSlider(popup);
JMenu menu = new JMenu("JSlider");
menu.getPopupMenu().addMouseWheelListener(InputEvent::consume);
menu.add(Box.createHorizontalStrut(200));
addCheckBoxAndSlider(menu);
addCheckBoxAndToggleSlider(menu);
addCheckBoxMenuItemAndSlider(menu);
JMenuBar mb = new JMenuBar();
mb.add(LookAndFeelUtil.createLookAndFeelMenu());
mb.add(menu);
EventQueue.invokeLater(() -> getRootPane().setJMenuBar(mb));
setComponentPopupMenu(popup);
setPreferredSize(new Dimension(320, 240));
}
private static void addCheckBoxAndSlider(JComponent popup) {
JSlider slider = makeSlider();
slider.setEnabled(false);
JCheckBox check = makeCheckBox();
check.addActionListener(e -> slider.setEnabled(((JCheckBox) e.getSource()).isSelected()));
JMenuItem mi = new JMenuItem(" ");
mi.setLayout(new BorderLayout());
mi.add(check, BorderLayout.WEST);
mi.add(slider);
popup.add(mi);
}
private static void addCheckBoxAndToggleSlider(JComponent popup) {
JMenuItem slider = makeBorderLayoutMenuItem();
slider.add(makeSlider());
JCheckBox check = makeCheckBox();
check.setText("JCheckBox + JSlider");
check.addActionListener(e -> {
AbstractButton b = (AbstractButton) e.getSource();
slider.setVisible(b.isSelected());
Container p = SwingUtilities.getAncestorOfClass(JPopupMenu.class, b);
if (p instanceof JPopupMenu) {
((JPopupMenu) p).pack();
}
});
JMenuItem mi = new JMenuItem(" ");
mi.setLayout(new BorderLayout());
mi.add(check);
popup.add(mi);
popup.add(slider);
}
private static void addCheckBoxMenuItemAndSlider(JComponent popup) {
JMenuItem slider = makeBorderLayoutMenuItem();
slider.add(makeSlider());
JMenuItem mi = new JCheckBoxMenuItem("JCheckBoxMenuItem + JSlider");
mi.addActionListener(e -> {
AbstractButton b = (AbstractButton) e.getSource();
slider.setVisible(b.isSelected());
Container p = SwingUtilities.getAncestorOfClass(JPopupMenu.class, b);
if (p instanceof JPopupMenu) {
p.setVisible(true);
((JPopupMenu) p).pack();
}
});
popup.add(mi);
popup.add(slider);
}
private static JSlider makeSlider() {
UIManager.put("Slider.paintValue", Boolean.FALSE); // GTKLookAndFeel
UIManager.put("Slider.focus", UIManager.get("Slider.background"));
JSlider slider = new JSlider();
slider.addMouseWheelListener(e -> {
JSlider s = (JSlider) e.getComponent();
if (s.isEnabled()) {
BoundedRangeModel m = s.getModel();
m.setValue(m.getValue() - e.getWheelRotation());
}
e.consume();
});
return slider;
}
private static JCheckBox makeCheckBox() {
return new JCheckBox() {
private transient MouseInputListener handler;
@Override public void updateUI() {
removeMouseListener(handler);
removeMouseMotionListener(handler);
super.updateUI();
handler = new DispatchParentHandler();
addMouseListener(handler);
addMouseMotionListener(handler);
setFocusable(false);
setOpaque(false);
}
};
}
private static JMenuItem makeBorderLayoutMenuItem() {
JMenuItem p = new JMenuItem(" ");
p.setLayout(new BorderLayout());
p.setVisible(false);
int w = UIManager.getInt("MenuItem.minimumTextOffset");
p.add(Box.createHorizontalStrut(w), BorderLayout.WEST);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class DispatchParentHandler extends MouseInputAdapter {
private void dispatchEvent(MouseEvent e) {
Component src = e.getComponent();
Container tgt = SwingUtilities.getUnwrappedParent(src);
tgt.dispatchEvent(SwingUtilities.convertMouseEvent(src, e, tgt));
}
@Override public void mouseEntered(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseExited(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseMoved(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseDragged(MouseEvent e) {
dispatchEvent(e);
}
}
final class LookAndFeelUtil {
private static String lookAndFeel = UIManager.getLookAndFeel().getClass().getName();
private LookAndFeelUtil() {
/* Singleton */
}
public static JMenu createLookAndFeelMenu() {
JMenu menu = new JMenu("LookAndFeel");
ButtonGroup lafGroup = new ButtonGroup();
for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName(), lafGroup));
}
return menu;
}
private static JMenuItem createLookAndFeelItem(String lafName, String lafClassName, ButtonGroup lafGroup) {
JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(lafName, lafClassName.equals(lookAndFeel));
lafItem.setActionCommand(lafClassName);
lafItem.setHideActionText(true);
lafItem.addActionListener(e -> {
ButtonModel m = lafGroup.getSelection();
try {
setLookAndFeel(m.getActionCommand());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
UIManager.getLookAndFeel().provideErrorFeedback((Component) e.getSource());
}
});
lafGroup.add(lafItem);
return lafItem;
}
private static void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
String oldLookAndFeel = LookAndFeelUtil.lookAndFeel;
if (!oldLookAndFeel.equals(lookAndFeel)) {
UIManager.setLookAndFeel(lookAndFeel);
LookAndFeelUtil.lookAndFeel = lookAndFeel;
updateLookAndFeel();
// firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel);
}
}
private static void updateLookAndFeel() {
for (Window window : Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(window);
}
}
} |
package com.soundcloud.api;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.AuthenticationHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.RequestDirector;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRequestDirector;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.json.JSONException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URI;
import java.util.Arrays;
public class ApiWrapper implements CloudAPI, Serializable {
public static final String DEFAULT_CONTENT_TYPE = "application/json";
private static final long serialVersionUID = 3662083416905771921L;
private static final Token EMPTY_TOKEN = new Token(null, null);
/** The current environment, only live possible for now */
public final Env env = Env.LIVE;
private Token mToken;
private final String mClientId, mClientSecret;
private final URI mRedirectUri;
transient private HttpClient httpClient;
transient private TokenListener listener;
private String mDefaultContentType;
private String mDefaultAcceptEncoding;
public static final int BUFFER_SIZE = 8192;
/** Connection timeout */
public static final int TIMEOUT = 20 * 1000;
/** Keepalive timeout */
public static final long KEEPALIVE_TIMEOUT = 20 * 1000;
/* maximum number of connections allowed */
public static final int MAX_TOTAL_CONNECTIONS = 10;
/** debug request details to stderr */
public boolean debugRequests;
public ApiWrapper(String clientId,
String clientSecret,
URI redirectUri,
Token token) {
mClientId = clientId;
mClientSecret = clientSecret;
mRedirectUri = redirectUri;
mToken = token == null ? EMPTY_TOKEN : token;
}
@Override public Token login(String username, String password, String... scopes) throws IOException {
if (username == null || password == null) {
throw new IllegalArgumentException("username or password is null");
}
final Request request = addScope(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, PASSWORD,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret,
USERNAME, username,
PASSWORD, password), scopes);
mToken = requestToken(request);
return mToken;
}
@Override public Token authorizationCode(String code, String... scopes) throws IOException {
if (code == null) {
throw new IllegalArgumentException("code is null");
}
final Request request = addScope(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, AUTHORIZATION_CODE,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret,
REDIRECT_URI, mRedirectUri,
CODE, code), scopes);
mToken = requestToken(request);
return mToken;
}
@Override public Token clientCredentials(String... scopes) throws IOException {
final Request req = addScope(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, CLIENT_CREDENTIALS,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret), scopes);
final Token token = requestToken(req);
if (scopes != null) {
for (String scope : scopes) {
if (!token.scoped(scope)) {
throw new InvalidTokenException(-1, "Could not obtain requested scope '"+scope+"' (got: '" +
token.scope + "')");
}
}
}
return token;
}
@Override
public Token extensionGrantType(String grantType, String... scopes) throws IOException {
final Request req = addScope(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, grantType,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret), scopes);
mToken = requestToken(req);
return mToken;
}
@Override public Token refreshToken() throws IOException {
if (mToken == null || mToken.refresh == null) throw new IllegalStateException("no refresh token available");
mToken = requestToken(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, REFRESH_TOKEN,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret,
REFRESH_TOKEN, mToken.refresh));
return mToken;
}
@Override public Token exchangeOAuth1Token(String oauth1AccessToken) throws IOException {
if (oauth1AccessToken == null) throw new IllegalArgumentException("need access token");
mToken = requestToken(Request.to(Endpoints.TOKEN).with(
GRANT_TYPE, OAUTH1_TOKEN_GRANT_TYPE,
CLIENT_ID, mClientId,
CLIENT_SECRET, mClientSecret,
REFRESH_TOKEN, oauth1AccessToken));
return mToken;
}
@Override public Token invalidateToken() {
if (mToken != null) {
Token alternative = listener == null ? null : listener.onTokenInvalid(mToken);
mToken.invalidate();
if (alternative != null) {
mToken = alternative;
return mToken;
} else {
return null;
}
} else {
return null;
}
}
@Override public URI authorizationCodeUrl(String... options) {
final Request req = Request.to(options.length == 0 ? Endpoints.CONNECT : options[0]).with(
REDIRECT_URI, mRedirectUri,
CLIENT_ID, mClientId,
RESPONSE_TYPE, CODE);
if (options.length == 2) req.add(SCOPE, options[1]);
return getURI(req, false, true);
}
/**
* Constructs URI path for a given resource.
* @param request the resource to access
* @param api api or web
* @param secure whether to use SSL or not
* @return a valid URI
*/
public URI getURI(Request request, boolean api, boolean secure) {
final URI uri = api ? env.getResourceURI(secure) : env.getAuthResourceURI(secure);
return uri.resolve(request.toUrl());
}
/**
* User-Agent to identify ourselves with - defaults to USER_AGENT
* @return the agent to use
* @see CloudAPI#USER_AGENT
*/
public String getUserAgent() {
return USER_AGENT;
}
/**
* Request an OAuth2 token from SoundCloud
* @param request the token request
* @return the token
* @throws java.io.IOException network error
* @throws com.soundcloud.api.CloudAPI.InvalidTokenException unauthorized
* @throws com.soundcloud.api.CloudAPI.ApiResponseException http error
*/
protected Token requestToken(Request request) throws IOException {
HttpResponse response = safeExecute(env.sslResourceHost, request.buildRequest(HttpPost.class));
final int status = response.getStatusLine().getStatusCode();
String error;
try {
if (status == HttpStatus.SC_OK) {
final Token token = new Token(Http.getJSON(response));
if (listener != null) listener.onTokenRefreshed(token);
return token;
} else {
error = Http.getJSON(response).getString("error");
}
} catch (IOException ignored) {
error = ignored.getMessage();
} catch (JSONException ignored) {
error = ignored.getMessage();
}
throw status == HttpStatus.SC_UNAUTHORIZED ?
new InvalidTokenException(status, error) :
new ApiResponseException(response, error);
}
protected HttpParams getParams() {
final HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
HttpConnectionParams.setSoTimeout(params, TIMEOUT);
HttpConnectionParams.setSocketBufferSize(params, BUFFER_SIZE);
ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
// fix contributed by Bjorn Roche XXX check if still needed
params.setBooleanParameter("http.protocol.expect-continue", false);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() {
@Override
public int getMaxForRoute(HttpRoute httpRoute) {
if (env.isApiHost(httpRoute.getTargetHost())) {
// there will be a lot of concurrent request to the API host
return MAX_TOTAL_CONNECTIONS;
} else {
return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE;
}
}
});
// apply system proxy settings
final String proxyHost = System.getProperty("http.proxyHost");
final String proxyPort = System.getProperty("http.proxyPort");
if (proxyHost != null) {
int port = 80;
try {
port = Integer.parseInt(proxyPort);
} catch (NumberFormatException ignored) {
}
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port));
}
return params;
}
/**
* @param proxy the proxy to use for the wrapper, or null to clear the current one.
*/
public void setProxy(URI proxy) {
final HttpHost host;
if (proxy != null) {
Scheme scheme = getHttpClient()
.getConnectionManager()
.getSchemeRegistry()
.getScheme(proxy.getScheme());
host = new HttpHost(proxy.getHost(), scheme.resolvePort(proxy.getPort()), scheme.getName());
} else {
host = null;
}
getHttpClient().getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
}
public URI getProxy() {
Object proxy = getHttpClient().getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
if (proxy instanceof HttpHost) {
return URI.create(((HttpHost)proxy).toURI());
} else {
return null;
}
}
public boolean isProxySet() {
return getProxy() != null;
}
/**
* @return SocketFactory used by the underlying HttpClient
*/
protected SocketFactory getSocketFactory() {
return PlainSocketFactory.getSocketFactory();
}
/**
* @return SSL SocketFactory used by the underlying HttpClient
*/
protected SSLSocketFactory getSSLSocketFactory() {
return SSLSocketFactory.getSocketFactory();
}
/** @return The HttpClient instance used to make the calls */
public HttpClient getHttpClient() {
if (httpClient == null) {
final HttpParams params = getParams();
HttpClientParams.setRedirecting(params, false);
HttpProtocolParams.setUserAgent(params, getUserAgent());
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", getSocketFactory(), 80));
final SSLSocketFactory sslFactory = getSSLSocketFactory();
registry.register(new Scheme("https", sslFactory, 443));
httpClient = new DefaultHttpClient(
new ThreadSafeClientConnManager(params, registry),
params) {
{
setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
return KEEPALIVE_TIMEOUT;
}
});
getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, CloudAPI.REALM, OAUTH_SCHEME),
OAuth2Scheme.EmptyCredentials.INSTANCE);
getAuthSchemes().register(CloudAPI.OAUTH_SCHEME, new OAuth2Scheme.Factory(ApiWrapper.this));
addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
if (response == null || response.getEntity() == null) return;
HttpEntity entity = response.getEntity();
Header header = entity.getContentEncoding();
if (header != null) {
for (HeaderElement codec : header.getElements()) {
if (codec.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(entity));
break;
}
}
}
}
});
}
@Override protected HttpContext createHttpContext() {
HttpContext ctxt = super.createHttpContext();
ctxt.setAttribute(ClientContext.AUTH_SCHEME_PREF,
Arrays.asList(CloudAPI.OAUTH_SCHEME, "digest", "basic"));
return ctxt;
}
@Override protected BasicHttpProcessor createHttpProcessor() {
BasicHttpProcessor processor = super.createHttpProcessor();
processor.addInterceptor(new OAuth2HttpRequestInterceptor());
return processor;
}
// for testability only
@Override protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec,
ClientConnectionManager conman,
ConnectionReuseStrategy reustrat,
ConnectionKeepAliveStrategy kastrat,
HttpRoutePlanner rouplan,
HttpProcessor httpProcessor,
HttpRequestRetryHandler retryHandler,
RedirectHandler redirectHandler,
AuthenticationHandler targetAuthHandler,
AuthenticationHandler proxyAuthHandler,
UserTokenHandler stateHandler,
HttpParams params) {
return getRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler,
redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params);
}
};
}
return httpClient;
}
@Override
public long resolve(String url) throws IOException {
HttpResponse resp = get(Request.to(Endpoints.RESOLVE).with("url", url));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
Header location = resp.getFirstHeader("Location");
if (location != null) {
String s = location.getValue();
if (s.contains("/")) {
try {
return Integer.parseInt(s.substring(s.lastIndexOf("/") + 1, s.length()));
} catch (NumberFormatException e) {
throw new ResolverException(e, resp);
}
} else {
throw new ResolverException("Invalid string:"+s, resp);
}
} else {
throw new ResolverException("No location header", resp);
}
} else {
throw new ResolverException("Invalid status code", resp);
}
}
@Override
public Stream resolveStreamUrl(final String url, boolean skipLogging) throws IOException {
HttpResponse resp = safeExecute(null, addHeaders(Request.to(url).buildRequest(HttpHead.class)));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
Header location = resp.getFirstHeader("Location");
if (location != null && location.getValue() != null) {
final String headRedirect = location.getValue();
resp = safeExecute(null, new HttpHead(headRedirect));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Stream stream = new Stream(url, headRedirect, resp);
// need to do another GET request to have a URL ready for client usage
Request req = Request.to(url);
if (skipLogging) {
// skip logging
req.with("skip_logging", "1");
}
resp = safeExecute(null, addHeaders(Request.to(url).buildRequest(HttpGet.class)));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
return stream.withNewStreamUrl(resp.getFirstHeader("Location").getValue());
} else {
throw new ResolverException("Unexpected response code", resp);
}
} else {
throw new ResolverException("Unexpected response code", resp);
}
} else {
throw new ResolverException("Location header not set", resp);
}
} else {
throw new ResolverException("Unexpected response code", resp);
}
}
@Override
public HttpResponse head(Request request) throws IOException {
return execute(request, HttpHead.class);
}
@Override public HttpResponse get(Request request) throws IOException {
return execute(request, HttpGet.class);
}
@Override public HttpResponse put(Request request) throws IOException {
return execute(request, HttpPut.class);
}
@Override public HttpResponse post(Request request) throws IOException {
return execute(request, HttpPost.class);
}
@Override public HttpResponse delete(Request request) throws IOException {
return execute(request, HttpDelete.class);
}
@Override public Token getToken() {
return mToken;
}
@Override public void setToken(Token newToken) {
mToken = newToken == null ? EMPTY_TOKEN : newToken;
}
@Override
public synchronized void setTokenListener(TokenListener listener) {
this.listener = listener;
}
/**
* Execute an API request, adds the necessary headers.
* @param request the HTTP request
* @return the HTTP response
* @throws java.io.IOException network error etc.
*/
public HttpResponse execute(HttpUriRequest request) throws IOException {
return safeExecute(env.sslResourceHost, addHeaders(request));
}
public HttpResponse safeExecute(HttpHost target, HttpUriRequest request) throws IOException {
if (target == null) {
target = determineTarget(request);
}
try {
return getHttpClient().execute(target, request);
} catch (NullPointerException e) {
// this is a workaround for a broken httpclient version,
// NPE in DefaultRequestDirector.java:456
if (!request.isAborted() && request.getParams().isParameterFalse("npe-retried")) {
request.getParams().setBooleanParameter("npe-retried", true);
return safeExecute(target, request);
} else {
request.abort();
throw new BrokenHttpClientException(e);
}
} catch (IllegalArgumentException e) {
// more brokenness
request.abort();
throw new BrokenHttpClientException(e);
} catch (ArrayIndexOutOfBoundsException e) {
// Caused by: java.lang.ArrayIndexOutOfBoundsException: length=7; index=-9
// org.apache.harmony.security.asn1.DerInputStream.readBitString(DerInputStream.java:72))
// org.apache.harmony.security.asn1.ASN1BitString.decode(ASN1BitString.java:64)
// org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:375)
request.abort();
throw new BrokenHttpClientException(e);
}
}
protected HttpResponse execute(Request req, Class<? extends HttpRequestBase> reqType) throws IOException {
Request defaults = ApiWrapper.defaultParams.get();
if (defaults != null && !defaults.getParams().isEmpty()) {
// copy + merge in default parameters
for (NameValuePair nvp : defaults) {
req = new Request(req);
req.add(nvp.getName(), nvp.getValue());
}
}
logRequest(reqType, req);
return execute(addClientIdIfNecessary(req).buildRequest(reqType));
}
protected Request addClientIdIfNecessary(Request req) {
return (mToken != EMPTY_TOKEN || req.getParams().containsKey(CLIENT_ID)) ?
req : new Request(req).add(CLIENT_ID, mClientId);
}
protected void logRequest( Class<? extends HttpRequestBase> reqType, Request request) {
if (debugRequests) System.err.println(reqType.getSimpleName()+" "+request);
}
protected HttpHost determineTarget(HttpUriRequest request) {
// A null target may be acceptable if there is a default target.
// Otherwise, the null target is detected in the director.
URI requestURI = request.getURI();
if (requestURI.isAbsolute()) {
return new HttpHost(
requestURI.getHost(),
requestURI.getPort(),
requestURI.getScheme());
} else {
return null;
}
}
/**
* serialize the wrapper to a File
* @param f target
* @throws java.io.IOException IO problems
*/
public void toFile(File f) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(this);
oos.close();
}
public String getDefaultContentType() {
return (mDefaultContentType == null) ? DEFAULT_CONTENT_TYPE : mDefaultContentType;
}
public void setDefaultContentType(String contentType) {
mDefaultContentType = contentType;
}
public String getDefaultAcceptEncoding() {
return mDefaultAcceptEncoding;
}
public void setDefaultAcceptEncoding(String encoding) {
mDefaultAcceptEncoding = encoding;
}
/* package */ static Request addScope(Request request, String[] scopes) {
if (scopes != null && scopes.length > 0) {
StringBuilder scope = new StringBuilder();
for (int i=0; i<scopes.length; i++) {
scope.append(scopes[i]);
if (i < scopes.length-1) scope.append(" ");
}
request.add(SCOPE, scope.toString());
}
return request;
}
/**
* Read wrapper from a file
* @param f the file
* @return the wrapper
* @throws IOException IO problems
* @throws ClassNotFoundException class not found
*/
public static ApiWrapper fromFile(File f) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
return (ApiWrapper) ois.readObject();
} finally {
ois.close();
}
}
/** Creates an OAuth2 header for the given token */
public static Header createOAuthHeader(Token token) {
return new BasicHeader(AUTH.WWW_AUTH_RESP, "OAuth " +
(token == null || !token.valid() ? "invalidated" : token.access));
}
/** Adds an OAuth2 header to a given request */
protected HttpUriRequest addAuthHeader(HttpUriRequest request) {
if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) {
if (mToken != EMPTY_TOKEN) {
request.addHeader(createOAuthHeader(mToken));
}
}
return request;
}
/** Forces JSON */
protected HttpUriRequest addAcceptHeader(HttpUriRequest request) {
if (!request.containsHeader("Accept")) {
request.addHeader("Accept", getDefaultContentType());
}
return request;
}
/** Adds all required headers to the request */
protected HttpUriRequest addHeaders(HttpUriRequest req) {
return addAcceptHeader(addAuthHeader(addEncodingHeader(req)));
}
protected HttpUriRequest addEncodingHeader(HttpUriRequest req) {
if (getDefaultAcceptEncoding() != null) {
req.addHeader("Accept-Encoding", getDefaultAcceptEncoding());
}
return req;
}
/** This method mainly exists to make the wrapper more testable. oh, apache's insanity. */
protected RequestDirector getRequestDirector(HttpRequestExecutor requestExec,
ClientConnectionManager conman,
ConnectionReuseStrategy reustrat,
ConnectionKeepAliveStrategy kastrat,
HttpRoutePlanner rouplan,
HttpProcessor httpProcessor,
HttpRequestRetryHandler retryHandler,
RedirectHandler redirectHandler,
AuthenticationHandler targetAuthHandler,
AuthenticationHandler proxyAuthHandler,
UserTokenHandler stateHandler,
HttpParams params
) {
return new DefaultRequestDirector(requestExec, conman, reustrat, kastrat, rouplan,
httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler,
stateHandler, params);
}
private static final ThreadLocal<Request> defaultParams = new ThreadLocal<Request>() {
@Override protected Request initialValue() {
return new Request();
}
};
/**
* Adds a default parameter which will get added to all requests in this thread.
* Use this method carefully since it might lead to unexpected side-effects.
* @param name the name of the parameter
* @param value the value of the parameter.
*/
public static void setDefaultParameter(String name, String value) {
defaultParams.get().set(name, value);
}
/**
* Clears the default parameters.
*/
public static void clearDefaultParameters() {
defaultParams.remove();
}
} |
package com.tas.jsonschema;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class JsonSchema {
@JsonProperty("$schema")
private String schema;
private String title;
private String id;
private Type type = Type.OBJECT;
@JsonInclude(Include.NON_EMPTY)
private Map<String, JsonSchema> properties = new LinkedHashMap<>();
private Boolean additionalProperties;
@JsonInclude(Include.NON_EMPTY)
private Set<String> required = new LinkedHashSet<>();
private String description;
@JsonProperty("default")
private String defaultText;
@JsonInclude(Include.NON_EMPTY)
private List<? extends JsonSchema> allOf = new ArrayList<>();
@JsonInclude(Include.NON_EMPTY)
private List<? extends JsonSchema> anyOf = new ArrayList<>();
@JsonInclude(Include.NON_EMPTY)
private List<? extends JsonSchema> oneOf = new ArrayList<>();
private Format format;
private Integer propertyOrder;
private Integer minItems;
private Integer minLength;
private Integer minimum;
private Integer maxItems;
private Integer maxLength;
private Integer maximum;
private String pattern;
private Media media;
@JsonProperty("enum")
private List<String> _enum;
private JsonSchema items;
private Boolean uniqueItems;
@JsonIgnore
private Map<String, Object> additionalPropertiesMap = new HashMap<>();
@JsonInclude(Include.ALWAYS)
@JsonAnyGetter
public Map<String, Object> getAdditionalPropertyMap() {
return this.additionalPropertiesMap;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalPropertiesMap.put(name, value);
}
public Integer getMinItems() {
return minItems;
}
public void setMinItems(Integer minItems) {
this.minItems = minItems;
}
public Integer getMaxItems() {
return maxItems;
}
public void setMaxItems(Integer maxItems) {
this.maxItems = maxItems;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDefaultText() {
return defaultText;
}
public void setDefaultText(String defaultText) {
this.defaultText = defaultText;
}
public Format getFormat() {
return format;
}
public void setFormat(Format format) {
this.format = format;
}
public Integer getPropertyOrder() {
return propertyOrder;
}
public void setPropertyOrder(Integer propertyOrder) {
this.propertyOrder = propertyOrder;
}
public Integer getMinLength() {
return minLength;
}
public void setMinLength(Integer minLength) {
this.minLength = minLength;
}
public Integer getMinimum() {
return minimum;
}
public void setMinimum(Integer minimum) {
this.minimum = minimum;
}
public Integer getMaxLength() {
return maxLength;
}
public void setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
}
public Integer getMaximum() {
return maximum;
}
public void setMaximum(Integer maximum) {
this.maximum = maximum;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Media getMedia() {
return media;
}
public void setMedia(Media media) {
this.media = media;
}
public List<? extends JsonSchema> getAllOf() {
return allOf;
}
public void setAllOf(List<? extends JsonSchema> allOf) {
this.allOf = allOf;
}
public List<? extends JsonSchema> getAnyOf() {
return anyOf;
}
public void setAnyOf(List<? extends JsonSchema> anyOf) {
this.anyOf = anyOf;
}
public List<? extends JsonSchema> getOneOf() {
return oneOf;
}
public void setOneOf(List<? extends JsonSchema> oneOf) {
this.oneOf = oneOf;
}
@JsonInclude(Include.NON_EMPTY)
public List<String> get_enum() {
if (_enum == null) {
_enum = new ArrayList<>();
}
return _enum;
}
public void set_enum(List<String> _enum) {
this._enum = _enum;
}
public JsonSchema getItems() {
return items;
}
public void setItems(JsonSchema items) {
this.items = items;
}
public Boolean getUniqueItems() {
return uniqueItems;
}
public void setUniqueItems(Boolean uniqueItems) {
this.uniqueItems = uniqueItems;
}
public JsonSchema() {
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Map<String, JsonSchema> getProperties() {
return properties;
}
public void setProperties(Map<String, JsonSchema> properties) {
this.properties = properties;
}
public Boolean getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(Boolean additionalProperties) {
this.additionalProperties = additionalProperties;
}
public Set<String> getRequired() {
return required;
}
public void setRequired(Collection<String> required) {
this.required = new LinkedHashSet<>(required);
}
} |
package com.technumen.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
@Slf4j
public class DateUtils implements Serializable {
/**
* Returns output java.util date in MM/dd/yyyy format for any given input date String.
*
* @param date
* @return
*/
public static Date parseDate(String date) {
try {
return new SimpleDateFormat("MM/dd/yyyy").parse(date);
} catch (ParseException e) {
log.error("Parse Exception: " + e);
return null;
}
}
/**
* Returns output String date in MM/dd/yyyy format for any given input java util date.
*
* @param inputDate
* @return
*/
public static String parseDate(Date inputDate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.format(inputDate);
} catch (Exception ex) {
log.error("Parse Exception: " + ex);
return null;
}
}
/**
* Returns java.util weekend date (Sunday) based on the current local date.
*
* @return
*/
public static Date getCurrentTimesheetWeekEndDate() {
LocalDate lastSunday = LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("lastSunday: " + lastSunday);
return Date.from(lastSunday.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
/**
* Returns java.time LocalDate weekend date (Sunday) based on the current local date.
*
* @return
*/
public static LocalDate getLocalTimesheetWeekEndDate() {
log.info("Inside getLocalTimesheetWeekEndDate");
LocalDate lastSunday = LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("lastSunday: " + lastSunday);
return lastSunday;
}
/**
* Returns java.util weekend date (Sunday) for a given date.
*
* @return
*/
public static Date getTimesheetWeekStartDate(Date inputDate) {
log.info("Inside getTimesheetWeekStartDate :: inputDate: " + inputDate);
if (inputDate != null) {
LocalDate localDate = inputDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstMonday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
log.info("Inside inputdate not null loop, firstMonday: " + firstMonday);
return Date.from(firstMonday.atStartOfDay(ZoneId.systemDefault()).toInstant());
} else {
log.error("Input date not found. So returning null.");
return null;
}
}
/**
* Returns java.time LocalDate weekend date (Sunday) for a given date.
*
* @return
*/
public static LocalDate getLocalTimesheetWeekStartDate(Date inputDate) {
log.info("Inside getLocalTimesheetWeekStartDate :: inputDate: " + inputDate);
if (inputDate != null) {
LocalDate localDate = inputDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstMonday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
log.info("Inside inputDate not null loop, firstMonday: " + firstMonday);
return firstMonday;
} else {
log.error("Input date not found. So returning null.");
return null;
}
}
/**
* Returns java.util weekend date (Sunday) for a given date.
*
* @return
*/
public static Date getTimesheetWeekEndDate(Date inputDate) {
log.info("Inside getTimesheetWeekEndDate :: inputDate: " + inputDate);
if (inputDate != null) {
LocalDate localDate = inputDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate lastSunday = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("Inside input date not null loop, lastSunday: " + lastSunday);
return Date.from(lastSunday.atStartOfDay(ZoneId.systemDefault()).toInstant());
} else {
log.error("Input date not found. So returning null.");
return null;
}
}
/**
* Returns java.time LocalDate weekend date (Sunday) for a given date.
*
* @return
*/
public static LocalDate getLocalTimesheetWeekEndDate(Date inputDate) {
log.info("Inside getLocalTimesheetWeekEndDate :: inputDate: " + inputDate);
if (inputDate != null) {
LocalDate localDate = inputDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate lastSunday = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("Inside inputDate not null loop, lastSunday: " + lastSunday);
return lastSunday;
} else {
log.error("Input date not found. So returning null.");
return null;
}
}
/**
* Returns list of LocaDate for end of timesheet week for last three months from current weekend Date.
*
* @return
*/
public static List<Date> getListWeekEndDatesOfLastThreeMonths() {
log.info("Inside getListEndDatesOfLastThreeMonths method of DateUtils.");
LocalDate lastSunday = LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("lastSunday: " + lastSunday);
long weeks = ChronoUnit.WEEKS.between(lastSunday.minusMonths(3L), lastSunday);
log.info("Number of weeks in last three months: " + weeks);
List<Date> collect = Stream.iterate(lastSunday.minusWeeks(weeks), d -> d.plusWeeks(1L))
.limit(weeks + 1)
.map(d -> Date.from(d.atStartOfDay(ZoneId.systemDefault()).toInstant()))
.collect(Collectors.toList());
return collect;
}
/**
* Returns list of java util end of timesheet week Dates for last three months from current weekend Date.
*
* @return
*/
public static List<LocalDate> getListLocalWeekEndDatesOfLastThreeMonths() {
log.info("Inside getListLocalEndDatesOfLastThreeMonths method of DateUtils.");
LocalDate lastSunday = LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
log.info("lastSunday: " + lastSunday);
long weeks = ChronoUnit.WEEKS.between(lastSunday.minusMonths(3L), lastSunday);
log.info("Number of weeks in last three months: " + weeks);
List<LocalDate> collect = Stream.iterate(lastSunday.minusWeeks(weeks), d -> d.plusWeeks(1L))
.limit(weeks + 1)
.collect(Collectors.toList());
return collect;
}
/**
* Returns list of LocaDate for start of timesheet week Dates for last three months from current week.
*
* @return
*/
public static List<Date> getListWeekStartDatesOfLastThreeMonths() {
log.info("Inside getListWeekStartDatesOfLastThreeMonths method of DateUtils.");
LocalDate startMonday = LocalDate.now()
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
long weeks = ChronoUnit.WEEKS.between(startMonday.minusMonths(3L), startMonday);
log.info("Number of weeks in last three months: " + weeks);
List<Date> collect = Stream.iterate(startMonday.minusWeeks(weeks), d -> d.plusWeeks(1L))
.limit(weeks + 1)
.map(d -> Date.from(d.atStartOfDay(ZoneId.systemDefault()).toInstant()))
.collect(Collectors.toList());
return collect;
}
/**
* Returns list of java util start of timesheet week Dates for last three months from current week.
*
* @return
*/
public static List<LocalDate> getListLocalStartDatesOfLastThreeMonths() {
log.info("Inside getListLocalStartDatesOfLastThreeMonths method of DateUtils.");
LocalDate startMonday = LocalDate.now()
.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
long weeks = ChronoUnit.WEEKS.between(startMonday.minusMonths(3L), startMonday);
log.info("Number of weeks in last three months: " + weeks);
List<LocalDate> collect = Stream.iterate(startMonday.minusWeeks(weeks), d -> d.plusWeeks(1L))
.limit(weeks + 1)
.collect(Collectors.toList());
return collect;
}
/**
* Return String with appending StartDate and EndDate for a given input date.
*
* @param inputDate
* @return
*/
public static String getWeekStartEndDatesString(Date inputDate) {
log.info("Inside getWeekStartEndDates:: inputDate: " + inputDate);
return parseDate(getTimesheetWeekStartDate(inputDate)) + " - " + parseDate(getTimesheetWeekEndDate(inputDate));
}
/**
* Returns a Map of Date, String for a given list of Dates.
*
* @param datesList
* @return
*/
public static Map<Date, String> getWeekDatesMap(List<Date> datesList) {
log.info("Inside getWeekDatesMap of DateUtils:: ");
Map<Date, String> datesMap = new TreeMap<>(Collections.reverseOrder());
for (Date inputDate : datesList) {
datesMap.put(inputDate, parseDate(inputDate));
}
return datesMap;
}
/**
* Returns a Map of Date, String of Weekly Start Dates.
*
* @return
*/
public static Map<Date, String> getWeekStartDatesMap() {
log.info("Inside getWeekStartDatesMap of DateUtils:: ");
Map<Date, String> datesMap = new TreeMap<>(Collections.reverseOrder());
for (Date inputDate : getListWeekStartDatesOfLastThreeMonths()) {
datesMap.put(inputDate, parseDate(inputDate));
}
return datesMap;
}
/**
* Returns a Map of Date, String of Weekly End Dates.
*
* @return
*/
public static Map<Date, String> getWeekEndDatesMap() {
log.info("Inside getWeekEndDatesMap of DateUtils:: ");
Map<Date, String> datesMap = new TreeMap<>(Collections.reverseOrder());
for (Date inputDate : getListWeekEndDatesOfLastThreeMonths()) {
datesMap.put(inputDate, parseDate(inputDate));
}
return datesMap;
}
/**
* Returns a map of Date, String values for a given endDatesList.
*
* @param endDatesList
* @return
*/
public static Map<Date, String> getWeekStartEndDatesMap(List<Date> endDatesList) {
log.info("Inside getWeekStartEndDatesMap of DateUtils:: ");
Map<Date, String> startEndDatesMap = new TreeMap<>(Collections.reverseOrder());
for (Date endDate : endDatesList) {
startEndDatesMap.put(endDate, getWeekStartEndDatesString(endDate));
}
return startEndDatesMap;
}
} |
package com.thindeck.dynamo;
import com.jcabi.aspects.Immutable;
import com.thindeck.api.Context;
import com.thindeck.api.Memo;
import java.io.IOException;
import java.util.logging.Level;
/**
* Dynamo implementation of the {@link com.thindeck.api.Context}.
* @author Mauricio Herrera (oruam85@gmail.com)
* @version $Id$
*/
@Immutable
public final class DyContext implements Context {
// @todo #462:30min DyContext.memo() should be implemented. This method
// should return the Memo object that will use in this context.
@Override
public Memo memo() throws IOException {
throw new UnsupportedOperationException("#memo");
}
// @todo #462:30min DyContext.log() should be implemented. This method
// should add a new line in the log.
@Override
public void log(final Level level, final String text,
final Object... args) {
throw new UnsupportedOperationException("#log");
}
} |
package coyote.commons.security;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Login extends PermissionEnabledSubject {
/** This logins identifier */
String id;
/** The credentials used to authenticate this login */
CredentialSet credentials;
/** The principal (entity) of this login. */
SecurityPrincipal principal;
/** A map of role names this login assumes. */
HashSet<String> roles = new HashSet<String>();
/**
* Constructs a Login with a security principal with the given name and a
* credential set with the given password.
*
* <p>The password is saved as a single round MD5 hash of its UTF8 encoding.
* This is to help ensure that the password is not stored in an easily
* retrievable format. This implies that the clear text password is not used
* in the system for authentication and that if the password is exposed by
* the system, the viewer of the password value will not have the original
* password provided by the user.</p>
*
* @param name name of the security principal (i.e. username)
* @param password authentication credential
*/
public Login( String name, String password ) {
principal = new GenericSecurityPrincipal( name );
credentials = new CredentialSet( CredentialSet.PASSWORD, password, 1 );
}
public Login( SecurityPrincipal principal, CredentialSet creds ) {
this.principal = principal;
credentials = creds;
}
/**
* Constructor Login
*/
public Login() {}
/**
* Add a role name to this login.
*
* @param role The name of the role to add.
*/
public void addRole( String role ) {
if ( role != null && role.length() > 0 ) {
roles.add( role );
}
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder( "Login: Principal=" );
if ( principal != null ) {
if ( principal.getName() != null )
b.append( principal.getName() );
else
b.append( "null" );
} else {
b.append( "NULL" );
}
b.append( " Creds:" );
b.append( credentials.size() );
return b.toString();
}
/**
* Test to see if all the given credentials match what is recorded in in
* this login.
*
* <p>The most common scenario is two credentials being passed to this method
* for matching; username and password. It is therefore important to match
* both credentials.</p>
*
* <p>Other scenarios involve multi-factor authentication with password and
* some other credential passed such as a biometric digest, or challenge
* response. The more credentials passed and matched, the higher the
* confidence of the authentication operation.</p>
*
* <p>While this login may have dozens of credentials, the given credentials
* are expected to be a subset, maybe even one credential. If all the given
* credentials match, return true. If even one of the given credentials fail
* to match, then return false.</p>
*
* @param creds The set of credentials to match.
*
* @return True if all the given credentials match, false otherwise.
*/
public boolean matchCredentials( CredentialSet creds ) {
if ( creds != null ) {
return credentials.matchAll( creds );
} else {
return false;
}
}
/**
* @return a list of role names to which this login belongs.
*/
public List<String> getRoles() {
return new ArrayList<String>( roles );
}
/**
* @return the identifier for this login
*/
public String getId() {
return id;
}
/**
* Set the identifier for this login
*
* @param id the identifier unique to the security context
*/
public void setId( String id ) {
this.id = id;
}
/**
* @return The principal associated to this login
*/
public SecurityPrincipal getPrincipal() {
return principal;
}
/**
* Set the security principal associated to this login.
*
* @param principal The principal associated with this login.
*/
public void setPrincipal( SecurityPrincipal principal ) {
this.principal = principal;
}
/**
* @return the credentials for this login
*/
public CredentialSet getCredentials() {
return credentials;
}
/**
* Set (replace) the credentials with this set of credentials.
*
* @param credentialset the credentials to set
*/
public void setCredentials( CredentialSet credentialset ) {
this.credentials = credentialset;
}
} |
package br.net.mirante.singular.util.wicket.menu;
import java.util.regex.Pattern;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import br.net.mirante.singular.util.wicket.resource.Icone;
import static br.net.mirante.singular.util.wicket.util.WicketUtils.$b;
public class MetronicMenuItem extends AbstractMenuItem {
private WebMarkupContainer menuItem;
private PageParameters parameters;
private Class<? extends IRequestablePage> responsePageClass;
private String menuItemUrl;
private String href;
private String target;
private WebMarkupContainer helper = new WebMarkupContainer("helper");
public MetronicMenuItem(Icone icon, String title, Class<? extends IRequestablePage> responsePageClass,
PageParameters parameters) {
this(icon, title);
this.responsePageClass = responsePageClass;
this.parameters = parameters;
add(buildMenuItem());
}
public MetronicMenuItem(Icone icon, String title, Class<? extends IRequestablePage> responsePageClass) {
this(icon, title, responsePageClass, null);
}
public MetronicMenuItem(Icone icon, String title, String href) {
this(icon, title);
this.href = href;
add(buildMenuItem());
}
public MetronicMenuItem(Icone icon, String title, String href, String target) {
this(icon, title);
this.href = href;
this.target = target;
add(buildMenuItem());
}
public MetronicMenuItem(Icone icon, String title) {
super("menu-item");
this.icon = icon;
this.title = title;
}
protected WebMarkupContainer buildMenuItem() {
menuItem = new WebMarkupContainer("menu-item");
MarkupContainer anchor = null;
if (href != null) {
anchor = new WebMarkupContainer("anchor");
anchor.add($b.attr("href", href));
if (target != null) {
anchor.add($b.attr("target", target));
}
this.menuItemUrl = href;
} else if (responsePageClass != null) {
anchor = new BookmarkablePageLink("anchor", responsePageClass, parameters) {
{
menuItemUrl = getURL().toString();
}
};
} else {
throw new WicketRuntimeException("É necessario informar o destino do item");
}
WebMarkupContainer iconMarkup = new WebMarkupContainer("icon");
if (icon != null) {
iconMarkup.add($b.classAppender(icon.getCssClass()));
} else {
iconMarkup.setVisible(false);
}
anchor.add(new Label("title", title));
anchor.add(helper);
anchor.add(iconMarkup);
menuItem.add(anchor);
return menuItem;
}
@Override
protected boolean configureActiveItem() {
if (menuItemUrl != null) {
Pattern onlyLetters = Pattern.compile("[^a-zA-Z0-9]");
String url = onlyLetters.matcher(getRequest().getUrl().toString()).replaceAll("");
String thisUrl = onlyLetters.matcher(menuItemUrl).replaceAll("");
if (url.endsWith(thisUrl)) {
menuItem.add($b.classAppender("active"));
return true;
}
}
return false;
}
public WebMarkupContainer getHelper() {
return helper;
}
} |
package de.cosmocode.commons;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
/**
* The {@link TrimMode} determines
* how a {@link String} is being trimmed.
*
* @author Willi Schoenborn
*/
public enum TrimMode implements Predicate<String>, Function<CharSequence, CharSequence> {
/**
* Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.
*
* See {@link StringUtils#trim(String)} for more details.
*/
NORMAL {
@Override
public String trim(String s) {
return StringUtils.trim(s);
}
},
/**
* Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is {@code null}.
*
* See {@link StringUtils#trimToEmpty(String)} for more details.
*/
EMPTY {
@Override
public String trim(String s) {
return StringUtils.trimToEmpty(s);
}
},
/**
* Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim or if it is {@code null}.
*
* See {@link StringUtils#trimToNull(String)} for more details.
*/
NULL {
@Override
public String trim(String s) {
return StringUtils.trimToNull(s);
}
};
/**
* Trims the given {@link String}.
*
* @param s the {@link String} being trimmed
* @return the trimmed version of s
*/
public abstract String trim(String s);
/**
* Trims the given {@link CharSequence}.
*
* @param sequence the {@link CharSequence} being trimmed
* @return the trimmed version of sequence
*/
public CharSequence trim(CharSequence sequence) {
return trim(sequence == null ? null : sequence.toString());
}
/**
* This is a kind of an adapter allowing
* it to use a {@link TrimMode} as a {@link Function}.
*
* <p>
* This method is delegating its work to {@link TrimMode#trim(CharSequence)}.
* </p>
*
* {@inheritDoc}
*/
@Override
public CharSequence apply(CharSequence from) {
return trim(from);
}
/**
* This implementation returns true if the given input is
* trimmed using the semantics of this {@link TrimMode}.
*
* {@inheritDoc}
*/
@Override
public boolean apply(String input) {
return trim(input) == input;
};
} |
package de.prob2.ui.states;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import de.prob.animator.command.GetMachineStructureCommand;
import de.prob.animator.domainobjects.AbstractEvalResult;
import de.prob.animator.domainobjects.EvalResult;
import de.prob.animator.domainobjects.EvaluationErrorResult;
import de.prob.animator.domainobjects.EvaluationException;
import de.prob.animator.domainobjects.FormulaExpand;
import de.prob.animator.domainobjects.IEvalElement;
import de.prob.animator.prologast.ASTCategory;
import de.prob.animator.prologast.ASTFormula;
import de.prob.animator.prologast.PrologASTNode;
import de.prob.exception.ProBError;
import de.prob.statespace.State;
import de.prob.statespace.Trace;
import de.prob2.ui.formula.FormulaGenerator;
import de.prob2.ui.internal.StageManager;
import de.prob2.ui.internal.StopActions;
import de.prob2.ui.layout.FontSize;
import de.prob2.ui.prob2fx.CurrentTrace;
import de.prob2.ui.statusbar.StatusBar;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.AnchorPane;
import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public final class StatesView extends AnchorPane {
private static final Logger LOGGER = LoggerFactory.getLogger(StatesView.class);
private static final TreeItem<StateItem<?>> LOADING_ITEM;
static {
LOADING_ITEM = new TreeItem<>(new StateItem<>("Loading...", false));
LOADING_ITEM.getChildren().add(new TreeItem<>(new StateItem<>("Loading", false)));
}
@FXML
private Button searchButton;
@FXML
private TextField filterState;
@FXML
private TreeTableView<StateItem<?>> tv;
@FXML
private TreeTableColumn<StateItem<?>, StateItem<?>> tvName;
@FXML
private TreeTableColumn<StateItem<?>, StateItem<?>> tvValue;
@FXML
private TreeTableColumn<StateItem<?>, StateItem<?>> tvPreviousValue;
@FXML
private TreeItem<StateItem<?>> tvRootItem;
private final Injector injector;
private final CurrentTrace currentTrace;
private final FormulaGenerator formulaGenerator;
private final StatusBar statusBar;
private final StageManager stageManager;
private final ResourceBundle bundle;
private List<PrologASTNode> rootNodes;
private final Map<IEvalElement, AbstractEvalResult> currentValues;
private final Map<IEvalElement, AbstractEvalResult> previousValues;
private final ExecutorService updater;
private String filter = "";
@Inject
private StatesView(final Injector injector, final CurrentTrace currentTrace,
final FormulaGenerator formulaGenerator, final StatusBar statusBar, final StageManager stageManager,
final ResourceBundle bundle, final StopActions stopActions) {
this.injector = injector;
this.currentTrace = currentTrace;
this.formulaGenerator = formulaGenerator;
this.statusBar = statusBar;
this.stageManager = stageManager;
this.bundle = bundle;
this.rootNodes = null;
this.currentValues = new HashMap<>();
this.previousValues = new HashMap<>();
this.updater = Executors.newSingleThreadExecutor(r -> new Thread(r, "StatesView Updater"));
stopActions.add(this.updater::shutdownNow);
stageManager.loadFXML(this, "states_view.fxml");
}
@FXML
private void initialize() {
tv.setRowFactory(view -> initTableRow());
this.tvName.setCellFactory(col -> new NameCell());
this.tvValue.setCellFactory(col -> new ValueCell(bundle, this.currentValues, true));
this.tvPreviousValue.setCellFactory(col -> new ValueCell(bundle, this.previousValues, false));
final Callback<TreeTableColumn.CellDataFeatures<StateItem<?>, StateItem<?>>, ObservableValue<StateItem<?>>> cellValueFactory = data -> Bindings
.createObjectBinding(data.getValue()::getValue, this.currentTrace);
this.tvName.setCellValueFactory(cellValueFactory);
this.tvValue.setCellValueFactory(cellValueFactory);
this.tvPreviousValue.setCellValueFactory(cellValueFactory);
this.tv.getRoot().setValue(new StateItem<>("Machine (this root item should be invisible)", false));
final ChangeListener<Trace> traceChangeListener = (observable, from, to) -> {
if (to == null) {
this.rootNodes = null;
this.currentValues.clear();
this.previousValues.clear();
this.tv.getRoot().getChildren().clear();
} else {
this.updater.execute(() -> this.updateRoot(from, to));
}
};
traceChangeListener.changed(this.currentTrace, null, currentTrace.get());
this.currentTrace.addListener(traceChangeListener);
bindIconSizeToFontSize();
}
private void bindIconSizeToFontSize() {
FontSize fontsize = injector.getInstance(FontSize.class);
((FontAwesomeIconView) (searchButton.getGraphic())).glyphSizeProperty().bind(fontsize);
}
private TreeTableRow<StateItem<?>> initTableRow() {
final TreeTableRow<StateItem<?>> row = new TreeTableRow<>();
row.itemProperty().addListener((observable, from, to) -> {
row.getStyleClass().remove("changed");
if (to != null && to.getContents() instanceof ASTFormula) {
final IEvalElement formula = ((ASTFormula) to.getContents()).getFormula();
final AbstractEvalResult current = this.currentValues.get(formula);
final AbstractEvalResult previous = this.previousValues.get(formula);
if (current != null && previous != null
&& (!current.getClass().equals(previous.getClass()) || current instanceof EvalResult
&& !((EvalResult) current).getValue().equals(((EvalResult) previous).getValue()))) {
row.getStyleClass().add("changed");
}
}
});
final MenuItem visualizeExpressionItem = new MenuItem(bundle.getString("states.menu.visualizeExpression"));
// Expression can only be shown if the row item contains an ASTFormula
// and the current state is initialized.
visualizeExpressionItem.disableProperty().bind(Bindings.createBooleanBinding(
() -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula), row.itemProperty())
.or(currentTrace.currentStateProperty().initializedProperty().not()));
visualizeExpressionItem.setOnAction(event -> {
try {
formulaGenerator.showFormula(((ASTFormula) row.getItem().getContents()).getFormula());
} catch (EvaluationException | ProBError e) {
LOGGER.error("Could not visualize formula", e);
stageManager.makeAlert(Alert.AlertType.ERROR,
String.format(bundle.getString("states.error.couldNotVisualize"), e)).showAndWait();
}
});
final MenuItem showFullValueItem = new MenuItem(bundle.getString("states.menu.showFullValue"));
// Full value can only be shown if the row item contains an ASTFormula,
// and the corresponding value is an EvalResult.
showFullValueItem.disableProperty().bind(Bindings.createBooleanBinding(
() -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula && this.currentValues
.get(((ASTFormula) row.getItem().getContents()).getFormula()) instanceof EvalResult),
row.itemProperty()));
showFullValueItem.setOnAction(event -> this.showFullValue(row.getItem()));
final MenuItem showErrorsItem = new MenuItem(bundle.getString("states.menu.showErrors"));
// Errors can only be shown if the row contains an ASTFormula whose
// value is an EvaluationErrorResult.
showErrorsItem.disableProperty().bind(Bindings.createBooleanBinding(
() -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula && this.currentValues
.get(((ASTFormula) row.getItem().getContents()).getFormula()) instanceof EvaluationErrorResult),
row.itemProperty()));
showErrorsItem.setOnAction(event -> this.showError(row.getItem()));
row.contextMenuProperty().bind(Bindings.when(row.emptyProperty()).then((ContextMenu) null)
.otherwise(new ContextMenu(visualizeExpressionItem, showFullValueItem, showErrorsItem)));
// Double-click on an item triggers "show full value" if allowed.
row.setOnMouseClicked(event -> {
if (!showFullValueItem.isDisable() && event.getButton() == MouseButton.PRIMARY
&& event.getClickCount() == 2) {
showFullValueItem.getOnAction().handle(null);
}
});
return row;
}
private static void getInitialExpandedFormulas(final List<PrologASTNode> nodes, final List<IEvalElement> formulas) {
for (final PrologASTNode node : nodes) {
if (node instanceof ASTFormula) {
formulas.add(((ASTFormula) node).getFormula());
}
if (node instanceof ASTCategory && ((ASTCategory) node).isExpanded()) {
getInitialExpandedFormulas(node.getSubnodes(), formulas);
}
}
}
private static List<IEvalElement> getInitialExpandedFormulas(final List<PrologASTNode> nodes) {
final List<IEvalElement> formulas = new ArrayList<>();
getInitialExpandedFormulas(nodes, formulas);
return formulas;
}
private static void getExpandedFormulas(final List<TreeItem<StateItem<?>>> treeItems,
final List<IEvalElement> formulas) {
for (final TreeItem<StateItem<?>> ti : treeItems) {
if (ti.getValue().getContents() instanceof ASTFormula) {
formulas.add(((ASTFormula) ti.getValue().getContents()).getFormula());
}
if (ti.isExpanded()) {
getExpandedFormulas(ti.getChildren(), formulas);
}
}
}
private static List<IEvalElement> getExpandedFormulas(final List<TreeItem<StateItem<?>>> treeItems) {
final List<IEvalElement> formulas = new ArrayList<>();
getExpandedFormulas(treeItems, formulas);
return formulas;
}
private void updateValueMaps(final Trace trace) {
this.currentValues.clear();
this.currentValues.putAll(trace.getCurrentState().getValues());
this.previousValues.clear();
if (trace.canGoBack()) {
this.previousValues.putAll(trace.getPreviousState().getValues());
}
}
@FXML
private void handleSearchButton() {
filter = filterState.getText();
this.tvRootItem.getChildren().clear();
buildNodes(this.tvRootItem, this.rootNodes);
this.currentTrace.getStateSpace().subscribe(this, getExpandedFormulas(tvRootItem.getChildren()));
this.updateValueMaps(this.currentTrace.get());
}
private void buildNodes(final TreeItem<StateItem<?>> treeItem, final List<PrologASTNode> nodes) {
Objects.requireNonNull(treeItem);
Objects.requireNonNull(nodes);
assert treeItem.getChildren().isEmpty();
for (final PrologASTNode node : nodes) {
final TreeItem<StateItem<?>> subTreeItem = new TreeItem<>();
if (node instanceof ASTCategory && ((ASTCategory) node).isExpanded()) {
subTreeItem.setExpanded(true);
}
if (hasFilter() && node instanceof ASTFormula) {
ASTFormula formula = (ASTFormula) node;
if (!formula.getFormula().getCode().toLowerCase().contains(filter.toLowerCase())) {
continue;
}
}
treeItem.getChildren().add(subTreeItem);
subTreeItem.setValue(new StateItem<>(node, false));
subTreeItem.expandedProperty().addListener((o, from, to) -> {
final List<IEvalElement> formulas = getExpandedFormulas(subTreeItem.getChildren());
if (to) {
this.currentTrace.getStateSpace().subscribe(this, formulas);
} else {
this.currentTrace.getStateSpace().unsubscribe(this, formulas);
}
this.updateValueMaps(this.currentTrace.get());
});
buildNodes(subTreeItem, node.getSubnodes());
if (node instanceof ASTCategory && subTreeItem.getChildren().isEmpty()) {
// remove categories without children
treeItem.getChildren().remove(subTreeItem);
}
}
}
private void updateNodes(final TreeItem<StateItem<?>> treeItem, final List<PrologASTNode> nodes) {
Objects.requireNonNull(treeItem);
Objects.requireNonNull(nodes);
if (treeItem.getChildren().size() != nodes.size()) {
treeItem.getChildren().clear();
buildNodes(treeItem, nodes);
return;
}
for (int i = 0; i < nodes.size(); i++) {
final TreeItem<StateItem<?>> subTreeItem = treeItem.getChildren().get(i);
final PrologASTNode node = nodes.get(i);
subTreeItem.setValue(new StateItem<>(node, false));
updateNodes(subTreeItem, node.getSubnodes());
}
}
private boolean hasFilter() {
return !this.filter.equals("");
}
private void updateRoot(final Trace from, final Trace to) {
final int selectedRow = tv.getSelectionModel().getSelectedIndex();
Platform.runLater(() -> {
this.statusBar.setStatesViewUpdating(true);
this.tv.setDisable(true);
});
// If the model has changed or the machine structure hasn't been loaded
// yet, update it and rebuild the tree view.
final boolean rebuildTree = this.rootNodes == null || from == null || !from.getModel().equals(to.getModel());
if (rebuildTree) {
final GetMachineStructureCommand cmd = new GetMachineStructureCommand();
to.getStateSpace().execute(cmd);
this.rootNodes = cmd.getPrologASTList();
to.getStateSpace().subscribe(this, getInitialExpandedFormulas(this.rootNodes));
}
this.updateValueMaps(to);
Platform.runLater(() -> {
if (rebuildTree || hasFilter()) {
this.tvRootItem.getChildren().clear();
buildNodes(this.tvRootItem, this.rootNodes);
} else {
updateNodes(this.tvRootItem, this.rootNodes);
}
this.tv.refresh();
this.tv.getSelectionModel().select(selectedRow);
this.tv.setDisable(false);
this.statusBar.setStatesViewUpdating(false);
});
}
private void showError(StateItem<?> stateItem) {
final FullValueStage stage = injector.getInstance(FullValueStage.class);
if (stateItem.getContents() instanceof ASTFormula) {
final AbstractEvalResult result = this.currentValues
.get(((ASTFormula) stateItem.getContents()).getFormula());
if (result instanceof EvaluationErrorResult) {
stage.setTitle(stateItem.toString());
stage.setCurrentValue(String.join("\n", ((EvaluationErrorResult) result).getErrors()));
stage.setFormattingEnabled(false);
stage.show();
} else {
throw new IllegalArgumentException("Row item result is not an error: " + result.getClass());
}
} else {
throw new IllegalArgumentException("Invalid row item type: " + stateItem.getClass());
}
}
private static String getResultValue(final ASTFormula element, final State state) {
final AbstractEvalResult result = state.eval(element.getFormula(FormulaExpand.EXPAND));
return result instanceof EvalResult ? ((EvalResult) result).getValue() : null;
}
private void showFullValue(StateItem<?> stateItem) {
final FullValueStage stage = injector.getInstance(FullValueStage.class);
if (stateItem.getContents() instanceof ASTFormula) {
final ASTFormula element = (ASTFormula) stateItem.getContents();
stage.setTitle(element.getFormula().toString());
stage.setCurrentValue(getResultValue(element, this.currentTrace.getCurrentState()));
stage.setPreviousValue(
this.currentTrace.canGoBack() ? getResultValue(element, this.currentTrace.get().getPreviousState())
: null);
stage.setFormattingEnabled(true);
} else {
throw new IllegalArgumentException("Invalid row item type: " + stateItem.getClass());
}
stage.show();
}
public TreeTableView<StateItem<?>> getTable() {
return tv;
}
} |
package de.unirostock.sems.bives;
import java.io.File;
import java.util.HashMap;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.simple.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import de.binfalse.bflog.LOGGER;
import de.unirostock.sems.bives.algorithm.GraphProducer;
import de.unirostock.sems.bives.algorithm.cellml.CellMLGraphProducer;
import de.unirostock.sems.bives.algorithm.sbml.SBMLGraphProducer;
import de.unirostock.sems.bives.api.CellMLDiff;
import de.unirostock.sems.bives.api.CellMLSingle;
import de.unirostock.sems.bives.api.Diff;
import de.unirostock.sems.bives.api.RegularDiff;
import de.unirostock.sems.bives.api.SBMLDiff;
import de.unirostock.sems.bives.api.SBMLSingle;
import de.unirostock.sems.bives.api.Single;
import de.unirostock.sems.bives.ds.cellml.CellMLDocument;
import de.unirostock.sems.bives.ds.sbml.SBMLDocument;
import de.unirostock.sems.bives.ds.xml.TreeDocument;
import de.unirostock.sems.bives.tools.DocumentClassifier;
import de.unirostock.sems.bives.tools.Tools;
import de.unirostock.sems.bives.tools.XmlTools;
//import de.unirostock.sems.bives.algorithm.sbmldeprecated.SBMLDiffInterpreter;
//TODO: detect document type
//TODO: graph producer
/**
* @author Martin Scharm
*
*/
public class Main
{
public static final int WANT_DIFF = 1;
public static final int WANT_DOCUMENTTYPE = 2;
public static final int WANT_META = 4;
public static final int WANT_REPORT_MD = 8;
public static final int WANT_REPORT_HTML = 16;
public static final int WANT_CRN_GRAPHML = 32;
public static final int WANT_CRN_DOT = 64;
public static final int WANT_COMP_HIERARCHY_GRAPHML = 128;
public static final int WANT_COMP_HIERARCHY_DOT = 256;
public static final int WANT_REPORT_RST = 512;
public static final int WANT_COMP_HIERARCHY_JSON = 1024;
public static final int WANT_CRN_JSON = 2048;
public static final int WANT_SBML = 4096;
public static final int WANT_CELLML = 8192;
public static final int WANT_REGULAR = 16384;
// single
public static final int WANT_SINGLE_CRN_GRAPHML = 32;
public static final int WANT_SINGLE_CRN_DOT = 64;
public static final int WANT_SINGLE_COMP_HIERARCHY_GRAPHML = 128;
public static final int WANT_SINGLE_COMP_HIERARCHY_DOT = 256;
public static final int WANT_SINGLE_COMP_HIERARCHY_JSON = 1024;
public static final int WANT_SINGLE_CRN_JSON = 2048;
public static final String REQ_FILES = "files";
public static final String REQ_WANT = "get";
public static final String REQ_WANT_META = "meta";
public static final String REQ_WANT_DOCUMENTTYPE = "documentType";
public static final String REQ_WANT_DIFF = "xmlDiff";
public static final String REQ_WANT_REPORT_MD = "reportMd";
public static final String REQ_WANT_REPORT_RST = "reportRST";
public static final String REQ_WANT_REPORT_HTML = "reportHtml";
public static final String REQ_WANT_CRN_GRAPHML = "crnGraphml";
public static final String REQ_WANT_CRN_DOT = "crnDot";
public static final String REQ_WANT_CRN_JSON = "crnJson";
public static final String REQ_WANT_COMP_HIERARCHY_GRAPHML = "compHierarchyGraphml";
public static final String REQ_WANT_COMP_HIERARCHY_DOT = "compHierarchyDot";
public static final String REQ_WANT_COMP_HIERARCHY_JSON = "compHierarchyJson";
public static final String REQ_WANT_SINGLE_CRN_GRAPHML = "singleCrnGraphml";
public static final String REQ_WANT_SINGLE_CRN_DOT = "singleCrnDot";
public static final String REQ_WANT_SINGLE_CRN_JSON = "singleCrnJson";
public static final String REQ_WANT_SINGLE_COMP_HIERARCHY_GRAPHML = "singleCompHierarchyGraphml";
public static final String REQ_WANT_SINGLE_COMP_HIERARCHY_DOT = "singleCompHierarchyDot";
public static final String REQ_WANT_SINGLE_COMP_HIERARCHY_JSON = "singleCompHierarchyJson";
private class Option
{
public String description;
public int value;
public Option (int value, String description)
{
this.description = description;
this.value = value;
}
}
private HashMap<String, Option> options;
private HashMap<String, Option> addOptions;
private void fillOptions ()
{
options = new HashMap<String, Option> ();
//options.put ("--meta", new Option (WANT_META, "get meta information about documents"));
//options.put ("--documentType", new Option (WANT_DOCUMENTTYPE, ""));
options.put ("--xmlDiff", new Option (WANT_DIFF, "get the diff encoded in XML format"));
options.put ("--reportMd", new Option (WANT_REPORT_MD, "get the report of changes encoded in MarkDown"));
options.put ("--reportRST", new Option (WANT_REPORT_RST, "get the report of changes encoded in ReStructuredText"));
options.put ("--reportHtml", new Option (WANT_REPORT_HTML, "get the report of changes encoded in HTML"));
options.put ("--crnGraphml", new Option (WANT_CRN_GRAPHML, "get the highlighted chemical reaction network encoded in GraphML"));
options.put ("--crnDot", new Option (WANT_CRN_DOT, "get the highlighted chemical reaction network encoded in DOT language"));
options.put ("--crnJson", new Option (WANT_CRN_JSON, "get the highlighted chemical reaction network encoded in JSON"));
options.put ("--compHierarchyGraphml", new Option (WANT_COMP_HIERARCHY_GRAPHML, "get the hierarchy of components in a CellML document encoded in GraphML"));
options.put ("--compHierarchyDot", new Option (WANT_COMP_HIERARCHY_DOT, "get the hierarchy of components in a CellML document encoded in DOT language"));
options.put ("--compHierarchyJson", new Option (WANT_COMP_HIERARCHY_JSON, "get the hierarchy of components in a CellML document encoded in JSON"));
options.put ("--SBML", new Option (WANT_SBML, "force SBML comparison"));
options.put ("--CellML", new Option (WANT_CELLML, "force CellML comparison"));
options.put ("--regular", new Option (WANT_REGULAR, "force regular XML comparison"));
addOptions = new HashMap<String, Option> ();
addOptions.put ("--documentType", new Option (WANT_DOCUMENTTYPE, "get the documentType of an XML file"));
addOptions.put ("--meta", new Option (WANT_META, "get some meta information about an XML file"));
addOptions.put ("--singleCrnJson", new Option (WANT_SINGLE_CRN_JSON, "get the chemical reaction network of a single file encoded in JSON"));
addOptions.put ("--singleCrnGraphml", new Option (WANT_SINGLE_CRN_GRAPHML, "get the chemical reaction network of a single file encoded in GraphML"));
addOptions.put ("--singleCrnDot", new Option (WANT_SINGLE_CRN_DOT, "get the chemical reaction network of a single file encoded in DOT language"));
addOptions.put ("--singleCompHierarchyJson", new Option (WANT_SINGLE_COMP_HIERARCHY_JSON, "get the hierarchy of components in a single CellML document encoded in JSON"));
addOptions.put ("--singleCompHierarchyGraphml", new Option (WANT_SINGLE_COMP_HIERARCHY_GRAPHML, "get the hierarchy of components in a single CellML document encoded in GraphML"));
addOptions.put ("--singleCompHierarchyDot", new Option (WANT_SINGLE_COMP_HIERARCHY_DOT, "get the hierarchy of components in a single CellML document encoded in DOT language"));
}
public void usage (String msg)
{
if (msg != null && msg.length () > 0)
{
System.err.println (msg);
System.out.println ();
}
System.out.println ("ARGUMENTS:");
System.out.println ("\t[option] FILE1 [FILE2] compute the differences between 2 XML files");
System.out.println ();
System.out.println ("FILE1 and FILE2 define XML files to compare");
System.out.println ();
System.out.println ("OPTIONS:");
SortedSet<String> keys = new TreeSet<String>(options.keySet());
int longest = 0;
for (String key : keys)
{
if (key.length () > longest)
longest = key.length ();
}
SortedSet<String> addKeys = new TreeSet<String>(addOptions.keySet());
for (String key : addKeys)
{
if (key.length () > longest)
longest = key.length ();
}
longest += 2;
System.out.println ("\tCOMMON OPTIONS");
System.out.println ("\t[none]"+Tools.repeat (" ", longest - "[none]".length ()) +"expect XML files and print patch");
System.out.println ("\t--help"+Tools.repeat (" ", longest - "--help".length ()) +"print this help");
System.out.println ("\t--debug"+Tools.repeat (" ", longest - "--debug".length ()) +"enable verbose mode");
System.out.println ("\t--debugg"+Tools.repeat (" ", longest - "--debugg".length ()) +"enable even more verbose mode");
System.out.println ();
System.out.println ("\tMAPPING OPTIONS");
for (String key : keys)
System.out.println ("\t"+key + Tools.repeat (" ", longest - key.length ()) + options.get (key).description);
System.out.println ();
System.out.println ("\tENCODING OPTIONS");
System.out.println ("\tby default we will just dump the result to the terminal. Thus, it's only usefull if you call for one single output.");
System.out.println ("\t--json"+Tools.repeat (" ", longest - "--json".length ()) +"encode results in JSON");
System.out.println ("\t--xml"+Tools.repeat (" ", longest - "--xml".length ()) +"encode results in XML");
System.out.println ();
System.out.println ("\tADDITIONAL OPTIONS for single files");
for (String key : addKeys)
System.out.println ("\t"+key + Tools.repeat (" ", longest - key.length ()) + addOptions.get (key).description);
System.out.println ();
System.exit (2);
}
/**
* @param args
* @throws Exception
*/
public static void main (String[] args)
{
LOGGER.setLogToStdErr (false);
LOGGER.setLogToStdOut (false);
LOGGER.setLevel (LOGGER.ERROR);
//args = new String [] {"test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--reportHtml", "--xml", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--reportHtml", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--reportHtml", "test/BSA-ptinst-2012-11-11", "test/BSA-ptinst-2012-11-11"};
//args = new String [] {"--reportRST", "--crnGraphml", "--json", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--reportRST", "--crnGraphml", "--json", "--CellML", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--reportRST", "--crnGraphml", "--json", "--regular", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--debugg", "--reportRST", "--crnGraphml", "--json", "--SBML", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--debugg", "--reportRST", "--crnGraphml", "--json", "--regular", "test/BSA-ptinst-2012-11-11", "test/BSA-sigbprlysis-2012-11-11"};
//args = new String [] {"--meta", "test/BSA-ptinst-2012-11-11"};
//args = new String [] {"--documentType", "test/BSA-ptinst-2012-11-11"};
//args = new String [] {"--documentType", "test/BSA-ptinst-2012-11-11", "test/BSA-ptinst-2012-11-11"};
//args = new String [] {"--debugg", "--reportHtml", "test/potato (3).xml", "test/potato (3).xml"};
//args = new String [] {"--help"};
//args = new String [] {"--singleCompHierarchyJson", "test/bhalla_iyengar_1999_j_v1.cellml"};
//args = new String [] {"--reportHtml", "--SBML", "test/teusink-1.dat", "test/teusink-1.dat"};
Main m = new Main ();
try
{
m.run (args);
}
catch (Exception e)
{
m.usage ("ERROR: " + e.getClass ().getSimpleName () + ": " + e.getMessage ());
}
}
private Main ()
{
fillOptions ();
}
@SuppressWarnings("unchecked")
private void run (String[] args) throws Exception
{
Diff diff = null;
File file1 = null, file2 = null;
int output = 0;
int want = 0;
DocumentClassifier classifier = null;
HashMap<String, String> toReturn = new HashMap<String, String> ();
for (int i = 0; i < args.length; i++)
{
Option o = options.get (args[i]);
if (o != null)
{
want |= o.value;
continue;
}
o = addOptions.get (args[i]);
if (o != null)
{
want |= o.value;
continue;
}
if (args[i].equals ("--debug"))
{
LOGGER.setLogToStdErr (true);
LOGGER.setLevel (LOGGER.INFO | LOGGER.WARN | LOGGER.ERROR);
continue;
}
if (args[i].equals ("--debugg"))
{
LOGGER.setLogToStdErr (true);
LOGGER.setLevel (LOGGER.DEBUG | LOGGER.INFO | LOGGER.WARN | LOGGER.ERROR);
continue;
}
if (args[i].equals ("--xml"))
{
output = 1;
continue;
}
if (args[i].equals ("--json"))
{
output = 2;
continue;
}
/*if (args[i].equals ("--meta"))
{
want = -1;
continue;
}
if (args[i].equals ("--documentType"))
{
want = -2;
continue;
}*/
if (args[i].equals ("--help"))
{
usage ("");
}
if (file1 == null)
file1 = new File (args[i]);
else if (file2 == null)
file2 = new File (args[i]);
else
usage ("do not understand " + args[i] + " (found files " + file1 + " and " + file2 + ")");
}
if (file1 == null)
usage ("no file provided");
if (!file1.exists ())
usage ("cannot find " + file1.getAbsolutePath ());
if (!file1.canRead ())
usage ("cannot read " + file1.getAbsolutePath ());
if (file2 == null)
{
// single mode
if ((WANT_META & want) > 0)
{
// meta
classifier = new DocumentClassifier ();
int type = classifier.classify (file1);
String ret = "";
if ((type & DocumentClassifier.SBML) > 0)
{
SBMLDocument doc = classifier.getSbmlDocument ();
ret += "sbmlVersion:" + doc.getVersion () + ";sbmlLevel:" + doc.getLevel () + ";modelId:" + doc.getModel ().getID () + ";modelName:" + doc.getModel ().getName () + ";";
}
if ((type & DocumentClassifier.CELLML) > 0)
{
CellMLDocument doc = classifier.getCellMlDocument ();
ret += "containsImports:" + doc.containsImports () + ";modelName:" + doc.getModel ().getName () + ";";
}
if ((type & DocumentClassifier.XML) > 0)
{
TreeDocument doc = classifier.getXmlDocument ();
ret += "nodestats:" + doc.getNodeStats () + ";";
}
toReturn.put (REQ_WANT_META, ret);
}
if ((WANT_DOCUMENTTYPE & want) > 0)
{
// doc type
classifier = new DocumentClassifier ();
int type = classifier.classify (file1);
toReturn.put (REQ_WANT_DOCUMENTTYPE, DocumentClassifier.humanReadable (type));
}
if ((WANT_SINGLE_COMP_HIERARCHY_DOT|WANT_SINGLE_COMP_HIERARCHY_JSON|WANT_SINGLE_COMP_HIERARCHY_GRAPHML|WANT_SINGLE_CRN_JSON|WANT_SINGLE_CRN_GRAPHML|WANT_SINGLE_CRN_DOT & want) > 0)
{
Single single = null;
classifier = new DocumentClassifier ();
int type = classifier.classify (file1);
if ((type & DocumentClassifier.SBML) != 0)
{
single = new SBMLSingle (file1);
}
else if ((type & DocumentClassifier.CELLML) != 0)
{
single = new CellMLSingle (file1);
}
if (single == null)
usage ("cannot produce the requested output for the provided file.");
if ((want & WANT_SINGLE_CRN_JSON) > 0)
toReturn.put (REQ_WANT_SINGLE_CRN_JSON, result (single.getCRNJsonGraph ()));
if ((want & WANT_SINGLE_CRN_GRAPHML) > 0)
toReturn.put (REQ_WANT_SINGLE_CRN_GRAPHML, result (single.getCRNGraphML ()));
if ((want & WANT_SINGLE_CRN_DOT) > 0)
toReturn.put (REQ_WANT_SINGLE_CRN_DOT, result (single.getCRNDotGraph ()));
if ((want & WANT_SINGLE_COMP_HIERARCHY_JSON) > 0)
toReturn.put (REQ_WANT_SINGLE_COMP_HIERARCHY_JSON, result (single.getHierarchyJsonGraph ()));
if ((want & WANT_SINGLE_COMP_HIERARCHY_GRAPHML) > 0)
toReturn.put (REQ_WANT_SINGLE_COMP_HIERARCHY_GRAPHML, result (single.getHierarchyGraphML ()));
if ((want & WANT_SINGLE_COMP_HIERARCHY_DOT) > 0)
toReturn.put (REQ_WANT_SINGLE_COMP_HIERARCHY_DOT, result (single.getHierarchyDotGraph ()));
}
}
else
{
// compare mode
if (!file2.exists ())
usage ("cannot find " + file2.getAbsolutePath ());
if (!file2.canRead ())
usage ("cannot read " + file2.getAbsolutePath ());
if (want == 0)
want = WANT_DIFF;
// decide which kind of mapper to use
if ((WANT_CELLML & want) > 0)
diff = new CellMLDiff (file1, file2);
else if ((WANT_SBML & want) > 0)
diff = new SBMLDiff (file1, file2);
else if ((WANT_REGULAR & want) > 0)
diff = new RegularDiff (file1, file2);
else
{
classifier = new DocumentClassifier ();
int type1 = classifier.classify (file1);
int type2 = classifier.classify (file2);
int type = type1 & type2;
if ((type & DocumentClassifier.SBML) != 0)
{
diff = new SBMLDiff (file1, file2);
}
else if ((type & DocumentClassifier.CELLML) != 0)
{
diff = new CellMLDiff (file1, file2);
}
else if ((type & DocumentClassifier.XML) != 0)
{
diff = new RegularDiff (file1, file2);
}
else
usage ("cannot compare these files (["+DocumentClassifier.humanReadable (type1) + "] ["+DocumentClassifier.humanReadable (type2)+"])");
}
if (diff == null)
usage ("cannot compare these files");
//System.out.println (want);
// create mapping
diff.mapTrees ();
// compute results
if ((want & WANT_DIFF) > 0)
toReturn.put (REQ_WANT_DIFF, result (diff.getDiff ()));
if ((want & WANT_CRN_GRAPHML) > 0)
toReturn.put (REQ_WANT_CRN_GRAPHML, result (diff.getCRNGraphML ()));
if ((want & WANT_CRN_DOT) > 0)
toReturn.put (REQ_WANT_CRN_DOT, result (diff.getCRNDotGraph ()));
if ((want & WANT_CRN_JSON) > 0)
toReturn.put (REQ_WANT_CRN_JSON, result (diff.getCRNJsonGraph ()));
if ((want & WANT_COMP_HIERARCHY_DOT) > 0)
toReturn.put (REQ_WANT_COMP_HIERARCHY_DOT, result (diff.getHierarchyDotGraph ()));
if ((want & WANT_COMP_HIERARCHY_JSON) > 0)
toReturn.put (REQ_WANT_COMP_HIERARCHY_JSON, result (diff.getHierarchyJsonGraph ()));
if ((want & WANT_COMP_HIERARCHY_GRAPHML) > 0)
toReturn.put (REQ_WANT_COMP_HIERARCHY_GRAPHML, result (diff.getHierarchyGraphML ()));
if ((want & WANT_REPORT_HTML) > 0)
toReturn.put (REQ_WANT_REPORT_HTML, result (diff.getHTMLReport ()));
if ((want & WANT_REPORT_MD) > 0)
toReturn.put (REQ_WANT_REPORT_MD, result (diff.getMarkDownReport ()));
if ((want & WANT_REPORT_RST) > 0)
toReturn.put (REQ_WANT_REPORT_RST, result (diff.getReStructuredTextReport ()));
}
if (toReturn.size () < 1)
{
usage ("invalid call. no output produced.");
}
if (output == 0)
{
for (String ret : toReturn.keySet ())
System.out.println (toReturn.get (ret));
}
else if (output == 1)
{
//xml
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = (Element) document.createElement("bivesResult");
document.appendChild(root);
for (String ret : toReturn.keySet ())
{
Element el = (Element) document.createElement(ret);
el.appendChild (document.createTextNode(toReturn.get (ret)));
root.appendChild(el);
}
System.out.println (XmlTools.prettyPrintDocument (document));
}
else
{
// json
JSONObject json = new JSONObject ();
for (String ret : toReturn.keySet ())
json.put (ret, toReturn.get (ret));
System.out.println (json);
}
}
public static String result (String s)
{
if (s == null)
return "";
return s;
}
} |
package edu.ufl.cise.cnt5106c;
import edu.ufl.cise.cnt5106c.conf.RemotePeerInfo;
import edu.ufl.cise.cnt5106c.log.EventLogger;
import edu.ufl.cise.cnt5106c.log.LogHelper;
import edu.ufl.cise.cnt5106c.messages.Have;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
* @author Giacomo Benincasa (giacomo@cise.ufl.edu)
*/
public class Process implements Runnable, FileManagerListener, PeerManagerListener {
private final int _peerId;
private final String _address;
private final int _port;
private final boolean _hasFile;
private final Properties _conf;
private final FileManager _fileMgr;
private final PeerManager _peerMgr;
private final EventLogger _eventLogger;
private final AtomicBoolean _fileCompleted = new AtomicBoolean (false);
private final AtomicBoolean _peersFileCompleted = new AtomicBoolean (false);
private final AtomicBoolean _terminate = new AtomicBoolean (false);
private final Collection<ConnectionHandler> _connHandlers =
Collections.newSetFromMap(new ConcurrentHashMap<ConnectionHandler,Boolean>());
public Process (int peerId, String address, int port, boolean hasFile, Collection<RemotePeerInfo> peerInfo, Properties conf) {
_peerId = peerId;
_address = address;
_port = port;
_hasFile = hasFile;
_conf = conf;
_fileMgr = new FileManager (_peerId, _conf);
_fileMgr.registerListener (this);
_peerMgr = new PeerManager (peerInfo, _conf);
_peerMgr.registerListener (this);
_eventLogger = new EventLogger (peerId);
}
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket (_port);
while (!_terminate.get()) {
try {
LogHelper.getLogger().debug (Thread.currentThread().getName() + ": Peer " + _peerId + " listening on port " + _port + ".");
addConnHandler (new ConnectionHandler (_peerId, serverSocket.accept(), _fileMgr, _peerMgr));
}
catch (Exception e) {
LogHelper.getLogger().warning (e);
}
}
}
catch (IOException ex) {
LogHelper.getLogger().warning (ex);
}
finally {
LogHelper.getLogger().warning (Thread.currentThread().getName()
+ " terminating, TCP connections will no longer be accepted.");
}
}
void connectToPeers (Collection<RemotePeerInfo> peersToConnectTo) {
Iterator<RemotePeerInfo> iter = peersToConnectTo.iterator();
while (iter.hasNext()) {
do {
RemotePeerInfo peer = iter.next();
try {
if (addConnHandler (new ConnectionHandler (_peerId, true, peer.getPeerId(),
new Socket (peer._peerAddress, peer.getPort()), _fileMgr, _peerMgr))) {
iter.remove();
LogHelper.getLogger().debug (" Connecting to peer: " + peer.getPeerId()
+ " (" + peer._peerAddress + ":" + peer.getPort() + ")");
}
}
catch (IOException ex) {
LogHelper.getLogger().warning (ex);
}
}
while (iter.hasNext());
// Keep trying until they all connect
iter = peersToConnectTo.iterator();
try { Thread.sleep(5000); }
catch (InterruptedException ex) {}
}
}
@Override
public void neighborsCompletedDownload() {
_peersFileCompleted.set (true);
if (_fileCompleted.get() && _peersFileCompleted.get()) {
// The process can quit
_terminate.set (true);
}
}
@Override
public synchronized void fileCompleted() {
_fileCompleted.set (true);
if (_fileCompleted.get() && _peersFileCompleted.get()) {
// The process can quit
_terminate.set (true);
}
}
@Override
public synchronized void pieceArrived(int partIdx) {
for (ConnectionHandler connHanlder : _connHandlers) {
try {
connHanlder.send (new Have (partIdx));
}
catch (Exception ex) {
LogHelper.getLogger().warning(ex);
}
}
}
private synchronized boolean addConnHandler (ConnectionHandler connHandler) {
if (!_connHandlers.contains(connHandler)) {
_connHandlers.add(connHandler);
new Thread (connHandler).run();
}
return true;
}
} |
package eu.goodlike.time;
import com.google.common.base.MoreObjects;
import eu.goodlike.time.impl.TimeHandler;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Objects;
/**
* <pre>
* Resolves epoch milliseconds from various formats
*
* Intended to reduce code duplication when checking for variables, etc
* </pre>
*/
public final class TimeResolver {
/**
* @return epoch milliseconds of the starting time
*/
public long getStartTime() {
return startTime;
}
/**
* @return epoch milliseconds of the ending time
*/
public long getEndTime() {
return endTime;
}
// CONSTRUCTORS
/**
* <pre>
* Resolves the time using the following logic:
*
* 1) if start and end are set, use those;
* 2) if at least one of them is not set, resolve the time from remaining parameters, then use that time
* to set start, end or both and use those;
* </pre>
*/
public static TimeResolver from(String timezone, String startDate, String endDate, Long start, Long end) {
if (start == null || end == null) {
TimeResolver step = TimeResolver.from(timezone, startDate, endDate);
if (start == null)
start = step.startTime;
if (end == null)
end = step.endTime;
}
return from(start, end);
}
/**
* <pre>
* Resolves the time using the following logic:
*
* 1) if timeZone is set, parse it, otherwise use default (UTC)
* 2) if startDate is set, parse it to LocalDate using the timezone, otherwise set to current date using the timezone;
* 3) if endDate is set, parse it to LocalDate using the timezone, otherwise set to startDate
* 4) Resolve time from resulting ZoneId, start and end LocalDates
* </pre>
*/
public static TimeResolver from(String timezone, String startDate, String endDate) {
ZoneId zoneId = timezone == null
? Time.UTC()
: ZoneId.of(timezone);
LocalDate localStartDate = startDate == null
? LocalDate.now(zoneId)
: LocalDate.parse(startDate);
LocalDate localEndDate = endDate == null
? localStartDate
: LocalDate.parse(endDate);
return from(zoneId, localStartDate, localEndDate);
}
/**
* Resolves the time using TimeHandler for given zoneId and given LocalDates
*/
public static TimeResolver from(ZoneId zoneId, LocalDate localStartDate, LocalDate localEndDate) {
return from(Time.at(zoneId), localStartDate, localEndDate);
}
/**
* <pre>
* Resolves the time using the following logic:
*
* 1) get start epoch milliseconds from localStartDate;
* 2) get end epoch milliseconds from localEndDate + 1 day (so it is inclusive);
* 3) use start and end to resolve time
* </pre>
*/
public static TimeResolver from(TimeHandler handler, LocalDate localStartDate, LocalDate localEndDate) {
long start = handler.from(localStartDate).toEpochMilli();
long end = handler.from(localEndDate.plusDays(1)).toEpochMilli();
return from(start, end);
}
/**
* @return TimeResolver for already known start/end epoch millisecond values; fairly pointless, exists for
* compatibility only
*/
public static TimeResolver from(long start, long end) {
return new TimeResolver(start, end);
}
public TimeResolver(long startTime, long endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
// PRIVATE
private final long startTime;
private final long endTime;
// OBJECT OVERRIDES
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("startTime", startTime)
.add("endTime", endTime)
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TimeResolver)) return false;
TimeResolver that = (TimeResolver) o;
return Objects.equals(startTime, that.startTime) &&
Objects.equals(endTime, that.endTime);
}
@Override
public int hashCode() {
return Objects.hash(startTime, endTime);
}
} |
package ev3dev.hardware;
import ev3dev.utils.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EV3DevDistros {
private static final Logger LOGGER = LoggerFactory.getLogger(EV3DevDistros.class);
private static final String DEBIAN_DISTRO_DETECTION_QUERY = "cat /etc/os-release";
private static final String JESSIE_DISTRO_DETECTION_PATTERN = "ev3dev-jessie";
private static final String STRETCH_DISTRO_DETECTION_PATTERN = "ev3dev-stretch";
private static final String DEBIAN_DISTRO_DETECTION_KEY = "EV3DEV_DISTRO";
private static final String DEBIAN_DISTRO_DETECTION_JESSIE = "jessie";
private static final String DEBIAN_DISTRO_DETECTION_STRETCH = "stretch";
private EV3DevDistro CURRENT_DISTRO;
public EV3DevDistros() {
final String osResult = Shell.execute(DEBIAN_DISTRO_DETECTION_QUERY);
if (osResult.contains(JESSIE_DISTRO_DETECTION_PATTERN)) {
setJessie();
} else if (osResult.contains(STRETCH_DISTRO_DETECTION_PATTERN)) {
setStretch();
} else {
String value = System.getProperty(DEBIAN_DISTRO_DETECTION_KEY);
if (value != null) {
switch (value) {
case DEBIAN_DISTRO_DETECTION_JESSIE:
setJessie();
return;
case DEBIAN_DISTRO_DETECTION_STRETCH:
setStretch();
return;
}
}
LOGGER.warn("Failed to detect distro, falling back to Stretch.");
setStretch();
}
}
private void setStretch() {
LOGGER.debug("Debian Stretch detected");
CURRENT_DISTRO = EV3DevDistro.STRETCH;
}
private void setJessie() {
LOGGER.debug("Debian Jessie detected");
CURRENT_DISTRO = EV3DevDistro.JESSIE;
}
public EV3DevDistro getDistro() {
return CURRENT_DISTRO;
}
} |
package com.orientechnologies.lucene.functions;
import com.orientechnologies.lucene.builder.OLuceneQueryBuilder;
import com.orientechnologies.lucene.collections.OLuceneCompositeKey;
import com.orientechnologies.lucene.index.OLuceneFullTextIndex;
import com.orientechnologies.lucene.query.OLuceneKeyAndMetadata;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.parser.*;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.memory.MemoryIndex;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class OLuceneSearchOnIndexFunction extends OLuceneSearchFunctionTemplate {
public static final String MEMORY_INDEX = "_memoryIndex";
public static final String NAME = "search_index";
public OLuceneSearchOnIndexFunction() {
super(NAME, 2, 3);
}
@Override
public String getName() {
return NAME;
}
@Override
public Object execute(Object iThis, OIdentifiable iCurrentRecord, Object iCurrentResult, Object[] params, OCommandContext ctx) {
OElement element = iThis instanceof OElement ? (OElement) iThis : ((OResult) iThis).toElement();
String indexName = (String) params[0];
OLuceneFullTextIndex index = searchForIndex(ctx, indexName);
if (index == null)
return false;
String query = (String) params[1];
MemoryIndex memoryIndex = getOrCreateMemoryIndex(ctx);
List<Object> key = index.getDefinition().getFields().stream().map(s -> element.getProperty(s)).collect(Collectors.toList());
for (IndexableField field : index.buildDocument(key).getFields()) {
memoryIndex.addField(field, index.indexAnalyzer());
}
ODocument metadata = getMetadata(params);
OLuceneKeyAndMetadata keyAndMetadata = new OLuceneKeyAndMetadata(new OLuceneCompositeKey(Arrays.asList(query)).setContext(ctx),
metadata);
return memoryIndex.search(index.buildQuery(keyAndMetadata)) > 0.0f;
}
private ODocument getMetadata(Object[] params) {
if (params.length == 3) {
return new ODocument().fromMap((Map<String, ?>) params[2]);
}
return OLuceneQueryBuilder.EMPTY_METADATA;
}
private MemoryIndex getOrCreateMemoryIndex(OCommandContext ctx) {
MemoryIndex memoryIndex = (MemoryIndex) ctx.getVariable(MEMORY_INDEX);
if (memoryIndex == null) {
memoryIndex = new MemoryIndex();
ctx.setVariable(MEMORY_INDEX, memoryIndex);
}
memoryIndex.reset();
return memoryIndex;
}
@Override
public String getSyntax() {
return "SEARCH_INDEX( indexName, [ metdatada {} ] )";
}
@Override
public boolean filterResult() {
return true;
}
@Override
public Iterable<OIdentifiable> searchFromTarget(OFromClause target, OBinaryCompareOperator operator, Object rightValue,
OCommandContext ctx, OExpression... args) {
OLuceneFullTextIndex index = searchForIndex(target, ctx, args);
OExpression expression = args[1];
String query = (String) expression.execute((OIdentifiable) null, ctx);
if (index != null && query != null) {
ODocument meta = getMetadata(index, query, args);
List<OIdentifiable> luceneResultSet;
try (Stream<ORID> rids = index.getInternal()
.getRids(new OLuceneKeyAndMetadata(new OLuceneCompositeKey(Arrays.asList(query)).setContext(ctx), meta))) {
luceneResultSet = rids.collect(Collectors.toList());
}
return luceneResultSet;
}
return Collections.emptyList();
}
private ODocument getMetadata(OLuceneFullTextIndex index, String query, OExpression[] args) {
if (args.length == 3) {
ODocument metadata = new ODocument().fromJSON(args[2].toString());
return metadata;
}
return new ODocument();
}
@Override
protected OLuceneFullTextIndex searchForIndex(OFromClause target, OCommandContext ctx, OExpression... args) {
OFromItem item = target.getItem();
OIdentifier identifier = item.getIdentifier();
return searchForIndex(identifier.getStringValue(), ctx, args);
}
private OLuceneFullTextIndex searchForIndex(String className, OCommandContext ctx, OExpression... args) {
String indexName = (String) args[0].execute((OIdentifiable) null, ctx);
final ODatabaseDocumentInternal database = (ODatabaseDocumentInternal) ctx.getDatabase();
OIndex index = database.getMetadata().getIndexManagerInternal().getClassIndex(database, className, indexName);
if (index != null && index.getInternal() instanceof OLuceneFullTextIndex) {
return (OLuceneFullTextIndex) index;
}
return null;
}
private OLuceneFullTextIndex searchForIndex(OCommandContext ctx, String indexName) {
final ODatabaseDocumentInternal database = (ODatabaseDocumentInternal) ctx.getDatabase();
OIndex index = database.getMetadata().getIndexManagerInternal().getIndex(database, indexName);
if (index != null && index.getInternal() instanceof OLuceneFullTextIndex) {
return (OLuceneFullTextIndex) index;
}
return null;
}
@Override
public Object getResult() {
return super.getResult();
}
} |
package galvin.swing.spell;
import com.swabunga.spell.engine.SpellDictionary;
import com.swabunga.spell.engine.SpellDictionaryHashMap;
import galvin.SystemUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SpellUtils
{
public static final String BASE_DICTIONARY = "spell/eng_com.dic";
public static final String[] AMERICA_ENGLISH_DICTIONARIES = new String[]
{
BASE_DICTIONARY, "spell/color.dic", "spell/labeled.dic", "spell/center.dic", "spell/ize.dic", "spell/yze.dic", "spell/aspell.dic"
};
public static final String[] BRITTISH_ENGLISH_DICTIONARIES = new String[]
{
BASE_DICTIONARY, "spell/colour.dic", "spell/labelled.dic", "spell/centre.dic", "spell/ise.dic", "spell/yse.dic"
};
public static final File MAC_SYSTEM_DICTIONARY = new File( "/usr/share/dict/words" );
public static final String CUSTOM_DICTIONARY_FOLDER = "Dictionaries";
public static final String CUSTOM_DICTIONARY_FILE = "customJazzyDictionary.dic";
private static SpellDictionary americanDictionary;
private static SpellDictionary brittishDictionary;
private static SpellDictionaryUser customDictionary;
public static SpellDictionary getAmericanDictionary()
throws IOException
{
if( americanDictionary == null )
{
americanDictionary = loadDictionary( AMERICA_ENGLISH_DICTIONARIES );
}
return americanDictionary;
}
public static SpellDictionary getBrittishDictionary()
throws IOException
{
if( brittishDictionary == null )
{
brittishDictionary = loadDictionary( BRITTISH_ENGLISH_DICTIONARIES );
}
return brittishDictionary;
}
public static SpellDictionary loadDictionary( String[] dictionaryNames )
throws IOException
{
SpellDictionaryHashMap result = new SpellDictionaryHashMap();
for( String dictionaryName : dictionaryNames )
{
ClassLoader classloader = result.getClass().getClassLoader();
InputStream stream = classloader.getResourceAsStream( dictionaryName );
InputStreamReader reader = new InputStreamReader( stream );
result.addDictionary( reader );
reader.close();
}
if( SystemUtils.IS_MAC ){
result.addDictionary( MAC_SYSTEM_DICTIONARY );
}
return result;
}
public static SpellDictionaryUser loadDictionary( File dictionaryFile )
throws IOException
{
SpellDictionaryUser result = new SpellDictionaryUser( dictionaryFile );
return result;
}
public static File getDictionariesDirectory()
throws IOException
{
String fileName = System.getProperty( "user.home" );
fileName += File.separatorChar;
if( SystemUtils.IS_MAC )
{
fileName += "Library" + File.separatorChar + CUSTOM_DICTIONARY_FOLDER + File.separatorChar;
}
else if( SystemUtils.IS_WINDOWS )
{
fileName += "Application Data" + File.separatorChar + CUSTOM_DICTIONARY_FOLDER + File.separatorChar;
}
else
{
//assuming a unix variant
fileName += "." + CUSTOM_DICTIONARY_FOLDER + File.separatorChar;
}
File file = new File( fileName );
file.mkdirs();
return file;
}
public static SpellDictionaryUser getCustomDictionary()
throws IOException
{
if( customDictionary == null )
{
customDictionary = loadDictionary( getCustomDictionaryFile() );
}
return customDictionary;
}
public static File getCustomDictionaryFile()
throws IOException
{
File file = new File( getDictionariesDirectory(), CUSTOM_DICTIONARY_FILE );
if( !file.exists() )
{
file.createNewFile();
}
return file;
}
} |
package hm.binkley.util;
import com.google.inject.Binder;
import com.google.inject.multibindings.Multibinder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static java.lang.Character.charCount;
import static java.lang.Character.isWhitespace;
import static java.lang.ClassLoader.getSystemClassLoader;
import static java.lang.Thread.currentThread;
import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.createBeanDefinition;
/**
* {@code Bindings} <b>needs documentation</b>.
*
* @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
* @todo Needs documentation.
*/
public final class ServiceBinder<E extends Exception> {
private static final String PREFIX = "META-INF/services/";
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Pattern COMMENT = Pattern.compile("
private final Bindings<E> bindings;
private interface Bindings<E extends Exception> {
<T> void bind(final Class<T> service, final Iterable<Class<? extends T>> implementation)
throws E;
}
public static ServiceBinder<RuntimeException> on(@Nonnull final Binder binder) {
return new ServiceBinder<RuntimeException>(new GuiceBindings(binder));
}
public static ServiceBinder<ClassNotFoundException> on(
@Nonnull final BeanDefinitionRegistry registry) {
return new ServiceBinder<ClassNotFoundException>(new SpringBindings(registry));
}
public <T> void bind(@Nonnull final Class<T> service) {
bind(service, currentThread().getContextClassLoader());
}
public <T> void bind(@Nonnull final Class<T> service, @Nullable ClassLoader classLoader) {
if (null == classLoader)
classLoader = getSystemClassLoader();
final Enumeration<URL> configs = configs(service, classLoader);
while (configs.hasMoreElements())
bind(service, classLoader, configs.nextElement());
}
private ServiceBinder(final Bindings<E> bindings) {
this.bindings = bindings;
}
private <T> void bind(final Class<T> service, final ClassLoader classLoader, final URL config) {
final BufferedReader reader = config(service, config);
try {
final List<Class<? extends T>> implementations = new ArrayList<Class<? extends T>>();
String implementation;
while (null != (implementation = implementation(service, config, reader)))
if (!skip(implementation))
implementations.add(loadClass(service, classLoader, config, implementation));
bindings.bind(service, implementations);
} catch (final Exception e) {
fail(service, config, "Cannot bind implemntations", e);
} finally {
try {
reader.close();
} catch (final IOException e) {
fail(service, config, "Cannot close", e);
}
}
}
@SuppressWarnings("unchecked")
private static <T> Class<? extends T> loadClass(final Class<T> service,
final ClassLoader classLoader, final URL config, final String className) {
try {
return (Class<? extends T>) classLoader.loadClass(className);
} catch (final ClassNotFoundException e) {
return fail(service, config, "Cannot bind implementation for " + className, e);
}
}
private static <T> String implementation(final Class<T> service, final URL config,
final BufferedReader reader) {
try {
final String line = reader.readLine();
if (null == line)
return null;
else
return COMMENT.matcher(line).replaceFirst("").trim();
} catch (final IOException e) {
return fail(service, config, "Cannot read service configuration", e);
}
}
private static <T> BufferedReader config(final Class<T> service, final URL config) {
try {
return new BufferedReader(new InputStreamReader(config.openStream(), UTF8));
} catch (final IOException e) {
return fail(service, config, "Cannot read service configuration", e);
}
}
private static <T> Enumeration<URL> configs(final Class<T> service,
final ClassLoader classLoader) {
try {
return classLoader.getResources(PREFIX + service.getName());
} catch (final IOException e) {
return fail(service, "Cannot load configuration", e);
}
}
private static boolean skip(final String s) {
if (null == s)
return true;
final int len = s.length();
if (0 == len)
return true;
for (int i = 0; i < len; ) {
final int cp = s.codePointAt(i);
if (!isWhitespace(cp))
return false;
i += charCount(cp);
}
return true;
}
private static <R> R fail(final Class<?> service, final String message, final Exception cause) {
throw new ServiceBinderError(service, message, cause);
}
private static <R> R fail(final Class<?> service, final URL config, final String message,
final Exception cause) {
throw new ServiceBinderError(service, config + ": " + message, cause);
}
private static class GuiceBindings
implements Bindings<RuntimeException> {
private final Binder binder;
public GuiceBindings(final Binder binder) {
this.binder = binder;
}
@Override
public <T> void bind(final Class<T> service,
final Iterable<Class<? extends T>> implementations) {
final Multibinder<T> bindings = newSetBinder(binder, service);
for (final Class<? extends T> implementation : implementations)
bindings.addBinding().to(implementation);
}
}
private static class SpringBindings
implements Bindings<ClassNotFoundException> {
private final BeanDefinitionRegistry registry;
public SpringBindings(final BeanDefinitionRegistry registry) {
this.registry = registry;
}
@Override
public <T> void bind(final Class<T> service,
final Iterable<Class<? extends T>> implementations)
throws ClassNotFoundException {
for (final Class<? extends T> implementation : implementations)
registry.registerBeanDefinition(
"_" + service.getName() + ":" + implementation.getName(),
createBeanDefinition(null, service.getName(), null));
}
}
} |
package org.apache.maven.lifecycle.statemgmt;
import org.apache.maven.lifecycle.MojoBindingUtils;
import org.apache.maven.lifecycle.binding.MojoBindingFactory;
import org.apache.maven.lifecycle.model.MojoBinding;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.loader.PluginLoader;
import org.apache.maven.plugin.loader.PluginLoaderException;
import org.apache.maven.project.MavenProject;
public class ResolveLateBoundPluginMojo extends AbstractMojo
{
/**
* @component
*/
private PluginLoader pluginLoader;
private String groupId;
private String artifactId;
private String version;
private String goal;
private boolean includeReportConfig = false;
private MavenProject project;
private MojoBindingFactory bindingFactory;
public void execute() throws MojoExecutionException, MojoFailureException
{
MojoBinding binding = bindingFactory.createMojoBinding( groupId, artifactId, version, artifactId, project, includeReportConfig );
try
{
PluginDescriptor descriptor = pluginLoader.loadPlugin( binding, project );
MojoDescriptor mojoDescriptor = descriptor.getMojo( goal );
if ( mojoDescriptor == null )
{
throw new MojoExecutionException( "Resolved plugin: " + descriptor.getId()
+ " does not contain a mojo called \'" + goal + "\'." );
}
}
catch ( PluginLoaderException e )
{
throw new MojoExecutionException( "Failed to load late-bound plugin: "
+ MojoBindingUtils.createPluginKey( binding ), e );
}
}
} |
package hu.sebcsaba.webfeed;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Processor implements Closeable {
private final Config config;
private final PrintWriter log;
public Processor(Config config) throws FileNotFoundException {
this.config = config;
this.log = new PrintWriter("webfeed.log");
}
public void close() {
log.close();
}
public Set<String> process() throws IOException {
HashSet<String> result = new HashSet<>();
for (String code : config.getUrls().keySet()) {
Set<String> site = processSite(code);
result.addAll(site);
}
return result;
}
private Set<String> processSite(String code) throws IOException {
String siteUrl = config.getUrls().get(code);
Set<String> result = new HashSet<>();
String nextPageUrl = siteUrl;
int page = 0;
do {
nextPageUrl = processSitePage(result, code, nextPageUrl, page++);
} while (nextPageUrl != null);
return result;
}
private String processSitePage(Set<String> result, String code, String siteUrl, int page) throws IOException {
log.println("processing "+code+" page "+page);
log.println("* loading "+siteUrl);
Document doc = Jsoup.connect(siteUrl).get();
Elements items = doc.select(config.getSelects().get(code));
log.println("* found items: "+items.size());
for (Element item : items) {
String href = item.attr("href");
result.add(getAbsoluteUrl(siteUrl, href));
}
String pager = config.getPagers().get(code);
if (pager != null) {
Element nextLink = doc.select(pager).first();
if (nextLink!=null) {
String href = nextLink.attr("href");
return getAbsoluteUrl(siteUrl, href);
}
}
return null;
}
private String getAbsoluteUrl(String startUrl, String href) {
int hash = href.indexOf('
if (hash>=0) {
href = href.substring(0, hash);
}
if (href.startsWith("http")) {
return href;
} else {
String baseUrl = getBaseUrl(startUrl, href.startsWith("/"));
return baseUrl + href;
}
}
private String getBaseUrl(String startUrl, boolean absolute) {
if (absolute) {
int idx = startUrl.indexOf('/', 7);
if (idx<0) {
return startUrl;
} else {
return startUrl.substring(0, idx);
}
} else {
int idx = startUrl.lastIndexOf('/');
if (idx<0) {
return startUrl+"/";
} else {
return startUrl.substring(0, idx+1);
}
}
}
} |
package infovis.embed;
import static infovis.VecUtil.*;
import infovis.ctrl.Controller;
import infovis.data.BusLine;
import infovis.data.BusStation;
import infovis.data.BusStation.Neighbor;
import infovis.data.BusTime;
import infovis.embed.pol.Interpolator;
import infovis.routing.RoutingManager;
import infovis.routing.RoutingManager.CallBack;
import infovis.routing.RoutingResult;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Weights the station network after the distance from one start station.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public final class StationDistance implements Weighter, NodeDrawer {
/**
* The backing map for the spring nodes.
*/
private final Map<SpringNode, BusStation> map;
/**
* The reverse backing map for the spring nodes.
*/
private final Map<BusStation, SpringNode> rev;
/**
* The routes from the bus station.
*/
protected volatile Map<BusStation, RoutingResult> routes;
/**
* The current reference time.
*/
protected BusTime time = new BusTime(12, 0);
/**
* The change time for lines.
*/
protected int changeTime = 5;
/**
* The start bus station or <code>null</code> if there is none.
*/
protected BusStation from;
/**
* The factor to scale the distances.
*/
private double factor = .1;
/**
* The controller.
*/
protected final Controller ctrl;
/**
* Creates a station distance without a reference station.
*
* @param ctrl The controller.
*/
public StationDistance(final Controller ctrl) {
this.ctrl = ctrl;
routes = Collections.EMPTY_MAP;
map = new HashMap<SpringNode, BusStation>();
rev = new HashMap<BusStation, SpringNode>();
for(final BusStation s : ctrl.getStations()) {
final SpringNode node = new SpringNode();
node.setPosition(s.getDefaultX(), s.getDefaultY());
map.put(node, s);
rev.put(s, node);
}
}
/**
* The predicted next bus station.
*/
protected volatile BusStation predict;
/**
* The current waiter thread.
*/
protected volatile Thread currentCalculator;
/**
* The fading bus station.
*/
protected BusStation fadeOut;
/**
* The fading start time.
*/
protected long fadingStart;
/**
* The fading end time.
*/
protected long fadingEnd;
/**
* Whether we do fade currently.
*/
protected boolean fade;
/**
* The routing manager.
*/
private final RoutingManager rm = RoutingManager.newInstance();
/**
* The animator to be notified when something has changed.
*/
private Animator animator;
/**
* Sets the values for the distance.
*
* @param from The reference station.
* @param time The reference time.
* @param changeTime The change time.
*/
public void set(final BusStation from, final BusTime time, final int changeTime) {
predict = from;
if(from == null) {
putSettings(Collections.EMPTY_MAP, from, time, changeTime);
return;
}
final CallBack<Collection<RoutingResult>> cb = new CallBack<Collection<RoutingResult>>() {
@Override
public void callBack(final Collection<RoutingResult> result) {
final Set<BusStation> all = new HashSet<BusStation>(
Arrays.asList(ctrl.getAllStations()));
final Map<BusStation, RoutingResult> route = new HashMap<BusStation, RoutingResult>();
for(final RoutingResult r : result) {
final BusStation end = r.getEnd();
route.put(end, r);
all.remove(end);
}
for(final BusStation s : all) {
route.put(s, new RoutingResult(from, s));
}
putSettings(route, from, time, changeTime);
}
};
rm.findRoutes(from, null, time != null ? time : BusTime.now(), changeTime,
ctrl.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR, ctrl.getRoutingAlgorithm(), cb);
}
/**
* Puts the new settings.
*
* @param route The routes.
* @param from The start station.
* @param time The start time.
* @param changeTime The change time.
*/
protected synchronized void putSettings(final Map<BusStation, RoutingResult> route,
final BusStation from, final BusTime time, final int changeTime) {
routes = route;
if(from != StationDistance.this.from) {
fadeOut = StationDistance.this.from;
fadingStart = System.currentTimeMillis();
fadingEnd = fadingStart + Interpolator.NORMAL;
fade = true;
}
changes = ((time != null && StationDistance.this.time != null) &&
(StationDistance.this.time != time || StationDistance.this.changeTime != changeTime))
? FAST_ANIMATION_CHANGE : NORMAL_CHANGE;
StationDistance.this.from = from;
StationDistance.this.time = time;
StationDistance.this.changeTime = changeTime;
animator.forceNextFrame();
}
@Override
public void setAnimator(final Animator animator) {
this.animator = animator;
}
/**
* Whether the weights have changed.
*/
protected volatile int changes;
@Override
public int changes() {
final int res = changes;
changes = NO_CHANGE;
return res;
}
/**
* Signals undefined changes.
*/
public void changeUndefined() {
set(from, time, changeTime);
}
/**
* Setter.
*
* @param from Sets the reference station.
*/
public void setFrom(final BusStation from) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The reference station.
*/
public BusStation getFrom() {
return from;
}
/**
* Setter.
*
* @param time Sets the reference time.
*/
public void setTime(final BusTime time) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The reference time.
*/
public BusTime getTime() {
return time;
}
/**
* Setter.
*
* @param changeTime Sets the change time.
*/
public void setChangeTime(final int changeTime) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The change time.
*/
public int getChangeTime() {
return changeTime;
}
/**
* Setter.
*
* @param factor Sets the distance factor.
*/
public void setFactor(final double factor) {
this.factor = factor;
}
/**
* Getter.
*
* @return The distance factor.
*/
public double getFactor() {
return factor;
}
/**
* The minimal distance between nodes.
*/
private double minDist = 15;
/**
* Setter.
*
* @param minDist Sets the minimal distance between nodes.
*/
public void setMinDist(final double minDist) {
this.minDist = minDist;
}
/**
* Getter.
*
* @return The minimal distance between nodes.
*/
public double getMinDist() {
return minDist;
}
@Override
public double weight(final SpringNode f, final SpringNode t) {
if(from == null || t == f) return 0;
final BusStation fr = map.get(f);
if(fr.equals(from)) return 0;
final BusStation to = map.get(t);
if(to.equals(from)) return factor * routes.get(fr).minutes();
return -minDist;
}
@Override
public boolean hasWeight(final SpringNode f, final SpringNode t) {
if(from == null || t == f) return false;
final BusStation fr = map.get(f);
if(fr.equals(from)) return false;
final BusStation to = map.get(t);
if(to.equals(from)) return !routes.get(fr).isNotReachable();
return true;
}
@Override
public Iterable<SpringNode> nodes() {
return map.keySet();
}
@Override
public double springConstant() {
return 0.75;
}
@Override
public void drawEdges(final Graphics2D g, final SpringNode n) {
final BusStation station = map.get(n);
final RoutingResult route = routes.get(station);
if(route != null && route.isNotReachable()) return;
final double x1 = n.getX();
final double y1 = n.getY();
for(final Neighbor edge : station.getNeighbors()) {
final BusStation neighbor = edge.station;
final SpringNode node = rev.get(neighbor);
final RoutingResult otherRoute = routes.get(neighbor);
if(otherRoute != null && otherRoute.isNotReachable()) {
continue;
}
final double x2 = node.getX();
final double y2 = node.getY();
int counter = 0;
for(final BusLine line : edge.lines) {
g.setStroke(new BasicStroke(edge.lines.length - counter, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_BEVEL));
g.setColor(line.getColor());
g.draw(new Line2D.Double(x1, y1, x2, y2));
++counter;
}
}
}
@Override
public void drawNode(final Graphics2D g, final SpringNode n) {
final BusStation station = map.get(n);
final RoutingResult route = routes.get(station);
if(route != null && route.isNotReachable()) return;
final Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(!station.equals(from) ? Color.WHITE : Color.RED);
final Shape shape = nodeClickArea(n, true);
g2.fill(shape);
g2.setStroke(new BasicStroke(.5f));
g2.setColor(Color.BLACK);
g2.draw(shape);
g2.dispose();
}
@Override
public void drawLabel(final Graphics2D g, final SpringNode n) {
final BusStation station = map.get(n);
final double x = n.getX();
final double y = n.getY();
if(station.getNeighbors().length == 2) return;
final Graphics2D gfx = (Graphics2D) g.create();
gfx.setColor(Color.BLACK);
gfx.translate(x, y);
gfx.drawString(station.getName(), 0, 0);
gfx.dispose();
}
@Override
public void dragNode(final SpringNode n, final double startX, final double startY,
final double dx, final double dy) {
final BusStation station = map.get(n);
if(!station.equals(from)) {
ctrl.selectStation(station);
}
n.setPosition(startX + dx, startY + dy);
}
@Override
public void selectNode(final SpringNode n) {
final BusStation station = map.get(n);
if(!station.equals(from)) {
ctrl.selectStation(station);
}
}
@Override
public Shape nodeClickArea(final SpringNode n, final boolean real) {
final BusStation station = map.get(n);
final double r = Math.max(2, station.getMaxDegree() / 2);
final double x = real ? n.getX() : n.getPredictX();
final double y = real ? n.getY() : n.getPredictY();
return new Ellipse2D.Double(x - r, y - r, r * 2, r * 2);
}
@Override
public void drawBackground(final Graphics2D g) {
final SpringNode ref = getReferenceNode();
if(ref == null && !fade) return;
Point2D center;
double alpha;
if(fade) {
final long time = System.currentTimeMillis();
final double t = ((double) time - fadingStart) / ((double) fadingEnd - fadingStart);
final double f = Interpolator.SMOOTH.interpolate(t);
final SpringNode n = f > 0.5 ? ref : rev.get(fadeOut);
center = n != null ? n.getPos() : null;
if(t >= 1.0) {
alpha = 1;
fadeOut = null;
fade = false;
} else {
alpha = f > 0.5 ? (f - 0.5) * 2 : 1 - f * 2;
}
} else {
center = ref.getPos();
alpha = 1;
}
if(center == null) return;
boolean b = true;
g.setColor(Color.WHITE);
for(int i = MAX_INTERVAL; i > 0; --i) {
final Shape circ = getCircle(i, center);
final Graphics2D g2 = (Graphics2D) g.create();
if(b) {
final double d = (MAX_INTERVAL - i + 2.0) / (MAX_INTERVAL + 2);
final double curAlpha = alpha * d;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
(float) curAlpha));
g2.setColor(Color.LIGHT_GRAY);
}
b = !b;
g2.fill(circ);
g2.dispose();
}
}
@Override
public boolean inAnimation() {
return fade;
}
/**
* The highest drawn circle interval.
*/
public static final int MAX_INTERVAL = 12;
/**
* Getter.
*
* @param i The interval.
* @param center The center of the circle.
* @return The circle.
*/
public Ellipse2D getCircle(final int i, final Point2D center) {
final Point2D c = center != null ? center : getReferenceNode().getPos();
final double radius = factor * 5 * i;
final double r2 = radius * 2;
return new Ellipse2D.Double(c.getX() - radius, c.getY() - radius, r2, r2);
}
@Override
public Point2D getDefaultPosition(final SpringNode node) {
final BusStation station = map.get(node);
return new Point2D.Double(station.getDefaultX(), station.getDefaultY());
}
@Override
public SpringNode getReferenceNode() {
return from == null ? null : rev.get(from);
}
@Override
public String getTooltipText(final SpringNode node) {
final BusStation station = map.get(node);
String dist;
if(from != null && from != station) {
final RoutingResult route = routes.get(station);
if(!route.isNotReachable()) {
dist = " (" + BusTime.minutesToString(route.minutes()) + ")";
} else {
dist = " (not reachable)";
}
} else {
dist = "";
}
return station.getName() + dist;
}
@Override
public void moveMouse(final Point2D cur) {
if(from != null) {
ctrl.setTitle(BusTime.minutesToString((int) Math.ceil(getLength(subVec(cur,
getReferenceNode().getPos())) / factor)));
} else {
ctrl.setTitle(null);
}
}
/**
* Getter.
*
* @param station The station.
* @return The corresponding node.
*/
public SpringNode getNode(final BusStation station) {
return station == null ? null : rev.get(station);
}
@Override
public Rectangle2D getBoundingBox() {
Rectangle2D bbox = null;
final BusStation s = predict;
if(s != null) {
final Point2D pos = getNode(s).getPos();
bbox = getCircle(StationDistance.MAX_INTERVAL, pos).getBounds2D();
} else {
for(final SpringNode n : nodes()) {
final Rectangle2D b = nodeClickArea(n, false).getBounds2D();
if(bbox == null) {
bbox = b;
} else {
bbox.add(b);
}
}
}
return bbox;
}
} |
package org.mifosplatform.portfolio.savings.domain;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.annualFeeAmountParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.annualFeeOnMonthDayParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.localeParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.lockinPeriodFrequencyParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.lockinPeriodFrequencyTypeParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeAmountParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeForTransfersParamName;
import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeTypeParamName;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.joda.time.LocalDate;
import org.joda.time.MonthDay;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.domain.LocalDateInterval;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import org.mifosplatform.infrastructure.core.service.DateUtils;
import org.mifosplatform.infrastructure.security.service.RandomPasswordGenerator;
import org.mifosplatform.organisation.monetary.data.CurrencyData;
import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency;
import org.mifosplatform.organisation.monetary.domain.Money;
import org.mifosplatform.organisation.staff.domain.Staff;
import org.mifosplatform.portfolio.accountdetails.domain.AccountType;
import org.mifosplatform.portfolio.client.domain.Client;
import org.mifosplatform.portfolio.group.domain.Group;
import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType;
import org.mifosplatform.portfolio.savings.SavingsApiConstants;
import org.mifosplatform.portfolio.savings.SavingsCompoundingInterestPeriodType;
import org.mifosplatform.portfolio.savings.SavingsInterestCalculationDaysInYearType;
import org.mifosplatform.portfolio.savings.SavingsInterestCalculationType;
import org.mifosplatform.portfolio.savings.SavingsPeriodFrequencyType;
import org.mifosplatform.portfolio.savings.SavingsPostingInterestPeriodType;
import org.mifosplatform.portfolio.savings.SavingsWithdrawalFeesType;
import org.mifosplatform.portfolio.savings.data.SavingsAccountTransactionDTO;
import org.mifosplatform.portfolio.savings.domain.interest.PostingPeriod;
import org.mifosplatform.portfolio.savings.exception.InsufficientAccountBalanceException;
import org.mifosplatform.portfolio.savings.service.SavingsEnumerations;
import org.mifosplatform.useradministration.domain.AppUser;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "m_savings_account", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "sa_account_no_UNIQUE"),
@UniqueConstraint(columnNames = { "external_id" }, name = "sa_external_id_UNIQUE") })
public class SavingsAccount extends AbstractPersistable<Long> {
@Column(name = "account_no", length = 20, unique = true, nullable = false)
private String accountNumber;
@Column(name = "external_id", nullable = true)
private String externalId;
@ManyToOne(optional = true)
@JoinColumn(name = "client_id", nullable = true)
private Client client;
@ManyToOne(optional = true)
@JoinColumn(name = "group_id", nullable = true)
private Group group;
@ManyToOne
@JoinColumn(name = "product_id", nullable = false)
private SavingsProduct product;
@ManyToOne
@JoinColumn(name = "field_officer_id", nullable = true)
private Staff fieldOfficer;
@Column(name = "status_enum", nullable = false)
private Integer status;
@Column(name = "account_type_enum", nullable = false)
private Integer accountType;
@Temporal(TemporalType.DATE)
@Column(name = "submittedon_date", nullable = true)
private Date submittedOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "submittedon_userid", nullable = true)
private AppUser submittedBy;
@Temporal(TemporalType.DATE)
@Column(name = "rejectedon_date")
private Date rejectedOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "rejectedon_userid", nullable = true)
private AppUser rejectedBy;
@Temporal(TemporalType.DATE)
@Column(name = "withdrawnon_date")
private Date withdrawnOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "withdrawnon_userid", nullable = true)
private AppUser withdrawnBy;
@Temporal(TemporalType.DATE)
@Column(name = "approvedon_date")
private Date approvedOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "approvedon_userid", nullable = true)
private AppUser approvedBy;
@Temporal(TemporalType.DATE)
@Column(name = "activatedon_date", nullable = true)
private Date activatedOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "activatedon_userid", nullable = true)
private AppUser activatedBy;
@Temporal(TemporalType.DATE)
@Column(name = "closedon_date")
private Date closedOnDate;
@ManyToOne(optional = true)
@JoinColumn(name = "closedon_userid", nullable = true)
private AppUser closedBy;
@Embedded
private MonetaryCurrency currency;
@Column(name = "nominal_annual_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal nominalAnnualInterestRate;
/**
* The interest period is the span of time at the end of which savings in a
* client's account earn interest.
*
* A value from the {@link SavingsCompoundingInterestPeriodType}
* enumeration.
*/
@Column(name = "interest_compounding_period_enum", nullable = false)
private Integer interestCompoundingPeriodType;
/**
* A value from the {@link SavingsPostingInterestPeriodType} enumeration.
*/
@Column(name = "interest_posting_period_enum", nullable = false)
private Integer interestPostingPeriodType;
/**
* A value from the {@link SavingsInterestCalculationType} enumeration.
*/
@Column(name = "interest_calculation_type_enum", nullable = false)
private Integer interestCalculationType;
/**
* A value from the {@link SavingsInterestCalculationDaysInYearType}
* enumeration.
*/
@Column(name = "interest_calculation_days_in_year_type_enum", nullable = false)
private Integer interestCalculationDaysInYearType;
@Column(name = "min_required_opening_balance", scale = 6, precision = 19, nullable = true)
private BigDecimal minRequiredOpeningBalance;
@Column(name = "lockin_period_frequency", nullable = true)
private Integer lockinPeriodFrequency;
@Column(name = "lockin_period_frequency_enum", nullable = true)
private Integer lockinPeriodFrequencyType;
/**
* When account becomes <code>active</code> this field is derived if
* <code>lockinPeriodFrequency</code> and
* <code>lockinPeriodFrequencyType</code> details are present.
*/
@Temporal(TemporalType.DATE)
@Column(name = "lockedin_until_date_derived", nullable = true)
private Date lockedInUntilDate;
@Column(name = "withdrawal_fee_amount", scale = 6, precision = 19, nullable = true)
private BigDecimal withdrawalFeeAmount;
@Column(name = "withdrawal_fee_type_enum", nullable = true)
private Integer withdrawalFeeType;
@Column(name = "withdrawal_fee_for_transfer", nullable = true)
private boolean withdrawalFeeApplicableForTransfer;
@Column(name = "annual_fee_amount", scale = 6, precision = 19, nullable = true)
private BigDecimal annualFeeAmount;
@Column(name = "annual_fee_on_month", nullable = true)
private Integer annualFeeOnMonth;
@Column(name = "annual_fee_on_day", nullable = true)
private Integer annualFeeOnDay;
@Temporal(TemporalType.DATE)
@Column(name = "annual_fee_next_due_date", nullable = true)
private Date annualFeeNextDueDate;
@Embedded
private SavingsAccountSummary summary;
@OrderBy(value = "dateOf, id")
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true)
private final List<SavingsAccountTransaction> transactions = new ArrayList<SavingsAccountTransaction>();
@Transient
private boolean accountNumberRequiresAutoGeneration = false;
@Transient
private SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper;
@Transient
private SavingsHelper savingsHelper;
protected SavingsAccount() {
}
public static SavingsAccount createNewApplicationForSubmittal(final Client client, final Group group, final SavingsProduct product,
final Staff fieldOfficer, final String accountNo, final String externalId, final AccountType accountType,
final LocalDate submittedOnDate, final BigDecimal interestRate,
final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType,
final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType,
final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance,
final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType,
final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType,
final boolean withdrawalFeeApplicableForTransfer, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay) {
final SavingsAccountStatusType status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL;
return new SavingsAccount(client, group, product, fieldOfficer, accountNo, externalId, status, accountType, submittedOnDate,
interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType,
interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType,
withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeApplicableForTransfer, annualFeeAmount, annualFeeOnMonthDay);
}
private SavingsAccount(final Client client, final Group group, final SavingsProduct product, final Staff fieldOfficer,
final String accountNo, final String externalId, final SavingsAccountStatusType status, final AccountType accountType,
final LocalDate submittedOnDate, final BigDecimal nominalAnnualInterestRate,
final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType,
final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType,
final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance,
final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType,
final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType,
final boolean withdrawalFeeApplicableForTransfer, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay) {
this.client = client;
this.group = group;
this.product = product;
this.fieldOfficer = fieldOfficer;
if (StringUtils.isBlank(accountNo)) {
this.accountNumber = new RandomPasswordGenerator(19).generate();
this.accountNumberRequiresAutoGeneration = true;
} else {
this.accountNumber = accountNo;
}
this.currency = product.currency();
this.externalId = externalId;
this.status = status.getValue();
this.accountType = accountType.getValue();
this.submittedOnDate = submittedOnDate.toDate();
this.nominalAnnualInterestRate = nominalAnnualInterestRate;
this.interestCompoundingPeriodType = interestCompoundingPeriodType.getValue();
this.interestPostingPeriodType = interestPostingPeriodType.getValue();
this.interestCalculationType = interestCalculationType.getValue();
this.interestCalculationDaysInYearType = interestCalculationDaysInYearType.getValue();
this.minRequiredOpeningBalance = minRequiredOpeningBalance;
this.lockinPeriodFrequency = lockinPeriodFrequency;
if (lockinPeriodFrequencyType != null) {
this.lockinPeriodFrequencyType = lockinPeriodFrequencyType.getValue();
}
this.withdrawalFeeAmount = withdrawalFeeAmount;
if (withdrawalFeeType != null) {
this.withdrawalFeeType = withdrawalFeeType.getValue();
}
this.withdrawalFeeApplicableForTransfer = withdrawalFeeApplicableForTransfer;
this.annualFeeAmount = annualFeeAmount;
if (annualFeeOnMonthDay != null) {
this.annualFeeOnMonth = annualFeeOnMonthDay.getMonthOfYear();
this.annualFeeOnDay = annualFeeOnMonthDay.getDayOfMonth();
}
this.summary = new SavingsAccountSummary();
}
/**
* Used after fetching/hydrating a {@link SavingsAccount} object to inject
* helper services/components used for update summary details after
* events/transactions on a {@link SavingsAccount}.
*/
public void setHelpers(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper,
final SavingsHelper savingsHelper) {
this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper;
this.savingsHelper = savingsHelper;
}
public boolean isNotActive() {
return !isActive();
}
public boolean isActive() {
return SavingsAccountStatusType.fromInt(this.status).isActive();
}
public boolean isNotSubmittedAndPendingApproval() {
return !isSubmittedAndPendingApproval();
}
public boolean isSubmittedAndPendingApproval() {
return SavingsAccountStatusType.fromInt(this.status).isSubmittedAndPendingApproval();
}
public boolean isApproved() {
return SavingsAccountStatusType.fromInt(this.status).isApproved();
}
public boolean isClosed() {
return SavingsAccountStatusType.fromInt(this.status).isClosed();
}
public void postInterest(final MathContext mc, final LocalDate interestPostingUpToDate, final List<Long> existingTransactionIds,
final List<Long> existingReversedTransactionIds) {
final List<PostingPeriod> postingPeriods = calculateInterestUsing(mc, interestPostingUpToDate);
Money interestPostedToDate = Money.zero(this.currency);
boolean recalucateDailyBalanceDetails = false;
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
for (final PostingPeriod interestPostingPeriod : postingPeriods) {
final LocalDate interestPostingTransactionDate = interestPostingPeriod.dateOfPostingTransaction();
final Money interestEarnedToBePostedForPeriod = interestPostingPeriod.getInterestEarned();
if (!interestPostingTransactionDate.isAfter(interestPostingUpToDate)) {
interestPostedToDate = interestPostedToDate.plus(interestEarnedToBePostedForPeriod);
final SavingsAccountTransaction postingTransaction = findInterestPostingTransactionFor(interestPostingTransactionDate);
if (postingTransaction == null) {
final SavingsAccountTransaction newPostingTransaction = SavingsAccountTransaction.interestPosting(this,
interestPostingTransactionDate, interestEarnedToBePostedForPeriod);
this.transactions.add(newPostingTransaction);
recalucateDailyBalanceDetails = true;
} else {
final boolean correctionRequired = postingTransaction.hasNotAmount(interestEarnedToBePostedForPeriod);
if (correctionRequired) {
postingTransaction.reverse();
final SavingsAccountTransaction newPostingTransaction = SavingsAccountTransaction.interestPosting(this,
interestPostingTransactionDate, interestEarnedToBePostedForPeriod);
this.transactions.add(newPostingTransaction);
recalucateDailyBalanceDetails = true;
}
}
}
}
if (recalucateDailyBalanceDetails) {
// no openingBalance concept supported yet but probably will to
// allow
// for migrations.
final Money openingAccountBalance = Money.zero(this.currency);
// update existing transactions so derived balance fields are
// correct.
recalculateDailyBalances(openingAccountBalance);
}
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
}
private SavingsAccountTransaction findInterestPostingTransactionFor(final LocalDate postingDate) {
SavingsAccountTransaction postingTransation = null;
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isInterestPostingAndNotReversed() && transaction.occursOn(postingDate)) {
postingTransation = transaction;
break;
}
}
return postingTransation;
}
/**
* All interest calculation based on END-OF-DAY-BALANCE.
*
* Interest calculation is performed on-the-fly over all account
* transactions.
*
*
* 1. Calculate Interest From Beginning Of Account 1a. determine the
* 'crediting' periods that exist for this savings acccount 1b. determine
* the 'compounding' periods that exist within each 'crediting' period
* calculate the amount of interest due at the end of each 'crediting'
* period check if an existing 'interest posting' transaction exists for
* date and matches the amount posted
*/
public List<PostingPeriod> calculateInterestUsing(final MathContext mc, final LocalDate upToInterestCalculationDate) {
// no openingBalance concept supported yet but probably will to allow
// for migrations.
final Money openingAccountBalance = Money.zero(this.currency);
// update existing transactions so derived balance fields are
// correct.
recalculateDailyBalances(openingAccountBalance);
// 1. default to calculate interest based on entire history OR
// 2. determine latest 'posting period' and find interest credited to
// that period
// A generate list of EndOfDayBalances (not including interest postings)
final SavingsPostingInterestPeriodType postingPeriodType = SavingsPostingInterestPeriodType.fromInt(this.interestPostingPeriodType);
final SavingsCompoundingInterestPeriodType compoundingPeriodType = SavingsCompoundingInterestPeriodType
.fromInt(this.interestCompoundingPeriodType);
final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType
.fromInt(this.interestCalculationDaysInYearType);
final List<LocalDateInterval> postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods(getActivationLocalDate(),
upToInterestCalculationDate, postingPeriodType);
final List<PostingPeriod> allPostingPeriods = new ArrayList<PostingPeriod>();
Money periodStartingBalance = Money.zero(this.currency);
final SavingsInterestCalculationType interestCalculationType = SavingsInterestCalculationType.fromInt(this.interestCalculationType);
final BigDecimal interestRateAsFraction = this.nominalAnnualInterestRate.divide(BigDecimal.valueOf(100l), mc);
for (final LocalDateInterval periodInterval : postingPeriodIntervals) {
final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance,
retreiveOrderedListOfTransactions(), this.currency, compoundingPeriodType, interestCalculationType,
interestRateAsFraction, daysInYearType.getValue());
periodStartingBalance = postingPeriod.closingBalance();
allPostingPeriods.add(postingPeriod);
}
this.savingsHelper.calculateInterestForAllPostingPeriods(this.currency, allPostingPeriods);
this.summary.updateFromInterestPeriodSummaries(this.currency, allPostingPeriods);
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
return allPostingPeriods;
}
private List<SavingsAccountTransaction> retreiveOrderedListOfTransactions() {
final List<SavingsAccountTransaction> listOfTransactionsSorted = retreiveListOfTransactions();
final List<SavingsAccountTransaction> orderedNonInterestPostingTransactions = new ArrayList<SavingsAccountTransaction>();
for (final SavingsAccountTransaction transaction : listOfTransactionsSorted) {
if (!transaction.isInterestPostingAndNotReversed() && transaction.isNotReversed()) {
orderedNonInterestPostingTransactions.add(transaction);
}
}
return orderedNonInterestPostingTransactions;
}
private List<SavingsAccountTransaction> retreiveListOfTransactions() {
final List<SavingsAccountTransaction> listOfTransactionsSorted = new ArrayList<SavingsAccountTransaction>();
for (final SavingsAccountTransaction transaction : this.transactions) {
listOfTransactionsSorted.add(transaction);
}
final SavingsAccountTransactionComparator transactionComparator = new SavingsAccountTransactionComparator();
Collections.sort(listOfTransactionsSorted, transactionComparator);
return listOfTransactionsSorted;
}
private void recalculateDailyBalances(final Money openingAccountBalance) {
Money runningBalance = openingAccountBalance.copy();
final List<SavingsAccountTransaction> accountTransactionsSorted = retreiveListOfTransactions();
for (final SavingsAccountTransaction transaction : accountTransactionsSorted) {
if (transaction.isReversed()) {
transaction.zeroBalanceFields();
} else {
Money transactionAmount = Money.zero(this.currency);
if (transaction.isCredit()) {
transactionAmount = transactionAmount.plus(transaction.getAmount(this.currency));
} else if (transaction.isDebit()) {
transactionAmount = transactionAmount.minus(transaction.getAmount(this.currency));
}
runningBalance = runningBalance.plus(transactionAmount);
transaction.updateRunningBalance(runningBalance);
}
}
// loop over transactions in reverse
LocalDate endOfBalanceDate = DateUtils.getLocalDateOfTenant();
for (int i = accountTransactionsSorted.size() - 1; i >= 0; i
final SavingsAccountTransaction transaction = accountTransactionsSorted.get(i);
if (transaction.isNotReversed()) {
transaction.updateCumulativeBalanceAndDates(this.currency, endOfBalanceDate);
// this transactions transaction date is end of balance date for
// previous transaction.
endOfBalanceDate = transaction.transactionLocalDate().minusDays(1);
}
}
}
public SavingsAccountTransaction deposit(final SavingsAccountTransactionDTO transactionDTO) {
if (isNotActive()) {
final String defaultUserMessage = "Transaction is not allowed. Account is not active.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.account.is.not.active",
defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()));
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (isDateInTheFuture(transactionDTO.getTransactionDate())) {
final String defaultUserMessage = "Transaction date cannot be in the future.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.in.the.future",
defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()));
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (transactionDTO.getTransactionDate().isBefore(getActivationLocalDate())) {
final Object[] defaultUserArgs = Arrays.asList(transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()),
getActivationLocalDate().toString(transactionDTO.getFormatter())).toArray();
final String defaultUserMessage = "Transaction date cannot be before accounts activation date.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.before.activation.date",
defaultUserMessage, "transactionDate", defaultUserArgs);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
transactionDTO.getExistingTransactionIds().addAll(findExistingTransactionIds());
transactionDTO.getExistingReversedTransactionIds().addAll(findExistingReversedTransactionIds());
final Money amount = Money.of(this.currency, transactionDTO.getTransactionAmount());
final SavingsAccountTransaction transaction = SavingsAccountTransaction.deposit(this, transactionDTO.getPaymentDetail(),
transactionDTO.getTransactionDate(), amount);
this.transactions.add(transaction);
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
return transaction;
}
private LocalDate getActivationLocalDate() {
LocalDate activationLocalDate = null;
if (this.activatedOnDate != null) {
activationLocalDate = new LocalDate(this.activatedOnDate);
}
return activationLocalDate;
}
public SavingsAccountTransaction withdraw(final SavingsAccountTransactionDTO transactionDTO, final boolean applyWithdrawFee) {
if (isNotActive()) {
final String defaultUserMessage = "Transaction is not allowed. Account is not active.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.account.is.not.active",
defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()));
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (isDateInTheFuture(transactionDTO.getTransactionDate())) {
final String defaultUserMessage = "Transaction date cannot be in the future.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.in.the.future",
defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()));
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (transactionDTO.getTransactionDate().isBefore(getActivationLocalDate())) {
final Object[] defaultUserArgs = Arrays.asList(transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()),
getActivationLocalDate().toString(transactionDTO.getFormatter())).toArray();
final String defaultUserMessage = "Transaction date cannot be before accounts activation date.";
final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.before.activation.date",
defaultUserMessage, "transactionDate", defaultUserArgs);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (isAccountLocked(transactionDTO.getTransactionDate())) {
final String defaultUserMessage = "Withdrawal is not allowed. No withdrawals are allowed until after "
+ getLockedInUntilLocalDate().toString(transactionDTO.getFormatter());
final ApiParameterError error = ApiParameterError.parameterError(
"error.msg.savingsaccount.transaction.withdrawals.blocked.during.lockin.period", defaultUserMessage, "transactionDate",
transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()),
getLockedInUntilLocalDate().toString(transactionDTO.getFormatter()));
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException(dataValidationErrors);
}
transactionDTO.getExistingTransactionIds().addAll(findExistingTransactionIds());
transactionDTO.getExistingReversedTransactionIds().addAll(findExistingReversedTransactionIds());
final Money transactionAmountMoney = Money.of(this.currency, transactionDTO.getTransactionAmount());
final SavingsAccountTransaction transaction = SavingsAccountTransaction.withdrawal(this, transactionDTO.getPaymentDetail(),
transactionDTO.getTransactionDate(), transactionAmountMoney);
this.transactions.add(transaction);
if (applyWithdrawFee && isAutomaticWithdrawalFee()) {
SavingsAccountTransaction withdrawalFeeTransaction = null;
Money feeAmount = Money.zero(this.currency);
switch (SavingsWithdrawalFeesType.fromInt(this.withdrawalFeeType)) {
case INVALID:
break;
case FLAT:
feeAmount = Money.of(this.currency, this.withdrawalFeeAmount);
withdrawalFeeTransaction = SavingsAccountTransaction.fee(this, transactionDTO.getTransactionDate(), feeAmount);
this.transactions.add(withdrawalFeeTransaction);
break;
case PERCENT_OF_AMOUNT:
final BigDecimal feeAmountDecimal = transactionDTO.getTransactionAmount().multiply(this.withdrawalFeeAmount)
.divide(BigDecimal.valueOf(100l));
feeAmount = Money.of(this.currency, feeAmountDecimal);
withdrawalFeeTransaction = SavingsAccountTransaction.fee(this, transactionDTO.getTransactionDate(), feeAmount);
this.transactions.add(withdrawalFeeTransaction);
break;
}
}
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
return transaction;
}
public boolean isBeforeLastPostingPeriod(final LocalDate transactionDate) {
boolean transactionBeforeLastInterestPosting = false;
for (final SavingsAccountTransaction transaction : retreiveListOfTransactions()) {
if (transaction.isInterestPostingAndNotReversed() && transaction.isAfter(transactionDate)) {
transactionBeforeLastInterestPosting = true;
break;
}
}
return transactionBeforeLastInterestPosting;
}
public void validateAccountBalanceDoesNotBecomeNegative(final BigDecimal transactionAmount) {
final List<SavingsAccountTransaction> transactionsSortedByDate = retreiveListOfTransactions();
Money runningBalance = Money.zero(this.currency);
for (final SavingsAccountTransaction transaction : transactionsSortedByDate) {
if (transaction.isNotReversed() && transaction.isCredit()) {
runningBalance = runningBalance.plus(transaction.getAmount(this.currency));
} else if (transaction.isNotReversed() && transaction.isDebit()) {
runningBalance = runningBalance.minus(transaction.getAmount(this.currency));
}
if (runningBalance.isLessThanZero()) {
final BigDecimal withdrawalFee = null;
throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee,
transactionAmount);
}
}
}
public void validateAccountBalanceDoesNotBecomeNegative(final String transactionAction) {
final List<SavingsAccountTransaction> transactionsSortedByDate = retreiveListOfTransactions();
Money runningBalance = Money.zero(this.currency);
for (final SavingsAccountTransaction transaction : transactionsSortedByDate) {
if (transaction.isNotReversed() && transaction.isCredit()) {
runningBalance = runningBalance.plus(transaction.getAmount(this.currency));
} else if (transaction.isNotReversed() && transaction.isDebit()) {
runningBalance = runningBalance.minus(transaction.getAmount(this.currency));
}
if (runningBalance.isLessThanZero()) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + transactionAction);
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("results.in.balance.going.negative");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
}
}
public SavingsAccountTransaction addAnnualFee(final MathContext mc, final DateTimeFormatter formatter,
final LocalDate annualFeeTransactionDate, final LocalDate today, final List<Long> existingTransactionIds,
final List<Long> existingReversedTransactionIds) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.applyAnnualFeeTransactionAction);
if (isNotActive()) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final LocalDate nextAnnualFeeDueDate = getNextAnnualFeeDueDate();
if (nextAnnualFeeDueDate == null || annualFeeSettingsNotSet()) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings");
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (nextAnnualFeeDueDate.isBefore(getActivationLocalDate())) {
baseDataValidator.reset().parameter("annualFeeTransactionDate").value(getActivationLocalDate().toString(formatter))
.failWithCodeNoParameterAddedToErrorCode("before.activationDate");
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (isDateInTheFuture(annualFeeTransactionDate)) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.in.the.future");
throw new PlatformApiDataValidationException(dataValidationErrors);
}
if (isNotValidAnnualFeeTransactionDate(annualFeeTransactionDate, today)) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("invalid.date");
throw new PlatformApiDataValidationException(dataValidationErrors);
}
Date currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
if (currentAnnualFeeNextDueDate != null && new LocalDate(currentAnnualFeeNextDueDate).isEqual(annualFeeTransactionDate)) {
baseDataValidator.reset().parameter("annualFeeTransactionDate").value(annualFeeTransactionDate.toString(formatter))
.failWithCodeNoParameterAddedToErrorCode("transaction.exists.on.date");
throw new PlatformApiDataValidationException(dataValidationErrors);
}
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
final Money annualFee = Money.of(this.currency, this.annualFeeAmount);
final SavingsAccountTransaction annualFeeTransaction = SavingsAccountTransaction.annualFee(this, annualFeeTransactionDate,
annualFee);
this.transactions.add(annualFeeTransaction);
validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.applyAnnualFeeTransactionAction);
this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions);
calculateInterestUsing(mc, today);
currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
if (currentAnnualFeeNextDueDate != null) {
final LocalDate newAnnualFeeNextDueDate = new LocalDate(currentAnnualFeeNextDueDate).withMonthOfYear(this.annualFeeOnMonth)
.withDayOfMonth(this.annualFeeOnDay).plusYears(1);
this.annualFeeNextDueDate = newAnnualFeeNextDueDate.toDate();
} else {
updateToNextAnnualFeeDueDateFrom(getActivationLocalDate());
}
return annualFeeTransaction;
}
private boolean isNotValidAnnualFeeTransactionDate(final LocalDate annualFeeTransactionDate, final LocalDate today) {
return !isValidAnnualFeeTransactionDate(annualFeeTransactionDate, today);
}
private boolean isValidAnnualFeeTransactionDate(final LocalDate annualFeeTransactionDate, final LocalDate today) {
LocalDate startingDate = getActivationLocalDate();
boolean isValid = false;
while (!startingDate.isAfter(today) && !isValid) {
LocalDate nextDueLocalDate = startingDate.withMonthOfYear(this.annualFeeOnMonth).withDayOfMonth(this.annualFeeOnDay);
if (startingDate.isAfter(nextDueLocalDate)) {
nextDueLocalDate = nextDueLocalDate.plusYears(1);
}
isValid = nextDueLocalDate.isEqual(annualFeeTransactionDate);
startingDate = nextDueLocalDate.plusYears(1);
}
return isValid;
}
private void updateToNextAnnualFeeDueDateFrom(final LocalDate startingDate) {
LocalDate nextDueLocalDate = startingDate.withMonthOfYear(this.annualFeeOnMonth).withDayOfMonth(this.annualFeeOnDay);
if (startingDate.isAfter(nextDueLocalDate)) {
nextDueLocalDate = nextDueLocalDate.plusYears(1);
}
this.annualFeeNextDueDate = nextDueLocalDate.toDate();
}
private LocalDate getNextAnnualFeeDueDate() {
LocalDate nextAnnualFeeDueDate = null;
if (this.annualFeeNextDueDate != null) {
nextAnnualFeeDueDate = new LocalDate(this.annualFeeNextDueDate);
}
return nextAnnualFeeDueDate;
}
private boolean annualFeeSettingsNotSet() {
return !annualFeeSettingsSet();
}
private boolean annualFeeSettingsSet() {
return this.annualFeeOnDay != null && this.annualFeeOnMonth != null;
}
private boolean isAutomaticWithdrawalFee() {
return this.withdrawalFeeType != null;
}
private boolean isAccountLocked(final LocalDate transactionDate) {
boolean isLocked = false;
final boolean accountHasLockedInSetting = this.lockedInUntilDate != null;
if (accountHasLockedInSetting) {
isLocked = getLockedInUntilLocalDate().isAfter(transactionDate);
}
return isLocked;
}
private LocalDate getLockedInUntilLocalDate() {
LocalDate lockedInUntilLocalDate = null;
if (this.lockedInUntilDate != null) {
lockedInUntilLocalDate = new LocalDate(this.lockedInUntilDate);
}
return lockedInUntilLocalDate;
}
private boolean isDateInTheFuture(final LocalDate transactionDate) {
return transactionDate.isAfter(DateUtils.getLocalDateOfTenant());
}
private BigDecimal getAccountBalance() {
return this.summary.getAccountBalance(this.currency).getAmount();
}
public void modifyApplication(final JsonCommand command, final Map<String, Object> actualChanges) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.modifyApplicationAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final String localeAsInput = command.locale();
final String dateFormat = command.dateFormat();
if (command.isChangeInLocalDateParameterNamed(SavingsApiConstants.submittedOnDateParamName, getSubmittedOnLocalDate())) {
final LocalDate newValue = command.localDateValueOfParameterNamed(SavingsApiConstants.submittedOnDateParamName);
final String newValueAsString = command.stringValueOfParameterNamed(SavingsApiConstants.submittedOnDateParamName);
actualChanges.put(SavingsApiConstants.submittedOnDateParamName, newValueAsString);
actualChanges.put(SavingsApiConstants.localeParamName, localeAsInput);
actualChanges.put(SavingsApiConstants.dateFormatParamName, dateFormat);
this.submittedOnDate = newValue.toDate();
}
if (command.isChangeInStringParameterNamed(SavingsApiConstants.accountNoParamName, this.accountNumber)) {
final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.accountNoParamName);
actualChanges.put(SavingsApiConstants.accountNoParamName, newValue);
this.accountNumber = StringUtils.defaultIfEmpty(newValue, null);
}
if (command.isChangeInStringParameterNamed(SavingsApiConstants.externalIdParamName, this.externalId)) {
final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.externalIdParamName);
actualChanges.put(SavingsApiConstants.externalIdParamName, newValue);
this.externalId = StringUtils.defaultIfEmpty(newValue, null);
}
if (command.isChangeInLongParameterNamed(SavingsApiConstants.clientIdParamName, clientId())) {
final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName);
actualChanges.put(SavingsApiConstants.clientIdParamName, newValue);
}
if (command.isChangeInLongParameterNamed(SavingsApiConstants.groupIdParamName, groupId())) {
final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName);
actualChanges.put(SavingsApiConstants.groupIdParamName, newValue);
}
if (command.isChangeInLongParameterNamed(SavingsApiConstants.productIdParamName, this.product.getId())) {
final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName);
actualChanges.put(SavingsApiConstants.productIdParamName, newValue);
}
if (command.isChangeInLongParameterNamed(SavingsApiConstants.fieldOfficerIdParamName, fieldOfficerId())) {
final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.fieldOfficerIdParamName);
actualChanges.put(SavingsApiConstants.fieldOfficerIdParamName, newValue);
}
if (command.isChangeInBigDecimalParameterNamed(SavingsApiConstants.nominalAnnualInterestRateParamName,
this.nominalAnnualInterestRate)) {
final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(SavingsApiConstants.nominalAnnualInterestRateParamName);
actualChanges.put(SavingsApiConstants.nominalAnnualInterestRateParamName, newValue);
actualChanges.put("locale", localeAsInput);
this.nominalAnnualInterestRate = newValue;
}
if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCompoundingPeriodTypeParamName,
this.interestCompoundingPeriodType)) {
final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCompoundingPeriodTypeParamName);
this.interestCompoundingPeriodType = newValue != null ? SavingsCompoundingInterestPeriodType.fromInt(newValue).getValue()
: newValue;
actualChanges.put(SavingsApiConstants.interestCompoundingPeriodTypeParamName, this.interestCompoundingPeriodType);
}
if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType)) {
final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName);
this.interestPostingPeriodType = newValue != null ? SavingsPostingInterestPeriodType.fromInt(newValue).getValue() : newValue;
actualChanges.put(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType);
}
if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCalculationTypeParamName, this.interestCalculationType)) {
final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCalculationTypeParamName);
this.interestCalculationType = newValue != null ? SavingsInterestCalculationType.fromInt(newValue).getValue() : newValue;
actualChanges.put(SavingsApiConstants.interestCalculationTypeParamName, this.interestCalculationType);
}
if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName,
this.interestCalculationDaysInYearType)) {
final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName);
this.interestCalculationDaysInYearType = newValue != null ? SavingsInterestCalculationDaysInYearType.fromInt(newValue)
.getValue() : newValue;
actualChanges.put(SavingsApiConstants.interestCalculationDaysInYearTypeParamName, this.interestCalculationDaysInYearType);
}
if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(SavingsApiConstants.minRequiredOpeningBalanceParamName,
this.minRequiredOpeningBalance)) {
final BigDecimal newValue = command
.bigDecimalValueOfParameterNamedDefaultToNullIfZero(SavingsApiConstants.minRequiredOpeningBalanceParamName);
actualChanges.put(SavingsApiConstants.minRequiredOpeningBalanceParamName, newValue);
actualChanges.put("locale", localeAsInput);
this.minRequiredOpeningBalance = Money.of(this.currency, newValue).getAmount();
}
if (command.isChangeInIntegerParameterNamedDefaultingZeroToNull(SavingsApiConstants.lockinPeriodFrequencyParamName,
this.lockinPeriodFrequency)) {
final Integer newValue = command
.integerValueOfParameterNamedDefaultToNullIfZero(SavingsApiConstants.lockinPeriodFrequencyParamName);
actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyParamName, newValue);
actualChanges.put("locale", localeAsInput);
this.lockinPeriodFrequency = newValue;
}
if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, this.lockinPeriodFrequencyType)) {
final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName);
actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, newValue);
this.lockinPeriodFrequencyType = newValue != null ? SavingsPeriodFrequencyType.fromInt(newValue).getValue() : newValue;
}
// set period type to null if frequency is null
if (this.lockinPeriodFrequency == null) {
this.lockinPeriodFrequencyType = null;
}
if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(withdrawalFeeAmountParamName, this.withdrawalFeeAmount)) {
final BigDecimal newValue = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero(withdrawalFeeAmountParamName);
actualChanges.put(withdrawalFeeAmountParamName, newValue);
actualChanges.put(localeParamName, localeAsInput);
this.withdrawalFeeAmount = newValue;
}
if (command.isChangeInIntegerParameterNamedDefaultingZeroToNull(withdrawalFeeTypeParamName, this.withdrawalFeeType)) {
final Integer newValue = command.integerValueOfParameterNamedDefaultToNullIfZero(withdrawalFeeTypeParamName);
actualChanges.put(withdrawalFeeTypeParamName, newValue);
this.withdrawalFeeType = newValue != null ? SavingsWithdrawalFeesType.fromInt(newValue).getValue() : newValue;
}
if (command.isChangeInBooleanParameterNamed(withdrawalFeeForTransfersParamName, this.withdrawalFeeApplicableForTransfer)) {
final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName);
actualChanges.put(withdrawalFeeForTransfersParamName, newValue);
this.withdrawalFeeApplicableForTransfer = newValue;
}
// set period type to null if frequency is null
if (this.withdrawalFeeAmount == null) {
this.withdrawalFeeType = null;
}
if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(annualFeeAmountParamName, this.annualFeeAmount)) {
final BigDecimal newValue = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero(annualFeeAmountParamName);
actualChanges.put(annualFeeAmountParamName, newValue);
actualChanges.put(localeParamName, localeAsInput);
this.annualFeeAmount = newValue;
}
if (command.hasParameter(annualFeeOnMonthDayParamName)) {
final MonthDay monthDay = command.extractMonthDayNamed(annualFeeOnMonthDayParamName);
final String actualValueEntered = command.stringValueOfParameterNamed(annualFeeOnMonthDayParamName);
final Integer dayOfMonthValue = monthDay.getDayOfMonth();
if (this.annualFeeOnDay != dayOfMonthValue) {
actualChanges.put(annualFeeOnMonthDayParamName, actualValueEntered);
actualChanges.put(localeParamName, localeAsInput);
this.annualFeeOnDay = dayOfMonthValue;
}
final Integer monthOfYear = monthDay.getMonthOfYear();
if (this.annualFeeOnMonth != monthOfYear) {
actualChanges.put(annualFeeOnMonthDayParamName, actualValueEntered);
actualChanges.put(localeParamName, localeAsInput);
this.annualFeeOnMonth = monthOfYear;
}
}
// set period type to null if frequency is null
if (this.annualFeeAmount == null) {
this.annualFeeOnDay = null;
this.annualFeeOnMonth = null;
}
validateLockinDetails();
validateWithdrawalFeeDetails();
validateAnnualFeeDetails();
}
private void validateAnnualFeeDetails() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME);
if (this.annualFeeAmount == null) {
if (this.annualFeeOnMonth != null || this.annualFeeOnDay != null) {
baseDataValidator.reset().parameter(annualFeeAmountParamName).value(this.annualFeeAmount).notNull();
}
} else {
if (this.annualFeeOnMonth == null || this.annualFeeOnDay == null) {
baseDataValidator.reset().parameter(annualFeeOnMonthDayParamName).value(this.annualFeeOnMonth).notNull();
}
baseDataValidator.reset().parameter(annualFeeAmountParamName).value(this.annualFeeAmount).zeroOrPositiveAmount();
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
private void validateWithdrawalFeeDetails() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME);
if (this.withdrawalFeeAmount == null) {
baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(this.withdrawalFeeType).ignoreIfNull()
.isOneOfTheseValues(1, 2);
if (this.withdrawalFeeType != null) {
baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(this.withdrawalFeeAmount).notNull();
}
} else {
baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(this.withdrawalFeeAmount).zeroOrPositiveAmount();
baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(this.withdrawalFeeType).notNull()
.isOneOfTheseValues(1, 2);
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
private void validateLockinDetails() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME);
if (this.lockinPeriodFrequency == null) {
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).ignoreIfNull()
.inMinMaxRange(0, 3);
if (this.lockinPeriodFrequencyType != null) {
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequency).notNull()
.integerZeroOrGreater();
}
} else {
baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequencyType)
.integerZeroOrGreater();
baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).notNull()
.inMinMaxRange(0, 3);
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
public Map<String, Object> deriveAccountingBridgeData(final CurrencyData currencyData, final List<Long> existingTransactionIds,
final List<Long> existingReversedTransactionIds) {
final Map<String, Object> accountingBridgeData = new LinkedHashMap<String, Object>();
accountingBridgeData.put("savingsId", getId());
accountingBridgeData.put("savingsProductId", productId());
accountingBridgeData.put("officeId", officeId());
accountingBridgeData.put("cashBasedAccountingEnabled", isCashBasedAccountingEnabledOnSavingsProduct());
accountingBridgeData.put("accrualBasedAccountingEnabled", isAccrualBasedAccountingEnabledOnSavingsProduct());
final List<Map<String, Object>> newLoanTransactions = new ArrayList<Map<String, Object>>();
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isReversed() && !existingReversedTransactionIds.contains(transaction.getId())) {
newLoanTransactions.add(transaction.toMapData(currencyData));
} else if (!existingTransactionIds.contains(transaction.getId())) {
newLoanTransactions.add(transaction.toMapData(currencyData));
}
}
accountingBridgeData.put("newSavingsTransactions", newLoanTransactions);
return accountingBridgeData;
}
private Collection<Long> findExistingTransactionIds() {
final Collection<Long> ids = new ArrayList<Long>();
for (final SavingsAccountTransaction transaction : this.transactions) {
ids.add(transaction.getId());
}
return ids;
}
private Collection<Long> findExistingReversedTransactionIds() {
final Collection<Long> ids = new ArrayList<Long>();
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isReversed()) {
ids.add(transaction.getId());
}
}
return ids;
}
public void update(final Client client) {
this.client = client;
}
public void update(final Group group) {
this.group = group;
}
public void update(final SavingsProduct product) {
this.product = product;
}
public void update(final Staff fieldOfficer) {
this.fieldOfficer = fieldOfficer;
}
public void updateAccountNo(final String newAccountNo) {
this.accountNumber = newAccountNo;
this.accountNumberRequiresAutoGeneration = false;
}
public boolean isAccountNumberRequiresAutoGeneration() {
return this.accountNumberRequiresAutoGeneration;
}
public Long productId() {
return this.product.getId();
}
private Boolean isCashBasedAccountingEnabledOnSavingsProduct() {
return this.product.isCashBasedAccountingEnabled();
}
private Boolean isAccrualBasedAccountingEnabledOnSavingsProduct() {
return this.product.isAccrualBasedAccountingEnabled();
}
public Long officeId() {
Long officeId = null;
if (this.client != null) {
officeId = this.client.officeId();
} else {
officeId = this.group.officeId();
}
return officeId;
}
public Long clientId() {
Long id = null;
if (this.client != null) {
id = this.client.getId();
}
return id;
}
public Long groupId() {
Long id = null;
if (this.group != null) {
id = this.group.getId();
}
return id;
}
public Long fieldOfficerId() {
Long id = null;
if (this.fieldOfficer != null) {
id = this.fieldOfficer.getId();
}
return id;
}
public MonetaryCurrency getCurrency() {
return this.currency;
}
public void validateNewApplicationState(final LocalDate todayDateOfTenant) {
validateLockinDetails();
validateWithdrawalFeeDetails();
validateAnnualFeeDetails();
final LocalDate submittedOn = getSubmittedOnLocalDate();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.summitalAction);
if (submittedOn.isAfter(todayDateOfTenant)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(submittedOn)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
}
if (this.client != null && this.client.isActivatedAfter(submittedOn)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.client.getActivationLocalDate())
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
} else if (this.group != null && this.group.isActivatedAfter(submittedOn)) {
baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.group.getActivationLocalDate())
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
private LocalDate getSubmittedOnLocalDate() {
LocalDate submittedOn = null;
if (this.submittedOnDate != null) {
submittedOn = new LocalDate(this.submittedOnDate);
}
return submittedOn;
}
private LocalDate getApprovedOnLocalDate() {
LocalDate approvedOnLocalDate = null;
if (this.approvedOnDate != null) {
approvedOnLocalDate = new LocalDate(this.approvedOnDate);
}
return approvedOnLocalDate;
}
public Client getClient() {
return this.client;
}
public Map<String, Object> approveApplication(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.approvalAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
this.status = SavingsAccountStatusType.APPROVED.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
// only do below if status has changed in the 'approval' case
final LocalDate approvedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
final String approvedOnDateChange = command.stringValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName);
this.approvedOnDate = approvedOn.toDate();
this.approvedBy = currentUser;
actualChanges.put(SavingsApiConstants.localeParamName, command.locale());
actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat());
actualChanges.put(SavingsApiConstants.approvedOnDateParamName, approvedOnDateChange);
final LocalDate submittalDate = getSubmittedOnLocalDate();
if (approvedOn.isBefore(submittalDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String submittalDateAsString = formatter.print(submittalDate);
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName).value(submittalDateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (approvedOn.isAfter(tenantsTodayDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
// FIXME - kw - support field officer history for savings accounts
// if (this.fieldOfficer != null) {
// final LoanOfficerAssignmentHistory loanOfficerAssignmentHistory =
// LoanOfficerAssignmentHistory.createNew(this,
// this.fieldOfficer, approvedOn);
// this.loanOfficerHistory.add(loanOfficerAssignmentHistory);
return actualChanges;
}
public Map<String, Object> undoApplicationApproval() {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.undoApprovalAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.approved.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
this.status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
this.approvedOnDate = null;
this.approvedBy = null;
this.rejectedOnDate = null;
this.rejectedBy = null;
this.withdrawnOnDate = null;
this.withdrawnBy = null;
this.closedOnDate = null;
this.closedBy = null;
actualChanges.put(SavingsApiConstants.approvedOnDateParamName, "");
// FIXME - kw - support field officer history for savings accounts
// this.loanOfficerHistory.clear();
return actualChanges;
}
public void undoTransaction(final Long transactionId, final List<Long> reversedTransactionIds) {
SavingsAccountTransaction transactionToUndo = null;
for (final SavingsAccountTransaction transaction : this.transactions) {
if (transaction.isIdentifiedBy(transactionId)) {
transactionToUndo = transaction;
}
}
if (transactionToUndo == null) {
// throw non found exception
} else {
transactionToUndo.reverse();
reversedTransactionIds.add(transactionId);
if (transactionToUndo.isAnnualFee()) {
this.annualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
if (this.annualFeeNextDueDate == null) {
updateToNextAnnualFeeDueDateFrom(getActivationLocalDate());
} else {
final LocalDate newAnnualFeeNextDueDate = new LocalDate(this.annualFeeNextDueDate)
.withMonthOfYear(this.annualFeeOnMonth).withDayOfMonth(this.annualFeeOnDay).plusYears(1);
this.annualFeeNextDueDate = newAnnualFeeNextDueDate.toDate();
}
}
}
}
private Date findLatestAnnualFeeTransactionDueDate() {
Date nextDueDate = null;
LocalDate lastAnnualFeeTransactionDate = null;
for (final SavingsAccountTransaction transaction : retreiveOrderedListOfTransactions()) {
if (transaction.isAnnualFeeAndNotReversed()) {
if (lastAnnualFeeTransactionDate == null) {
lastAnnualFeeTransactionDate = transaction.transactionLocalDate();
nextDueDate = lastAnnualFeeTransactionDate.toDate();
}
if (transaction.transactionLocalDate().isAfter(lastAnnualFeeTransactionDate)) {
lastAnnualFeeTransactionDate = transaction.transactionLocalDate();
nextDueDate = lastAnnualFeeTransactionDate.toDate();
}
}
}
return nextDueDate;
}
public Map<String, Object> rejectApplication(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.rejectAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
this.status = SavingsAccountStatusType.REJECTED.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
final LocalDate rejectedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName);
final String rejectedOnAsString = command.stringValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName);
this.rejectedOnDate = rejectedOn.toDate();
this.rejectedBy = currentUser;
this.withdrawnOnDate = null;
this.withdrawnBy = null;
this.closedOnDate = rejectedOn.toDate();
this.closedBy = currentUser;
actualChanges.put(SavingsApiConstants.localeParamName, command.locale());
actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat());
actualChanges.put(SavingsApiConstants.rejectedOnDateParamName, rejectedOnAsString);
actualChanges.put(SavingsApiConstants.closedOnDateParamName, rejectedOnAsString);
final LocalDate submittalDate = getSubmittedOnLocalDate();
if (rejectedOn.isBefore(submittalDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String submittalDateAsString = formatter.print(submittalDate);
baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName).value(submittalDateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (rejectedOn.isAfter(tenantsTodayDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName).value(rejectedOn)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
return actualChanges;
}
public Map<String, Object> applicantWithdrawsFromApplication(final AppUser currentUser, final JsonCommand command,
final LocalDate tenantsTodayDate) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.withdrawnByApplicantAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
this.status = SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
final LocalDate withdrawnOn = command.localDateValueOfParameterNamed(SavingsApiConstants.withdrawnOnDateParamName);
final String withdrawnOnAsString = command.stringValueOfParameterNamed(SavingsApiConstants.withdrawnOnDateParamName);
this.rejectedOnDate = null;
this.rejectedBy = null;
this.withdrawnOnDate = withdrawnOn.toDate();
this.withdrawnBy = currentUser;
this.closedOnDate = withdrawnOn.toDate();
this.closedBy = currentUser;
actualChanges.put(SavingsApiConstants.localeParamName, command.locale());
actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat());
actualChanges.put(SavingsApiConstants.withdrawnOnDateParamName, withdrawnOnAsString);
actualChanges.put(SavingsApiConstants.closedOnDateParamName, withdrawnOnAsString);
final LocalDate submittalDate = getSubmittedOnLocalDate();
if (withdrawnOn.isBefore(submittalDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String submittalDateAsString = formatter.print(submittalDate);
baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName).value(submittalDateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (withdrawnOn.isAfter(tenantsTodayDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName).value(withdrawnOn)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
return actualChanges;
}
public Map<String, Object> activate(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate,
final List<Long> existingTransactionIds, final List<Long> existingReversedTransactionIds) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.activateAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) {
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName)
.failWithCodeNoParameterAddedToErrorCode("not.in.approved.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
final LocalDate activationDate = command.localDateValueOfParameterNamed(SavingsApiConstants.activatedOnDateParamName);
this.status = SavingsAccountStatusType.ACTIVE.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
actualChanges.put(SavingsApiConstants.localeParamName, command.locale());
actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat());
actualChanges.put(SavingsApiConstants.activatedOnDateParamName, activationDate.toString(fmt));
this.rejectedOnDate = null;
this.rejectedBy = null;
this.withdrawnOnDate = null;
this.withdrawnBy = null;
this.closedOnDate = null;
this.closedBy = null;
this.activatedOnDate = activationDate.toDate();
this.activatedBy = currentUser;
this.lockedInUntilDate = calculateDateAccountIsLockedUntil(getActivationLocalDate());
if (annualFeeSettingsSet()) {
updateToNextAnnualFeeDueDateFrom(getActivationLocalDate());
}
if (this.client != null && this.client.isActivatedAfter(activationDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String dateAsString = formatter.print(this.client.getActivationLocalDate());
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (this.group != null && this.group.isActivatedAfter(activationDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String dateAsString = formatter.print(this.client.getActivationLocalDate());
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.group.activation.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final LocalDate approvalDate = getApprovedOnLocalDate();
if (activationDate.isBefore(approvalDate)) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat()).withLocale(command.extractLocale());
final String dateAsString = formatter.print(approvalDate);
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.before.approval.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (activationDate.isAfter(tenantsTodayDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(activationDate)
.failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
// auto enter deposit for minimum required opening balance when
// activating account.
final Money minRequiredOpeningBalance = Money.of(this.currency, this.minRequiredOpeningBalance);
if (minRequiredOpeningBalance.isGreaterThanZero()) {
final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, activationDate, minRequiredOpeningBalance.getAmount(),
existingTransactionIds, existingReversedTransactionIds, null);
deposit(transactionDTO);
// no openingBalance concept supported yet but probably will to allow
// for migrations.
final Money openingAccountBalance = Money.zero(this.currency);
// update existing transactions so derived balance fields are
// correct.
recalculateDailyBalances(openingAccountBalance);
}
return actualChanges;
}
public Map<String, Object> close(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>();
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.closeAction);
final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status);
if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.active.state");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName);
if (closedDate.isBefore(getActivationLocalDate())) {
baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate)
.failWithCode("must.be.after.activation.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
if (closedDate.isAfter(tenantsTodayDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate)
.failWithCode("cannot.be.a.future.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
final List<SavingsAccountTransaction> savingsAccountTransactions = retreiveListOfTransactions();
if (savingsAccountTransactions.size() > 0) {
final SavingsAccountTransaction accountTransaction = savingsAccountTransactions.get(savingsAccountTransactions.size() - 1);
if (accountTransaction.isAfter(closedDate)) {
baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate)
.failWithCode("must.be.after.last.transaction.date");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
}
if (getAccountBalance().doubleValue() > 0) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("results.in.balance.not.zero");
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
this.status = SavingsAccountStatusType.CLOSED.getValue();
actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status));
actualChanges.put(SavingsApiConstants.localeParamName, command.locale());
actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat());
actualChanges.put(SavingsApiConstants.closedOnDateParamName, closedDate.toString(fmt));
this.rejectedOnDate = null;
this.rejectedBy = null;
this.withdrawnOnDate = null;
this.withdrawnBy = null;
this.closedOnDate = closedDate.toDate();
this.closedBy = currentUser;
return actualChanges;
}
private Date calculateDateAccountIsLockedUntil(final LocalDate activationLocalDate) {
Date lockedInUntilLocalDate = null;
final PeriodFrequencyType lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(this.lockinPeriodFrequencyType);
switch (lockinPeriodFrequencyType) {
case INVALID:
break;
case DAYS:
lockedInUntilLocalDate = activationLocalDate.plusDays(this.lockinPeriodFrequency).toDate();
break;
case WEEKS:
lockedInUntilLocalDate = activationLocalDate.plusWeeks(this.lockinPeriodFrequency).toDate();
break;
case MONTHS:
lockedInUntilLocalDate = activationLocalDate.plusMonths(this.lockinPeriodFrequency).toDate();
break;
case YEARS:
lockedInUntilLocalDate = activationLocalDate.plusYears(this.lockinPeriodFrequency).toDate();
break;
}
return lockedInUntilLocalDate;
}
public Group group() {
return this.group;
}
public boolean isWithdrawalFeeApplicableForTransfer() {
return this.withdrawalFeeApplicableForTransfer;
}
public void activateAccountBasedOnBalance() {
if (SavingsAccountStatusType.fromInt(this.status).isClosed() && !this.summary.getAccountBalance(getCurrency()).isZero()) {
this.status = SavingsAccountStatusType.ACTIVE.getValue();
}
}
public LocalDate getClosedOnDate() {
return (LocalDate) ObjectUtils.defaultIfNull(new LocalDate(this.closedOnDate), null);
}
} |
package io.jboot.utils;
import io.jboot.app.config.ConfigUtil;
public class AnnotationUtil {
public static String get(String value) {
return StrUtil.isNotBlank(value) ? ConfigUtil.parseValue(value.trim()) : StrUtil.EMPTY;
}
public static Integer getInt(String value) {
String intValue = get(value);
if (intValue == null) return null;
return Integer.valueOf(intValue);
}
public static Integer getInt(String value, int defaultValue) {
String intValue = get(value);
if (intValue == null) return defaultValue;
return Integer.valueOf(intValue);
}
public static Long getLong(String value) {
String longValue = get(value);
if (longValue == null) return null;
return Long.valueOf(longValue);
}
public static Long getLong(String value, long defaultValue) {
String longValue = get(value);
if (longValue == null) return defaultValue;
return Long.valueOf(longValue);
}
public static Boolean getBool(String value) {
String boolValue = get(value);
if (boolValue == null) return null;
return Boolean.valueOf(boolValue);
}
public static Boolean getBool(String value, boolean defaultValue) {
String boolValue = get(value);
if (boolValue == null) return defaultValue;
return Boolean.valueOf(boolValue);
}
public static String[] get(String[] value) {
if (ArrayUtil.isNullOrEmpty(value)) {
return null;
}
String[] rets = new String[value.length];
for (int i = 0; i < rets.length; i++) {
rets[i] = get(value[i]);
}
return rets;
}
} |
// This string is autogenerated by ChangeAppSettings.sh, do not change spaces amount anywhere
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import java.util.Vector;
import android.view.KeyEvent;
class Globals {
public static String ApplicationName = "CommanderGenius";
public static final boolean Using_SDL_1_3 = false;
// Should be zip file
public static String DataDownloadUrl = "Data files are 2 Mb|https:
// Set this value to true if you're planning to render 3D using OpenGL - it eats some GFX resources, so disabled for 2D
public static boolean NeedDepthBuffer = false;
public static boolean SwVideoMode = false;
public static boolean HorizontalOrientation = true;
// prevent device from going to suspend mode
public static boolean InhibitSuspend = false;
// Readme text to be shown on download page
public static String ReadmeText = "^You may press \"Home\" now - the data will be downloaded in background".replace("^","\n");
public static String CommandLine = "";
public static boolean AppUsesMouse = false;
public static boolean AppNeedsTwoButtonMouse = false;
public static boolean AppNeedsArrowKeys = true;
public static boolean AppNeedsTextInput = true;
public static boolean AppUsesJoystick = false;
public static boolean AppHandlesJoystickSensitivity = false;
public static boolean AppUsesMultitouch = false;
public static boolean NonBlockingSwapBuffers = false;
public static int AppTouchscreenKeyboardKeysAmount = 4;
public static int AppTouchscreenKeyboardKeysAmountAutoFire = 1;
// Phone-specific config, TODO: move this to settings
public static boolean DownloadToSdcard = true;
public static boolean PhoneHasTrackball = false;
public static boolean PhoneHasArrowKeys = false;
public static boolean UseAccelerometerAsArrowKeys = false;
public static boolean UseTouchscreenKeyboard = true;
public static int TouchscreenKeyboardSize = 1;
public static int TouchscreenKeyboardTheme = 2;
public static int TouchscreenKeyboardTransparency = 2;
public static int AccelerometerSensitivity = 2;
public static int AccelerometerCenterPos = 2;
public static int TrackballDampening = 0;
public static int AudioBufferConfig = 0;
public static boolean OptionalDataDownload[] = null;
public static final int LEFT_CLICK_NORMAL = 0;
public static final int LEFT_CLICK_NEAR_CURSOR = 1;
public static final int LEFT_CLICK_WITH_MULTITOUCH = 2;
public static final int LEFT_CLICK_WITH_PRESSURE = 3;
public static final int LEFT_CLICK_WITH_KEY = 4;
public static final int LEFT_CLICK_WITH_TIMEOUT = 5;
public static final int LEFT_CLICK_WITH_TAP = 6;
public static final int LEFT_CLICK_WITH_TAP_OR_TIMEOUT = 7;
public static int LeftClickMethod = AppNeedsTwoButtonMouse ? LEFT_CLICK_WITH_TAP_OR_TIMEOUT : LEFT_CLICK_NORMAL;
public static int LeftClickKey = KeyEvent.KEYCODE_DPAD_CENTER;
public static int LeftClickTimeout = 3;
public static final int RIGHT_CLICK_NONE = 0;
public static final int RIGHT_CLICK_WITH_MULTITOUCH = 1;
public static final int RIGHT_CLICK_WITH_PRESSURE = 2;
public static final int RIGHT_CLICK_WITH_KEY = 3;
public static final int RIGHT_CLICK_WITH_TIMEOUT = 4;
public static int RightClickTimeout = 4;
public static int RightClickMethod = AppNeedsTwoButtonMouse ? RIGHT_CLICK_WITH_MULTITOUCH : RIGHT_CLICK_NONE;
public static int RightClickKey = KeyEvent.KEYCODE_MENU;
public static boolean MoveMouseWithJoystick = false;
public static int MoveMouseWithJoystickSpeed = 0;
public static int MoveMouseWithJoystickAccel = 0;
public static boolean ClickMouseWithDpad = false;
public static boolean RelativeMouseMovement = AppNeedsTwoButtonMouse; // Laptop touchpad mode
public static int RelativeMouseMovementSpeed = 2;
public static int RelativeMouseMovementAccel = 0;
public static boolean ShowScreenUnderFinger = false;
public static boolean KeepAspectRatio = false;
public static int ClickScreenPressure = 0;
public static int ClickScreenTouchspotSize = 0;
public static int RemapHwKeycode[] = new int[SDL_Keys.JAVA_KEYCODE_LAST];
public static int RemapScreenKbKeycode[] = new int[6];
public static boolean ScreenKbControlsShown[] = new boolean[8]; /* Also joystick and text input button added */
public static int ScreenKbControlsLayout[][] = new int[8][4];
public static int RemapMultitouchGestureKeycode[] = new int[4];
public static boolean MultitouchGesturesUsed[] = new boolean[4];
public static int MultitouchGestureSensitivity = 1;
public static int TouchscreenCalibration[] = new int[4];
public static String DataDir = new String("");
public static boolean SmoothVideo = false;
public static boolean MultiThreadedVideo = SwVideoMode;
}
class LoadLibrary {
public LoadLibrary() { System.loadLibrary("sdl-1.2"); };
} |
package istc.bigdawg.rest;
import istc.bigdawg.BDConstants;
import istc.bigdawg.database.AttributeMetaData;
import istc.bigdawg.database.ObjectMetaData;
import istc.bigdawg.exceptions.ApiException;
import istc.bigdawg.executor.RESTQueryResult;
import istc.bigdawg.query.AbstractJSONQueryParser;
import istc.bigdawg.shims.ApiToRESTShim;
import istc.bigdawg.executor.ExecutorEngine;
import istc.bigdawg.executor.QueryResult;
import istc.bigdawg.query.DBHandler;
import istc.bigdawg.utils.Tuple;
import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.annotation.Nullable;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
public class RESTHandler implements ExecutorEngine, DBHandler {
private RESTConnectionInfo restConnectionInfo;
private static Logger log = Logger
.getLogger(RESTHandler.class.getName());
public RESTHandler(RESTConnectionInfo restConnectionInfo) {
this.restConnectionInfo = restConnectionInfo;
}
// Use Hashtable for reentrancy concerns
// @TODO - how to clean this out periodically?
// @TODO - how to prevent multiple entries of the same tag name?
private static Map<String, RESTQueryResult> restQueryResults = new Hashtable<>();
@Override
public Optional<QueryResult> execute(String query) {
String bigdawgResultTag = "";
Optional<QueryResult> queryResult;
try {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(query);
if (jsonObject.containsKey("tag")) {
bigdawgResultTag = (String) jsonObject.get("tag");
}
String url = restConnectionInfo.getUrl();
HttpMethod method = restConnectionInfo.getMethod();
String postData = null;
String queryParameters = null;
switch(method) {
case POST:
String contentType = restConnectionInfo.getContentType();
if (contentType == null) {
throw new ApiException("Null Content-Type");
}
if (jsonObject.containsKey("query-raw")) {
postData = (String) jsonObject.get("query-raw");
}
else if (jsonObject.containsKey("query")) {
Map<String, String> queryParametersMap = AbstractJSONQueryParser.jsonObjectToKeyValueString((JSONObject) jsonObject.get("query"));
switch (contentType) {
case "application/x-www-form-urlencoded":
postData = URLUtil.encodeParameters(queryParametersMap);
break;
case "application/json":
postData = JSONObject.toJSONString(queryParametersMap);
break;
default:
throw new ApiException("Unknown Content-Type: " + contentType);
}
}
queryParameters = restConnectionInfo.getFinalQueryParameters(null);
break;
case GET:
String queryString = null;
if (jsonObject.containsKey("query-raw")) {
queryString = (String) jsonObject.get("query-raw");
}
else if (jsonObject.containsKey("query")) {
Map<String, String> queryParametersMap = AbstractJSONQueryParser.jsonObjectToKeyValueString((JSONObject) jsonObject.get("query"));
queryString = URLUtil.encodeParameters(queryParametersMap);
}
queryParameters = restConnectionInfo.getFinalQueryParameters(queryString);
break;
default:
throw new ApiException("Unknown/Unsupported HttpMethod: " + method);
}
if (queryParameters != null) {
url = URLUtil.appendQueryParameters(url, queryParameters);
}
Map<String, String> headers = restConnectionInfo.getHeaders(queryParameters);
// @TODO Connect / read timeout could be parameterized either in query or in connection parameters, or both
URLUtil.FetchResult fetchResult = URLUtil.fetch(url, method, headers, postData, restConnectionInfo.getConnectTimeout(), restConnectionInfo.getReadTimeout());
String resultKey = null;
if (jsonObject.containsKey("result-key")) {
resultKey = (String) jsonObject.get("result-key");
}
RESTQueryResult restQueryResult = this.parseResult(fetchResult, resultKey);
if (restQueryResult == null) {
queryResult = Optional.empty();
}
else {
RESTHandler.restQueryResults.put(bigdawgResultTag, restQueryResult);
queryResult = Optional.of(restQueryResult);
}
}
catch (Exception e) {
RESTHandler.log.error("Error executing REST query", e); // how to bubble this up?
queryResult = Optional.empty();
}
return queryResult;
}
/**
* Parses the result from a fetch
* @param fetchResult Result structure from teh fetch
* @return List of results as parsed
* @throws ApiException when there's a problem parsing
*/
private RESTQueryResult parseResult(URLUtil.FetchResult fetchResult, String resultKey) throws ApiException {
if (resultKey == null) {
resultKey = restConnectionInfo.getResultKey();
}
RESTHandler.log.info("RESTHandler - result_key" + String.valueOf(resultKey == null ? resultKey : "<null>"));
try {
// @TODO support other content types e.g. text/csv or tsv or even maybe xml?
JSONParser jsonParser = new JSONParser();
if (!URLUtil.headersContain(fetchResult.responseHeaders, "content-type", URLUtil.HeaderMatch.jsonHeaderMatchTypes, ";")) {
throw new ApiException("Unsupported content type: " + fetchResult.responseHeaders.get("content-type").get(0));
}
Object object = jsonParser.parse(fetchResult.response);
RESTHandler.log.info("RESTHandler - parsing result: " + String.valueOf(fetchResult.response));
return this.parseJSONResult(resultKey, object);
} catch (ParseException e) {
throw new ApiException("Exception encountered trying to parse the result: " + e.toString());
}
}
private RESTQueryResult parseJSONArray(JSONArray jsonArray) {
// Tuple3 (colname, type, nullable)
List<Tuple.Tuple3<String, String, Boolean>> headers = new ArrayList<>();
Map<String, Integer> headerNames = new HashMap<>();
List<String> rows = new ArrayList<>();
List<Map<String, Object>> rowsWithHeadings = new ArrayList<>();
for (Object o : jsonArray) {
String row = "";
Map<String, Object> rowWithHeadings = new HashMap<>();
if (o == null) {
int idx = 0;
if (headerNames.containsKey("col1")) {
idx = headerNames.get("col1");
Tuple.Tuple3<String, String, Boolean> tuple3 = headers.get(idx);
if (!tuple3.getT3()) {
headers.set(idx, new Tuple.Tuple3<String, String, Boolean>(tuple3.getT1(), tuple3.getT2(), true));
}
}
else {
headers.add(new Tuple.Tuple3<>("col1", "text", true));
}
rowWithHeadings.put("col1", null);
row = "";
} else if (o.getClass() == JSONArray.class) {
row = getFromJSONArray(headers, headerNames, rowWithHeadings, (JSONArray) o);
} else if (o.getClass() == JSONObject.class) {
row = getFromJSONObject(headers, headerNames, rowWithHeadings, (JSONObject) o);
}
else {
final Tuple.Tuple2<String, Boolean> headerInfo = determineHeaderTypeNullable(o);
final String headerType = headerInfo.getT1();
final boolean nullable = headerInfo.getT2();
if (!headerNames.containsKey("col1")){
headerNames.put("col1", headers.size());
headers.add(new Tuple.Tuple3<String, String, Boolean>("col1", headerType, nullable));
}
final int headersSize = headers.size();
for (int i = 0; i < headersSize; i++) {
Tuple.Tuple3<String, String, Boolean> header = headers.get(i);
if (header.getT1().equals("col1")) {
if (nullable && !header.getT3()) {
headers.set(i, new Tuple.Tuple3<String, String, Boolean>("col1", header.getT2(), true));
}
rowWithHeadings.put("col1", o);
}
else {
if (!header.getT3()) {
headers.set(i, new Tuple.Tuple3<String, String, Boolean>("col1", header.getT2(), true));
}
}
}
}
rows.add(row);
rowsWithHeadings.add(rowWithHeadings);
}
return new RESTQueryResult(headers, rows, rowsWithHeadings, restConnectionInfo);
}
private String getFromJSONObject(List<Tuple.Tuple3<String, String, Boolean>> headers,
Map<String, Integer> headerNames,
Map<String, Object> rowWithHeaders,
JSONObject jsonObject) {
List<Object> row = new ArrayList<>();
for (Object key : jsonObject.keySet()) {
String keyStr = String.valueOf(key);
Object obj = jsonObject.get(key);
final Tuple.Tuple2<String, Boolean> headerInfo = determineHeaderTypeNullable(obj);
final String headerType = headerInfo.getT1();
final boolean nullable = headerInfo.getT2();
if (headerNames.containsKey(keyStr)) {
final int idx = headerNames.get(keyStr);
final Tuple.Tuple3<String, String, Boolean> tuple3 = headers.get(idx);
if (nullable) {
if (!tuple3.getT3()) {
headers.set(idx, new Tuple.Tuple3<String, String, Boolean>(tuple3.getT1(), tuple3.getT2(), true));
}
} else {
final String t2 = tuple3.getT2();
if (!t2.equals("json") && !t2.equals(headerType)) {
headers.set(idx, new Tuple.Tuple3<String, String, Boolean>(tuple3.getT1(), "json", true));
}
}
} else {
headerNames.put(keyStr, headers.size());
headers.add(new Tuple.Tuple3<String, String, Boolean>(keyStr, headerType, nullable));
}
}
final int headersSize = headers.size();
for (int i = 0; i < headersSize; i++) {
Tuple.Tuple3<String, String, Boolean> tuple3 = headers.get(i);
final String headerName = tuple3.getT1();
if (jsonObject.containsKey(headerName)) {
final Object obj = jsonObject.get(headerName);
rowWithHeaders.put(headerName, obj);
}
else {
if (!tuple3.getT3()) {
headers.set(i, new Tuple.Tuple3<String, String, Boolean>(headerName, tuple3.getT2(), true));
}
}
}
return jsonObject.toString();
}
private String getFromJSONArray(List<Tuple.Tuple3<String, String, Boolean>> headers, Map<String, Integer> headerNames, Map<String, Object> rowWithHeadings, JSONArray jsonArray) {
final int jsonSize = jsonArray.size();
List<Object> row = new ArrayList<>();
for (int i = 0 ; i < jsonSize; i++) {
final String colName = "col" + String.valueOf(i);
final Object obj = jsonArray.get(i);
if (!headerNames.containsKey(colName)) {
final Tuple.Tuple2<String, Boolean> headerInfo = determineHeaderTypeNullable(obj);
final String headerType = headerInfo.getT1();
final boolean nullable = headerInfo.getT2();
headers.add(new Tuple.Tuple3<String, String, Boolean>(colName, headerType, nullable));
headerNames.put(colName, headers.size() - 1);
}
}
int j = 0;
final int headersSize = headers.size();
for (int i = 0; i < headersSize; i++) {
final Tuple.Tuple3<String, String, Boolean> header = headers.get(i);
if (j < jsonSize) {
final String colName = "col" + String.valueOf(j);
if (header.getT1().equals(colName)) {
final Object obj = jsonArray.get(j);
j++;
final Tuple.Tuple2<String, Boolean> headerInfo = determineHeaderTypeNullable(obj);
final String headerType = headerInfo.getT1();
final boolean nullable = headerInfo.getT2();
final String t2 = header.getT2();
if (nullable) {
if (!header.getT3()) {
headers.set(i, new Tuple.Tuple3<>(header.getT1(), header.getT2(), true));
}
}
else if (!t2.equals("json") && !t2.equals(headerType)) {
headers.set(i, new Tuple.Tuple3<>(header.getT1(), "json", header.getT3()));
}
rowWithHeadings.put(colName, obj);
}
}
else {
if (!header.getT3()) {
headers.set(i, new Tuple.Tuple3<>(header.getT1(), header.getT2(), true));
}
}
}
return jsonArray.toString();
}
/**
* Determines what the header type should be given the object passed in, and whether it should be nullable or not
* @param obj object to examine
* @return Tuple.Tuple2 of the header type (String), and whether it should be nullable (Boolean)
*/
private Tuple.Tuple2<String, Boolean> determineHeaderTypeNullable(Object obj) {
if (obj == null){
return new Tuple.Tuple2<String, Boolean>("json", true);
}
else if (obj.getClass() == JSONObject.class || obj.getClass() == JSONArray.class) {
return new Tuple.Tuple2<String, Boolean>("json", false);
}
else if (obj.getClass() == Integer.class) {
return new Tuple.Tuple2<String, Boolean>("integer", false);
}
else if (obj.getClass() == Long.class) {
return new Tuple.Tuple2<String, Boolean>("bigint", false);
}
else if (obj.getClass() == Double.class) {
return new Tuple.Tuple2<String, Boolean>("double precision", false);
}
else if (obj.getClass() == Boolean.class) {
return new Tuple.Tuple2<String, Boolean>("boolean", false);
}
return new Tuple.Tuple2<String, Boolean>("text", false);
}
/**
* Parses a json result
* @param resultKey Index into the json object
* @param object Object to search
* @throws ApiException when something goes wrong
*/
private RESTQueryResult parseJSONResult(String resultKey, Object object) throws ApiException {
if (object == null) {
return null;
}
if (object.getClass() == JSONArray.class) {
if (resultKey != null && resultKey.length() > 0) {
throw new ApiException("Response is a list, but expected an object due to resultKey of '" + resultKey + "'");
}
return parseJSONArray((JSONArray) object);
}
if (object.getClass() != JSONObject.class) {
if (resultKey != null && resultKey.length() > 0) {
throw new ApiException("Response is a JSONValue: " + object.toString() + ", but expected an object due to resultKey of '" + resultKey + "'");
}
return this.getBasicRESTQueryResult(object);
}
JSONObject jsonObject = (JSONObject) object;
if (resultKey == null || resultKey.length() == 0) {
List<Tuple.Tuple3<String, String, Boolean>> headers = new ArrayList<>();
Map<String, Integer> headerNames = new HashMap<>();
List<Map<String, Object>> rowsWithHeaders = new ArrayList<>();
Map<String, Object> rowWithHeaders = new HashMap<>();
String row = getFromJSONObject(headers, headerNames, rowWithHeaders, jsonObject);
List<String> rows = new ArrayList<>();
rows.add(row);
rowsWithHeaders.add(rowWithHeaders);
return new RESTQueryResult(headers, rows, rowsWithHeaders, restConnectionInfo);
}
// Determine if the index key is nested
if (!jsonObject.containsKey(resultKey)) { // nested key? e.g. something.something_else
int pos;
if ((pos = resultKey.indexOf('.')) > 0 && pos < resultKey.length() - 1) {
String key = resultKey.substring(0, pos);
String rest = resultKey.substring(pos + 1);
if (jsonObject.containsKey(key)) {
return this.parseJSONResult(rest, jsonObject.get(key));
}
}
return null;
}
Object result = jsonObject.get(resultKey);
if (result == null || result.getClass() != JSONArray.class) {
return this.getBasicRESTQueryResult(result);
}
final JSONArray jsonArray = (JSONArray) result;
return parseJSONArray(jsonArray);
}
/**
* Handles a basic result
* @param object
* @return
*/
private RESTQueryResult getBasicRESTQueryResult(@Nullable Object object) {
if (object == null) {
return null;
}
List<String> rows = new ArrayList<>();
String row = object.toString();
rows.add(row);
List<Map<String, Object>> rowsWithHeaders = new ArrayList<>();
Map<String, Object> rowWithHeaders = new HashMap<>();
rowWithHeaders.put("col1", object);
rowsWithHeaders.add(rowWithHeaders);
Tuple.Tuple2<String, Boolean> tuple2 = determineHeaderTypeNullable(object);
Tuple.Tuple3<String, String, Boolean> header = new Tuple.Tuple3<>("col1", tuple2.getT1(), tuple2.getT2());
List<Tuple.Tuple3<String, String, Boolean>> headers = new ArrayList<>();
headers.add(header);
return new RESTQueryResult(headers, rows, rowsWithHeaders, restConnectionInfo);
}
@Override
public void dropDataSetIfExists(String dataSetName) {
// Not implemented
assert(false);
}
/**
*
* @param queryString
* the query to be executed
* @return result of the query
*/
@Override
public Response executeQuery(String queryString) {
Optional<QueryResult> result = this.execute(queryString);
return null;
}
/**
*
* @return The name of the shim in which the handler operates.
*/
@Override
public BDConstants.Shim getShim() {
return null;
}
/**
*
* @param name
* name of the object (table, array, etc.)
* @return the meta data about the object (e.g. names of the attributes)
* @throws Exception
* (probably a connection to the database failed).
*/
@Override
public ObjectMetaData getObjectMetaData(String name) throws Exception {
final RESTQueryResult restQueryResult = RESTHandler.restQueryResults.getOrDefault(name, null);
return new ObjectMetaData() {
@Override
public String getName() {
return null;
}
@Override
public List<AttributeMetaData> getAttributesOrdered() {
List <AttributeMetaData> resultList = new ArrayList<>();
if (restQueryResult == null) {
AttributeMetaData attribute = new AttributeMetaData("col1", "json", true, false);
resultList.add(attribute);
return resultList;
}
List<Tuple.Tuple3<String, String, Boolean>> headers = restQueryResult.getColumns();
for(Tuple.Tuple3<String, String, Boolean> header: headers) {
AttributeMetaData attribute = new AttributeMetaData(header.getT1(), header.getT2(), header.getT3(), false);
resultList.add(attribute);
}
return resultList;
}
};
}
/**
* Get a JDBC connection to a database.
*
* @return connection to a database
*/
@Override
public Connection getConnection() throws SQLException {
return null;
}
/**
*
* @param name
* Name of the object (table/array etc.)
* @return true if the object with the specified name exists, false
* otherwise.
*/
@Override
public boolean existsObject(String name) throws Exception {
return false;
}
/**
* Release all the resources hold by the handler.
*/
@Override
public void close() throws Exception {
}
@Override
public String getCsvExportDelimiter() {
return ",";
}
} |
package jwebform.processors;
import jwebform.element.structure.ElementContainer;
import jwebform.element.structure.ElementResult;
import jwebform.element.structure.GroupType;
import jwebform.element.structure.SingleType;
import jwebform.env.Env.EnvWithSubmitInfo;
import jwebform.validation.FormValidator;
import jwebform.validation.ValidationResult;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
// this is doing the "hard work": Let each element do the apply function, run validations, run
// form-validations
public class Processor {
// do the processing of the elements, the validation and the form-validation
public final ElementResults run(EnvWithSubmitInfo envWithSubmitInfo, GroupType group) {
// call the apply Method
ElementResults elementResults = processElements(envWithSubmitInfo, group.getChilds());
// run preprocessors
elementResults = this.runPostProcessors(elementResults);
// run the form validators
ElementValdationResults overridenValidationResults =
this.runFormValidations(elementResults, group.getValidators(group.of()));
// if form-validators changed validaiton results, correct them on the elemtns
return this.correctElementResults(elementResults, overridenValidationResults);
}
// process each element. This is used for elements, that have children... (Lke Date-Selects)
public ElementResults processElements(EnvWithSubmitInfo env,
ElementContainer... elementsToProcess) {
return this.processElements(env, packElementContainerInList(elementsToProcess));
}
private List<PostProcessor> getPostProcessors() {
return Collections.singletonList(new CheckDoubleElementsPostProcessor());
}
private ElementResults runPostProcessors(ElementResults elementResults) {
for (PostProcessor postProcessor : getPostProcessors()) {
elementResults = postProcessor.postProcess(elementResults);
}
return elementResults;
}
private ElementResults processElements(EnvWithSubmitInfo env, List<ElementContainer> elements) {
ElementResults elementResults = new ElementResults();
for (ElementContainer container : elements) {
if (container.element instanceof GroupType) {
processGroup(env, elementResults, container);
} else {
proessSingleElement(env, elementResults, container);
}
}
return elementResults;
}
private void proessSingleElement(
EnvWithSubmitInfo env, ElementResults elementResults, ElementContainer container) {
// here is where the magic happens! The "apply" method of the elements is called.
ElementResult result = ((SingleType) container.element).apply(env);
if (env.isSubmitted()) {
if (result.getValidationResult() != ValidationResult.undefined()) {
// element has set the validation itself. This might happen in complex elements. And
// will
// override the following validation
} else {
result = result.ofValidationResult(container.validator.validate(result.getValue()));
}
} else {
// do nothing
}
if (elementResults.containsElement(container)) {
throw new IdenticalElementException(container);
}
elementResults.put(container, result);
}
private void processGroup(
EnvWithSubmitInfo env, ElementResults elementResults, ElementContainer container) {
ElementResults groupElementResults = this.run(env, (GroupType) container.element);
ElementResult groupResult =
((GroupType) container.element).process(env, groupElementResults);
elementResults.put(container, groupResult.cloneWithChilds(groupElementResults));
// TODO: das eigentliche element (groupElement) brauch auch ein Value. Wie kommt es da dran?
}
private ElementValdationResults runFormValidations(ElementResults elementResults,
List<FormValidator> formValidators) {
// run the form-validators
ElementValdationResults overridenValidationResults = new ElementValdationResults();
for (FormValidator formValidator : formValidators) {
overridenValidationResults.merge(formValidator.validate(elementResults));
}
return overridenValidationResults;
}
public boolean checkAllValidationResults(ElementResults correctedElementResults) {
boolean formIsValid = true;
for (Map.Entry<ElementContainer, ElementResult> entry : correctedElementResults) {
if (entry.getValue().getValidationResult() != ValidationResult.ok()) {
formIsValid = false;
break;
}
}
return formIsValid;
}
private ElementResults correctElementResults(ElementResults elementResults,
ElementValdationResults overridenValidationResults) {
overridenValidationResults.getResutls().forEach((element, overridenValidationResult) -> {
ElementResult re = elementResults.get(element);
elementResults.put(element, re.cloneWithNewValidationResult(overridenValidationResult));
});
return elementResults;
}
@SuppressWarnings("serial")
public class IdenticalElementException extends RuntimeException {
public IdenticalElementException(ElementContainer container) {
super("Identical Elements are not allowed. Plese remove double container: "
+ container.element);
}
}
private static List<ElementContainer> packElementContainerInList(ElementContainer... elements) {
List<ElementContainer> ec = new ArrayList<>();
Collections.addAll(ec, elements);
return ec;
}
} |
package net.blay09.javatmi;
import lombok.Data;
import net.blay09.javairc.IRCMessage;
import net.blay09.javairc.IRCUser;
import java.util.Objects;
@Data
public class TwitchUser {
private final IRCUser user;
private String color;
private String displayName;
private int userId;
private UserType userType;
private boolean mod;
private boolean subscriber;
private boolean turbo;
public TwitchUser(IRCUser user) {
this.user = user;
}
public boolean hasColor() {
return color != null && !color.isEmpty();
}
public String getDisplayName() {
return displayName != null ? displayName : user.getNick();
}
public String getNick() {
return user.getNick();
}
public static TwitchUser fromMessage(IRCMessage message) {
TwitchUser twitchUser = new TwitchUser(message.parseSender());
twitchUser.color = message.getTagByKey("color");
twitchUser.displayName = message.getTagByKey("display-name");
twitchUser.mod = Objects.equals(message.getTagByKey("mod"), "1");
twitchUser.subscriber = Objects.equals(message.getTagByKey("subscriber"), "1");
twitchUser.turbo = Objects.equals(message.getTagByKey("turbo"), "1");
try {
twitchUser.userId = Integer.parseInt(message.getTagByKey("user-id"));
} catch(NumberFormatException ignored) {
}
twitchUser.userType = UserType.fromTag(message.getTagByKey("user-type"));
return twitchUser;
}
} |
package yuku.alkitab.base.ac;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.PopupMenu;
import android.text.SpannableStringBuilder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import yuku.afw.App;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.alkitab.base.S;
import yuku.alkitab.base.config.AppConfig;
import yuku.alkitab.base.model.Ari;
import yuku.alkitab.base.model.ReadingPlan;
import yuku.alkitab.base.model.Version;
import yuku.alkitab.base.storage.Prefkey;
import yuku.alkitab.base.util.IntArrayList;
import yuku.alkitab.base.util.ReadingPlanManager;
import yuku.alkitab.debug.R;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class ReadingPlanActivity extends ActionBarActivity {
public static final String READING_PLAN_ARI_RANGES = "reading_plan_ari_ranges";
public static final String READING_PLAN_ID = "reading_plan_id";
public static final String READING_PLAN_DAY_NUMBER = "reading_plan_day_number";
private ReadingPlan readingPlan;
private List<ReadingPlan.ReadingPlanInfo> downloadedReadingPlanInfos;
private int todayNumber;
private int dayNumber;
private IntArrayList readingCodes;
private boolean newDropDownItems;
private ImageButton bLeft;
private ImageButton bRight;
private Button bToday;
private ListView lsTodayReadings;
private ReadingPlanAdapter readingPlanAdapter;
private ActionBar actionBar;
private LinearLayout llNavigations;
private FrameLayout flNoData;
private Button bDownload;
public static Intent createIntent(int dayNumber) {
Intent intent = new Intent(App.context, ReadingPlanActivity.class);
intent.putExtra(READING_PLAN_DAY_NUMBER, dayNumber);
return intent;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading_plan);
llNavigations = V.get(this, R.id.llNavigations);
flNoData = V.get(this, R.id.flNoDataContainer);
lsTodayReadings = V.get(this, R.id.lsTodayReadings);
bToday = V.get(this, R.id.bToday);
bLeft = V.get(this, R.id.bLeft);
bRight = V.get(this, R.id.bRight);
bDownload = V.get(this, R.id.bDownload);
actionBar = getSupportActionBar();
long id = Preferences.getLong(Prefkey.active_reading_plan, 0);
loadReadingPlan(id);
loadReadingPlanProgress();
loadDayNumber();
prepareDropDownNavigation();
prepareDisplay();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_reading_plan, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuReset) {
resetReadingPlan();
return true;
} else if (itemId == R.id.menuDownload) {
downloadReadingPlan();
return true;
} else if (itemId == R.id.menuDelete) {
deleteReadingPlan();
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToIsiActivity(final int dayNumber, final int sequence) {
final int[] selectedVerses = readingPlan.dailyVerses.get(dayNumber);
int ari = selectedVerses[sequence * 2];
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("ari", ari);
intent.putExtra(READING_PLAN_ID, readingPlan.info.id);
intent.putExtra(READING_PLAN_DAY_NUMBER, dayNumber);
intent.putExtra(READING_PLAN_ARI_RANGES, selectedVerses);
setResult(RESULT_OK, intent);
finish();
}
public void prepareDisplay() {
if (readingPlan == null) {
llNavigations.setVisibility(View.GONE);
lsTodayReadings.setVisibility(View.GONE);
flNoData.setVisibility(View.VISIBLE);
bDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
downloadReadingPlan();
}
});
return;
}
llNavigations.setVisibility(View.VISIBLE);
lsTodayReadings.setVisibility(View.VISIBLE);
flNoData.setVisibility(View.GONE);
//Listviews
readingPlanAdapter = new ReadingPlanAdapter();
readingPlanAdapter.load();
lsTodayReadings.setAdapter(readingPlanAdapter);
lsTodayReadings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
final int todayReadingsSize = readingPlan.dailyVerses.get(dayNumber).length / 2;
if (position < todayReadingsSize) {
goToIsiActivity(dayNumber, position);
} else if (position > todayReadingsSize) {
goToIsiActivity(position - todayReadingsSize - 1, 0);
}
}
});
//buttons
updateButtonStatus();
bToday.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final PopupMenu popupMenu = new PopupMenu(ReadingPlanActivity.this, v);
popupMenu.getMenu().add(Menu.NONE, 1, 1, "Show calendar");
popupMenu.getMenu().add(Menu.NONE, 2, 2, "Go to first unread");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
popupMenu.dismiss();
int itemId = menuItem.getItemId();
if (itemId == 1) {
showCalendar();
} else if (itemId == 2) {
gotoFirstUnread();
}
return true;
}
});
popupMenu.show();
}
private void gotoFirstUnread() {
dayNumber = findFirstUnreadDay(readingPlan.info.duration - 1);
changeDay(0);
}
public void showCalendar() {Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(readingPlan.info.startDate));
calendar.add(Calendar.DATE, dayNumber);
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
Calendar newCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
newCalendar.set(Calendar.HOUR_OF_DAY, 0);
newCalendar.set(Calendar.MINUTE, 1); //TODO: find another way to calculate difference
newCalendar.set(Calendar.SECOND, 0);
Calendar startCalendar = GregorianCalendar.getInstance();
startCalendar.setTime(new Date(readingPlan.info.startDate));
startCalendar.set(Calendar.HOUR_OF_DAY, 0);
startCalendar.set(Calendar.MINUTE, 0);
startCalendar.set(Calendar.SECOND, 0);
int newDay = (int) ((newCalendar.getTime().getTime() - startCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
if (newDay < 0) {
newDay = 0;
} else if (newDay >= readingPlan.info.duration) {
newDay = readingPlan.info.duration - 1;
}
dayNumber = newDay;
changeDay(0);
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(ReadingPlanActivity.this, dateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
});
bLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
changeDay(-1);
}
});
bRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
changeDay(+1);
}
});
}
public boolean prepareDropDownNavigation() {
if (downloadedReadingPlanInfos.size() == 0) {
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
return true;
}
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
long id = Preferences.getLong(Prefkey.active_reading_plan, 0);
int itemNumber = 0;
//Drop-down navigation
List<String> titles = new ArrayList<String>();
for (int i = 0; i < downloadedReadingPlanInfos.size(); i++) {
ReadingPlan.ReadingPlanInfo info = downloadedReadingPlanInfos.get(i);
titles.add(info.title);
if (info.id == id) {
itemNumber = i;
}
}
ArrayAdapter<String> navigationAdapter = new ArrayAdapter<String>(this, R.layout.item_dropdown_reading_plan, titles);
newDropDownItems = false;
actionBar.setListNavigationCallbacks(navigationAdapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(final int i, final long l) {
if (newDropDownItems) {
loadReadingPlan(downloadedReadingPlanInfos.get(i).id);
loadReadingPlanProgress();
prepareDisplay();
}
return true;
}
});
actionBar.setSelectedNavigationItem(itemNumber);
newDropDownItems = true;
return false;
}
private void resetReadingPlan() {
new AlertDialog.Builder(this)
.setMessage("This action will shift your last fully read to yesterday.")
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
int lastUnreadDay = findFirstUnreadDay(dayNumber);
Calendar calendar = GregorianCalendar.getInstance();
calendar.add(Calendar.DATE, -lastUnreadDay);
S.getDb().updateStartDate(readingPlan.info.id, calendar.getTime().getTime());
loadReadingPlan(readingPlan.info.id);
loadDayNumber();
readingPlanAdapter.load();
readingPlanAdapter.notifyDataSetChanged();
updateButtonStatus();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private int findFirstUnreadDay(final int dayUntil) {
int lastUnreadDay = dayUntil;
loop1:
for (int i = 0; i < dayUntil; i++) {
boolean[] readMarks = new boolean[readingPlan.dailyVerses.get(i).length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, i);
for (boolean readMark : readMarks) {
if (!readMark) {
lastUnreadDay = i;
break loop1;
}
}
}
return lastUnreadDay;
}
private void deleteReadingPlan() {
new AlertDialog.Builder(this)
.setMessage("Delete " + readingPlan.info.title + "?")
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
S.getDb().deleteReadingPlanById(readingPlan.info.id);
readingPlan = null;
Preferences.remove(Prefkey.active_reading_plan);
loadReadingPlan(0);
loadReadingPlanProgress();
loadDayNumber();
prepareDropDownNavigation();
prepareDisplay();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private void changeDay(int day) {
dayNumber += day;
readingPlanAdapter.load();
readingPlanAdapter.notifyDataSetChanged();
updateButtonStatus();
}
private void updateButtonStatus() { //TODO look disabled
if (dayNumber == 0) {
bLeft.setEnabled(false);
bRight.setEnabled(true);
} else if (dayNumber == readingPlan.info.duration - 1) {
bLeft.setEnabled(true);
bRight.setEnabled(false);
} else {
bLeft.setEnabled(true);
bRight.setEnabled(true);
}
bToday.setText(getReadingDateHeader(dayNumber));
}
private void loadDayNumber() {
if (readingPlan == null) {
return;
}
todayNumber = (int) ((new Date().getTime() - readingPlan.info.startDate) / (1000 * 60 * 60 * 24));
dayNumber = getIntent().getIntExtra(READING_PLAN_DAY_NUMBER, -1);
if (dayNumber == -1) {
dayNumber = todayNumber;
}
}
private void downloadReadingPlan() {
AppConfig config = AppConfig.get();
final List<ReadingPlan.ReadingPlanInfo> infos = config.readingPlanInfos;
final List<String> readingPlanTitles = new ArrayList<String>();
final List<Integer> resources = new ArrayList<Integer>();
for (int i = 0; i < infos.size(); i++) {
String title = infos.get(i).title;
boolean downloaded = false;
for (ReadingPlan.ReadingPlanInfo downloadedReadingPlanInfo : downloadedReadingPlanInfos) {
if (title.equals(downloadedReadingPlanInfo.title)) {
downloaded = true;
break;
}
}
if (!downloaded) {
readingPlanTitles.add(title);
String filename = infos.get(i).filename.replace(".rpb", ""); //TODO: proper method. testing only
resources.add(getResources().getIdentifier(filename, "raw", getPackageName())); //TODO: proper method
}
}
if (readingPlanTitles.size() == 0) {
new AlertDialog.Builder(this)
.setMessage("No reading plan can be downloaded.")
.setPositiveButton(R.string.ok, null)
.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, readingPlanTitles), new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
long id = ReadingPlanManager.copyReadingPlanToDb(resources.get(which));
Preferences.setLong(Prefkey.active_reading_plan, id);
loadDayNumber();
loadReadingPlan(id);
loadReadingPlanProgress();
prepareDropDownNavigation();
prepareDisplay();
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null)
.show();
}
}
private void loadReadingPlan(long id) {
downloadedReadingPlanInfos = S.getDb().listAllReadingPlanInfo();
if (downloadedReadingPlanInfos.size() == 0) {
return;
}
long startDate = 0;
if (id == 0) {
id = downloadedReadingPlanInfos.get(0).id;
startDate = downloadedReadingPlanInfos.get(0).startDate;
} else {
for (ReadingPlan.ReadingPlanInfo info : downloadedReadingPlanInfos) {
if (id == info.id) {
startDate = info.startDate;
}
}
}
byte[] binaryReadingPlan = S.getDb().getBinaryReadingPlanById(id);
InputStream inputStream = new ByteArrayInputStream(binaryReadingPlan);
ReadingPlan res = ReadingPlanManager.readVersion1(inputStream);
res.info.id = id;
res.info.startDate = startDate;
readingPlan = res;
Preferences.setLong(Prefkey.active_reading_plan, id);
}
private void loadReadingPlanProgress() {
if (readingPlan == null) {
return;
}
readingCodes = S.getDb().getAllReadingCodesByReadingPlanId(readingPlan.info.id);
}
private float getActualPercentage() {
float res = (float) countRead() / (float) countAllReadings() * 100;
res = (float)Math.round(res * 100) / 100;
return res;
}
private float getTargetPercentage() {
float res = (float) countTarget() / (float) countAllReadings() * 100;
res = (float)Math.round(res * 100) / 100;
return res;
}
private int countRead() {
IntArrayList filteredReadingCodes = ReadingPlanManager.filterReadingCodesByDayStartEnd(readingCodes, 0, todayNumber);
for (int i = 0; i < filteredReadingCodes.size(); i++) {
}
return filteredReadingCodes.size();
}
private int countTarget() {
int res = 0;
for (int i = 0; i <= todayNumber; i++) {
res += readingPlan.dailyVerses.get(i).length / 2;
}
return res;
}
private int countAllReadings() {
int res = 0;
for (int i = 0; i < readingPlan.info.duration; i++) {
res += readingPlan.dailyVerses.get(i).length / 2;
}
return res;
}
public String getReadingDateHeader(final int dayNumber) {
String date = "Day " + (dayNumber + 1) + ": ";
if (readingPlan.info.version == 1) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(readingPlan.info.startDate));
calendar.add(Calendar.DATE, dayNumber);
date += new SimpleDateFormat("MMMM dd, yyyy").format(calendar.getTime());
}
return date;
}
public static SpannableStringBuilder getReference(Version version, int[] ari) {
SpannableStringBuilder sb = new SpannableStringBuilder();
String book = version.getBook(Ari.toBook(ari[0])).shortName;
sb.append(book);
int startChapter = Ari.toChapter(ari[0]);
int startVerse = Ari.toVerse(ari[0]);
int lastVerse = Ari.toVerse(ari[1]);
int lastChapter = Ari.toChapter(ari[1]);
sb.append(" " + startChapter);
if (startVerse == 0) {
if (lastVerse == 0) {
if (startChapter != lastChapter) {
sb.append("-" + lastChapter);
}
} else {
sb.append("-" + lastChapter + ":" + lastVerse);
}
} else {
if (startChapter == lastChapter) {
sb.append(":" + startVerse + "-" + lastVerse);
} else {
sb.append(":" + startVerse + "-" + lastChapter + ":" + lastVerse);
}
}
return sb;
}
class ReadingPlanAdapter extends BaseAdapter {
private int[] todayReadings;
public void load() {
todayReadings = readingPlan.dailyVerses.get(dayNumber);
}
@Override
public int getCount() {
return (todayReadings.length / 2) + readingPlan.info.duration + 1;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int itemViewType = getItemViewType(position);
if (itemViewType == 0) {
CheckBox checkBox = new CheckBox(ReadingPlanActivity.this);
LinearLayout layout = new LinearLayout(ReadingPlanActivity.this);
layout.addView(checkBox);
convertView = layout;
boolean[] readMarks = new boolean[todayReadings.length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, dayNumber);
if (readMarks[position * 2]) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
ReadingPlanManager.updateReadingPlanProgress(readingPlan.info.id, dayNumber, position, isChecked);
loadReadingPlanProgress();
load();
notifyDataSetChanged();
}
});
int start = position * 2;
int[] aris = {todayReadings[start], todayReadings[start + 1]};
checkBox.setText(getReference(S.activeVersion, aris));
checkBox.setFocusable(false);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
checkBox.setLayoutParams(layoutParams);
} else if (itemViewType == 1) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item_reading_plan_summary, parent, false);
}
final ProgressBar pbReadingProgress = V.get(convertView, R.id.pbReadingProgress);
final TextView tActual = V.get(convertView, R.id.tActual);
final TextView tTarget = V.get(convertView, R.id.tTarget);
final TextView tComment = V.get(convertView, R.id.tComment);
float actualPercentage = getActualPercentage();
float targetPercentage = getTargetPercentage();
pbReadingProgress.setMax(100);
pbReadingProgress.setProgress((int) actualPercentage);
pbReadingProgress.setSecondaryProgress((int) targetPercentage);
tActual.setText("You have finished: " + actualPercentage + "%");
tTarget.setText("Target by today: " + targetPercentage + "%");
String comment;
if (actualPercentage == targetPercentage) {
comment = "You are on schedule";
} else {
float diff = (float) Math.round((targetPercentage - actualPercentage) * 100) / 100;
comment = "You are behind the schedule by " + diff + "%";
}
tComment.setText(comment);
} else if (itemViewType == 2) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item_reading_plan_one_day, parent, false);
}
final LinearLayout layout = V.get(convertView, R.id.llOneDayReadingPlan);
final int currentViewTypePosition = position - todayReadings.length / 2 - 1;
//Text title
TextView tTitle = V.get(convertView, android.R.id.text1);
tTitle.setText(getReadingDateHeader(currentViewTypePosition));
//Text reading
while (true) {
final View reading = layout.findViewWithTag("reading");
if (reading != null) {
layout.removeView(reading);
} else {
break;
}
}
int[] aris = readingPlan.dailyVerses.get(currentViewTypePosition);
for (int i = 0; i < aris.length / 2; i++) {
final int ariPosition = i;
int[] ariStartEnd = {aris[i * 2], aris[i * 2 + 1]};
final SpannableStringBuilder reference = getReference(S.activeVersion, ariStartEnd);
CheckBox checkBox = new CheckBox(ReadingPlanActivity.this);
checkBox.setText(reference);
checkBox.setTag("reading");
boolean[] readMarks = new boolean[aris.length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, currentViewTypePosition);
checkBox.setChecked(readMarks[ariPosition * 2]);
checkBox.setFocusable(false);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
checkBox.setLayoutParams(layoutParams);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
ReadingPlanManager.updateReadingPlanProgress(readingPlan.info.id, currentViewTypePosition, ariPosition, isChecked);
loadReadingPlanProgress();
load();
notifyDataSetChanged();
}
});
layout.addView(checkBox);
}
}
return convertView;
}
@Override
public Object getItem(final int position) {
return null;
}
@Override
public long getItemId(final int position) {
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType(final int position) {
if (position < todayReadings.length / 2) {
return 0;
} else if (position == todayReadings.length / 2) {
return 1;
} else {
return 2;
}
}
}
} |
package net.sf.jacclog.api.domain.http;
public class UnknownHttpRequestHeader implements ReadableHttpRequestHeader {
/**
* The name of the unknown HTTP request header
*/
private final String name;
public UnknownHttpRequestHeader(final String name) {
if (name == null) {
throw new IllegalArgumentException("Argument 'name' can not be null.");
}
this.name = name;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UnknownHttpRequestHeader other = (UnknownHttpRequestHeader) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
/**
* Gets the name of the unknown (probably non-standardized) request header which is never <code>null</code>.
*
* @return the name of the request header
*/
@Override
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("UnknownHttpRequestHeader [name=");
builder.append(name);
builder.append("]");
return builder.toString();
}
} |
package net.clgd.ccemux.init;
import static org.apache.commons.cli.Option.builder;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.file.*;
import java.util.HashSet;
import java.util.Optional;
import javax.swing.*;
import org.apache.commons.cli.*;
import org.apache.logging.log4j.LogManager;
import dan200.computercraft.ComputerCraft;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import net.clgd.ccemux.OperatingSystem;
import net.clgd.ccemux.emulation.CCEmuX;
import net.clgd.ccemux.plugins.PluginManager;
import net.clgd.ccemux.rendering.RendererFactory;
import net.clgd.ccemux.rendering.TerminalFont;
@Slf4j
public class Launcher {
private static final Options opts = new Options();
// initialize cli options
static {
opts.addOption(builder("h").longOpt("help").desc("Shows this help information").build());
opts.addOption(builder("d").longOpt("data-dir")
.desc("Sets the data directory where plugins, configs, and other data are stored.").hasArg()
.argName("path").build());
opts.addOption(builder("r").longOpt("renderer")
.desc("Sets the renderer to use. Run without a value to list all available renderers.").hasArg()
.optionalArg(true).argName("renderer").build());
opts.addOption(builder().longOpt("plugin").desc(
"Used to load additional plugins not present in the default plugin directory. Value should be a path to a .jar file.")
.hasArg().argName("file").build());
}
private static void printHelp() {
new HelpFormatter().printHelp("ccemux [args]", opts);
}
public static void main(String args[]) {
if (System.getProperty("ccemux.forceDirectLaunch") != null) {
log.info("Skipping custom classloader, some features may be unavailable");
new Launcher(args).launch();
} else {
try (final CCEmuXClassloader loader = new CCEmuXClassloader(
((URLClassLoader) Launcher.class.getClassLoader()).getURLs())) {
@SuppressWarnings("unchecked")
final Class<Launcher> klass = (Class<Launcher>) loader.findClass(Launcher.class.getName());
final Constructor<Launcher> constructor = klass.getDeclaredConstructor(String[].class);
constructor.setAccessible(true);
final Method launch = klass.getDeclaredMethod("launch");
launch.setAccessible(true);
launch.invoke(constructor.newInstance(new Object[] { args }));
} catch (Exception e) {
log.warn("Failed to setup rewriting classloader - some features may be unavailable", e);
new Launcher(args).launch();
}
}
System.exit(0);
}
private final CommandLine cli;
private final Path dataDir;
private Launcher(String args[]) {
// parse cli options
CommandLine _cli = null;
try {
_cli = new DefaultParser().parse(opts, args);
} catch (org.apache.commons.cli.ParseException e) {
System.err.println(e.getLocalizedMessage());
printHelp();
System.exit(1);
}
cli = _cli;
if (cli.hasOption('h')) {
printHelp();
System.exit(0);
}
log.info("Starting CCEmuX");
log.debug("ClassLoader in use: {}", this.getClass().getClassLoader().getClass().getName());
// set data dir
if (cli.hasOption('d')) {
dataDir = Paths.get(cli.getOptionValue('d'));
} else {
dataDir = OperatingSystem.get().getAppDataDir().resolve("ccemux");
}
log.info("Data directory is {}", dataDir.toString());
}
private void crashMessage(Throwable e) {
CrashReport report = new CrashReport(e);
log.error("Unexpected exception occurred!", e);
log.error("CCEmuX has crashed!");
if (!GraphicsEnvironment.isHeadless()) {
JTextArea textArea = new JTextArea(12, 60);
textArea.setEditable(false);
textArea.setText(report.toString());
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setMaximumSize(new Dimension(600, 400));
int result = JOptionPane.showConfirmDialog(null,
new Object[] { "CCEmuX has crashed!", scrollPane,
"Would you like to create a bug report on GitHub?" },
"CCEmuX Crash", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
try {
report.createIssue();
} catch (URISyntaxException | IOException e1) {
log.error("Failed to open GitHub to create issue", e1);
}
}
}
}
private void setSystemLAF() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
log.warn("Failed to set system look and feel", e);
}
}
private PluginManager loadPlugins(UserConfig cfg) throws ReflectiveOperationException {
File pd = dataDir.resolve("plugins").toFile();
if (pd.isFile())
pd.delete();
if (!pd.exists())
pd.mkdirs();
HashSet<URL> urls = new HashSet<>();
for (File f : pd.listFiles()) {
if (f.isFile()) {
log.debug("Adding plugin source '{}'", f.getName());
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException e) {
log.warn("Failed to add plugin source", e);
}
}
}
if (cli.hasOption("plugin")) {
for (String s : cli.getOptionValues("plugin")) {
File f = Paths.get(s).toFile();
log.debug("Adding external plugin source '{}'", f.getName());
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException e) {
log.warn("Failed to add plugin source '{}'", f.getName());
}
}
}
return new PluginManager(new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader()), cfg);
}
private File getCCSource() throws URISyntaxException {
URI source = Optional.ofNullable(ComputerCraft.class.getProtectionDomain().getCodeSource())
.orElseThrow(() -> new IllegalStateException("Cannot locate CC")).getLocation().toURI();
log.debug("CC is loaded from {}", source);
if (!source.getScheme().equals("file"))
throw new IllegalStateException("Incompatible CC location: " + source.toString());
return new File(source);
}
private void launch() {
try {
setSystemLAF();
Files.createDirectories(dataDir);
log.info("Loading user config");
UserConfig cfg = UserConfig.loadConfig(dataDir);
log.debug("Config: {}", cfg);
if (cfg.termScale.get() != cfg.termScale.get().intValue())
log.warn("Terminal scale is not an integer - stuff might look bad! Don't blame us!");
PluginManager pluginMgr = loadPlugins(cfg);
pluginMgr.loaderSetup(getClass().getClassLoader());
if (getClass().getClassLoader() instanceof CCEmuXClassloader) {
val loader = (CCEmuXClassloader) getClass().getClassLoader();
loader.chain.finalise();
log.warn("ClassLoader chain finalized");
loader.allowCC();
log.debug("CC access now allowed");
} else {
log.warn("Incompatible classloader type: {}", getClass().getClassLoader().getClass());
}
ComputerCraft.log = LogManager.getLogger(ComputerCraft.class);
pluginMgr.setup();
if (cli.hasOption('r') && cli.getOptionValue('r') == null) {
log.info("Available rendering methods:");
RendererFactory.implementations.keySet().stream().forEach(k -> log.info(" {}", k));
System.exit(0);
} else if (cli.hasOption('r')) {
// TODO: figure out this
}
if (!RendererFactory.implementations.containsKey(cfg.renderer.get())) {
log.error("Specified renderer '{}' does not exist - are you missing a plugin?", cfg.renderer.get());
if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessageDialog(null,
"Specified renderer '" + cfg.renderer.get() + "' does not exist.\n"
+ "Please double check your config file and plugin list.",
"Configuration Error", JOptionPane.ERROR_MESSAGE);
}
}
pluginMgr.onInitializationCompleted();
TerminalFont.loadImplicitFonts();
log.info("Setting up emulation environment");
if (!GraphicsEnvironment.isHeadless())
Optional.ofNullable(SplashScreen.getSplashScreen()).ifPresent(SplashScreen::close);
CCEmuX emu = new CCEmuX(cfg, pluginMgr, getCCSource());
emu.createComputer();
emu.run();
pluginMgr.onClosing(emu);
log.info("Emulation complete, goodbye!");
} catch (Throwable e) {
crashMessage(e);
}
}
} |
package yuku.alkitab;
import java.io.*;
import java.util.Scanner;
import yuku.bintex.BintexWriter;
public class KonvertEdisi {
public static void main(String[] args) throws Exception {
String pkgName = args[0];
String nama = args[1];
new KonvertEdisi().convert("../Alkitab/publikasi/edisi_index-" + pkgName + ".txt", "../Alkitab/publikasi/" + nama + "_raw/edisi_index_bt.bt");
}
int bolong = 0;
private void convert(String nfi, String nfo) throws Exception {
Scanner sc = new Scanner(new File(nfi));
BintexWriter out = new BintexWriter(new FileOutputStream(nfo));
while (sc.hasNext()) {
String s = sc.next();
if (s.equals("Edisi")) {
out.writeShortString(s);
} else if (s.equals("nama") || s.equals("pembaca") || s.equals("url")) {
out.writeShortString(s);
out.writeShortString(sc.next()); // sstring
} else if (s.equals("nkitab") || s.equals("perikopAda")) {
out.writeShortString(s);
out.writeInt(sc.nextInt()); // int
} else if (s.equals("judul")) {
out.writeShortString(s);
out.writeShortString(sc.next().replace('_', ' '));
} else if (s.equals("end")) {
out.writeShortString("end");
} else {
throw new RuntimeException("apaan nih? " + s);
}
}
out.close();
}
} |
package net.glowstone.chunk;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import net.glowstone.EventFactory;
import net.glowstone.GlowServer;
import net.glowstone.GlowWorld;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.ItemTable;
import net.glowstone.block.blocktype.BlockType;
import net.glowstone.block.entity.BlockEntity;
import net.glowstone.entity.GlowEntity;
import net.glowstone.net.message.play.game.BlockChangeMessage;
import net.glowstone.net.message.play.game.ChunkDataMessage;
import net.glowstone.util.TickUtil;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.Chunk;
import org.bukkit.Difficulty;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.entity.Entity;
import org.bukkit.event.world.ChunkUnloadEvent;
/**
* Represents a chunk of the map.
*
* @author Graham Edgecombe
*/
public class GlowChunk implements Chunk {
/**
* The width of a chunk (x axis).
*/
public static final int WIDTH = 16;
/**
* The height of a chunk (z axis).
*/
public static final int HEIGHT = 16;
/**
* The depth of a chunk (y axis).
*/
public static final int DEPTH = 256;
/**
* The Y depth of a single chunk section.
*/
public static final int SEC_DEPTH = 16;
/**
* The number of chunk sections in a single chunk column.
*/
public static final int SEC_COUNT = DEPTH / SEC_DEPTH;
/**
* The world of this chunk.
*/
@Getter
private final GlowWorld world;
/**
* The x-coordinate of this chunk.
*/
@Getter
private final int x;
/**
* The z-coordinate of this chunk.
*/
@Getter
private final int z;
/**
* The block entities that reside in this chunk.
*/
private final Int2ObjectOpenHashMap<BlockEntity> blockEntities = new Int2ObjectOpenHashMap<>(32, 0.5f);
/**
* The entities that reside in this chunk.
*/
private final Set<GlowEntity> entities = ConcurrentHashMap.newKeySet(4);
/**
* The array of chunk sections this chunk contains, or null if it is unloaded.
*
* @return The chunk sections array.
*/
@Getter
private ChunkSection[] sections;
/**
* The array of biomes this chunk contains, or null if it is unloaded.
*/
private byte[] biomes;
/**
* The height map values values of each column, or null if it is unloaded. The height for a
* column is one plus the y-index of the highest non-air block in the column.
*/
private byte[] heightMap;
/**
* Whether the chunk has been populated by special features. Used in map generation.
*
* @param populated Population status.
* @return Population status.
*/
@Getter
@Setter
private boolean populated;
@Setter
private int isSlimeChunk = -1;
@Getter
@Setter
private long inhabitedTime;
/**
* A list of BlockChangeMessages to be sent to all players in this chunk.
*/
private final List<BlockChangeMessage> blockChanges = new ArrayList<>();
/**
* Creates a new chunk with a specified X and Z coordinate.
*
* @param x The X coordinate.
* @param z The Z coordinate.
*/
GlowChunk(GlowWorld world, int x, int z) {
this.world = world;
this.x = x;
this.z = z;
}
@Override
public String toString() {
return "GlowChunk{world=" + world.getName() + ",x=" + x + ",z=" + z + '}';
}
@Override
public GlowBlock getBlock(int x, int y, int z) {
return new GlowBlock(this, this.x << 4 | x & 0xf, y & 0xff, this.z << 4 | z & 0xf);
}
@Override
public Entity[] getEntities() {
return entities.toArray(new Entity[entities.size()]);
}
public Collection<GlowEntity> getRawEntities() {
return entities;
}
@Override
@Deprecated
public GlowBlockState[] getTileEntities() {
return getBlockEntities();
}
/**
* Returns the states of the block entities (e.g. container blocks) in this chunk.
*
* @return the states of the block entities in this chunk
*/
public GlowBlockState[] getBlockEntities() {
List<GlowBlockState> states = new ArrayList<>(blockEntities.size());
for (BlockEntity blockEntity : blockEntities.values()) {
GlowBlockState state = blockEntity.getState();
if (state != null) {
states.add(state);
}
}
return states.toArray(new GlowBlockState[states.size()]);
}
public Collection<BlockEntity> getRawBlockEntities() {
return Collections.unmodifiableCollection(blockEntities.values());
}
@Override
public boolean isSlimeChunk() {
if (isSlimeChunk == -1) {
boolean isSlimeChunk = new Random(this.world.getSeed()
+ (long) (this.x * this.x * 0x4c1906)
+ (long) (this.x * 0x5ac0db)
+ (long) (this.z * this.z) * 0x4307a7L
+ (long) (this.z * 0x5f24f) ^ 0x3ad8025f).nextInt(10) == 0;
this.isSlimeChunk = (isSlimeChunk ? 1 : 0);
}
return this.isSlimeChunk == 1;
}
@Override
public GlowChunkSnapshot getChunkSnapshot() {
return getChunkSnapshot(true, false, false);
}
@Override
public GlowChunkSnapshot getChunkSnapshot(boolean includeMaxBlockY, boolean includeBiome,
boolean includeBiomeTempRain) {
return new GlowChunkSnapshot(x, z, world, sections,
includeMaxBlockY ? heightMap.clone() : null, includeBiome ? biomes.clone() : null,
includeBiomeTempRain, isSlimeChunk());
}
@Override
public boolean isLoaded() {
return sections != null;
}
@Override
public boolean load() {
return load(true);
}
@Override
public boolean load(boolean generate) {
return isLoaded() || world.getChunkManager().loadChunk(this, generate);
}
@Override
public boolean unload() {
return unload(true, true);
}
@Override
public boolean unload(boolean save) {
return unload(save, true);
}
@Override
public boolean unload(boolean save, boolean safe) {
if (!isLoaded()) {
return true;
}
if (safe && world.isChunkInUse(x, z)) {
return false;
}
if (save && !world.getChunkManager().performSave(this)) {
return false;
}
if (EventFactory.getInstance()
.callEvent(new ChunkUnloadEvent(this)).isCancelled()) {
return false;
}
sections = null;
biomes = null;
heightMap = null;
blockEntities.clear();
if (save) {
for (GlowEntity entity : entities) {
entity.remove();
}
entities.clear();
}
return true;
}
/**
* Initialize this chunk from the given sections.
*
* @param initSections The {@link ChunkSection}s to use. Should have a length of {@value
* #SEC_COUNT}.
*/
public void initializeSections(ChunkSection[] initSections) {
if (isLoaded()) {
GlowServer.logger.log(Level.SEVERE,
"Tried to initialize already loaded chunk (" + x + "," + z + ")",
new Throwable());
return;
}
if (initSections.length != SEC_COUNT) {
GlowServer.logger.log(Level.WARNING,
"Got an unexpected section length - wanted " + SEC_COUNT + ", but length was "
+ initSections.length,
new Throwable());
}
//GlowServer.logger.log(Level.INFO, "Initializing chunk ({0},{1})", new Object[]{x, z});
sections = new ChunkSection[SEC_COUNT];
biomes = new byte[WIDTH * HEIGHT];
heightMap = new byte[WIDTH * HEIGHT];
for (int y = 0; y < SEC_COUNT && y < initSections.length; y++) {
if (initSections[y] != null) {
initializeSection(y, initSections[y]);
}
}
}
private void initializeSection(int y, ChunkSection section) {
sections[y] = section;
}
/**
* If needed, create a new block entity at the given location.
*
* @param cx the X coordinate of the BlockEntity
* @param cy the Y coordinate of the BlockEntity
* @param cz the Z coordinate of the BlockEntity
* @param type the type of BlockEntity
* @return The BlockEntity that was created.
*/
public BlockEntity createEntity(int cx, int cy, int cz, int type) {
Material material = Material.getMaterial(type);
switch (material) {
case SIGN:
case SIGN_POST:
case WALL_SIGN:
case BED_BLOCK:
case CHEST:
case TRAPPED_CHEST:
case BURNING_FURNACE:
case FURNACE:
case DISPENSER:
case DROPPER:
case END_GATEWAY:
case HOPPER:
case MOB_SPAWNER:
case NOTE_BLOCK:
case JUKEBOX:
case BREWING_STAND:
case SKULL:
case COMMAND:
case COMMAND_CHAIN:
case COMMAND_REPEATING:
case BEACON:
case BANNER:
case WALL_BANNER:
case STANDING_BANNER:
case FLOWER_POT:
case STRUCTURE_BLOCK:
case WHITE_SHULKER_BOX:
case ORANGE_SHULKER_BOX:
case MAGENTA_SHULKER_BOX:
case LIGHT_BLUE_SHULKER_BOX:
case YELLOW_SHULKER_BOX:
case LIME_SHULKER_BOX:
case PINK_SHULKER_BOX:
case GRAY_SHULKER_BOX:
case SILVER_SHULKER_BOX:
case CYAN_SHULKER_BOX:
case PURPLE_SHULKER_BOX:
case BLUE_SHULKER_BOX:
case BROWN_SHULKER_BOX:
case GREEN_SHULKER_BOX:
case RED_SHULKER_BOX:
case BLACK_SHULKER_BOX:
case ENCHANTMENT_TABLE:
case ENDER_CHEST:
case DAYLIGHT_DETECTOR:
case DAYLIGHT_DETECTOR_INVERTED:
case REDSTONE_COMPARATOR_OFF:
case REDSTONE_COMPARATOR_ON:
BlockType blockType = ItemTable.instance().getBlock(material);
if (blockType == null) {
return null;
}
try {
BlockEntity entity = blockType.createBlockEntity(this, cx, cy, cz);
if (entity == null) {
return null;
}
blockEntities.put(coordinateToIndex(cx, cz, cy), entity);
return entity;
} catch (Exception ex) {
GlowServer.logger
.log(Level.SEVERE, "Unable to initialize block entity for " + type, ex);
return null;
}
default:
return null;
}
}
/**
* Attempt to get the ChunkSection at the specified height.
*
* @param y the y value.
* @return The ChunkSection, or null if it is empty.
*/
private ChunkSection getSection(int y) {
int idx = y >> 4;
if (y < 0 || y >= DEPTH || !load() || idx >= sections.length) {
return null;
}
return sections[idx];
}
/**
* Attempt to get the block entity located at the given coordinates.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return A GlowBlockState if the entity exists, or null otherwise.
*/
public BlockEntity getEntity(int x, int y, int z) {
if (y >= DEPTH || y < 0) {
return null;
}
load();
return blockEntities.get(coordinateToIndex(x, z, y));
}
/**
* Gets the type of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The type.
*/
public int getType(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : section.getType(x, y, z) >> 4;
}
/**
* Sets the type of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param type The type.
*/
public void setType(int x, int z, int y, int type) {
if (type < 0 || type > 0xfff) {
throw new IllegalArgumentException("Block type out of range: " + type);
}
ChunkSection section = getSection(y);
if (section == null) {
if (type == 0) {
// don't need to create chunk for air
return;
} else {
// create new ChunkSection for this y coordinate
int idx = y >> 4;
if (y < 0 || y >= DEPTH || idx >= sections.length) {
// y is out of range somehow
return;
}
sections[idx] = section = new ChunkSection();
}
}
// destroy any block entity there
int blockEntityIndex = coordinateToIndex(x, z, y);
if (blockEntities.containsKey(blockEntityIndex)) {
blockEntities.remove(blockEntityIndex).destroy();
}
// update the air count and height map
int heightIndex = z * WIDTH + x;
if (type == 0) {
if (heightMap[heightIndex] == y + 1) {
// erased just below old height map -> lower
heightMap[heightIndex] = (byte) lowerHeightMap(x, y, z);
}
} else {
if (heightMap[heightIndex] <= y) {
// placed between old height map and top -> raise
heightMap[heightIndex] = (byte) Math.min(y + 1, 255);
}
}
// update the type - also sets metadata to 0
section.setType(x, y, z, (char) (type << 4));
if (section.isEmpty()) {
// destroy the empty section
sections[y / SEC_DEPTH] = null;
return;
}
// create a new block entity if we need
createEntity(x, y, z, type);
}
/**
* Scan downwards to determine the new height map value.
*/
private int lowerHeightMap(int x, int y, int z) {
for (--y; y >= 0; --y) {
if (getType(x, z, y) != 0) {
break;
}
}
return y + 1;
}
/**
* Gets the metadata of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The metadata.
*/
public int getMetaData(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : section.getType(x, y, z) & 0xF;
}
/**
* Sets the metadata of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param metaData The metadata.
*/
public void setMetaData(int x, int z, int y, int metaData) {
if (metaData < 0 || metaData >= 16) {
throw new IllegalArgumentException("Metadata out of range: " + metaData);
}
ChunkSection section = getSection(y);
if (section == null) {
return; // can't set metadata on an empty section
}
int type = section.getType(x, y, z);
if (type == 0) {
return; // can't set metadata on air
}
section.setType(x, y, z, (char) (type & 0xfff0 | metaData));
}
/**
* Gets the sky light level of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The sky light level.
*/
public byte getSkyLight(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? ChunkSection.EMPTY_SKYLIGHT : section.getSkyLight(x, y, z);
}
/**
* Sets the sky light level of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param skyLight The sky light level.
*/
public void setSkyLight(int x, int z, int y, int skyLight) {
ChunkSection section = getSection(y);
if (section == null) {
return; // can't set light on an empty section
}
section.setSkyLight(x, y, z, (byte) skyLight);
}
/**
* Gets the block light level of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The block light level.
*/
public byte getBlockLight(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? ChunkSection.EMPTY_BLOCK_LIGHT : section.getBlockLight(x, y, z);
}
/**
* Sets the block light level of a block within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param blockLight The block light level.
*/
public void setBlockLight(int x, int z, int y, int blockLight) {
ChunkSection section = getSection(y);
if (section == null) {
return; // can't set light on an empty section
}
section.setBlockLight(x, y, z, (byte) blockLight);
}
/**
* Gets the biome of a column within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @return The biome.
*/
public int getBiome(int x, int z) {
if (biomes == null && !load()) {
return 0;
}
return biomes[z * WIDTH + x] & 0xFF;
}
/**
* Sets the biome of a column within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param biome The biome.
*/
public void setBiome(int x, int z, int biome) {
if (biomes == null) {
return;
}
biomes[z * WIDTH + x] = (byte) biome;
}
/**
* Set the entire biome array of this chunk.
*
* @param newBiomes The biome array.
*/
public void setBiomes(byte... newBiomes) {
if (biomes == null) {
throw new IllegalStateException("Must initialize chunk first");
}
if (newBiomes.length != biomes.length) {
throw new IllegalArgumentException("Biomes array not of length " + biomes.length);
}
System.arraycopy(newBiomes, 0, biomes, 0, biomes.length);
}
/**
* Get the height map value of a column within this chunk.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @return The height map value.
*/
public int getHeight(int x, int z) {
if (heightMap == null && !load()) {
return 0;
}
return heightMap[z * WIDTH + x] & 0xff;
}
public double getRegionalDifficulty() {
final double moonPhase = world.getMoonPhase();
final long worldTime = world.getFullTime();
final Difficulty worldDifficulty = world.getDifficulty();
double totalTimeFactor;
if (worldTime > (21 * TickUtil.TICKS_PER_HOUR)) {
totalTimeFactor = 0.25;
} else if (worldTime < TickUtil.TICKS_PER_HOUR) {
totalTimeFactor = 0;
} else {
totalTimeFactor = (worldTime - TickUtil.TICKS_PER_HOUR) / 5760000d;
}
double chunkFactor;
if (inhabitedTime > (50 * TickUtil.TICKS_PER_HOUR)) {
chunkFactor = 1;
} else {
chunkFactor = inhabitedTime / 3600000d;
}
if (worldDifficulty != Difficulty.HARD) {
chunkFactor *= 3d / 4d;
}
if (moonPhase / 4 > totalTimeFactor) {
chunkFactor += totalTimeFactor;
} else {
chunkFactor += moonPhase / 4;
}
if (worldDifficulty == Difficulty.EASY) {
chunkFactor /= 2;
}
double regionalDifficulty = 0.75 + totalTimeFactor + chunkFactor;
if (worldDifficulty == Difficulty.NORMAL) {
regionalDifficulty *= 2;
}
if (worldDifficulty == Difficulty.HARD) {
regionalDifficulty *= 3;
}
return regionalDifficulty;
}
public double getClampedRegionalDifficulty() {
final double rd = getRegionalDifficulty();
if (rd < 2.0) {
return 0;
} else if (rd > 4.0) {
return 1;
} else {
return (rd - 2) / 2;
}
}
/**
* Set the entire height map of this chunk.
*
* @param newHeightMap The height map.
*/
public void setHeightMap(int... newHeightMap) {
if (heightMap == null) {
throw new IllegalStateException("Must initialize chunk first");
}
if (newHeightMap.length != heightMap.length) {
throw new IllegalArgumentException("Height map not of length " + heightMap.length);
}
for (int i = 0; i < heightMap.length; ++i) {
heightMap[i] = (byte) newHeightMap[i];
}
}
/**
* Automatically fill the height map after chunks have been initialized.
*/
public void automaticHeightMap() {
// determine max Y chunk section at a time
int sy = sections.length - 1;
for (; sy >= 0; --sy) {
if (sections[sy] != null) {
break;
}
}
int y = (sy + 1) << 4;
for (int x = 0; x < WIDTH; ++x) {
for (int z = 0; z < HEIGHT; ++z) {
heightMap[z * WIDTH + x] = (byte) lowerHeightMap(x, y, z);
}
}
}
/**
* Converts a three-dimensional coordinate to an index within the one-dimensional arrays.
*
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The index within the arrays.
*/
private int coordinateToIndex(int x, int z, int y) {
if (x < 0 || z < 0 || y < 0 || x >= WIDTH || z >= HEIGHT || y >= DEPTH) {
throw new IndexOutOfBoundsException(
"Coords (x=" + x + ",y=" + y + ",z=" + z + ") invalid");
}
return (y * HEIGHT + z) * WIDTH + x;
}
/**
* Queues block change notification to all players in this chunk
*
* @param message The block change message to broadcast
*/
public void broadcastBlockChange(BlockChangeMessage message) {
blockChanges.add(message);
}
public List<BlockChangeMessage> getBlockChanges() {
return new ArrayList<>(blockChanges);
}
void clearBlockChanges() {
blockChanges.clear();
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream this entire
* chunk to them.
*
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage() {
// this may need to be changed to "true" depending on resolution of
// some inconsistencies on the wiki
return toMessage(world.getEnvironment() == Environment.NORMAL);
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream this entire
* chunk to them.
*
* @param skylight Whether to include skylight data.
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage(boolean skylight) {
return toMessage(skylight, true);
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream parts of this
* chunk to them.
*
* @param skylight Whether to include skylight data.
* @param entireChunk Whether to send all chunk sections.
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage(boolean skylight, boolean entireChunk) {
return toMessage(skylight, entireChunk, null);
}
public ChunkDataMessage toMessage(boolean skylight, boolean entireChunk, ByteBufAllocator alloc) {
load();
int sectionBitmask = 0;
// filter sectionBitmask based on actual chunk contents
if (sections != null) {
int maxBitmask = (1 << sections.length) - 1;
if (entireChunk) {
sectionBitmask = maxBitmask;
} else {
sectionBitmask &= maxBitmask;
}
for (int i = 0; i < sections.length; ++i) {
if (sections[i] == null || sections[i].isEmpty()) {
// remove empty sections from bitmask
sectionBitmask &= ~(1 << i);
}
}
}
ByteBuf buf = alloc == null ? Unpooled.buffer() : alloc.buffer();
if (sections != null) {
// get the list of sections
for (int i = 0; i < sections.length; ++i) {
if ((sectionBitmask & 1 << i) == 0) {
continue;
}
sections[i].writeToBuf(buf, skylight);
}
}
// biomes
if (entireChunk && biomes != null) {
buf.writeBytes(biomes);
}
Set<CompoundTag> blockEntities = new HashSet<>();
for (BlockEntity blockEntity : getRawBlockEntities()) {
CompoundTag tag = new CompoundTag();
blockEntity.saveNbt(tag);
blockEntities.add(tag);
}
return new ChunkDataMessage(x, z, entireChunk, sectionBitmask, buf, blockEntities);
}
public void addTick() {
inhabitedTime++;
}
/**
* A chunk key represents the X and Z coordinates of a chunk in a manner suitable for use as a
* key in a hash table or set.
*/
@Data
public static final class Key {
// Key cache storage
private static final Long2ObjectOpenHashMap<Key> keys
= new Long2ObjectOpenHashMap<>(512, 0.5F);
/**
* The x-coordinate.
*/
private final int x;
/**
* The z-coordinate.
*/
private final int z;
/**
* A pre-computed hash code based on the coordinates.
*/
private final int hashCode;
private Key(int x, int z) {
this.x = x;
this.z = z;
this.hashCode = x * 31 + z;
}
private static long mapCode(int x, int z) {
return (((long) x) << 32) | (z & 0xffffffffL);
}
public static Key of(int x, int z) {
long id = mapCode(x, z);
Key v;
if ((v = keys.get(id)) == null) {
v = new Key(x, z);
keys.put(id, v);
}
return v;
}
public static Key of(long id) {
Key v;
if ((v = keys.get(id)) == null) {
v = new Key((int) id, (int) (id >> 32));
keys.put(id, v);
}
return v;
}
public static Key to(Chunk chunk) {
return of(chunk.getX(), chunk.getZ());
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Key) {
Key otherKey = ((Key) obj);
return x == otherKey.x && z == otherKey.z;
}
return false;
}
}
} |
package net.sf.jabref.bst;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* The |built_in| function {\.{purify\$}} pops the top (string) literal, removes
* nonalphanumeric characters except for |white_space| and |sep_char| characters
* (these get converted to a |space|) and removes certain alphabetic characters
* contained in the control sequences associated with a special character, and
* pushes the resulting string. If the literal isn't a string, it complains and
* pushes the null string.
*
*/
public class BibtexWidth {
private static final Log LOGGER = LogFactory.getLog(BibtexWidth.class);
/*
* Quoted from Bibtex:
*
* Now we initialize the system-dependent |char_width| array, for which
* |space| is the only |white_space| character given a nonzero printing
* width. The widths here are taken from Stanford's June~'87 $cmr10$~font
* and represent hundredths of a point (rounded), but since they're used
* only for relative comparisons, the units have no meaning.
*/
private static int[] widths;
static {
if (BibtexWidth.widths == null) {
BibtexWidth.widths = new int[128];
for (int i = 0; i < 128; i++) {
BibtexWidth.widths[i] = 0;
}
BibtexWidth.widths[32] = 278;
BibtexWidth.widths[33] = 278;
BibtexWidth.widths[34] = 500;
BibtexWidth.widths[35] = 833;
BibtexWidth.widths[36] = 500;
BibtexWidth.widths[37] = 833;
BibtexWidth.widths[38] = 778;
BibtexWidth.widths[39] = 278;
BibtexWidth.widths[40] = 389;
BibtexWidth.widths[41] = 389;
BibtexWidth.widths[42] = 500;
BibtexWidth.widths[43] = 778;
BibtexWidth.widths[44] = 278;
BibtexWidth.widths[45] = 333;
BibtexWidth.widths[46] = 278;
BibtexWidth.widths[47] = 500;
BibtexWidth.widths[48] = 500;
BibtexWidth.widths[49] = 500;
BibtexWidth.widths[50] = 500;
BibtexWidth.widths[51] = 500;
BibtexWidth.widths[52] = 500;
BibtexWidth.widths[53] = 500;
BibtexWidth.widths[54] = 500;
BibtexWidth.widths[55] = 500;
BibtexWidth.widths[56] = 500;
BibtexWidth.widths[57] = 500;
BibtexWidth.widths[58] = 278;
BibtexWidth.widths[59] = 278;
BibtexWidth.widths[60] = 278;
BibtexWidth.widths[61] = 778;
BibtexWidth.widths[62] = 472;
BibtexWidth.widths[63] = 472;
BibtexWidth.widths[64] = 778;
BibtexWidth.widths[65] = 750;
BibtexWidth.widths[66] = 708;
BibtexWidth.widths[67] = 722;
BibtexWidth.widths[68] = 764;
BibtexWidth.widths[69] = 681;
BibtexWidth.widths[70] = 653;
BibtexWidth.widths[71] = 785;
BibtexWidth.widths[72] = 750;
BibtexWidth.widths[73] = 361;
BibtexWidth.widths[74] = 514;
BibtexWidth.widths[75] = 778;
BibtexWidth.widths[76] = 625;
BibtexWidth.widths[77] = 917;
BibtexWidth.widths[78] = 750;
BibtexWidth.widths[79] = 778;
BibtexWidth.widths[80] = 681;
BibtexWidth.widths[81] = 778;
BibtexWidth.widths[82] = 736;
BibtexWidth.widths[83] = 556;
BibtexWidth.widths[84] = 722;
BibtexWidth.widths[85] = 750;
BibtexWidth.widths[86] = 750;
BibtexWidth.widths[87] = 1028;
BibtexWidth.widths[88] = 750;
BibtexWidth.widths[89] = 750;
BibtexWidth.widths[90] = 611;
BibtexWidth.widths[91] = 278;
BibtexWidth.widths[92] = 500;
BibtexWidth.widths[93] = 278;
BibtexWidth.widths[94] = 500;
BibtexWidth.widths[95] = 278;
BibtexWidth.widths[96] = 278;
BibtexWidth.widths[97] = 500;
BibtexWidth.widths[98] = 556;
BibtexWidth.widths[99] = 444;
BibtexWidth.widths[100] = 556;
BibtexWidth.widths[101] = 444;
BibtexWidth.widths[102] = 306;
BibtexWidth.widths[103] = 500;
BibtexWidth.widths[104] = 556;
BibtexWidth.widths[105] = 278;
BibtexWidth.widths[106] = 306;
BibtexWidth.widths[107] = 528;
BibtexWidth.widths[108] = 278;
BibtexWidth.widths[109] = 833;
BibtexWidth.widths[110] = 556;
BibtexWidth.widths[111] = 500;
BibtexWidth.widths[112] = 556;
BibtexWidth.widths[113] = 528;
BibtexWidth.widths[114] = 392;
BibtexWidth.widths[115] = 394;
BibtexWidth.widths[116] = 389;
BibtexWidth.widths[117] = 556;
BibtexWidth.widths[118] = 528;
BibtexWidth.widths[119] = 722;
BibtexWidth.widths[120] = 528;
BibtexWidth.widths[121] = 528;
BibtexWidth.widths[122] = 444;
BibtexWidth.widths[123] = 500;
BibtexWidth.widths[124] = 1000;
BibtexWidth.widths[125] = 500;
BibtexWidth.widths[126] = 500;
}
}
private static int getSpecialCharWidth(char[] c, int pos) {
if ((pos + 1) < c.length) {
if ((c[pos] == 'o') && (c[pos + 1] == 'e')) {
return 778;
}
if ((c[pos] == 'O') && (c[pos + 1] == 'E')) {
return 1014;
}
if ((c[pos] == 'a') && (c[pos + 1] == 'e')) {
return 722;
}
if ((c[pos] == 'A') && (c[pos + 1] == 'E')) {
return 903;
}
if ((c[pos] == 's') && (c[pos + 1] == 's')) {
return 500;
}
}
return BibtexWidth.getCharWidth(c[pos]);
}
public static int getCharWidth(char c) {
if ((c >= 0) && (c < 128)) {
return BibtexWidth.widths[c];
} else {
return 0;
}
}
/**
*
* @param toMeasure
* @param warn
* may-be-null
* @return
*/
public static int width(String toMeasure) {
/*
* From Bibtex: We use the natural width for all but special characters,
* and we complain if the string isn't brace-balanced.
*/
int i = 0;
int n = toMeasure.length();
int braceLevel = 0;
char[] c = toMeasure.toCharArray();
int result = 0;
/*
* From Bibtex:
*
* We use the natural widths of all characters except that some
* characters have no width: braces, control sequences (except for the
* usual 13 accented and foreign characters, whose widths are given in
* the next module), and |white_space| following control sequences (even
* a null control sequence).
*
*/
while (i < n) {
if (c[i] == '{') {
braceLevel++;
if ((braceLevel == 1) && ((i + 1) < n) && (c[i + 1] == '\\')) {
i++; // skip brace
while ((i < n) && (braceLevel > 0)) {
i++; // skip backslash
int afterBackslash = i;
while ((i < n) && Character.isLetter(c[i])) {
i++;
}
if ((i < n) && (i == afterBackslash)) {
i++; // Skip non-alpha control seq
} else {
if (BibtexCaseChanger.findSpecialChar(c, afterBackslash) != null) {
result += BibtexWidth.getSpecialCharWidth(c, afterBackslash);
}
}
while ((i < n) && Character.isWhitespace(c[i])) {
i++;
}
while ((i < n) && (braceLevel > 0) && (c[i] != '\\')) {
if (c[i] == '}') {
braceLevel
} else if (c[i] == '{') {
braceLevel++;
} else {
result += BibtexWidth.getCharWidth(c[i]);
}
i++;
}
}
continue;
}
} else if (c[i] == '}') {
if (braceLevel > 0) {
braceLevel
} else {
LOGGER.warn("Too many closing braces in string: " + toMeasure);
}
}
result += BibtexWidth.getCharWidth(c[i]);
i++;
}
if (braceLevel > 0) {
LOGGER.warn("No enough closing braces in string: " + toMeasure);
}
return result;
}
} |
package anchormodeler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
@SuppressWarnings("serial")
public class AnchormodelerServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Anchormodeler server");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//resp.setContentType("text/html");
//This is needed in combination with doOptions to allow cross-site-scripting
resp.setHeader("Access-Control-Allow-Credentials", "true");
String s = req.getHeader("Origin");
if(s!=null)
resp.setHeader("Access-Control-Allow-Origin", s);
else
resp.setHeader("Access-Control-Allow-Origin", "*");
ServletFileUpload upload = new ServletFileUpload();
AnchorRequest areq = new AnchorRequest();
try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if(item.isFormField()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
String value = reader.readLine();
areq.stringParams.put(item.getFieldName(), value);
} else {
areq.fileParams.put(item.getFieldName(),item);
}
}
UserService userService = UserServiceFactory.getUserService();
if (req.getUserPrincipal()!=null) {
areq.user = userService.getCurrentUser();
} else {
//if a google account is required then return LOGIN:loginurl
String url = req.getHeader("Referer");
if(url==null)
url="null";
//String url = req.getRequestURI();
areq.requireLoginMessage="LOGIN: " + userService.createLoginURL(url); //req.getRequestURI());
}
String action = areq.stringParams.get("action");
action=(action == null) ? "" : action;
action=action.toLowerCase();
if (action.equals("save")) {
actionSave(areq, resp);
} else if (action.equals("load")) {
actionLoad(areq, resp);
} else if (action.equals("list")) {
actionList(areq, resp);
} else if (action.equals("status")) {
actionStatus(areq, resp);
} else {
resp.getWriter().println("ERROR: unknown action");
}
} catch (Exception e) {
resp.getWriter().println("ERROR: " + e.toString());
}
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// CORS requires that browsers do an OPTIONS request before allowing
// cross-site POSTs. UMP does not require this, but no browser
// implements
// UMP at this time. So, we reply to the OPTIONS request to trick
// browsers into effectively implementing UMP.
//super.doOptions(req, resp);
String s;
s = req.getHeader("Origin");
if(s!=null)
resp.setHeader("Access-Control-Allow-Origin", s);
else
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
s = req.getHeader("Access-Control-Request-Headers");
if(s!=null)
resp.setHeader("Access-Control-Allow-Headers", s);
else
resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Max-Age", "86400");
}
private void actionStatus(AnchorRequest areq, HttpServletResponse resp) throws IOException {
if(areq.user==null) {
resp.getWriter().println(areq.requireLoginMessage);
} else {
resp.getWriter().println("OK: You are logged in as " + areq.user.getEmail());
}
}
private void actionSave(AnchorRequest areq, HttpServletResponse resp) throws ServletException, IOException {
/*
* scope "public","private"
* modelName
* modelId (om nytt dokument s slopar man detta, annars overwrite model med detta id)
* keywords
* icon (textencoded png-image)
* modelXml
*
* returnerar ok/error
*/
if(areq.user==null) {
resp.getWriter().println(areq.requireLoginMessage);
return;
}
String modelName = areq.stringParams.get("modelName");
String modelXml = areq.stringParams.get("modelXml");
String icon = areq.stringParams.get("icon");
String keywords = areq.stringParams.get("keywords");
String scope = areq.stringParams.get("scope");
boolean isPublic = (scope!=null) && (scope.equalsIgnoreCase("public"));
String userId = areq.user.getUserId();
String modelId = areq.stringParams.get("modelId");
//TODO: keywords should be stored as a list in order to be queried?
PersistenceManager pm = PMF.get().getPersistenceManager();
Model m;
if(modelId!=null) {
m = (Model)pm.getObjectById(Model.class, KeyFactory.stringToKey(modelId));
if(m==null)
throw new ServletException("Tried to update nonexisting model with id: " + modelId);
if(!m.getUserId().equals(userId))
throw new ServletException("A public model can only be updated by the person who created it");
} else
m = new Model();
m.setModelName(modelName);
m.setModelXml(new Text(modelXml));
m.setIcon(new Text(icon));
m.setUserId(userId);
m.setKeywords(keywords);
m.setPublic( isPublic );
try {
pm.makePersistent(m);
} finally {
pm.close();
}
resp.getWriter().println("OK");
}
private void actionLoad(AnchorRequest areq, HttpServletResponse resp) throws IOException {
String modelId = areq.stringParams.get("modelId");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Key key = KeyFactory.stringToKey(modelId);
Model m = (Model)pm.getObjectById(Model.class, key);
resp.getWriter().println( m.getModelXml().getValue() );
} finally {
pm.close();
}
}
@SuppressWarnings("unchecked")
private void actionList(AnchorRequest areq, HttpServletResponse resp) throws Exception {
/*list
scope "public","private","public/private"
filterBy "keyword"
filterValue "lkslejg"
maxItemsReturned 20
returnerar i xmlformat
modelId, modelName, icon, domain, keyword, authorName
*/
//TODO: more parameters
String scope = areq.stringParams.get("scope");
boolean isPublic = (scope!=null) && (scope.contains("public"));
boolean isPrivate = (scope!=null) && (scope.contains("private"));
String filterBy = areq.stringParams.get("filterBy");
String filterValue = areq.stringParams.get("filterValue");
String filterString=null;
if( (filterBy!=null) && (filterValue!=null) ) {
filterString=filterBy + ".contains('" + filterValue + "')";
//filterString.contains("hello");
}
String maxItemsReturned = areq.stringParams.get("maxItemsReturned");
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query=null;
try {
query = pm.newQuery(Model.class);
int maxHits=20;
if(maxItemsReturned!=null) {
maxHits=Integer.parseInt(maxItemsReturned);
if(maxHits>100)
throw new ServletException("Max 100 hits allowed");
}
query.setRange(0, maxHits);
String s=null;
if(isPublic && isPrivate)
;
else if(isPublic)
s="isPublic == true";
else if(isPrivate)
s="isPublic == false";
if(s!=null) {
filterString = ((filterString==null) ? "" : filterString + " && ") + s;
}
if(filterString!=null)
query.setFilter(filterString);
List<Model> results = (List<Model>) query.execute();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
//creating a new instance of a DOM to build a DOM tree.
Document doc = docBuilder.newDocument();
Element root = doc.createElement("Models");
doc.appendChild(root);
for (Model m : results) {
Element child = doc.createElement("Model");
child.setAttribute("modelName", m.getModelName());
child.setAttribute("modelId", KeyFactory.keyToString(m.getKey()) );
child.setAttribute("icon", m.getIcon().getValue() );
child.setAttribute("keywords", m.getKeywords() );
child.setAttribute("scope", m.isPublic() ? "public" : "private" );
root.appendChild(child);
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = sw.toString();
resp.getWriter().println(xmlString);
} finally {
if(query!=null)
query.closeAll();
pm.close();
}
}
} |
package com.yahoo.vespa.hosted.provision.maintenance;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.node.History;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* This moves expired failed nodes:
*
* - To parked: If the node has known hardware failure, hosts are moved to parked only when all of their
* children are already in parked.
* - To dirty: If the node is a host and has failed less than 5 times, or always if the node is a child.
* - Otherwise the node will remain in failed.
*
* Failed content nodes are given a long expiry time to enable us to manually moved them back to
* active to recover data in cases where the node was failed accidentally.
*
* Failed containers (Vespa, not Linux) are expired early as there's no data to potentially recover.
*
* The purpose of the automatic recycling to dirty + fail count is that nodes which were moved
* to failed due to some undetected hardware failure will end up being failed again.
* When that has happened enough they will not be recycled, and need manual inspection to move on.
*
* Nodes with detected hardware issues will not be recycled.
*
* @author bratseth
* @author mpolden
*/
public class FailedExpirer extends NodeRepositoryMaintainer {
private static final Logger log = Logger.getLogger(FailedExpirer.class.getName());
private final NodeRepository nodeRepository;
private final Duration statefulExpiry; // Stateful nodes: Grace period to allow recovery of data
private final Duration statelessExpiry; // Stateless nodes: No data to recover
FailedExpirer(NodeRepository nodeRepository, Zone zone, Duration interval, Metric metric) {
super(nodeRepository, interval, metric);
this.nodeRepository = nodeRepository;
if (zone.system().isCd()) {
statefulExpiry = statelessExpiry = Duration.ofMinutes(30);
} else {
if (zone.environment() == Environment.staging || zone.environment() == Environment.test) {
statefulExpiry = Duration.ofHours(1);
} else {
statefulExpiry = Duration.ofDays(4);
}
statelessExpiry = Duration.ofHours(1);
}
}
@Override
protected double maintain() {
List<Node> remainingNodes = new ArrayList<>(nodeRepository.nodes().list(Node.State.failed)
.nodeType(NodeType.tenant, NodeType.host)
.asList());
recycleIf(remainingNodes, node -> node.allocation().isEmpty());
recycleIf(remainingNodes, node ->
!node.allocation().get().membership().cluster().isStateful() &&
node.history().hasEventBefore(History.Event.Type.failed, clock().instant().minus(statelessExpiry)));
recycleIf(remainingNodes, node ->
node.allocation().get().membership().cluster().isStateful() &&
node.history().hasEventBefore(History.Event.Type.failed, clock().instant().minus(statefulExpiry)));
return 1.0;
}
/** Recycle the nodes matching condition, and remove those nodes from the nodes list. */
private void recycleIf(List<Node> nodes, Predicate<Node> recycleCondition) {
List<Node> nodesToRecycle = nodes.stream().filter(recycleCondition).collect(Collectors.toList());
nodes.removeAll(nodesToRecycle);
recycle(nodesToRecycle);
}
/** Move eligible nodes to dirty. This may be a subset of the given nodes */
private void recycle(List<Node> nodes) {
List<Node> nodesToRecycle = new ArrayList<>();
for (Node candidate : nodes) {
if (NodeFailer.hasHardwareIssue(candidate, nodeRepository)) {
List<String> unparkedChildren = !candidate.type().isHost() ? List.of() :
nodeRepository.nodes().list()
.childrenOf(candidate)
.not().state(Node.State.parked)
.mapToList(Node::hostname);
if (unparkedChildren.isEmpty()) {
nodeRepository.nodes().park(candidate.hostname(), false, Agent.FailedExpirer,
"Parked by FailedExpirer due to hardware issue");
} else {
log.info(String.format("Expired failed node %s with hardware issue was not parked because of " +
"unparked children: %s", candidate.hostname(),
String.join(", ", unparkedChildren)));
}
} else {
nodesToRecycle.add(candidate);
}
}
nodeRepository.nodes().deallocate(nodesToRecycle, Agent.FailedExpirer, "Expired by FailedExpirer");
}
} |
package ninja;
import com.google.common.base.Charsets;
import com.google.common.io.BaseEncoding;
import io.netty.handler.codec.http.HttpHeaders;
import sirius.kernel.commons.Strings;
import sirius.kernel.di.std.Part;
import sirius.kernel.di.std.Register;
import sirius.web.http.WebContext;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static sirius.kernel.commons.Strings.join;
/**
* Hash calculator for legacy AWS signature calculation
*/
@Register(classes = AwsLegacyHashCalculator.class)
public class AwsLegacyHashCalculator {
@Part
private Storage storage;
private static final List<String> SIGNED_PARAMETERS = Arrays.asList("acl",
"torrent",
"logging",
"location",
"policy",
"requestPayment",
"versioning",
"versions",
"versionId",
"notification",
"uploadId",
"uploads",
"partNumber",
"website",
"delete",
"lifecycle",
"tagging",
"cors",
"restore");
/**
* Computes the authentication hash as specified by the AWS SDK for verification purposes.
*
* @param ctx the current request to fetch parameters from
* @param pathPrefix the path prefix to append to the current uri
* @return the computes hash value
* @throws Exception in case of an unexpected error
*/
public String computeHash(WebContext ctx, String pathPrefix) throws Exception {
StringBuilder stringToSign = new StringBuilder(ctx.getRequest().getMethod().name());
stringToSign.append("\n");
stringToSign.append(ctx.getHeaderValue("Content-MD5").asString(""));
stringToSign.append("\n");
stringToSign.append(ctx.getHeaderValue("Content-Type").asString(""));
stringToSign.append("\n");
stringToSign.append(ctx.get("Expires")
.asString(ctx.getHeaderValue("x-amz-date")
.asString(ctx.getHeaderValue("Date").asString(""))));
stringToSign.append("\n");
HttpHeaders requestHeaders = ctx.getRequest().headers();
List<String> headers = requestHeaders.names()
.stream()
.filter(this::relevantAmazonHeader)
.map(name -> toHeaderStringRepresentation(name, requestHeaders))
.sorted()
.collect(Collectors.toList());
for (String header : headers) {
stringToSign.append(header);
stringToSign.append("\n");
}
stringToSign.append(pathPrefix).append(ctx.getRequestedURI().substring(3));
char separator = '?';
for (String parameterName : ctx.getParameterNames().stream().sorted().collect(Collectors.toList())) {
// Skip parameters that aren't part of the canonical signed string
if (!SIGNED_PARAMETERS.contains(parameterName)) continue;
stringToSign.append(separator).append(parameterName);
String parameterValue = ctx.get(parameterName).asString();
if (Strings.isFilled(parameterValue)) {
stringToSign.append("=").append(parameterValue);
}
separator = '&';
}
SecretKeySpec keySpec = new SecretKeySpec(storage.getAwsSecretKey().getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
byte[] result = mac.doFinal(stringToSign.toString().getBytes(Charsets.UTF_8.name()));
return BaseEncoding.base64().encode(result);
}
private boolean relevantAmazonHeader(final String name) {
return name.toLowerCase().startsWith("x-amz-") && !"x-amz-date".equals(name.toLowerCase());
}
private String toHeaderStringRepresentation(final String headerName, final HttpHeaders requestHeaders) {
return headerName.toLowerCase().trim() + ":" +
join(requestHeaders.getAll(headerName), ",").trim();
}
} |
package nl.tudelft.jpacman.board;
import nl.tudelft.jpacman.sprite.Sprite;
/**
* A unit that can be placed on a {@link Square}.
*
* @author Jeroen Roosen
*/
public abstract class Unit {
/**
* The square this unit is currently occupying.
*/
private Square square;
/**
* The direction this unit is facing.
*/
private Direction direction;
/**
* Creates a unit that is facing east.
*/
protected Unit() {
this.direction = Direction.EAST;
}
/**
* Sets this unit to face the new direction.
* @param newDirection The new direction this unit is facing.
*/
public void setDirection(Direction newDirection) {
this.direction = newDirection;
}
/**
* Returns the current direction this unit is facing.
* @return The current direction this unit is facing.
*/
public Direction getDirection() {
return this.direction;
}
/**
* Returns the square this unit is currently occupying.
* Precondition: <code>hasSquare()</code>.
*
* @return The square this unit is currently occupying.
*/
public Square getSquare() {
assert invariant();
assert square != null;
return square;
}
/**
* Returns whether this unit is currently on a square.
*
* @return True iff the unit is occupying a square at the moment.
*/
public boolean hasSquare() {
return square != null;
}
/**
* Occupies the target square iff this unit is allowed to as decided by
* {@link Square#isAccessibleTo(Unit)}.
*
* @param target
* The square to occupy.
*/
public void occupy(Square target) {
assert target != null;
if (square != null) {
square.remove(this);
}
square = target;
target.put(this);
assert invariant();
}
/**
* Leaves the currently occupying square, thus removing this unit from the board.
*/
public void leaveSquare() {
if (square != null) {
square.remove(this);
square = null;
}
assert invariant();
}
/**
* Tests whether the square this unit is occupying has this unit listed as
* one of its occupiers.
*
* @return <code>true</code> if the square this unit is occupying has this
* unit listed as one of its occupiers, or if this unit is currently
* not occupying any square.
*/
protected boolean invariant() {
return square == null || square.getOccupants().contains(this);
}
/**
* Returns the sprite of this unit.
*
* @return The sprite of this unit.
*/
public abstract Sprite getSprite();
/**
* A utility method for implementing the ghost AI.
*
* @param amountToLookAhead the amount of squares to follow this units direction in.
* @return The square amountToLookAhead spaces in front of this unit.
*/
public Square squaresAheadOf(int amountToLookAhead) {
Direction targetDirection = this.getDirection();
Square destination = this.getSquare();
for (int i = 0; i < amountToLookAhead; i++) {
destination = destination.getSquareAt(targetDirection);
}
return destination;
}
} |
package nuclibook.server;
import org.apache.commons.lang.StringEscapeUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HtmlRenderer {
// location of template HTML file
private String templateFile;
// data to be threaded into HTML
private HashMap<String, String> fields;
private HashMap<String, Collection<Renderable>> collections;
/**
* PATTERNS
*/
private static int regexOptions = Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE;
private static Pattern filePattern = Pattern.compile("##([a-z0-9\\-\\._]+)", regexOptions);
private static Pattern definitionPattern = Pattern.compile("#\\[def: ([a-z0-9\\-]+) = (.*?)\\]", regexOptions);
private static Pattern conditionalSetFieldPattern = Pattern.compile("#\\[(if|!if): ([a-z0-9\\-]+)\\](.*?)#\\[/(if|!if)\\]", regexOptions);
private static Pattern conditionalValueFieldPattern = Pattern.compile("#\\[(if|!if): ([a-z0-9\\-]+)=([a-z0-9\\-]+)\\](.*?)#\\[/(if|!if)\\]", regexOptions);
private static Pattern fieldPattern = Pattern.compile("#([a-z0-9\\-]+)", regexOptions);
private static Pattern collectionPattern = Pattern.compile("#\\[collection: ([a-z0-9\\-]+)\\](.*?)#\\[/collection\\]", regexOptions);
/**
* CONSTRUCTOR
*/
public HtmlRenderer(String templateFile) {
this.templateFile = templateFile;
fields = new HashMap<>();
collections = new HashMap<>();
}
/**
* DATA SETTERS
*/
// set a data field (set null to "remove")
public void setField(String key, String value) {
fields.put(key, value);
}
// set a data collection (set null to "remove")
public void setCollection(String key, Collection<Renderable> collection) {
collections.put(key, collection);
}
// set all fields in one go (replaces any existing fields)
protected void setBulkFields(HashMap<String, String> fields) {
this.fields = fields;
}
// set all collections in one go (replaces any existing collections)
protected void setBulkCollections(HashMap<String, Collection<Renderable>> collections) {
this.collections = collections;
}
/**
* DEFINITION PARSING
*/
// parse any defined fields
private String parseDefinitions(String html) {
Matcher definitionMatcher = definitionPattern.matcher(html);
StringBuffer output = new StringBuffer();
while (definitionMatcher.find()) {
definitionMatcher.appendReplacement(output, "");
fields.put(definitionMatcher.group(1), definitionMatcher.group(2));
}
definitionMatcher.appendTail(output);
return output.toString();
}
/**
* FILE PARSING
*/
// include referenced files
private String parseFiles(String html) {
Matcher fileMatcher = filePattern.matcher(html);
StringBuffer output = new StringBuffer();
while (fileMatcher.find()) {
fileMatcher.appendReplacement(output, getFile(fileMatcher.group(1)));
}
fileMatcher.appendTail(output);
return output.toString();
}
// get a referenced file
private String getFile(String path) {
HtmlRenderer renderer = new HtmlRenderer(path);
renderer.setBulkFields(fields);
renderer.setBulkCollections(collections);
return renderer.render();
}
/**
* COLLECTION PARSING
*/
// parse any collection statements
private String parseCollections(String html) {
Matcher collectionMatcher = collectionPattern.matcher(html);
StringBuffer output = new StringBuffer();
while (collectionMatcher.find()) {
collectionMatcher.appendReplacement(output, getCollectionHtml(collectionMatcher.group(1), collectionMatcher.group(2)));
}
collectionMatcher.appendTail(output);
return output.toString();
}
// return the HTML for an iterated collection
private String getCollectionHtml(String key, String original) {
// get collection iteration "chunks"
String pre = getSegment(original, "pre");
String post = getSegment(original, "post");
String empty = getSegment(original, "empty");
String each = getSegment(original, "each");
// no collection?
if (!collections.containsKey(key) || collections.get(key) == null || collections.get(key).isEmpty()) {
return empty;
}
// get collection
Collection collection = collections.get(key);
// start output
StringBuilder sb = new StringBuilder();
sb.append(pre);
// add to output for each element in the collection
Iterator iterator = collection.iterator();
Renderable entry;
String entryHtml;
int i = 0;
while (iterator.hasNext()) {
// get entry and handle fields
entry = (Renderable) iterator.next();
entryHtml = parseConditionalSetFields(each, entry.getHashMap());
entryHtml = parseFields(entryHtml, entry.getHashMap());
// insert index and guid
entryHtml = basicReplace(entryHtml, "_index", "" + i);
entryHtml = basicReplace(entryHtml, "_guid", UUID.randomUUID().toString());
sb.append(entryHtml);
++i;
}
// finish output
sb.append(post);
return sb.toString();
}
/**
* CONDITIONAL SET FIELD PARSING
*/
// parse any conditional set field statements, defaulting to the global fields
private String parseConditionalSetFields(String html) {
return parseConditionalSetFields(html, fields);
}
// parse any conditional set field statements with a specific set of fields
private String parseConditionalSetFields(String html, HashMap<String, String> fields) {
// "positive" conditionals
Matcher fieldMatcher = conditionalSetFieldPattern.matcher(html);
StringBuffer output = new StringBuffer();
while (fieldMatcher.find()) {
fieldMatcher.appendReplacement(output, getConditionalSetFieldValue(fieldMatcher.group(1), fieldMatcher.group(2), fieldMatcher.group(3), fields));
}
fieldMatcher.appendTail(output);
// done
return output.toString();
}
// return the original text, or "", for a conditional set field statement
private String getConditionalSetFieldValue(String ifField, String key, String original, HashMap<String, String> fields) {
return ifField.startsWith("!") ?
((!fields.containsKey(key) || fields.get(key) == null) ? original : ""):
((fields.containsKey(key) && fields.get(key) != null) ? original : "");
}
/**
* CONDITIONAL VALUE FIELD CHECKING
*/
// parse any conditional value field statements, defaulting to the global fields
private String parseConditionalValueFields(String html) {
return parseConditionalValueFields(html, fields);
}
// parse any conditional value field statements with a specific set of fields
private String parseConditionalValueFields(String html, HashMap<String, String> fields) {
// "positive" conditionals
Matcher matcher = conditionalValueFieldPattern.matcher(html);
StringBuffer output = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(output, getConditionalValueFieldValue(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), fields));
}
matcher.appendTail(output);
// done
return output.toString();
}
// return the original text, or "", for a conditional value field statement
private String getConditionalValueFieldValue(String ifField, String key, String value, String original, HashMap<String, String> fields) {
return ifField.startsWith("!") ?
((!fields.containsKey(key) || fields.get(key) == null || !fields.get(key).equals(value)) ? original : ""):
((fields.containsKey(key) && fields.get(key) != null && fields.get(key).equals(value)) ? original : "");
}
/**
* SIMPLE FIELD PARSING
*/
// parse any field statements, defaulting to the global fields
private String parseFields(String html) {
return parseFields(html, fields);
}
// parse any conditional field statements with a specific set of fields
private String parseFields(String html, HashMap<String, String> fields) {
Matcher fieldMatcher = fieldPattern.matcher(html);
StringBuffer output = new StringBuffer();
while (fieldMatcher.find()) {
fieldMatcher.appendReplacement(output, getFieldValue(fieldMatcher.group(1), fields));
}
fieldMatcher.appendTail(output);
return output.toString();
}
// return the value, or "", for a given field key
private String getFieldValue(String key, HashMap<String, String> fields) {
return (fields.containsKey(key) && fields.get(key) != null) ? StringEscapeUtils.escapeHtml(fields.get(key)) : "";
}
/**
* HELPER METHODS
*/
// read the plain template in as a string
private String readSimpleFile() {
// load file
try {
URL url = getClass().getClassLoader().getResource("static/" + templateFile);
if (url == null) throw new NullPointerException();
File file = new File(url.getFile());
// read HTML
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
} catch (IOException | NullPointerException e) {
return "<html>" +
"<head>" +
"</head>" +
"<body>" +
"Failed to load template: <em>" + templateFile + "</em>" +
"</body>" +
"</html>";
}
}
// get an HTML segment between basic #[tag] and #[/tag] wrappers
private String getSegment(String html, String tag) {
Pattern segmentPattern = Pattern.compile("#\\[" + tag + "\\](.*?)#\\[/" + tag + "\\]", regexOptions);
Matcher segmentMatcher = segmentPattern.matcher(html);
if (segmentMatcher.find()) {
return segmentMatcher.group(1);
} else {
return "";
}
}
// replace a given keyword with a given value
private String basicReplace(String html, String tag, String value) {
Pattern basicReplacePattern = Pattern.compile("#" + tag, regexOptions);
Matcher basicReplaceMatcher = basicReplacePattern.matcher(html);
StringBuffer output = new StringBuffer();
while (basicReplaceMatcher.find()) {
basicReplaceMatcher.appendReplacement(output, value);
}
basicReplaceMatcher.appendTail(output);
return output.toString();
}
/**
* RENDERER
*/
// run the parsing methods in the right order
public String render() {
String parsedHtml = readSimpleFile();
parsedHtml = parseDefinitions(parsedHtml);
parsedHtml = parseFiles(parsedHtml);
parsedHtml = parseCollections(parsedHtml);
parsedHtml = parseConditionalSetFields(parsedHtml);
parsedHtml = parseConditionalValueFields(parsedHtml);
parsedHtml = parseFields(parsedHtml);
return parsedHtml;
}
} |
package org.ethereum.manager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.ethereum.core.Block;
import org.ethereum.core.Genesis;
import org.ethereum.core.Transaction;
import org.ethereum.core.Wallet;
import org.ethereum.crypto.HashUtil;
import org.ethereum.net.client.ClientPeer;
import org.ethereum.net.client.PeerData;
import org.ethereum.net.message.StaticMessages;
import org.spongycastle.util.encoders.Hex;
public class MainData {
private List<PeerData> peers = Collections.synchronizedList(new ArrayList<PeerData>());
private List<Block> blockChainDB = new ArrayList<Block>();
private Wallet wallet = new Wallet();
private ClientPeer activePeer;
public static MainData instance = new MainData();
public MainData() {
wallet.importKey(HashUtil.sha3("cow".getBytes()));
wallet.importKey(HashUtil.sha3("cat".getBytes()));
}
public void addPeers(List<PeerData> newPeers){
for (PeerData peer : newPeers){
if (this.peers.indexOf(peer) == -1){
this.peers.add(peer);
}
}
// for (PeerData peerData : this.peers){
// Location location = IpGeoDB.getLocationForIp(peerData.getInetAddress());
// if (location != null)
// System.out.println("Hello: " + " [" + peerData.getInetAddress().toString()
// + "] " + location.countryName);
}
public void addBlocks(List<Block> blocks) {
// TODO: redesign this part when the state part and the genesis block is ready
if (blocks.isEmpty()) return;
Block firstBlockToAdd = blocks.get(blocks.size() - 1);
// if it is the first block to add
// check that the parent is the genesis
if (blockChainDB.isEmpty() &&
!Arrays.equals(StaticMessages.GENESIS_HASH, firstBlockToAdd.getParentHash())){
return;
}
// if there is some blocks already
// keep chain continuity
if (!blockChainDB.isEmpty() ){
Block lastBlock = blockChainDB.get(blockChainDB.size() - 1);
String hashLast = Hex.toHexString(lastBlock.getHash());
String blockParentHash = Hex.toHexString(firstBlockToAdd.getParentHash());
if (!hashLast.equals(blockParentHash)) return;
}
for (int i = blocks.size() - 1; i >= 0 ; --i){
Block block = blocks.get(i);
blockChainDB.add(block);
wallet.processBlock(block);
}
System.out.println("*** Block chain size: [" + blockChainDB.size() + "]");
}
public byte[] getLatestBlockHash(){
if (blockChainDB.isEmpty())
return (new Genesis()).getHash();
else
return blockChainDB.get(blockChainDB.size() - 1).getHash();
}
public List<Block> getAllBlocks(){
return blockChainDB;
}
public Wallet getWallet() {
return wallet;
}
public void setActivePeer(ClientPeer peer){
this.activePeer = peer;
}
public ClientPeer getActivePeer() {
return activePeer;
}
public void addTransactions(List<Transaction> transactions) {}
public List<PeerData> getPeers() {
return peers;
}
} |
package org.javacs;
import com.google.gson.*;
import com.sun.source.tree.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.function.Predicate;
import java.util.logging.Logger;
import javax.lang.model.element.*;
import javax.tools.JavaFileObject;
import org.javacs.lsp.*;
class JavaLanguageServer extends LanguageServer {
// TODO allow multiple workspace roots
private Path workspaceRoot;
private final LanguageClient client;
private JavaCompilerService cacheCompiler;
private JsonObject cacheSettings;
private JsonObject settings = new JsonObject();
JavaCompilerService compiler() {
if (!settings.equals(cacheSettings)) {
LOG.info("Recreating compiler because\n\t" + settings + "\nis different than\n\t" + cacheSettings);
cacheCompiler = createCompiler();
cacheSettings = settings;
}
return cacheCompiler;
}
private final Map<Path, CachedLint> lintCache = new HashMap<>();
// TODO consider putting edits into some kind of queue instead of linting synchronously
// TODO measure the benefit of limiting linting; is it worth the added complexity?
void lint(Collection<Path> files) {
LOG.info("Lint " + files.size() + " files...");
var started = Instant.now();
var sources = pruneLint(files);
if (sources.isEmpty()) {
LOG.info("...nothing has changed, skipping lint");
return;
}
// Compile mixed list
try (var batch = compiler().compileBatch(sources)) {
var compiled = Instant.now();
var elapsed = Duration.between(started, compiled).toMillis();
LOG.info(String.format("...compiled in %d ms", elapsed));
// Update cache and publish
var errors = batch.reportErrors();
var colors = batch.colors();
for (var source : sources) {
var cached = lintCache.get(source.path);
var span = cached.edited();
cached.update(span, errors.get(source.path), colors.get(source.path));
client.publishDiagnostics(cached.lspDiagnostics());
client.customNotification("java/colors", GSON.toJsonTree(cached.lspColors()));
}
// Done
uncheckedChanges = false;
}
// Log timing
var done = Instant.now();
var elapsed = Duration.between(started, done).toMillis();
LOG.info(String.format("...linted in %d ms", elapsed));
}
private List<SourceFileObject> pruneLint(Collection<Path> files) {
// Update cache
lintCache.keySet().retainAll(files);
for (var file : files) {
if (!lintCache.containsKey(file)) {
lintCache.put(file, new CachedLint(file));
}
}
// Construct todo list, using fast lint when possible
var sources = new ArrayList<SourceFileObject>();
for (var file : files) {
var cached = lintCache.get(file);
var span = cached.edited();
if (span == Span.INVALID) {
// OPTIMIZATION: If the signature is unchanged, linting the entire file is sufficient
LOG.info(String.format("...edits escape method in %s", file.getFileName()));
return lintAll(files);
} else if (span == Span.EMPTY) {
LOG.info(String.format("...skip linting %s", file.getFileName()));
} else {
LOG.info(String.format("...re-lint %s %d-%d", file.getFileName(), span.start, span.until));
var contents = cached.pruneNewContents(span);
var source = new SourceFileObject(file, contents, Instant.now());
sources.add(source);
}
}
return sources;
}
private List<SourceFileObject> lintAll(Collection<Path> files) {
var sources = new ArrayList<SourceFileObject>();
for (var file : files) {
sources.add(new SourceFileObject(file));
}
return sources;
}
static final Gson GSON = new GsonBuilder().registerTypeAdapter(Ptr.class, new PtrAdapter()).create();
private void javaStartProgress(JavaStartProgressParams params) {
client.customNotification("java/startProgress", GSON.toJsonTree(params));
}
private void javaReportProgress(JavaReportProgressParams params) {
client.customNotification("java/reportProgress", GSON.toJsonTree(params));
}
private void javaEndProgress() {
client.customNotification("java/endProgress", JsonNull.INSTANCE);
}
private JavaCompilerService createCompiler() {
Objects.requireNonNull(workspaceRoot, "Can't create compiler because workspaceRoot has not been initialized");
javaStartProgress(new JavaStartProgressParams("Configure javac"));
javaReportProgress(new JavaReportProgressParams("Finding source roots"));
var externalDependencies = externalDependencies();
var classPath = classPath();
var addExports = addExports();
// If classpath is specified by the user, don't infer anything
if (!classPath.isEmpty()) {
javaEndProgress();
return new JavaCompilerService(classPath, Collections.emptySet(), addExports);
}
// Otherwise, combine inference with user-specified external dependencies
else {
var infer = new InferConfig(workspaceRoot, externalDependencies);
javaReportProgress(new JavaReportProgressParams("Inferring class path"));
classPath = infer.classPath();
javaReportProgress(new JavaReportProgressParams("Inferring doc path"));
var docPath = infer.buildDocPath();
javaEndProgress();
return new JavaCompilerService(classPath, docPath, addExports);
}
}
private Set<String> externalDependencies() {
if (!settings.has("externalDependencies")) return Set.of();
var array = settings.getAsJsonArray("externalDependencies");
var strings = new HashSet<String>();
for (var each : array) {
strings.add(each.getAsString());
}
return strings;
}
private Set<Path> classPath() {
if (!settings.has("classPath")) return Set.of();
var array = settings.getAsJsonArray("classPath");
var paths = new HashSet<Path>();
for (var each : array) {
paths.add(Paths.get(each.getAsString()).toAbsolutePath());
}
return paths;
}
private Set<String> addExports() {
if (!settings.has("addExports")) return Set.of();
var array = settings.getAsJsonArray("addExports");
var strings = new HashSet<String>();
for (var each : array) {
strings.add(each.getAsString());
}
return strings;
}
@Override
public InitializeResult initialize(InitializeParams params) {
this.workspaceRoot = Paths.get(params.rootUri);
FileStore.setWorkspaceRoots(Set.of(Paths.get(params.rootUri)));
var c = new JsonObject();
c.addProperty("textDocumentSync", 2); // Incremental
c.addProperty("hoverProvider", true);
var completionOptions = new JsonObject();
completionOptions.addProperty("resolveProvider", true);
var triggerCharacters = new JsonArray();
triggerCharacters.add(".");
completionOptions.add("triggerCharacters", triggerCharacters);
c.add("completionProvider", completionOptions);
var signatureHelpOptions = new JsonObject();
var signatureTrigger = new JsonArray();
signatureTrigger.add("(");
signatureTrigger.add(",");
signatureHelpOptions.add("triggerCharacters", signatureTrigger);
c.add("signatureHelpProvider", signatureHelpOptions);
c.addProperty("referencesProvider", true);
c.addProperty("definitionProvider", true);
c.addProperty("workspaceSymbolProvider", true);
c.addProperty("documentSymbolProvider", true);
c.addProperty("documentFormattingProvider", true);
var codeLensOptions = new JsonObject();
c.add("codeLensProvider", codeLensOptions);
c.addProperty("foldingRangeProvider", true);
return new InitializeResult(c);
}
@Override
public void initialized() {
// Register for didChangeWatchedFiles notifications
var options = new JsonObject();
var watchers = new JsonArray();
var watchJava = new JsonObject();
watchJava.addProperty("globPattern", "**/*.java");
watchers.add(watchJava);
options.add("watchers", watchers);
client.registerCapability("workspace/didChangeWatchedFiles", GSON.toJsonTree(options));
}
@Override
public void shutdown() {}
public JavaLanguageServer(LanguageClient client) {
this.client = client;
}
@Override
public List<SymbolInformation> workspaceSymbols(WorkspaceSymbolParams params) {
return compiler().findSymbols(params.query, 50);
}
@Override
public void didChangeConfiguration(DidChangeConfigurationParams change) {
var java = change.settings.getAsJsonObject().get("java");
LOG.info("Received java settings " + java);
settings = java.getAsJsonObject();
}
@Override
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
// TODO update config when pom.xml changes
for (var c : params.changes) {
if (!FileStore.isJavaFile(c.uri)) continue;
var file = Paths.get(c.uri);
switch (c.type) {
case FileChangeType.Created:
FileStore.externalCreate(file);
break;
case FileChangeType.Changed:
FileStore.externalChange(file);
break;
case FileChangeType.Deleted:
FileStore.externalDelete(file);
break;
}
}
}
static int isMemberSelect(String contents, int cursor) {
// Start at char before cursor
cursor
// Move back until we find a non-identifier char
while (cursor > 0 && Character.isJavaIdentifierPart(contents.charAt(cursor))) {
cursor
}
if (cursor <= 0 || contents.charAt(cursor) != '.') {
return -1;
}
// Move cursor back until we find a non-whitespace char
while (cursor > 0 && Character.isWhitespace(contents.charAt(cursor - 1))) {
cursor
}
return cursor;
}
static int isMemberReference(String contents, int cursor) {
// Start at char before cursor
cursor
// Move back until we find a non-identifier char
while (cursor > 1 && Character.isJavaIdentifierPart(contents.charAt(cursor))) {
cursor
}
if (!contents.startsWith("::", cursor - 1)) {
return -1;
}
// Skip first : in ::
cursor
// Move cursor back until we find a non-whitespace char
while (cursor > 0 && Character.isWhitespace(contents.charAt(cursor - 1))) {
cursor
}
return cursor;
}
private static boolean isQualifiedIdentifierPart(char c) {
return Character.isJavaIdentifierPart(c) || c == '.';
}
static int isPartialAnnotation(String contents, int cursor) {
// Start at char before cursor
cursor
// Move back until we find a non-identifier char
while (cursor > 0 && isQualifiedIdentifierPart(contents.charAt(cursor))) {
cursor
}
if (cursor >= 0 && contents.charAt(cursor) == '@') {
return cursor;
} else {
return -1;
}
}
static boolean isPartialCase(String contents, int cursor) {
// Start at char before cursor
cursor
// Move back until we find a non-identifier char
while (cursor > 0 && Character.isJavaIdentifierPart(contents.charAt(cursor))) {
cursor
}
// Skip space
while (cursor > 0 && Character.isWhitespace(contents.charAt(cursor))) {
cursor
}
return contents.startsWith("case", cursor - 3);
}
static String partialName(String contents, int cursor) {
// Start at char before cursor
var start = cursor - 1;
// Move back until we find a non-identifier char
while (start >= 0 && Character.isJavaIdentifierPart(contents.charAt(start))) {
start
}
return contents.substring(start + 1, cursor);
}
private static String restOfLine(String contents, int cursor) {
var endOfLine = contents.indexOf('\n', cursor);
if (endOfLine == -1) {
return contents.substring(cursor);
}
return contents.substring(cursor, endOfLine);
}
private static boolean hasParen(String contents, int cursor) {
return cursor < contents.length() && contents.charAt(cursor) == '(';
}
private static String eraseRegion(String contents, long start, long end) {
var buffer = new StringBuffer(contents);
for (int i = (int) start; i < end; i++) {
switch (buffer.charAt(i)) {
case '\r':
case '\n':
break;
default:
buffer.setCharAt(i, ' ');
}
}
return buffer.toString();
}
@Override
public Optional<CompletionList> completion(TextDocumentPositionParams position) {
var started = Instant.now();
var uri = position.textDocument.uri;
if (!FileStore.isJavaFile(uri)) return Optional.empty();
var file = Paths.get(uri);
var line = position.position.line + 1;
var column = position.position.character + 1;
LOG.info(String.format("Complete at %s(%d,%d)...", file, line, column));
// Figure out what kind of completion we want to do
var contents = FileStore.contents(file);
var cursor = FileStore.offset(contents, line, column);
var addParens = !hasParen(contents, cursor);
var addSemi = restOfLine(contents, cursor).matches("\\s*");
// Complete object. or object.partial
var dot = isMemberSelect(contents, cursor);
if (dot != -1) {
LOG.info("...complete members");
// Erase .partial
// contents = eraseRegion(contents, dot, cursor);
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.prune(dot);
try (var compile = compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
var list = compile.completeMembers(file, dot, addParens, addSemi);
logCompletionTiming(started, list, false);
return Optional.of(new CompletionList(false, list));
}
}
// Complete object:: or object::partial
var ref = isMemberReference(contents, cursor);
if (ref != -1) {
LOG.info("...complete references");
// Erase ::partial
// contents = eraseRegion(contents, ref, cursor);
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.prune(ref);
try (var compile = compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
var list = compile.completeReferences(file, ref);
logCompletionTiming(started, list, false);
return Optional.of(new CompletionList(false, list));
}
}
// Complete @Partial
var at = isPartialAnnotation(contents, cursor);
if (at != -1) {
LOG.info("...complete annotations");
var partialName = contents.substring(at + 1, cursor);
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.prune(cursor);
try (var compile = compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
var list = compile.completeAnnotations(file, cursor, partialName);
var isIncomplete = list.size() >= CompileBatch.MAX_COMPLETION_ITEMS;
logCompletionTiming(started, list, isIncomplete);
return Optional.of(new CompletionList(isIncomplete, list));
}
}
// Complete case partial
if (isPartialCase(contents, cursor)) {
LOG.info("...complete members");
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.eraseCase(cursor);
parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.prune(cursor);
try (var compile = compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
var list = compile.completeCases(file, cursor);
logCompletionTiming(started, list, false);
return Optional.of(new CompletionList(false, list));
}
}
// Complete partial
var looksLikeIdentifier = Character.isJavaIdentifierPart(contents.charAt(cursor - 1));
if (looksLikeIdentifier) {
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
if (parse.isIdentifier(cursor)) {
LOG.info("...complete identifiers");
contents = parse.prune(cursor);
parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
var path = parse.findPath(cursor);
try (var compile =
compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
var list =
compile.completeIdentifiers(
file,
cursor,
Parser.inClass(path),
Parser.inMethod(path),
partialName(contents, cursor),
addParens,
addSemi);
var isIncomplete = list.size() >= CompileBatch.MAX_COMPLETION_ITEMS;
logCompletionTiming(started, list, isIncomplete);
return Optional.of(new CompletionList(isIncomplete, list));
}
}
}
LOG.info("...complete keywords");
var items = new ArrayList<CompletionItem>();
for (var name : CompileBatch.TOP_LEVEL_KEYWORDS) {
var i = new CompletionItem();
i.label = name;
i.kind = CompletionItemKind.Keyword;
i.detail = "keyword";
items.add(i);
}
return Optional.of(new CompletionList(true, items));
}
private void logCompletionTiming(Instant started, List<?> list, boolean isIncomplete) {
var elapsedMs = Duration.between(started, Instant.now()).toMillis();
if (isIncomplete) LOG.info(String.format("Found %d items (incomplete) in %,d ms", list.size(), elapsedMs));
else LOG.info(String.format("...found %d items in %,d ms", list.size(), elapsedMs));
}
private Optional<MarkupContent> findDocs(Ptr ptr) {
LOG.info(String.format("Find docs for `%s`...", ptr));
// Find el in the doc path
var file = compiler().docs().find(ptr);
if (!file.isPresent()) return Optional.empty();
// Parse file and find el
var parse = Parser.parseJavaFileObject(file.get());
var path = parse.fuzzyFind(ptr);
if (!path.isPresent()) return Optional.empty();
// Parse the doctree associated with el
var docTree = parse.doc(path.get());
var string = Parser.asMarkupContent(docTree);
return Optional.of(string);
}
private Optional<String> findMethodDetails(Ptr ptr) {
LOG.info(String.format("Find details for method `%s`...", ptr));
// TODO find and parse happens twice
// Find method in the doc path
var file = compiler().docs().find(ptr);
if (!file.isPresent()) return Optional.empty();
// Parse file and find method
var parse = Parser.parseJavaFileObject(file.get());
var path = parse.fuzzyFind(ptr);
if (!path.isPresent()) return Optional.empty();
// Should be a MethodTree
var tree = path.get().getLeaf();
if (!(tree instanceof MethodTree)) {
LOG.warning(String.format("...method `%s` associated with non-method tree `%s`", ptr, tree));
return Optional.empty();
}
// Write description of method using info from source
var methodTree = (MethodTree) tree;
var args = new StringJoiner(", ");
for (var p : methodTree.getParameters()) {
args.add(p.getType() + " " + p.getName());
}
var details = String.format("%s %s(%s)", methodTree.getReturnType(), methodTree.getName(), args);
return Optional.of(details);
}
@Override
public CompletionItem resolveCompletionItem(CompletionItem unresolved) {
if (unresolved.data == null) return unresolved;
var data = GSON.fromJson(unresolved.data, CompletionData.class);
var markdown = findDocs(data.ptr);
if (markdown.isPresent()) {
unresolved.documentation = markdown.get();
}
if (data.ptr.isMethod()) {
var details = findMethodDetails(data.ptr);
if (details.isPresent()) {
unresolved.detail = details.get();
if (data.plusOverloads != 0) {
unresolved.detail += " (+" + data.plusOverloads + " overloads)";
}
}
}
return unresolved;
}
private String hoverTypeDeclaration(TypeElement t) {
var result = new StringBuilder();
switch (t.getKind()) {
case ANNOTATION_TYPE:
result.append("@interface");
break;
case INTERFACE:
result.append("interface");
break;
case CLASS:
result.append("class");
break;
case ENUM:
result.append("enum");
break;
default:
LOG.warning("Don't know what to call type element " + t);
result.append("???");
}
result.append(" ").append(ShortTypePrinter.DEFAULT.print(t.asType()));
var superType = ShortTypePrinter.DEFAULT.print(t.getSuperclass());
switch (superType) {
case "Object":
case "none":
break;
default:
result.append(" extends ").append(superType);
}
return result.toString();
}
private String hoverCode(Element e) {
if (e instanceof ExecutableElement) {
var m = (ExecutableElement) e;
return ShortTypePrinter.DEFAULT.printMethod(m);
} else if (e instanceof VariableElement) {
var v = (VariableElement) e;
return ShortTypePrinter.DEFAULT.print(v.asType()) + " " + v;
} else if (e instanceof TypeElement) {
var t = (TypeElement) e;
var lines = new StringJoiner("\n");
lines.add(hoverTypeDeclaration(t) + " {");
for (var member : t.getEnclosedElements()) {
// TODO check accessibility
if (member instanceof ExecutableElement || member instanceof VariableElement) {
lines.add(" " + hoverCode(member) + ";");
} else if (member instanceof TypeElement) {
lines.add(" " + hoverTypeDeclaration((TypeElement) member) + " { /* removed */ }");
}
}
lines.add("}");
return lines.toString();
} else {
return e.toString();
}
}
private Optional<String> hoverDocs(Element e) {
var ptr = new Ptr(e);
var file = compiler().docs().find(ptr);
if (!file.isPresent()) return Optional.empty();
var parse = Parser.parseJavaFileObject(file.get());
var path = parse.fuzzyFind(ptr);
if (!path.isPresent()) return Optional.empty();
var doc = parse.doc(path.get());
var md = Parser.asMarkdown(doc);
return Optional.of(md);
}
@Override
public Optional<Hover> hover(TextDocumentPositionParams position) {
var uri = position.textDocument.uri;
var line = position.position.line + 1;
var column = position.position.character + 1;
if (!FileStore.isJavaFile(uri)) return Optional.empty();
var file = Paths.get(uri);
// Log start time
LOG.info(String.format("Hover over %s(%d,%d) ...", uri.getPath(), line, column));
var started = Instant.now();
// Compile entire file
var sources = Set.of(new SourceFileObject(file));
try (var compile = compiler().compileBatch(sources)) {
// Find element under cursor
var el = compile.element(file, line, column);
if (!el.isPresent()) {
LOG.info("...no element under cursor");
return Optional.empty();
}
// Result is combination of docs and code
var result = new ArrayList<MarkedString>();
// Add docs hover message
var docs = hoverDocs(el.get());
docs.filter(Predicate.not(String::isBlank))
.ifPresent(
doc -> {
result.add(new MarkedString(doc));
});
// Add code hover message
var code = hoverCode(el.get());
result.add(new MarkedString("java.hover", code));
// Log duration
var elapsed = Duration.between(started, Instant.now());
LOG.info(String.format("...found hover in %d ms", elapsed.toMillis()));
return Optional.of(new Hover(result));
}
}
@Override
public Optional<SignatureHelp> signatureHelp(TextDocumentPositionParams position) {
var uri = position.textDocument.uri;
if (!FileStore.isJavaFile(uri)) return Optional.empty();
var file = Paths.get(uri);
var line = position.position.line + 1;
var column = position.position.character + 1;
LOG.info(String.format("Find signature at at %s(%d,%d)...", file, line, column));
var contents = FileStore.contents(file);
var cursor = FileStore.offset(contents, line, column);
var parse = Parser.parseJavaFileObject(new SourceFileObject(file, contents, Instant.now()));
contents = parse.prune(cursor);
try (var compile = compiler().compileBatch(List.of(new SourceFileObject(file, contents, Instant.now())))) {
return compile.signatureHelp(file, cursor);
}
}
@Override
public Optional<List<Location>> gotoDefinition(TextDocumentPositionParams position) {
var fromUri = position.textDocument.uri;
if (!FileStore.isJavaFile(fromUri)) return Optional.empty();
var fromFile = Paths.get(fromUri);
var fromLine = position.position.line + 1;
var fromColumn = position.position.character + 1;
// Compile from-file and identify element under cursor
LOG.info(String.format("Go-to-def at %s:%d...", fromUri, fromLine));
Optional<Element> toEl;
var sources = Set.of(new SourceFileObject(fromFile));
try (var compile = compiler().compileBatch(sources)) {
toEl = compile.element(fromFile, fromLine, fromColumn);
if (!toEl.isPresent()) {
LOG.info(String.format("...no element at cursor"));
return Optional.empty();
}
}
// Compile all files that *might* contain definitions of fromEl
var toFiles = Parser.potentialDefinitions(toEl.get());
toFiles.add(fromFile);
var eraseCode = pruneWord(toFiles, Parser.simpleName(toEl.get()));
try (var batch = compiler().compileBatch(eraseCode)) {
// Find fromEl again, so that we have an Element from the current batch
var fromElAgain = batch.element(fromFile, fromLine, fromColumn).get();
// Find all definitions of fromElAgain
var toTreePaths = batch.definitions(fromElAgain);
if (!toTreePaths.isPresent()) return Optional.empty();
var result = new ArrayList<Location>();
for (var path : toTreePaths.get()) {
var toUri = path.getCompilationUnit().getSourceFile().toUri();
var toRange = batch.range(path);
if (!toRange.isPresent()) {
LOG.warning(String.format("Couldn't locate `%s`", path.getLeaf()));
continue;
}
var from = new Location(toUri, toRange.get());
result.add(from);
}
return Optional.of(result);
}
}
@Override
public Optional<List<Location>> findReferences(ReferenceParams position) {
var toUri = position.textDocument.uri;
if (!FileStore.isJavaFile(toUri)) return Optional.empty();
var toFile = Paths.get(toUri);
var toLine = position.position.line + 1;
var toColumn = position.position.character + 1;
// TODO use parser to figure out batch to compile, avoiding compiling twice
// Compile from-file and identify element under cursor
LOG.warning(String.format("Looking for references to %s(%d,%d)...", toUri.getPath(), toLine, toColumn));
Optional<Element> toEl;
var sources = Set.of(new SourceFileObject(toFile));
try (var compile = compiler().compileBatch(sources)) {
toEl = compile.element(toFile, toLine, toColumn);
if (!toEl.isPresent()) {
LOG.warning("...no element under cursor");
return Optional.empty();
}
}
// Compile all files that *might* contain references to toEl
var name = Parser.simpleName(toEl.get());
var fromFiles = new HashSet<Path>();
var isLocal =
toEl.get() instanceof VariableElement && !(toEl.get().getEnclosingElement() instanceof TypeElement);
if (!isLocal) {
var isType = false;
switch (toEl.get().getKind()) {
case ANNOTATION_TYPE:
case CLASS:
case INTERFACE:
isType = true;
}
var flags = toEl.get().getModifiers();
var possible = Parser.potentialReferences(toFile, name, isType, flags);
fromFiles.addAll(possible);
}
fromFiles.add(toFile);
var eraseCode = pruneWord(fromFiles, name);
try (var batch = compiler().compileBatch(eraseCode)) {
var fromTreePaths = batch.references(toFile, toLine, toColumn);
LOG.info(String.format("...found %d references", fromTreePaths.map(List::size).orElse(0)));
if (!fromTreePaths.isPresent()) return Optional.empty();
var result = new ArrayList<Location>();
for (var path : fromTreePaths.get()) {
var fromUri = path.getCompilationUnit().getSourceFile().toUri();
var fromRange = batch.range(path);
if (!fromRange.isPresent()) {
LOG.warning(String.format("...couldn't locate `%s`", path.getLeaf()));
continue;
}
var from = new Location(fromUri, fromRange.get());
result.add(from);
}
return Optional.of(result);
}
}
private List<JavaFileObject> pruneWord(Collection<Path> files, String name) {
LOG.info(String.format("...prune code that doesn't contain `%s`", name));
var sources = new ArrayList<JavaFileObject>();
for (var f : files) {
var pruned = Parser.parseFile(f).prune(name);
sources.add(new SourceFileObject(f, pruned, Instant.EPOCH));
}
return sources;
}
private Parser cacheParse;
private Path cacheParseFile = Paths.get("/NONE");
private int cacheParseVersion = -1;
private void updateCachedParse(Path file) {
if (file.equals(cacheParseFile) && FileStore.version(file) == cacheParseVersion) return;
cacheParse = Parser.parseFile(file);
cacheParseFile = file;
cacheParseVersion = FileStore.version(file);
}
@Override
public List<SymbolInformation> documentSymbol(DocumentSymbolParams params) {
var uri = params.textDocument.uri;
if (!FileStore.isJavaFile(uri)) return List.of();
var file = Paths.get(uri);
updateCachedParse(file);
var infos = cacheParse.documentSymbols();
return infos;
}
@Override
public List<CodeLens> codeLens(CodeLensParams params) {
var uri = params.textDocument.uri;
if (!FileStore.isJavaFile(uri)) return List.of();
var file = Paths.get(uri);
updateCachedParse(file);
var declarations = cacheParse.codeLensDeclarations();
var result = new ArrayList<CodeLens>();
for (var d : declarations) {
var range = cacheParse.range(d);
if (!range.isPresent()) continue;
var className = Parser.className(d);
var memberName = Parser.memberName(d);
// If test class or method, add "Run Test" code lens
if (cacheParse.isTestClass(d)) {
var arguments = new JsonArray();
arguments.add(uri.toString());
arguments.add(className);
arguments.add(JsonNull.INSTANCE);
var command = new Command("Run All Tests", "java.command.test.run", arguments);
var lens = new CodeLens(range.get(), command, null);
result.add(lens);
// TODO run all tests in file
// TODO run all tests in package
}
if (cacheParse.isTestMethod(d)) {
var arguments = new JsonArray();
arguments.add(uri.toString());
arguments.add(className);
if (!memberName.isEmpty()) arguments.add(memberName);
else arguments.add(JsonNull.INSTANCE);
// 'Run Test' code lens
var command = new Command("Run Test", "java.command.test.run", arguments);
var lens = new CodeLens(range.get(), command, null);
result.add(lens);
// 'Debug Test' code lens
// TODO this could be a CPU hot spot
var sourceRoots = new JsonArray();
for (var path : FileStore.sourceRoots()) {
sourceRoots.add(path.toString());
}
arguments.add(sourceRoots);
command = new Command("Debug Test", "java.command.test.debug", arguments);
lens = new CodeLens(range.get(), command, null);
result.add(lens);
}
}
return result;
}
@Override
public CodeLens resolveCodeLens(CodeLens unresolved) {
return null;
}
@Override
public List<TextEdit> formatting(DocumentFormattingParams params) {
var file = Paths.get(params.textDocument.uri);
var sources = Set.of(new SourceFileObject(file));
try (var compile = compiler().compileBatch(sources)) {
var edits = new ArrayList<TextEdit>();
edits.addAll(fixImports(compile, file));
edits.addAll(addOverrides(compile, file));
// TODO replace var with type name when vars are copy-pasted into fields
// TODO replace ThisClass.staticMethod() with staticMethod() when ThisClass is useless
return edits;
}
}
private List<TextEdit> fixImports(CompileBatch compile, Path file) {
// TODO if imports already match fixed-imports, return empty list
// TODO preserve comments and other details of existing imports
var imports = compile.fixImports(file);
var pos = compile.sourcePositions();
var lines = compile.lineMap(file);
var edits = new ArrayList<TextEdit>();
// Delete all existing imports
for (var i : compile.imports(file)) {
if (!i.isStatic()) {
var offset = pos.getStartPosition(compile.root(file), i);
var line = (int) lines.getLineNumber(offset) - 1;
var delete = new TextEdit(new Range(new Position(line, 0), new Position(line + 1, 0)), "");
edits.add(delete);
}
}
if (imports.isEmpty()) return edits;
// Find a place to insert the new imports
long insertLine = -1;
var insertText = new StringBuilder();
// If there are imports, use the start of the first import as the insert position
for (var i : compile.imports(file)) {
if (!i.isStatic() && insertLine == -1) {
long offset = pos.getStartPosition(compile.root(file), i);
insertLine = lines.getLineNumber(offset) - 1;
}
}
// If there are no imports, insert after the package declaration
if (insertLine == -1 && compile.root(file).getPackageName() != null) {
long offset = pos.getEndPosition(compile.root(file), compile.root(file).getPackageName());
insertLine = lines.getLineNumber(offset);
insertText.append("\n");
}
// If there are no imports and no package, insert at the top of the file
if (insertLine == -1) {
insertLine = 0;
}
// Insert each import
for (var i : imports) {
insertText.append("import ").append(i).append(";\n");
}
var insertPosition = new Position((int) insertLine, 0);
var insert = new TextEdit(new Range(insertPosition, insertPosition), insertText.toString());
edits.add(insert);
return edits;
}
private List<TextEdit> addOverrides(CompileBatch compile, Path file) {
var edits = new ArrayList<TextEdit>();
var methods = compile.needsOverrideAnnotation(file);
var pos = compile.sourcePositions();
var lines = compile.lineMap(file);
for (var t : methods) {
var methodStart = pos.getStartPosition(t.getCompilationUnit(), t.getLeaf());
var insertLine = lines.getLineNumber(methodStart);
var indent = methodStart - lines.getPosition(insertLine, 0);
var insertText = new StringBuilder();
for (var i = 0; i < indent; i++) insertText.append(' ');
insertText.append("@Override");
insertText.append('\n');
var insertPosition = new Position((int) insertLine - 1, 0);
var insert = new TextEdit(new Range(insertPosition, insertPosition), insertText.toString());
edits.add(insert);
}
return edits;
}
@Override
public List<FoldingRange> foldingRange(FoldingRangeParams params) {
if (!FileStore.isJavaFile(params.textDocument.uri)) return List.of();
var file = Paths.get(params.textDocument.uri);
updateCachedParse(file);
return cacheParse.foldingRanges();
}
@Override
public Optional<RenameResponse> prepareRename(TextDocumentPositionParams params) {
throw new RuntimeException("TODO");
}
@Override
public WorkspaceEdit rename(RenameParams params) {
throw new RuntimeException("TODO");
}
@Override
public void didOpenTextDocument(DidOpenTextDocumentParams params) {
FileStore.open(params);
if (!FileStore.isJavaFile(params.textDocument.uri)) return;
// So that subsequent documentSymbol and codeLens requests will be faster
var file = Paths.get(params.textDocument.uri);
updateCachedParse(file);
uncheckedChanges = true;
}
@Override
public void didChangeTextDocument(DidChangeTextDocumentParams params) {
FileStore.change(params);
uncheckedChanges = true;
}
@Override
public void didCloseTextDocument(DidCloseTextDocumentParams params) {
FileStore.close(params);
if (FileStore.isJavaFile(params.textDocument.uri)) {
// Clear diagnostics
client.publishDiagnostics(new PublishDiagnosticsParams(params.textDocument.uri, List.of()));
}
}
@Override
public void didSaveTextDocument(DidSaveTextDocumentParams params) {
if (FileStore.isJavaFile(params.textDocument.uri)) {
// Re-lint all active documents
lint(FileStore.activeDocuments());
}
}
private boolean uncheckedChanges = false;
@Override
public void doAsyncWork() {
if (uncheckedChanges) {
// Re-lint all active documents
lint(FileStore.activeDocuments());
}
}
private static final Logger LOG = Logger.getLogger("main");
}
class CompletionData {
public Ptr ptr;
public int plusOverloads;
} |
package org.javacs;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeScanner;
import io.typefox.lsapi.services.*;
import io.typefox.lsapi.*;
import io.typefox.lsapi.impl.*;
import javax.tools.*;
import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import static org.javacs.Main.JSON;
class JavaLanguageServer implements LanguageServer {
private static final Logger LOG = Logger.getLogger("main");
private Path workspaceRoot;
private Consumer<PublishDiagnosticsParams> publishDiagnostics = p -> {};
private Consumer<MessageParams> showMessage = m -> {};
private Map<Path, String> sourceByPath = new HashMap<>();
public JavaLanguageServer() {
this.testJavac = Optional.empty();
}
public JavaLanguageServer(JavacHolder testJavac) {
this.testJavac = Optional.of(testJavac);
}
public void onError(String message, Throwable error) {
if (error instanceof ShowMessageException)
showMessage.accept(((ShowMessageException) error).message);
else if (error instanceof NoJavaConfigException) {
// Swallow error
// If you want to show a message for no-java-config,
// you have to specifically catch the error lower down and re-throw it
LOG.warning(error.getMessage());
}
else {
LOG.log(Level.SEVERE, message, error);
MessageParamsImpl m = new MessageParamsImpl();
m.setMessage(message);
m.setType(MessageType.Error);
showMessage.accept(m);
}
}
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
workspaceRoot = Paths.get(params.getRootPath()).toAbsolutePath().normalize();
InitializeResultImpl result = new InitializeResultImpl();
ServerCapabilitiesImpl c = new ServerCapabilitiesImpl();
c.setTextDocumentSync(TextDocumentSyncKind.Incremental);
c.setDefinitionProvider(true);
c.setCompletionProvider(new CompletionOptionsImpl());
c.setHoverProvider(true);
c.setWorkspaceSymbolProvider(true);
c.setReferencesProvider(true);
c.setDocumentSymbolProvider(true);
result.setCapabilities(c);
return CompletableFuture.completedFuture(result);
}
@Override
public void shutdown() {
}
@Override
public void exit() {
}
@Override
public void onTelemetryEvent(Consumer<Object> consumer) {
// Nothing to do
}
@Override
public TextDocumentService getTextDocumentService() {
return new TextDocumentService() {
@Override
public CompletableFuture<CompletionList> completion(TextDocumentPositionParams position) {
return CompletableFuture.completedFuture(autocomplete(position));
}
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
return null;
}
@Override
public CompletableFuture<Hover> hover(TextDocumentPositionParams position) {
return CompletableFuture.completedFuture(doHover(position));
}
@Override
public CompletableFuture<SignatureHelp> signatureHelp(TextDocumentPositionParams position) {
return null;
}
@Override
public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams position) {
return CompletableFuture.completedFuture(gotoDefinition(position));
}
@Override
public CompletableFuture<List<? extends Location>> references(ReferenceParams params) {
return CompletableFuture.completedFuture(findReferences(params));
}
@Override
public CompletableFuture<DocumentHighlight> documentHighlight(TextDocumentPositionParams position) {
return null;
}
@Override
public CompletableFuture<List<? extends SymbolInformation>> documentSymbol(DocumentSymbolParams params) {
return CompletableFuture.completedFuture(findDocumentSymbols(params));
}
@Override
public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) {
return null;
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
return null;
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
return null;
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
return null;
}
@Override
public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) {
return null;
}
@Override
public CompletableFuture<List<? extends TextEdit>> onTypeFormatting(DocumentOnTypeFormattingParams params) {
return null;
}
@Override
public CompletableFuture<WorkspaceEdit> rename(RenameParams params) {
return null;
}
@Override
public void didOpen(DidOpenTextDocumentParams params) {
try {
TextDocumentItem document = params.getTextDocument();
URI uri = URI.create(document.getUri());
Optional<Path> path = getFilePath(uri);
if (path.isPresent()) {
String text = document.getText();
sourceByPath.put(path.get(), text);
doLint(path.get());
}
} catch (NoJavaConfigException e) {
throw ShowMessageException.warning(e.getMessage(), e);
}
}
@Override
public void didChange(DidChangeTextDocumentParams params) {
VersionedTextDocumentIdentifier document = params.getTextDocument();
URI uri = URI.create(document.getUri());
Optional<Path> path = getFilePath(uri);
if (path.isPresent()) {
for (TextDocumentContentChangeEvent change : params.getContentChanges()) {
if (change.getRange() == null)
sourceByPath.put(path.get(), change.getText());
else {
String existingText = sourceByPath.get(path.get());
String newText = patch(existingText, change);
sourceByPath.put(path.get(), newText);
}
}
}
}
@Override
public void didClose(DidCloseTextDocumentParams params) {
TextDocumentIdentifier document = params.getTextDocument();
URI uri = URI.create(document.getUri());
Optional<Path> path = getFilePath(uri);
if (path.isPresent()) {
JavacHolder compiler = findCompiler(path.get());
JavaFileObject file = findFile(compiler, path.get());
// Remove from source cache
sourceByPath.remove(path.get());
}
}
@Override
public void didSave(DidSaveTextDocumentParams params) {
TextDocumentIdentifier document = params.getTextDocument();
URI uri = URI.create(document.getUri());
Optional<Path> path = getFilePath(uri);
// TODO re-lint dependencies as well as changed files
if (path.isPresent())
doLint(path.get());
}
@Override
public void onPublishDiagnostics(Consumer<PublishDiagnosticsParams> callback) {
publishDiagnostics = callback;
}
};
}
private String patch(String sourceText, TextDocumentContentChangeEvent change) {
try {
Range range = change.getRange();
BufferedReader reader = new BufferedReader(new StringReader(sourceText));
StringWriter writer = new StringWriter();
// Skip unchanged lines
int line = 0;
while (line < range.getStart().getLine()) {
writer.write(reader.readLine() + '\n');
line++;
}
// Skip unchanged chars
for (int character = 0; character < range.getStart().getCharacter(); character++)
writer.write(reader.read());
// Write replacement text
writer.write(change.getText());
// Skip replaced text
reader.skip(change.getRangeLength());
// Write remaining text
while (true) {
int next = reader.read();
if (next == -1)
return writer.toString();
else
writer.write(next);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Optional<Path> getFilePath(URI uri) {
if (!uri.getScheme().equals("file"))
return Optional.empty();
else
return Optional.of(Paths.get(uri));
}
private void doLint(Path path) {
LOG.info("Lint " + path);
DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
JavacHolder compiler = findCompiler(path);
SymbolIndex index = findIndex(path);
JavaFileObject file = findFile(compiler, path);
compiler.onError(errors);
JCTree.JCCompilationUnit parsed = compiler.parse(file);
compiler.compile(parsed);
// TODO compiler should do this automatically
index.update(parsed, compiler.context);
publishDiagnostics(Collections.singleton(path), errors);
}
@Override
public WorkspaceService getWorkspaceService() {
return new WorkspaceService() {
@Override
public CompletableFuture<List<? extends SymbolInformation>> symbol(WorkspaceSymbolParams params) {
List<SymbolInformation> infos = indexCache.values()
.stream()
.flatMap(symbolIndex -> symbolIndex.search(params.getQuery()))
.limit(100)
.collect(Collectors.toList());
return CompletableFuture.completedFuture(infos);
}
@Override
public void didChangeConfiguraton(DidChangeConfigurationParams params) {
}
@Override
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
for (FileEvent event : params.getChanges()) {
if (event.getUri().endsWith(".java")) {
if (event.getType() == FileChangeType.Deleted) {
URI uri = URI.create(event.getUri());
getFilePath(uri).ifPresent(path -> {
JavacHolder compiler = findCompiler(path);
JavaFileObject file = findFile(compiler, path);
SymbolIndex index = findIndex(path);
compiler.clear(file);
index.clear(file.toUri());
});
}
}
else if (event.getUri().endsWith("javaconfig.json")) {
// TODO invalidate caches when javaconfig.json changes
}
}
}
};
}
@Override
public WindowService getWindowService() {
return new WindowService() {
@Override
public void onShowMessage(Consumer<MessageParams> callback) {
showMessage = callback;
}
@Override
public void onShowMessageRequest(Consumer<ShowMessageRequestParams> callback) {
}
@Override
public void onLogMessage(Consumer<MessageParams> callback) {
}
};
}
private void publishDiagnostics(Collection<Path> paths, DiagnosticCollector<JavaFileObject> errors) {
Map<URI, PublishDiagnosticsParamsImpl> files = new HashMap<>();
paths.forEach(p -> files.put(p.toUri(), newPublishDiagnostics(p.toUri())));
errors.getDiagnostics().forEach(error -> {
if (error.getStartPosition() != javax.tools.Diagnostic.NOPOS) {
URI uri = error.getSource().toUri();
PublishDiagnosticsParamsImpl publish = files.computeIfAbsent(uri, this::newPublishDiagnostics);
RangeImpl range = position(error);
DiagnosticImpl diagnostic = new DiagnosticImpl();
DiagnosticSeverity severity = severity(error.getKind());
diagnostic.setSeverity(severity);
diagnostic.setRange(range);
diagnostic.setCode(error.getCode());
diagnostic.setMessage(error.getMessage(null));
publish.getDiagnostics().add(diagnostic);
}
});
files.values().forEach(publishDiagnostics::accept);
}
private DiagnosticSeverity severity(javax.tools.Diagnostic.Kind kind) {
switch (kind) {
case ERROR:
return DiagnosticSeverity.Error;
case WARNING:
case MANDATORY_WARNING:
return DiagnosticSeverity.Warning;
case NOTE:
case OTHER:
default:
return DiagnosticSeverity.Information;
}
}
private PublishDiagnosticsParamsImpl newPublishDiagnostics(URI newUri) {
PublishDiagnosticsParamsImpl p = new PublishDiagnosticsParamsImpl();
p.setDiagnostics(new ArrayList<>());
p.setUri(newUri.toString());
return p;
}
private Map<JavacConfig, JavacHolder> compilerCache = new HashMap<>();
/**
* Instead of looking for javaconfig.json and creating a JavacHolder, just use this.
* For testing.
*/
private final Optional<JavacHolder> testJavac;
/**
* Look for a configuration in a parent directory of uri
*/
private JavacHolder findCompiler(Path path) {
if (testJavac.isPresent())
return testJavac.get();
Path dir = path.getParent();
Optional<JavacConfig> config = findConfig(dir);
// If config source path doesn't contain source file, then source file has no config
if (config.isPresent() && !config.get().sourcePath.stream().anyMatch(s -> path.startsWith(s)))
throw new NoJavaConfigException(path.getFileName() + " is not on the source path");
Optional<JavacHolder> maybeHolder = config.map(c -> compilerCache.computeIfAbsent(c, this::newJavac));
return maybeHolder.orElseThrow(() -> new NoJavaConfigException(path));
}
private JavacHolder newJavac(JavacConfig c) {
return new JavacHolder(c.classPath,
c.sourcePath,
c.outputDirectory);
}
private Map<JavacConfig, SymbolIndex> indexCache = new HashMap<>();
private SymbolIndex findIndex(Path path) {
Path dir = path.getParent();
Optional<JavacConfig> config = findConfig(dir);
Optional<SymbolIndex> index = config.map(c -> indexCache.computeIfAbsent(c, this::newIndex));
return index.orElseThrow(() -> new NoJavaConfigException(path));
}
private SymbolIndex newIndex(JavacConfig c) {
return new SymbolIndex(c.classPath, c.sourcePath, c.outputDirectory);
}
// TODO invalidate cache when VSCode notifies us config file has changed
private Map<Path, Optional<JavacConfig>> configCache = new HashMap<>();
private Optional<JavacConfig> findConfig(Path dir) {
return configCache.computeIfAbsent(dir, this::doFindConfig);
}
private Optional<JavacConfig> doFindConfig(Path dir) {
if (testJavac.isPresent())
return testJavac.map(j -> new JavacConfig(j.sourcePath, j.classPath, j.outputDirectory));
while (true) {
Optional<JavacConfig> found = readIfConfig(dir);
if (found.isPresent())
return found;
else if (workspaceRoot.startsWith(dir))
return Optional.empty();
else
dir = dir.getParent();
}
}
/**
* If directory contains a config file, for example javaconfig.json or an eclipse project file, read it.
*/
private Optional<JavacConfig> readIfConfig(Path dir) {
if (Files.exists(dir.resolve("javaconfig.json"))) {
JavaConfigJson json = readJavaConfigJson(dir.resolve("javaconfig.json"));
Set<Path> classPath = json.classPathFile.map(classPathFile -> {
Path classPathFilePath = dir.resolve(classPathFile);
return readClassPathFile(classPathFilePath);
}).orElse(Collections.emptySet());
Set<Path> sourcePath = json.sourcePath.stream().map(dir::resolve).collect(Collectors.toSet());
Path outputDirectory = dir.resolve(json.outputDirectory);
JavacConfig config = new JavacConfig(sourcePath, classPath, outputDirectory);
return Optional.of(config);
}
else if (Files.exists(dir.resolve("pom.xml"))) {
Path pomXml = dir.resolve("pom.xml");
// Invoke maven to get classpath
Set<Path> classPath = buildClassPath(pomXml);
// Get source directory from pom.xml
Set<Path> sourcePath = sourceDirectories(pomXml);
// Use target/javacs
Path outputDirectory = Paths.get("target/javacs").toAbsolutePath();
JavacConfig config = new JavacConfig(sourcePath, classPath, outputDirectory);
return Optional.of(config);
}
// TODO add more file types
else {
return Optional.empty();
}
}
public static Set<Path> buildClassPath(Path pomXml) {
try {
Objects.requireNonNull(pomXml, "pom.xml path is null");
// Tell maven to output classpath to a temporary file
// TODO if pom.xml already specifies outputFile, use that location
Path classPathTxt = Files.createTempFile("classpath", ".txt");
LOG.info("Emit classpath to " + classPathTxt);
String cmd = getMvnCommand() + " dependency:build-classpath -Dmdep.outputFile=" + classPathTxt;
File workingDirectory = pomXml.toAbsolutePath().getParent().toFile();
int result = Runtime.getRuntime().exec(cmd, null, workingDirectory).waitFor();
if (result != 0)
throw new RuntimeException("`" + cmd + "` returned " + result);
return readClassPathFile(classPathTxt);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
private static String getMvnCommand() {
String mvnCommand = "mvn";
if (File.separatorChar == '\\') {
mvnCommand = findExecutableOnPath("mvn.cmd");
if (mvnCommand == null) {
mvnCommand = findExecutableOnPath("mvn.bat");
}
}
return mvnCommand;
}
private static String findExecutableOnPath(String name) {
for (String dirname : System.getenv("PATH").split(File.pathSeparator)) {
File file = new File(dirname, name);
if (file.isFile() && file.canExecute()) {
return file.getAbsolutePath();
}
}
return null;
}
private static Set<Path> sourceDirectories(Path pomXml) {
try {
Set<Path> all = new HashSet<>();
// Parse pom.xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(pomXml.toFile());
// Find source directory
String sourceDir = XPathFactory.newInstance().newXPath().compile("/project/build/sourceDirectory").evaluate(doc);
if (sourceDir == null || sourceDir.isEmpty()) {
LOG.info("Use default source directory src/main/java");
sourceDir = "src/main/java";
}
else LOG.info("Use source directory from pom.xml " + sourceDir);
all.add(pomXml.resolveSibling(sourceDir).toAbsolutePath());
// Find test directory
String testDir = XPathFactory.newInstance().newXPath().compile("/project/build/testSourceDirectory").evaluate(doc);
if (testDir == null || testDir.isEmpty()) {
LOG.info("Use default test directory src/test/java");
testDir = "src/test/java";
}
else LOG.info("Use test directory from pom.xml " + testDir);
all.add(pomXml.resolveSibling(testDir).toAbsolutePath());
return all;
} catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException e) {
throw new RuntimeException(e);
}
}
private JavaConfigJson readJavaConfigJson(Path configFile) {
try {
return JSON.readValue(configFile.toFile(), JavaConfigJson.class);
} catch (IOException e) {
MessageParamsImpl message = new MessageParamsImpl();
message.setMessage("Error reading " + configFile);
message.setType(MessageType.Error);
throw new ShowMessageException(message, e);
}
}
private static Set<Path> readClassPathFile(Path classPathFilePath) {
try {
InputStream in = Files.newInputStream(classPathFilePath);
String text = new BufferedReader(new InputStreamReader(in))
.lines()
.collect(Collectors.joining());
Path dir = classPathFilePath.getParent();
return Arrays.stream(text.split(File.pathSeparator))
.map(dir::resolve)
.collect(Collectors.toSet());
} catch (IOException e) {
MessageParamsImpl message = new MessageParamsImpl();
message.setMessage("Error reading " + classPathFilePath);
message.setType(MessageType.Error);
throw new ShowMessageException(message, e);
}
}
private JavaFileObject findFile(JavacHolder compiler, Path path) {
if (sourceByPath.containsKey(path))
return new StringFileObject(sourceByPath.get(path), path);
else
return compiler.fileManager.getRegularFile(path.toFile());
}
private RangeImpl position(javax.tools.Diagnostic<? extends JavaFileObject> error) {
// Compute start position
PositionImpl start = new PositionImpl();
start.setLine((int) (error.getLineNumber() - 1));
start.setCharacter((int) (error.getColumnNumber() - 1));
// Compute end position
PositionImpl end = endPosition(error);
// Combine into Range
RangeImpl range = new RangeImpl();
range.setStart(start);
range.setEnd(end);
return range;
}
private PositionImpl endPosition(javax.tools.Diagnostic<? extends JavaFileObject> error) {
try (Reader reader = error.getSource().openReader(true)) {
long startOffset = error.getStartPosition();
long endOffset = error.getEndPosition();
reader.skip(startOffset);
int line = (int) error.getLineNumber() - 1;
int column = (int) error.getColumnNumber() - 1;
for (long i = startOffset; i < endOffset; i++) {
int next = reader.read();
if (next == '\n') {
line++;
column = 0;
}
else
column++;
}
PositionImpl end = new PositionImpl();
end.setLine(line);
end.setCharacter(column);
return end;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private List<? extends Location> findReferences(ReferenceParams params) {
URI uri = URI.create(params.getTextDocument().getUri());
int line = params.getPosition().getLine();
int character = params.getPosition().getCharacter();
List<Location> result = new ArrayList<>();
getFilePath(uri).ifPresent(path -> {
JCTree.JCCompilationUnit compilationUnit = findTree(path);
findSymbol(compilationUnit, line, character).ifPresent(symbol -> {
if (SymbolIndex.shouldIndex(symbol)) {
SymbolIndex index = findIndex(path);
index.references(symbol).forEach(result::add);
}
else {
compilationUnit.accept(new TreeScanner() {
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
super.visitSelect(tree);
if (tree.sym != null && tree.sym.equals(symbol))
result.add(SymbolIndex.location(tree, compilationUnit));
}
@Override
public void visitReference(JCTree.JCMemberReference tree) {
super.visitReference(tree);
if (tree.sym != null && tree.sym.equals(symbol))
result.add(SymbolIndex.location(tree, compilationUnit));
}
@Override
public void visitIdent(JCTree.JCIdent tree) {
super.visitIdent(tree);
if (tree.sym != null && tree.sym.equals(symbol))
result.add(SymbolIndex.location(tree, compilationUnit));
}
});
}
});
});
return result;
}
private List<? extends SymbolInformation> findDocumentSymbols(DocumentSymbolParams params) {
URI uri = URI.create(params.getTextDocument().getUri());
return getFilePath(uri).map(path -> {
SymbolIndex index = findIndex(path);
List<? extends SymbolInformation> found = index.allInFile(uri).collect(Collectors.toList());
return found;
}).orElse(Collections.emptyList());
}
private JCTree.JCCompilationUnit findTree(Path path) {
JavacHolder compiler = findCompiler(path);
SymbolIndex index = findIndex(path);
JavaFileObject file = findFile(compiler, path);
compiler.onError(err -> {});
JCTree.JCCompilationUnit tree = compiler.parse(file);
compiler.compile(tree);
// TODO compiler should do this automatically
index.update(tree, compiler.context);
return tree;
}
public Optional<Symbol> findSymbol(JCTree.JCCompilationUnit tree, int line, int character) {
JavaFileObject file = tree.getSourceFile();
return getFilePath(file.toUri()).flatMap(path -> {
JavacHolder compiler = findCompiler(path);
long cursor = findOffset(file, line, character);
SymbolUnderCursorVisitor visitor = new SymbolUnderCursorVisitor(file, cursor, compiler.context);
tree.accept(visitor);
return visitor.found;
});
}
public List<? extends Location> gotoDefinition(TextDocumentPositionParams position) {
URI uri = URI.create(position.getTextDocument().getUri());
int line = position.getPosition().getLine();
int character = position.getPosition().getCharacter();
List<Location> result = new ArrayList<>();
getFilePath(uri).ifPresent(path -> {
JCTree.JCCompilationUnit compilationUnit = findTree(path);
findSymbol(compilationUnit, line, character).ifPresent(symbol -> {
if (SymbolIndex.shouldIndex(symbol)) {
SymbolIndex index = findIndex(path);
index.findSymbol(symbol).ifPresent(info -> {
result.add(info.getLocation());
});
}
else {
JCTree symbolTree = TreeInfo.declarationFor(symbol, compilationUnit);
if (symbolTree != null)
result.add(SymbolIndex.location(symbolTree, compilationUnit));
}
});
});
return result;
}
/**
* Convert on offset-based range to a {@link io.typefox.lsapi.Range}
*/
public static RangeImpl findPosition(JavaFileObject file, long startOffset, long endOffset) {
try (Reader in = file.openReader(true)) {
long offset = 0;
int line = 0;
int character = 0;
// Find the start position
while (offset < startOffset) {
int next = in.read();
if (next < 0)
break;
else {
offset++;
character++;
if (next == '\n') {
line++;
character = 0;
}
}
}
PositionImpl start = createPosition(line, character);
// Find the end position
while (offset < endOffset) {
int next = in.read();
if (next < 0)
break;
else {
offset++;
character++;
if (next == '\n') {
line++;
character = 0;
}
}
}
PositionImpl end = createPosition(line, character);
// Combine into range
RangeImpl range = new RangeImpl();
range.setStart(start);
range.setEnd(end);
return range;
} catch (IOException e) {
throw ShowMessageException.error(e.getMessage(), e);
}
}
private static PositionImpl createPosition(int line, int character) {
PositionImpl p = new PositionImpl();
p.setLine(line);
p.setCharacter(character);
return p;
}
private static long findOffset(JavaFileObject file, int targetLine, int targetCharacter) {
try (Reader in = file.openReader(true)) {
long offset = 0;
int line = 0;
int character = 0;
while (line < targetLine) {
int next = in.read();
if (next < 0)
return offset;
else {
offset++;
if (next == '\n')
line++;
}
}
while (character < targetCharacter) {
int next = in.read();
if (next < 0)
return offset;
else {
offset++;
character++;
}
}
return offset;
} catch (IOException e) {
throw ShowMessageException.error(e.getMessage(), e);
}
}
private HoverImpl doHover(TextDocumentPositionParams position) {
HoverImpl result = new HoverImpl();
List<MarkedStringImpl> contents = new ArrayList<>();
result.setContents(contents);
URI uri = URI.create(position.getTextDocument().getUri());
int line = position.getPosition().getLine();
int character = position.getPosition().getCharacter();
getFilePath(uri).ifPresent(path -> {
JCTree.JCCompilationUnit compilationUnit = findTree(path);
findSymbol(compilationUnit, line, character).ifPresent(symbol -> {
switch (symbol.getKind()) {
case PACKAGE:
contents.add(markedString("package " + symbol.getQualifiedName()));
break;
case ENUM:
contents.add(markedString("enum " + symbol.getQualifiedName()));
break;
case CLASS:
contents.add(markedString("class " + symbol.getQualifiedName()));
break;
case ANNOTATION_TYPE:
contents.add(markedString("@interface " + symbol.getQualifiedName()));
break;
case INTERFACE:
contents.add(markedString("interface " + symbol.getQualifiedName()));
break;
case METHOD:
case CONSTRUCTOR:
case STATIC_INIT:
case INSTANCE_INIT:
Symbol.MethodSymbol method = (Symbol.MethodSymbol) symbol;
String signature = AutocompleteVisitor.methodSignature(method);
String returnType = ShortTypePrinter.print(method.getReturnType());
contents.add(markedString(returnType + " " + signature));
break;
case PARAMETER:
case LOCAL_VARIABLE:
case EXCEPTION_PARAMETER:
case ENUM_CONSTANT:
case FIELD:
contents.add(markedString(ShortTypePrinter.print(symbol.type)));
break;
case TYPE_PARAMETER:
case OTHER:
case RESOURCE_VARIABLE:
break;
}
});
});
return result;
}
private MarkedStringImpl markedString(String value) {
MarkedStringImpl result = new MarkedStringImpl();
result.setLanguage("java");
result.setValue(value);
return result;
}
public CompletionList autocomplete(TextDocumentPositionParams position) {
CompletionListImpl result = new CompletionListImpl();
result.setIncomplete(false);
result.setItems(new ArrayList<>());
Optional<Path> maybePath = getFilePath(URI.create(position.getTextDocument().getUri()));
if (maybePath.isPresent()) {
Path path = maybePath.get();
DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
JavacHolder compiler = findCompiler(path);
JavaFileObject file = findFile(compiler, path);
long cursor = findOffset(file, position.getPosition().getLine(), position.getPosition().getCharacter());
JavaFileObject withSemi = withSemicolonAfterCursor(file, path, cursor);
AutocompleteVisitor autocompleter = new AutocompleteVisitor(withSemi, cursor, compiler.context);
compiler.onError(errors);
JCTree.JCCompilationUnit ast = compiler.parse(withSemi);
// Remove all statements after the cursor
// There are often parse errors after the cursor, which can generate unrecoverable type errors
ast.accept(new AutocompletePruner(withSemi, cursor, compiler.context));
compiler.compile(ast);
ast.accept(autocompleter);
result.getItems().addAll(autocompleter.suggestions);
}
return result;
}
/**
* Insert ';' after the users cursor so we recover from parse errors in a helpful way when doing autocomplete.
*/
private JavaFileObject withSemicolonAfterCursor(JavaFileObject file, Path path, long cursor) {
try (Reader reader = file.openReader(true)) {
StringBuilder acc = new StringBuilder();
for (int i = 0; i < cursor; i++) {
int next = reader.read();
if (next == -1)
throw new RuntimeException("End of file " + file + " before cursor " + cursor);
acc.append((char) next);
}
acc.append(";");
for (int next = reader.read(); next > 0; next = reader.read()) {
acc.append((char) next);
}
return new StringFileObject(acc.toString(), path);
} catch (IOException e) {
throw ShowMessageException.error("Error reading " + file, e);
}
}
} |
package org.caleydo.core.view.opengl.layout2.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.media.opengl.GL;
import org.caleydo.core.util.color.Color;
import org.caleydo.core.view.opengl.layout.util.multiform.IMultiFormChangeListener;
import org.caleydo.core.view.opengl.layout.util.multiform.MultiFormRenderer;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLElementContainer;
import org.caleydo.core.view.opengl.layout2.GLGraphics;
import org.caleydo.core.view.opengl.layout2.basic.GLButton;
import org.caleydo.core.view.opengl.layout2.basic.GLButton.EButtonMode;
import org.caleydo.core.view.opengl.layout2.layout.GLLayouts;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.core.view.opengl.layout2.renderer.IGLRenderer;
import org.caleydo.core.view.opengl.picking.APickingListener;
import org.caleydo.core.view.opengl.picking.IPickingListener;
import org.caleydo.core.view.opengl.picking.Pick;
/**
* @author Christian
*
*/
public class GLElementViewSwitchingBar extends GLElementContainer implements IMultiFormChangeListener {
public final static int DEFAULT_HEIGHT_PIXELS = 16;
public final static int BUTTON_SPACING_PIXELS = 2;
/**
* Picking type used for buttons.
*/
// private final String buttonPickingType;
/**
* MultiFormRenderer the buttons of this bar are for.
*/
private MultiFormRenderer multiFormRenderer;
/**
* Map associating rendererIDs with corresponding buttons and layouts.
*/
private Map<Integer, GLButton> buttons = new HashMap<>();
/**
* PickingListener for buttons to switch views.
*/
private IPickingListener buttonPickingListener = new APickingListener() {
@Override
public void clicked(Pick pick) {
GLElementViewSwitchingBar.this.multiFormRenderer.setActive(pick.getObjectID(), true);
}
};
/**
* @param multiFormRenderer
* The {@link MultiFormRenderer} buttons for view switching shall be created for.
*/
public GLElementViewSwitchingBar(MultiFormRenderer multiFormRenderer) {
setSize(Float.NaN, DEFAULT_HEIGHT_PIXELS);
setLayout(GLLayouts.flowHorizontal(BUTTON_SPACING_PIXELS));
multiFormRenderer.addChangeListener(this);
// buttonPickingType = MultiFormViewSwitchingBar.class.getName() + hashCode();
this.multiFormRenderer = multiFormRenderer;
createButtonsForMultiformRenderer(multiFormRenderer);
}
/**
* Adds a specified picking listener for a button identified by the corresponding rendererID, if such a button is
* present in the bar. This listener will be unregistered when the button is removed from the bar or the bar is
* destroyed.
*
* @param pickingListener
* @param rendererID
*/
public void addButtonPickingListener(IPickingListener pickingListener, int rendererID) {
GLButton button = buttons.get(rendererID);
if (button != null) {
button.onPick(pickingListener);
}
}
/**
* Sets the tooltip of the button of the associated renderer.
*
* @param toolTip
* @param rendererID
*/
public void setButtonToolTip(String toolTip, int rendererID) {
GLButton button = buttons.get(rendererID);
if (button != null) {
button.setTooltip(toolTip);
}
}
private void createButtonsForMultiformRenderer(MultiFormRenderer multiFormRenderer) {
Set<Integer> rendererIDs = multiFormRenderer.getRendererIDs();
List<Integer> idList = new ArrayList<>(rendererIDs);
Collections.sort(idList);
for (int i = 0; i < idList.size(); i++) {
int rendererID = idList.get(i);
addButton(rendererID, multiFormRenderer);
}
}
/**
* Adds a button for a specified renderer. If a button already exists for this renderer, it will be replaced. Note
* that buttons usually do not have to be added manually, as they are created automatically for all renderers of a
* {@link MultiFormRenderer}.
*
* @param rendererID
* ID of the renderer a button should be added for.
* @param multiFormRenderer
* The <code>MultiFormRenderer</code> the renderer belongs to.
*/
public void addButton(final int rendererID, final MultiFormRenderer multiFormRenderer) {
// Button button = new Button(buttonPickingType, rendererID, multiFormRenderer.getIconPath(rendererID));
// ElementLayout buttonLayout = ElementLayouts.createButton(view, button, DEFAULT_HEIGHT_PIXELS,
// DEFAULT_HEIGHT_PIXELS, 0.22f);
GLButton button = new GLButton(EButtonMode.CHECKBOX);
button.setRenderer(GLRenderers.fillImage(multiFormRenderer.getIconPath(rendererID)));
button.setSelectedRenderer(new IGLRenderer() {
@Override
public void render(GLGraphics g, float w, float h, GLElement parent) {
g.fillImage(multiFormRenderer.getIconPath(rendererID), 0, 0, w, h);
g.gl.glEnable(GL.GL_BLEND);
g.gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
g.gl.glEnable(GL.GL_LINE_SMOOTH);
g.color(new Color(1, 1, 1, 0.5f)).fillRoundedRect(0, 0, w, h, Math.min(w, h) * 0.25f);
g.gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA);
}
});
int activeRendererID = multiFormRenderer.getActiveRendererID();
if (activeRendererID == -1) {
activeRendererID = multiFormRenderer.getDefaultRendererID();
}
if (rendererID == activeRendererID) {
button.setSelected(true);
}
button.onPick(buttonPickingListener);
button.setPickingObjectId(rendererID);
// GLElementAdapter(view, new ButtonRenderer.Builder(view, button)
// .zCoordinate(0.22f).build());
button.setSize(DEFAULT_HEIGHT_PIXELS, DEFAULT_HEIGHT_PIXELS);
if (buttons.containsKey(rendererID)) {
GLButton oldButton = buttons.get(rendererID);
// GLElement element = buttonPair.getSecond();
int elementIndex = indexOf(oldButton);
add(elementIndex, button);
remove(oldButton);
} else {
add(button);
}
buttons.put(rendererID, button);
setSize(buttons.size() * DEFAULT_HEIGHT_PIXELS + (buttons.size() - 1) * BUTTON_SPACING_PIXELS,
DEFAULT_HEIGHT_PIXELS);
}
/**
* Removes the button corresponding to the renderer specified by the provided ID from the toolbar.
*
* @param rendererID
* ID of the renderer the button corresponds to.
*/
public void removeButton(int rendererID) {
GLButton button = buttons.get(rendererID);
if (button == null)
return;
remove(button);
buttons.remove(rendererID);
}
@Override
public void destroyed(MultiFormRenderer multiFormRenderer) {
this.multiFormRenderer = null;
takeDown();
}
@Override
public void activeRendererChanged(MultiFormRenderer multiFormRenderer, int rendererID, int previousRendererID,
boolean wasTriggeredByUser) {
selectButton(previousRendererID, false);
selectButton(rendererID, true);
}
private void selectButton(int rendererID, boolean select) {
GLButton button = buttons.get(rendererID);
if (button != null) {
button.setSelected(select);
// buttonPair.getSecond().repaint();
}
}
@Override
public void rendererAdded(MultiFormRenderer multiFormRenderer, int rendererID) {
addButton(rendererID, multiFormRenderer);
}
@Override
public void rendererRemoved(MultiFormRenderer multiFormRenderer, int rendererID) {
removeButton(rendererID);
}
@Override
public void takeDown() {
if (multiFormRenderer != null)
multiFormRenderer.removeChangeListener(this);
buttons.clear();
super.takeDown();
}
} |
package org.jboss.msc.service;
import org.jboss.msc.value.ImmediateValue;
import org.jboss.msc.value.Value;
/**
* A service is a thing which can be started and stopped.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public interface Service {
/**
* Start the service. Do not return until the service has been fully started, unless an asynchronous service
* start is performed. All injections will be complete before this method is called.
*
* @param context the context which can be used to trigger an asynchronous service start
* @throws StartException if the service could not be started for some reason
*/
void start(StartContext context) throws StartException;
/**
* Stop the service. Do not return until the service has been fully stopped, unless an asynchronous service
* stop is performed. All injections will remain intact until the service is fully stopped. This method should
* not throw an exception.
*
* @param context the context which can be used to trigger an asynchronous service stop
*/
void stop(StopContext context);
/**
* A simple null service which performs no start or stop action.
*/
Service NULL = new Service() {
public void start(final StartContext context) {
}
public void stop(final StopContext context) {
}
};
/**
* A value which resolves to the {@link #NULL null service}.
*/
Value<Service> NULL_VALUE = new ImmediateValue<Service>(NULL);
} |
package org.eclipse.mylyn.tasks.ui.editors;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.ITaskListRunnable;
import org.eclipse.mylyn.internal.tasks.core.data.ITaskDataManagerListener;
import org.eclipse.mylyn.internal.tasks.core.data.TaskDataManagerEvent;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.actions.ClearOutgoingAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.NewSubTaskAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.editors.EditorUtil;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskAttachmentDropListener;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorActionContributor;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorActionPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorAttachmentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorAttributePart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorCommentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorDescriptionPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorNewCommentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorOutlineNode;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorOutlinePage;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorPeoplePart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorPlanningPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorRichTextPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorSummaryPart;
import org.eclipse.mylyn.internal.tasks.ui.util.AttachmentUtil;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.ITask.SynchronizationState;
import org.eclipse.mylyn.tasks.core.data.ITaskDataWorkingCopy;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelEvent;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelListener;
import org.eclipse.mylyn.tasks.core.sync.SubmitJob;
import org.eclipse.mylyn.tasks.core.sync.SubmitJobEvent;
import org.eclipse.mylyn.tasks.core.sync.SubmitJobListener;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* Extend to provide a task editor page.
*
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
* @since 3.0
*/
public abstract class AbstractTaskEditorPage extends FormPage implements ISelectionProvider, ISelectionChangedListener {
private class SubmitTaskJobListener extends SubmitJobListener {
private final boolean attachContext;
public SubmitTaskJobListener(boolean attachContext) {
this.attachContext = attachContext;
}
@Override
public void done(SubmitJobEvent event) {
final SubmitJob job = event.getJob();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
private void openNewTask(ITask newTask) {
AbstractTaskContainer parent = null;
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorAttributePart) {
parent = ((TaskEditorActionPart) actionPart).getCategory();
}
// TODO copy context and scheduling
TasksUiInternal.getTaskList().addTask(newTask, parent);
close();
TasksUiInternal.getTaskList().deleteTask(getTask());
TasksUiInternal.openTaskInBackground(newTask, false);
}
public void run() {
try {
if (job.getStatus() == null) {
TasksUiInternal.synchronizeRepository(getTaskRepository(), false);
if (job.getTask().equals(getTask())) {
refreshFormContent();
} else {
openNewTask(job.getTask());
}
} else {
handleSubmitError(job);
}
} finally {
showEditorBusy(false);
}
}
});
}
@Override
public void taskSubmitted(SubmitJobEvent event, IProgressMonitor monitor) throws CoreException {
if (attachContext) {
AttachmentUtil.postContext(connector, getModel().getTaskRepository(), task, "", null, monitor);
}
}
@Override
public void taskSynchronized(SubmitJobEvent event, IProgressMonitor monitor) {
}
}
// private class TaskListChangeListener extends TaskListChangeAdapter {
// @Override
// public void containersChanged(Set<TaskContainerDelta> containers) {
// if (refreshDisabled) {
// return;
// ITask taskToRefresh = null;
// for (TaskContainerDelta taskContainerDelta : containers) {
// if (task.equals(taskContainerDelta.getElement())) {
// if (taskContainerDelta.getKind().equals(TaskContainerDelta.Kind.CONTENT)
// && !taskContainerDelta.isTransient()) {
// taskToRefresh = (ITask) taskContainerDelta.getElement();
// break;
// if (taskToRefresh != null) {
// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
// public void run() {
// if (!isDirty() && task.getSynchronizationState() == SynchronizationState.SYNCHRONIZED) {
// // automatically refresh if the user has not made any changes and there is no chance of missing incomings
// refreshFormContent();
// } else {
// getTaskEditor().setMessage("Task has incoming changes", IMessageProvider.WARNING,
// new HyperlinkAdapter() {
// @Override
// public void linkActivated(HyperlinkEvent e) {
// refreshFormContent();
// setSubmitEnabled(false);
private final ITaskDataManagerListener TASK_DATA_LISTENER = new ITaskDataManagerListener() {
public void taskDataUpdated(final TaskDataManagerEvent event) {
ITask task = event.getTask();
if (task.equals(AbstractTaskEditorPage.this.getTask()) && event.getTaskDataUpdated()) {
refresh(task);
}
}
private void refresh(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (refreshDisabled) {
return;
}
if (!isDirty() && task.getSynchronizationState() == SynchronizationState.SYNCHRONIZED) {
// automatically refresh if the user has not made any changes and there is no chance of missing incomings
refreshFormContent();
} else {
getTaskEditor().setMessage("Task has incoming changes", IMessageProvider.WARNING,
new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshFormContent();
}
});
setSubmitEnabled(false);
}
}
});
}
public void editsDiscarded(TaskDataManagerEvent event) {
if (event.getTask().equals(AbstractTaskEditorPage.this.getTask())) {
refresh(event.getTask());
}
}
};
private static final String ERROR_NOCONNECTIVITY = "Unable to submit at this time. Check connectivity and retry.";
public static final String ID_PART_ACTIONS = "org.eclipse.mylyn.tasks.ui.editors.parts.actions";
public static final String ID_PART_ATTACHMENTS = "org.eclipse.mylyn.tasks.ui.editors.parts.attachments";
public static final String ID_PART_ATTRIBUTES = "org.eclipse.mylyn.tasks.ui.editors.parts.attributes";
public static final String ID_PART_COMMENTS = "org.eclipse.mylyn.tasks.ui.editors.parts.comments";
public static final String ID_PART_DESCRIPTION = "org.eclipse.mylyn.tasks.ui.editors.part.descriptions";
public static final String ID_PART_NEW_COMMENT = "org.eclipse.mylyn.tasks.ui.editors.part.newComment";
public static final String ID_PART_PEOPLE = "org.eclipse.mylyn.tasks.ui.editors.part.people";
public static final String ID_PART_PLANNING = "org.eclipse.mylyn.tasks.ui.editors.part.planning";
public static final String ID_PART_SUMMARY = "org.eclipse.mylyn.tasks.ui.editors.part.summary";
public static final String PATH_ACTIONS = "actions";
public static final String PATH_ATTACHMENTS = "attachments";
public static final String PATH_ATTRIBUTES = "attributes";
public static final String PATH_COMMENTS = "comments";
public static final String PATH_HEADER = "header";
public static final String PATH_PEOPLE = "people";
public static final String PATH_PLANNING = "planning";
// private static final String ID_POPUP_MENU = "org.eclipse.mylyn.tasks.ui.editor.menu.page";
private AttributeEditorFactory attributeEditorFactory;
private AttributeEditorToolkit attributeEditorToolkit;
private Action clearOutgoingAction;
private AbstractRepositoryConnector connector;
private final String connectorKind;
private StructuredSelection defaultSelection;
private Composite editorComposite;
private ScrolledForm form;
private boolean formBusy;
private Action historyAction;
private Control lastFocusControl;
private ISelection lastSelection;
private TaskDataModel model;
private boolean needsAddToCategory;
private NewSubTaskAction newSubTaskAction;
private Action openBrowserAction;
private boolean reflow;
private volatile boolean refreshDisabled;
private final ListenerList selectionChangedListeners;
private SynchronizeEditorAction synchronizeEditorAction;
private ITask task;
private TaskData taskData;
// private ITaskListChangeListener taskListChangeListener;
private FormToolkit toolkit;
private TaskEditorOutlinePage outlinePage;
private TaskAttachmentDropListener defaultDropListener;
public AbstractTaskEditorPage(TaskEditor editor, String connectorKind) {
super(editor, "id", "label");
Assert.isNotNull(connectorKind);
this.connectorKind = connectorKind;
this.reflow = true;
this.selectionChangedListeners = new ListenerList();
}
private void addFocusListener(Composite composite, FocusListener listener) {
Control[] children = composite.getChildren();
for (Control control : children) {
if ((control instanceof Text) || (control instanceof Button) || (control instanceof Combo)
|| (control instanceof CCombo) || (control instanceof Tree) || (control instanceof Table)
|| (control instanceof Spinner) || (control instanceof Link) || (control instanceof List)
|| (control instanceof TabFolder) || (control instanceof CTabFolder)
|| (control instanceof Hyperlink) || (control instanceof FilteredTree)
|| (control instanceof StyledText)) {
control.addFocusListener(listener);
}
if (control instanceof Composite) {
addFocusListener((Composite) control, listener);
}
}
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
public void appendTextToNewComment(String text) {
AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT);
if (newCommentPart instanceof TaskEditorRichTextPart) {
((TaskEditorRichTextPart) newCommentPart).appendText(text);
newCommentPart.setFocus();
}
}
public boolean canPerformAction(String actionId) {
return EditorUtil.canPerformAction(actionId, EditorUtil.getFocusControl(this));
}
public void close() {
Display activeDisplay = getSite().getShell().getDisplay();
activeDisplay.asyncExec(new Runnable() {
public void run() {
if (getSite() != null && getSite().getPage() != null && !getManagedForm().getForm().isDisposed()) {
if (getTaskEditor() != null) {
getSite().getPage().closeEditor(getTaskEditor(), false);
} else {
getSite().getPage().closeEditor(AbstractTaskEditorPage.this, false);
}
}
}
});
}
protected AttributeEditorFactory createAttributeEditorFactory() {
return new AttributeEditorFactory(getModel(), getTaskRepository());
}
AttributeEditorToolkit createAttributeEditorToolkit() {
IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
return new AttributeEditorToolkit(handlerService);
}
@Override
protected void createFormContent(final IManagedForm managedForm) {
form = managedForm.getForm();
toolkit = managedForm.getToolkit();
registerDefaultDropListener(form);
try {
setReflow(false);
editorComposite = form.getBody();
GridLayout editorLayout = new GridLayout();
editorComposite.setLayout(editorLayout);
editorComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
//form.setData("focusScrolling", Boolean.FALSE);
// menuManager = new MenuManager();
// menuManager.setRemoveAllWhenShown(true);
// getEditorSite().registerContextMenu(ID_POPUP_MENU, menuManager, this, true);
// editorComposite.setMenu(menuManager.createContextMenu(editorComposite));
editorComposite.setMenu(getTaskEditor().getMenu());
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(getConnectorKind());
if (connectorUi == null) {
getTaskEditor().setMessage("Synchronize to update editor contents", IMessageProvider.INFORMATION,
new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshFormContent();
}
});
}
if (taskData != null) {
createFormContentInternal();
}
updateHeaderMessage();
} finally {
setReflow(true);
}
}
private void createFormContentInternal() {
// end life-cycle of previous editor controls
if (attributeEditorToolkit != null) {
attributeEditorToolkit.dispose();
}
// start life-cycle of previous editor controls
if (attributeEditorFactory == null) {
attributeEditorFactory = createAttributeEditorFactory();
Assert.isNotNull(attributeEditorFactory);
}
attributeEditorToolkit = createAttributeEditorToolkit();
Assert.isNotNull(attributeEditorToolkit);
attributeEditorToolkit.setMenu(editorComposite.getMenu());
attributeEditorToolkit.setSelectionChangedListener(this);
createParts();
FocusListener listener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
lastFocusControl = (Control) e.widget;
}
};
addFocusListener(editorComposite, listener);
AbstractTaskEditorPart summaryPart = getPart(ID_PART_SUMMARY);
if (summaryPart != null) {
lastFocusControl = summaryPart.getControl();
}
}
protected TaskDataModel createModel(TaskEditorInput input) throws CoreException {
ITaskDataWorkingCopy taskDataState = TasksUi.getTaskDataManager().getWorkingCopy(task);
TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository(getConnectorKind(),
taskDataState.getRepositoryUrl());
return new TaskDataModel(taskRepository, input.getTask(), taskDataState);
}
/**
* To suppress a section, just remove its descriptor from the list. To add your own section in a specific order on
* the page, use the path value for where you want it to appear (your descriptor will appear after previously added
* descriptors with the same path), and add it to the descriptors list in your override of this method.
*/
protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
Set<TaskEditorPartDescriptor> descriptors = new LinkedHashSet<TaskEditorPartDescriptor>();
descriptors.add(new TaskEditorPartDescriptor(ID_PART_SUMMARY) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorSummaryPart();
}
}.setPath(PATH_HEADER));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTRIBUTES) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttributePart();
}
}.setPath(PATH_ATTRIBUTES));
if (!taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTACHMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttachmentPart();
}
}.setPath(PATH_ATTACHMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_DESCRIPTION) {
@Override
public AbstractTaskEditorPart createPart() {
TaskEditorDescriptionPart part = new TaskEditorDescriptionPart();
if (getModel().getTaskData().isNew()) {
part.setExpandVertically(true);
part.setSectionStyle(ExpandableComposite.TITLE_BAR | ExpandableComposite.EXPANDED);
}
return part;
}
}.setPath(PATH_COMMENTS));
if (!taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_COMMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorCommentPart();
}
}.setPath(PATH_COMMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_NEW_COMMENT) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorNewCommentPart();
}
}.setPath(PATH_COMMENTS));
if (taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PLANNING) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPlanningPart();
}
}.setPath(PATH_PLANNING));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ACTIONS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorActionPart();
}
}.setPath(PATH_ACTIONS));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PEOPLE) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPeoplePart();
}
}.setPath(PATH_PEOPLE));
return descriptors;
}
protected void createParts() {
List<TaskEditorPartDescriptor> descriptors = new LinkedList<TaskEditorPartDescriptor>(createPartDescriptors());
// single column
createParts(PATH_HEADER, editorComposite, descriptors);
createParts(PATH_ATTRIBUTES, editorComposite, descriptors);
createParts(PATH_ATTACHMENTS, editorComposite, descriptors);
createParts(PATH_COMMENTS, editorComposite, descriptors);
createParts(PATH_PLANNING, editorComposite, descriptors);
// two column
Composite bottomComposite = toolkit.createComposite(editorComposite);
bottomComposite.setLayout(new GridLayout(2, false));
GridDataFactory.fillDefaults().grab(true, false).applyTo(bottomComposite);
createParts(PATH_ACTIONS, bottomComposite, descriptors);
createParts(PATH_PEOPLE, bottomComposite, descriptors);
bottomComposite.pack(true);
}
private void createParts(String path, final Composite parent, Collection<TaskEditorPartDescriptor> descriptors) {
for (Iterator<TaskEditorPartDescriptor> it = descriptors.iterator(); it.hasNext();) {
final TaskEditorPartDescriptor descriptor = it.next();
if (path == null || path.equals(descriptor.getPath())) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Error creating task editor part: \"" + descriptor.getId() + "\"", e));
}
public void run() throws Exception {
AbstractTaskEditorPart part = descriptor.createPart();
part.setPartId(descriptor.getId());
initializePart(parent, part);
}
});
it.remove();
}
}
}
@Override
public void dispose() {
if (attributeEditorToolkit != null) {
attributeEditorToolkit.dispose();
}
TasksUiPlugin.getTaskDataManager().removeListener(TASK_DATA_LISTENER);
super.dispose();
}
public void doAction(String actionId) {
EditorUtil.doAction(actionId, EditorUtil.getFocusControl(this));
}
@Override
public void doSave(IProgressMonitor monitor) {
if (!isDirty()) {
return;
}
getManagedForm().commit(true);
try {
model.save(monitor);
} catch (final CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Error saving task", e));
getTaskEditor().setMessage("Could not save task", IMessageProvider.ERROR, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent event) {
TasksUiInternal.displayStatus("Save failed", e.getStatus());
}
});
}
// update the summary of unsubmitted repository tasks
if (getTask().getSynchronizationState() == SynchronizationState.OUTGOING_NEW) {
final String summary = connector.getTaskMapping(model.getTaskData()).getSummary();
try {
TasksUiPlugin.getTaskList().run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
task.setSummary(summary);
}
});
TasksUiPlugin.getTaskList().notifyElementChanged(task);
} catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Failed to set summary for task \"" + task + "\"", e));
}
}
updateHeaderMessage();
getManagedForm().dirtyStateChanged();
getTaskEditor().updateHeaderToolBar();
}
@Override
public void doSaveAs() {
throw new UnsupportedOperationException();
}
public void doSubmit() {
showEditorBusy(true);
doSave(new NullProgressMonitor());
SubmitJob submitJob = TasksUiInternal.getJobFactory().createSubmitTaskJob(connector,
getModel().getTaskRepository(), task, getModel().getTaskData(), getModel().getChangedOldAttributes());
submitJob.addSubmitJobListener(new SubmitTaskJobListener(getAttachContext()));
submitJob.schedule();
}
/**
* Override for customizing the tool bar.
*/
public void fillToolBar(IToolBarManager toolBarManager) {
final TaskRepository taskRepository = (model != null) ? getModel().getTaskRepository() : null;
if (taskRepository != null) {
ControlContribution repositoryLabelControl = new ControlContribution("Title") {
@Override
protected Control createControl(Composite parent) {
FormToolkit toolkit = getTaskEditor().getHeaderForm().getToolkit();
Composite composite = toolkit.createComposite(parent);
composite.setLayout(new RowLayout());
composite.setBackground(null);
String label = taskRepository.getRepositoryLabel();
if (label.indexOf("
label = label.substring((taskRepository.getRepositoryUrl().indexOf("
}
Hyperlink link = new Hyperlink(composite, SWT.NONE);
link.setText(label);
link.setFont(JFaceResources.getBannerFont());
link.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TasksUiUtil.openEditRepositoryWizard(taskRepository);
}
});
return composite;
}
};
toolBarManager.add(repositoryLabelControl);
}
if (taskRepository != null && !taskData.isNew()) {
clearOutgoingAction = new ClearOutgoingAction(Collections.singletonList((IRepositoryElement) task));
if (clearOutgoingAction.isEnabled()) {
toolBarManager.add(clearOutgoingAction);
}
synchronizeEditorAction = new SynchronizeEditorAction();
synchronizeEditorAction.selectionChanged(new StructuredSelection(getTaskEditor()));
toolBarManager.add(synchronizeEditorAction);
newSubTaskAction = new NewSubTaskAction();
newSubTaskAction.selectionChanged(newSubTaskAction, new StructuredSelection(task));
if (newSubTaskAction.isEnabled()) {
toolBarManager.add(newSubTaskAction);
}
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(taskData.getConnectorKind());
if (connectorUi != null) {
final String historyUrl = connectorUi.getTaskHistoryUrl(taskRepository, task);
if (historyUrl != null) {
historyAction = new Action() {
@Override
public void run() {
TasksUiUtil.openUrl(historyUrl);
}
};
historyAction.setImageDescriptor(TasksUiImages.TASK_REPOSITORY_HISTORY);
historyAction.setToolTipText("History");
toolBarManager.add(historyAction);
}
}
final String taskUrlToOpen = task.getUrl();
if (taskUrlToOpen != null) {
openBrowserAction = new Action() {
@Override
public void run() {
TasksUiUtil.openUrl(taskUrlToOpen);
}
};
openBrowserAction.setImageDescriptor(CommonImages.BROWSER_OPEN_TASK);
openBrowserAction.setToolTipText("Open with Web Browser");
toolBarManager.add(openBrowserAction);
}
}
}
protected void fireSelectionChanged(ISelection selection) {
// create an event
final SelectionChangedEvent event = new SelectionChangedEvent(this, selection);
// fire the event
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i) {
final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
SafeRunner.run(new SafeRunnable() {
public void run() {
l.selectionChanged(event);
}
});
}
}
@SuppressWarnings("unchecked")
@Override
public Object getAdapter(Class adapter) {
if (adapter == IContentOutlinePage.class) {
updateOutlinePage();
return outlinePage;
}
return super.getAdapter(adapter);
}
private void updateOutlinePage() {
if (outlinePage == null) {
outlinePage = new TaskEditorOutlinePage();
outlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof StructuredSelection) {
Object select = ((StructuredSelection) selection).getFirstElement();
if (select instanceof TaskEditorOutlineNode) {
TaskEditorOutlineNode node = (TaskEditorOutlineNode) select;
TaskAttribute attribute = node.getData();
if (attribute != null) {
if (TaskAttribute.TYPE_COMMENT.equals(attribute.getMetaData().getType())) {
AbstractTaskEditorPart actionPart = getPart(ID_PART_COMMENTS);
if (actionPart != null && actionPart.getControl() instanceof ExpandableComposite) {
EditorUtil.toggleExpandableComposite(true,
(ExpandableComposite) actionPart.getControl());
}
}
EditorUtil.reveal(form, attribute.getId());
} else {
EditorUtil.reveal(form, node.getLabel());
}
}
}
}
});
}
if (getModel() != null) {
TaskEditorOutlineNode node = TaskEditorOutlineNode.parse(getModel().getTaskData());
outlinePage.setInput(getTaskRepository(), node);
} else {
outlinePage.setInput(null, null);
}
}
private boolean getAttachContext() {
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorActionPart) {
return ((TaskEditorActionPart) actionPart).getAttachContext();
}
return false;
}
public AttributeEditorFactory getAttributeEditorFactory() {
return attributeEditorFactory;
}
public AttributeEditorToolkit getAttributeEditorToolkit() {
return attributeEditorToolkit;
}
public AbstractRepositoryConnector getConnector() {
return connector;
}
public String getConnectorKind() {
return connectorKind;
}
/**
* @return The composite for the whole editor.
*/
public Composite getEditorComposite() {
return editorComposite;
}
public TaskDataModel getModel() {
return model;
}
public AbstractTaskEditorPart getPart(String partId) {
Assert.isNotNull(partId);
for (IFormPart part : getManagedForm().getParts()) {
if (part instanceof AbstractTaskEditorPart) {
AbstractTaskEditorPart taskEditorPart = (AbstractTaskEditorPart) part;
if (partId.equals(taskEditorPart.getPartId())) {
return taskEditorPart;
}
}
}
return null;
}
public ISelection getSelection() {
return lastSelection;
}
public ITask getTask() {
return task;
}
public TaskEditor getTaskEditor() {
return (TaskEditor) getEditor();
}
public TaskRepository getTaskRepository() {
return getModel().getTaskRepository();
}
private void handleSubmitError(SubmitJob job) {
if (form != null && !form.isDisposed()) {
final IStatus status = job.getStatus();
if (status.getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) {
TasksUiInternal.displayStatus("Comment required", status);
AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT);
if (newCommentPart != null) {
newCommentPart.setFocus();
}
} else if (status.getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) {
if (TasksUiUtil.openEditRepositoryWizard(getTaskRepository()) == Window.OK) {
doSubmit();
}
} else {
String message;
if (status.getCode() == RepositoryStatus.ERROR_IO) {
message = ERROR_NOCONNECTIVITY;
} else if (status.getMessage().length() > 0) {
message = "Submit failed: " + status.getMessage();
} else {
message = "Submit failed";
}
getTaskEditor().setMessage(message, IMessageProvider.ERROR, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TasksUiInternal.displayStatus("Submit failed", status);
}
});
}
}
}
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
site.setSelectionProvider(this);
TaskEditorInput taskEditorInput = (TaskEditorInput) input;
this.task = taskEditorInput.getTask();
this.defaultSelection = new StructuredSelection(task);
this.lastSelection = defaultSelection;
try {
setModel(createModel(taskEditorInput));
} catch (final CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Error opening task", e));
getTaskEditor().setStatus("Error opening task", "Open failed", e.getStatus());
}
TasksUiPlugin.getTaskDataManager().addListener(TASK_DATA_LISTENER);
}
private void initializePart(Composite parent, AbstractTaskEditorPart part) {
getManagedForm().addPart(part);
part.initialize(this);
part.createControl(parent, toolkit);
if (part.getControl() != null) {
if (part.getExpandVertically()) {
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(part.getControl());
} else {
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, false).applyTo(part.getControl());
}
// for outline
if (ID_PART_COMMENTS.equals(part.getPartId())) {
EditorUtil.setMarker(part.getControl(), TaskEditorOutlineNode.LABEL_COMMENTS);
}
}
}
@Override
public boolean isDirty() {
return (getModel() != null && getModel().isDirty()) || (getManagedForm() != null && getManagedForm().isDirty());
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
public boolean needsAddToCategory() {
return needsAddToCategory;
}
/**
* Force a re-layout of entire form.
*/
public void reflow() {
if (reflow) {
form.layout(true, true);
form.reflow(true);
}
}
/**
* Updates the editor contents in place.
*/
public void refreshFormContent() {
if (getManagedForm().getForm().isDisposed()) {
// editor possibly closed as part of submit
return;
}
try {
showEditorBusy(true);
doSave(new NullProgressMonitor());
refreshInput();
if (taskData != null) {
try {
setReflow(false);
// save menu
Menu menu = editorComposite.getMenu();
setMenu(editorComposite, null);
// clear old controls and parts
for (Control control : editorComposite.getChildren()) {
control.dispose();
}
lastFocusControl = null;
lastSelection = null;
for (IFormPart part : getManagedForm().getParts()) {
part.dispose();
getManagedForm().removePart(part);
}
// restore menu
editorComposite.setMenu(menu);
createFormContentInternal();
getTaskEditor().setMessage(null, 0);
getTaskEditor().setActivePage(getId());
setSubmitEnabled(true);
} finally {
setReflow(true);
}
}
updateOutlinePage();
updateHeaderMessage();
getManagedForm().dirtyStateChanged();
getTaskEditor().updateHeaderToolBar();
} finally {
showEditorBusy(false);
}
reflow();
}
private void refreshInput() {
try {
refreshDisabled = true;
model.refresh(null);
} catch (CoreException e) {
getTaskEditor().setMessage("Failed to read task data: " + e.getMessage(), IMessageProvider.ERROR);
taskData = null;
return;
} finally {
refreshDisabled = false;
}
setTaskData(model.getTaskData());
}
public void registerDefaultDropListener(final Control control) {
DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_DEFAULT);
final TextTransfer textTransfer = TextTransfer.getInstance();
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] { textTransfer, fileTransfer };
target.setTransfer(types);
if (defaultDropListener == null) {
defaultDropListener = new TaskAttachmentDropListener(this);
}
target.addDropListener(defaultDropListener);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
public void selectionChanged(Object element) {
selectionChanged(new SelectionChangedEvent(this, new StructuredSelection(element)));
}
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof TextSelection) {
// only update global actions
((TaskEditorActionContributor) getEditorSite().getActionBarContributor()).updateSelectableActions(event.getSelection());
return;
}
if (selection.isEmpty()) {
// something was unselected, reset to default selection
selection = defaultSelection;
// XXX a styled text widget has lost focus, re-enable all edit actions
((TaskEditorActionContributor) getEditorSite().getActionBarContributor()).forceActionsEnabled();
}
if (!selection.equals(lastSelection)) {
this.lastSelection = selection;
fireSelectionChanged(lastSelection);
}
}
@Override
public void setFocus() {
if (lastFocusControl != null && !lastFocusControl.isDisposed()) {
lastFocusControl.setFocus();
}
}
/**
* Used to prevent form menu from being disposed when disposing elements on the form during refresh
*/
private void setMenu(Composite comp, Menu menu) {
if (!comp.isDisposed()) {
comp.setMenu(menu);
for (Control child : comp.getChildren()) {
child.setMenu(menu);
if (child instanceof Composite) {
setMenu((Composite) child, menu);
}
}
}
}
private void setModel(TaskDataModel model) {
Assert.isNotNull(model);
this.model = model;
this.connector = TasksUi.getRepositoryManager().getRepositoryConnector(getConnectorKind());
setTaskData(model.getTaskData());
model.addModelListener(new TaskDataModelListener() {
@Override
public void attributeChanged(TaskDataModelEvent event) {
getManagedForm().dirtyStateChanged();
}
});
}
public void setNeedsAddToCategory(boolean needsAddToCategory) {
this.needsAddToCategory = needsAddToCategory;
}
public void setReflow(boolean reflow) {
this.reflow = reflow;
form.setRedraw(reflow);
}
public void setSelection(ISelection selection) {
IFormPart[] parts = getManagedForm().getParts();
for (IFormPart formPart : parts) {
if (formPart instanceof AbstractTaskEditorPart) {
if (((AbstractTaskEditorPart) formPart).setSelection(selection)) {
lastSelection = selection;
return;
}
}
}
}
// TODO EDITOR this needs to be tracked somewhere else
private void setSubmitEnabled(boolean enabled) {
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorActionPart) {
((TaskEditorActionPart) actionPart).setSubmitEnabled(enabled);
}
}
private void setTaskData(TaskData taskData) {
this.taskData = taskData;
}
@Override
public void showBusy(boolean busy) {
if (!getManagedForm().getForm().isDisposed() && busy != formBusy) {
// parentEditor.showBusy(busy);
// if (synchronizeEditorAction != null) {
// synchronizeEditorAction.setEnabled(!busy);
// if (openBrowserAction != null) {
// openBrowserAction.setEnabled(!busy);
// if (historyAction != null) {
// historyAction.setEnabled(!busy);
// if (actionPart != null) {
// actionPart.setSubmitEnabled(!busy);
// if (newSubTaskAction != null) {
// newSubTaskAction.setEnabled(!busy);
// if (clearOutgoingAction != null) {
// clearOutgoingAction.setEnabled(!busy);
EditorUtil.setEnabledState(editorComposite, !busy);
formBusy = busy;
}
}
public void showEditorBusy(boolean busy) {
getTaskEditor().showBusy(busy);
refreshDisabled = busy;
}
private void updateHeaderMessage() {
if (taskData == null) {
getTaskEditor().setMessage(
"Task data not available. Press synchronize button (right) to retrieve latest data.",
IMessageProvider.WARNING, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
if (synchronizeEditorAction != null) {
synchronizeEditorAction.run();
}
}
});
}
}
} |
package org.metaborg.spoofax.core.stratego;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.metaborg.core.resource.IResourceService;
import org.metaborg.util.log.Level;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.IOAgent;
import org.spoofax.interpreter.library.PrintStreamWriter;
import com.google.common.collect.Maps;
public class ResourceAgent extends IOAgent {
private static class ResourceHandle {
public final FileObject resource;
public Reader reader;
public Writer writer;
public InputStream inputStream;
public OutputStream outputStream;
ResourceHandle(FileObject resource) {
this.resource = resource;
}
}
private final IResourceService resourceService;
private final FileObject tempDir;
private final Map<Integer, ResourceHandle> openFiles = Maps.newHashMap();
private final OutputStream stdout;
private final Writer stdoutWriter;
private final OutputStream stderr;
private final Writer stderrWriter;
private FileObject workingDir;
private FileObject definitionDir;
private boolean acceptDirChanges = false;
public static OutputStream defaultStdout(String... excludePatterns) {
return LoggerUtils.stream(LoggerUtils.logger("stdout"), Level.Info, excludePatterns);
}
public static OutputStream defaultStderr(String... excludePatterns) {
return LoggerUtils.stream(LoggerUtils.logger("stderr"), Level.Info, excludePatterns);
}
public ResourceAgent(IResourceService resourceService) {
this(resourceService, resourceService.resolve(System.getProperty("user.dir")));
}
public ResourceAgent(IResourceService resourceService, FileObject initialDir) {
this(resourceService, initialDir, defaultStdout());
}
public ResourceAgent(IResourceService resourceService, FileObject initialDir, OutputStream stdout) {
this(resourceService, initialDir, stdout, defaultStderr());
}
public ResourceAgent(IResourceService resourceService, FileObject initialDir, OutputStream stdout,
OutputStream stderr) {
super();
this.acceptDirChanges = true; // Start accepting dir changes after IOAgent constructor call.
this.resourceService = resourceService;
this.tempDir = resourceService.resolve(System.getProperty("java.io.tmpdir"));
this.workingDir = initialDir;
this.definitionDir = initialDir;
this.stdout = stdout;
this.stdoutWriter = new PrintStreamWriter(new PrintStream(stdout));
this.stderr = stderr;
this.stderrWriter = new PrintStreamWriter(new PrintStream(stderr));
}
@Override public String getWorkingDir() {
return workingDir.getName().getURI();
}
public FileObject getWorkingDirResource() {
return workingDir;
}
@Override public String getDefinitionDir() {
return definitionDir.getName().getURI();
}
public FileObject getDefinitionDirResource() {
return definitionDir;
}
@Override public String getTempDir() {
return tempDir.getName().getURI();
}
public FileObject getTempDirResource() {
return tempDir;
}
@Override public void setWorkingDir(String newWorkingDir) throws IOException {
if(!acceptDirChanges)
return;
workingDir = resourceService.resolve(workingDir, newWorkingDir);
}
public void setAbsoluteWorkingDir(FileObject dir) {
workingDir = dir;
}
@Override public void setDefinitionDir(String newDefinitionDir) {
if(!acceptDirChanges)
return;
definitionDir = resourceService.resolve(definitionDir, newDefinitionDir);
}
public void setAbsoluteDefinitionDir(FileObject dir) {
definitionDir = dir;
}
@Override public Writer getWriter(int fd) {
if(fd == CONST_STDOUT) {
return stdoutWriter;
} else if(fd == CONST_STDERR) {
return stderrWriter;
} else {
final ResourceHandle handle = openFiles.get(fd);
if(handle.writer == null) {
assert handle.outputStream == null;
try {
handle.writer =
new BufferedWriter(new OutputStreamWriter(internalGetOutputStream(fd), FILE_ENCODING));
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return handle.writer;
}
}
@Override public OutputStream internalGetOutputStream(int fd) {
if(fd == CONST_STDOUT) {
return stdout;
} else if(fd == CONST_STDERR) {
return stderr;
} else {
final ResourceHandle handle = openFiles.get(fd);
if(handle.outputStream == null) {
assert handle.writer == null;
try {
handle.outputStream = handle.resource.getContent().getOutputStream();
} catch(FileSystemException e) {
throw new RuntimeException("Could not get output stream for resource", e);
}
}
return handle.outputStream;
}
}
@Override public void writeChar(int fd, int c) throws IOException {
if(fd == CONST_STDOUT || fd == CONST_STDERR) {
getWriter(fd).append((char) c);
} else {
getWriter(fd).append((char) c);
}
}
@Override public boolean closeRandomAccessFile(int fd) throws InterpreterException {
if(fd == CONST_STDOUT || fd == CONST_STDERR || fd == CONST_STDIN) {
return true;
}
final ResourceHandle handle = openFiles.remove(fd);
if(handle == null)
return true; // already closed: be forgiving
try {
if(handle.writer != null)
handle.writer.close();
if(handle.outputStream != null)
handle.outputStream.close();
handle.resource.getContent().close();
} catch(IOException e) {
throw new RuntimeException("Could not close resource", e);
}
return true;
}
@Override public void closeAllFiles() {
for(ResourceHandle handle : openFiles.values()) {
try {
if(handle.writer != null)
handle.writer.close();
if(handle.outputStream != null)
handle.outputStream.close();
handle.resource.getContent().close();
} catch(IOException e) {
throw new RuntimeException("Could not close resource", e);
}
}
openFiles.clear();
}
@Override public int openRandomAccessFile(String fn, String mode) throws IOException {
boolean appendMode = mode.indexOf('a') >= 0;
boolean writeMode = appendMode || mode.indexOf('w') >= 0;
boolean clearFile = false;
final FileObject resource = resourceService.resolve(workingDir, fn);
if(writeMode) {
if(!resource.exists()) {
resource.createFile();
} else if(!appendMode) {
clearFile = true;
}
}
if(clearFile) {
resource.delete();
resource.createFile();
}
openFiles.put(fileCounter, new ResourceHandle(resource));
return fileCounter++;
}
@Override public InputStream internalGetInputStream(int fd) {
if(fd == CONST_STDIN) {
return stdin;
}
final ResourceHandle handle = openFiles.get(fd);
if(handle.inputStream == null) {
try {
handle.inputStream = handle.resource.getContent().getInputStream();
} catch(FileSystemException e) {
throw new RuntimeException("Could not get input stream for resource", e);
}
}
return handle.inputStream;
}
@Override public Reader getReader(int fd) {
if(fd == CONST_STDIN) {
return stdinReader;
}
final ResourceHandle handle = openFiles.get(fd);
try {
if(handle.reader == null)
handle.reader = new BufferedReader(new InputStreamReader(internalGetInputStream(fd), FILE_ENCODING));
} catch(UnsupportedEncodingException e) {
throw new RuntimeException("Could not get reader for resource", e);
}
return handle.reader;
}
@Override public String readString(int fd) throws IOException {
char[] buffer = new char[2048];
final StringBuilder result = new StringBuilder();
final Reader reader = getReader(fd);
for(int read = 0; read != -1; read = reader.read(buffer)) {
result.append(buffer, 0, read);
}
return result.toString();
}
@Override public String[] readdir(String fn) {
try {
final FileObject resource = resourceService.resolve(workingDir, fn);
if(!resource.exists() || resource.getType() == FileType.FILE) {
return new String[0];
}
final FileName name = resource.getName();
final FileObject[] children = resource.getChildren();
final String[] strings = new String[children.length];
for(int i = 0; i < children.length; ++i) {
final FileName absName = children[i].getName();
strings[i] = name.getRelativeName(absName);
}
return strings;
} catch(FileSystemException e) {
throw new RuntimeException("Could not list contents of directory " + fn, e);
}
}
@Override public void printError(String error) {
try {
getWriter(CONST_STDERR).write(error + "\n");
} catch(IOException e) {
// Like System.err.println, we swallow exceptions
}
}
@Override public InputStream openInputStream(String fn, boolean isDefinitionFile) throws FileNotFoundException {
final FileObject dir = isDefinitionFile ? definitionDir : workingDir;
try {
final FileObject file = resourceService.resolve(dir, fn);
return file.getContent().getInputStream();
} catch(FileSystemException e) {
throw new RuntimeException("Could not get input stream for resource", e);
}
}
@Override public OutputStream openFileOutputStream(String fn) throws FileNotFoundException {
try {
return resourceService.resolve(workingDir, fn).getContent().getOutputStream();
} catch(FileSystemException e) {
throw new RuntimeException("Could not get output stream for resource", e);
}
}
@Override public File openFile(String fn) {
final FileObject resource = resourceService.resolve(workingDir, fn);
File localResource = resourceService.localPath(resource);
if(localResource == null) {
final File localWorkingDir = resourceService.localPath(workingDir);
if(localWorkingDir == null) {
// Local working directory does not reside on the local file system, just return a File.
return new File(fn);
}
// Could not get a local File using the FileObject interface, fall back to composing Files.
return new File(getAbsolutePath(localWorkingDir.getPath(), fn));
}
return localResource;
}
@Override public String createTempFile(String prefix) throws IOException {
// GTODO: should use FileObject interface
final File tempFile = File.createTempFile(prefix, null);
tempFile.deleteOnExit();
return tempFile.getPath();
}
@Override public String createTempDir(String prefix) throws IOException {
// GTODO: should use FileObject interface
File result;
do {
result = File.createTempFile(prefix, null);
result.delete();
} while(!result.mkdir());
result.deleteOnExit();
return result.getPath();
}
@Override public boolean mkdir(String dn) {
try {
final FileObject resource = resourceService.resolve(workingDir, dn);
final boolean created = !resource.exists();
resource.createFolder();
return created;
} catch(FileSystemException e) {
throw new RuntimeException("Could not create directories", e);
}
}
@Override @Deprecated public boolean mkDirs(String dn) {
return mkdir(dn);
}
@Override public boolean rmdir(String dn) {
try {
final FileObject resource = resourceService.resolve(workingDir, dn);
return resource.delete(new AllFileSelector()) > 0;
} catch(FileSystemException e) {
throw new RuntimeException("Could not delete directory " + dn, e);
}
}
@Override public boolean exists(String fn) {
try {
final FileObject resource = resourceService.resolve(workingDir, fn);
return resource.exists();
} catch(FileSystemException e) {
throw new RuntimeException("Could not check if file " + fn + " exists", e);
}
}
@Override public boolean readable(String fn) {
try {
final FileObject resource = resourceService.resolve(workingDir, fn);
return resource.isReadable();
} catch(FileSystemException e) {
throw new RuntimeException("Could not check if file " + fn + " is readable", e);
}
}
@Override public boolean writable(String fn) {
try {
final FileObject resource = resourceService.resolve(workingDir, fn);
return resource.isWriteable();
} catch(FileSystemException e) {
throw new RuntimeException("Could not check if file " + fn + " is writeable", e);
}
}
@Override public boolean isDirectory(String fn) {
try {
final FileObject resource = resourceService.resolve(workingDir, fn);
final FileType type = resource.getType();
return type == FileType.FOLDER || type == FileType.FILE_OR_FOLDER;
} catch(FileSystemException e) {
throw new RuntimeException("Could not check if file " + fn + " is a directory", e);
}
}
} |
package org.jtrfp.trcl;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.TimerTask;
import javax.media.opengl.GL3;
import org.jtrfp.trcl.beh.FacingObject;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.RotateAroundObject;
import org.jtrfp.trcl.core.Camera;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.TXTMissionBriefFile;
import org.jtrfp.trcl.flow.Game;
import org.jtrfp.trcl.flow.Mission.Result;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.obj.EnemyIntro;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.Sprite2D;
import org.jtrfp.trcl.obj.WorldObject;
public class BriefingScreen extends RenderableSpacePartitioningGrid {
private static final double Z = .000000001;
private final TR tr;
private final Sprite2D briefingScreen;
private final CharAreaDisplay briefingChars;
private final Sprite2D blackRectangle;
private volatile double scrollPos = 0;
private double scrollIncrement=.01;
private final int NUM_LINES=10;
private final int WIDTH_CHARS=36;
private ArrayList<Runnable> scrollFinishCallbacks = new ArrayList<Runnable>();
private TXTMissionBriefFile missionTXT;
private ColorPaletteVectorList palette;
private LVLFile lvl;
private TimerTask scrollTimer;
public BriefingScreen(SpacePartitioningGrid<PositionedRenderable> parent, final TR tr, GLFont font) {
super(parent);
briefingScreen = new Sprite2D(tr,0, 2, 2,
tr.getResourceManager().getSpecialRAWAsTextures("BRIEF.RAW", tr.getGlobalPalette(),
tr.gpu.get().getGl(), 0,false),true);
add(briefingScreen);
this.tr = tr;
briefingChars = new CharAreaDisplay(this,.047,WIDTH_CHARS,NUM_LINES,tr,font);
//briefingChars.setFontSize(.035);//TODO: Implement
briefingChars.activate();
briefingChars.setPosition(-.7, -.45, Z*200);
briefingScreen.setPosition(0,0,Z);
briefingScreen.notifyPositionChange();
briefingScreen.setActive(true);
briefingScreen.setVisible(true);
blackRectangle = new Sprite2D(tr,0, 2, .6, tr.gpu.get().textureManager.get().solidColor(Color.BLACK), true);
add(blackRectangle);
blackRectangle.setPosition(0, -.7, Z*300);
blackRectangle.setVisible(true);
blackRectangle.setActive(true);
}//end constructor
protected void notifyScrollFinishCallbacks() {
for(Runnable r:scrollFinishCallbacks){
r.run();
}
}//end notifyScrollFinishCallbacks()
public void addScrollFinishCallback(Runnable r){
scrollFinishCallbacks.add(r);
}
public void removeScrollFinishCallback(Runnable r){
scrollFinishCallbacks.remove(r);
}
public void setContent(String content) {
briefingChars.setContent(content);
}
public void startScroll() {
scrollPos=0;
tr.getThreadManager().getLightweightTimer().scheduleAtFixedRate(scrollTimer = new TimerTask(){
@Override
public void run() {
scrollPos+=scrollIncrement;
briefingChars.setScrollPosition(scrollPos);
if(scrollPos>briefingChars.getNumActiveLines()+NUM_LINES){
BriefingScreen.this.stopScroll();
notifyScrollFinishCallbacks();
scrollFinishCallbacks.clear();
}
}}, 0, 20);
}//end startScroll()
public void stopScroll() {
scrollTimer.cancel();
}
private void planetDisplayMode(LVLFile lvl){
final Game game = tr.getGame();
final ResourceManager rm = tr.getResourceManager();
final Camera camera = tr.renderer.get().getCamera();
final GL3 gl = tr.gpu.get().getGl();
this.lvl = lvl;
camera.probeForBehavior(MatchPosition.class) .setEnable(false);
camera.probeForBehavior(MatchDirection.class) .setEnable(false);
camera.probeForBehavior(FacingObject.class) .setEnable(true);
camera.probeForBehavior(RotateAroundObject.class).setEnable(true);
//Planet introduction
game.setDisplayMode(game.briefingMode);
WorldObject planetObject;
try{
final Model planetModel = rm.getBINModel(
missionTXT.getPlanetModelFile(),
rm.getRAWAsTexture(missionTXT.getPlanetTextureFile(),
getPalette(), gl, true),
8,true,getPalette(),gl);
planetObject = new WorldObject(tr,planetModel);
planetObject.setPosition(0, TR.mapSquareSize*20, 0);
add(planetObject);
planetObject.setVisible(true);
camera.probeForBehavior(FacingObject.class) .setTarget(planetObject);
camera.probeForBehavior(RotateAroundObject.class).setTarget(planetObject);
camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.05);
camera.probeForBehavior(RotateAroundObject.class).setOffset(
new double []{0,-planetModel.getTriangleList().getMaximumVertexDims().getY(),0});
camera.probeForBehavior(RotateAroundObject.class).setDistance(
planetModel.getTriangleList().getMaximumVertexDims().getX()*4);
}catch(Exception e){tr.showStopper(e);}
}//end planetDisplayMode()
public void missionCompleteSummary(LVLFile lvl, Result r){
planetDisplayMode(lvl);
final Game game = tr.getGame();
setContent("Air targets destroyed: "+r.getAirTargetsDestroyed()+
"\nGround targets destroyed: "+r.getGroundTargetsDestroyed()+
"\nVegetation destroyed: "+r.getFoliageDestroyed()+
"\nTunnels found: "+(int)(r.getTunnelsFoundPctNorm()*100.)+"%");
game.getCurrentMission().getOverworldSystem().activate();
tr.getWorld().setFogColor(Color.black);
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
final Camera camera = tr.renderer.get().getCamera();
camera.probeForBehavior(MatchPosition.class) .setEnable(true);
camera.probeForBehavior(MatchDirection.class) .setEnable(true);
camera.probeForBehavior(FacingObject.class) .setEnable(false);
camera.probeForBehavior(RotateAroundObject.class).setEnable(false);
game.getCurrentMission().getOverworldSystem().deactivate();
}//end missionCompleteSummary()
public void briefingSequence(LVLFile lvl) {
final Game game = tr.getGame();
final ResourceManager rm = tr.getResourceManager();
final Camera camera = tr.renderer.get().getCamera();
missionTXT
= rm.getMissionText(lvl.getBriefingTextFile());
planetDisplayMode(lvl);
setContent(
missionTXT.getMissionText().replace("\r","").replace("$C", ""+game.getPlayerName()));
game.getCurrentMission().getOverworldSystem().activate();
tr.getWorld().setFogColor(Color.black);
startScroll();
final boolean [] mWait = new boolean[]{false};
addScrollFinishCallback(new Runnable(){
@Override
public void run() {
synchronized(mWait){mWait[0] = true; mWait.notifyAll();}
}});
final Thread spacebarWaitThread;
(spacebarWaitThread = new Thread(){
@Override
public void run(){
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
synchronized(mWait){mWait[0] = true; mWait.notifyAll();}
}//end run()
}).start();
try{synchronized(mWait){while(!mWait[0])mWait.wait();}}
catch(InterruptedException e){}
stopScroll();
spacebarWaitThread.interrupt();
//Enemy introduction
tr.getWorld().setFogColor(game.getCurrentMission().getOverworldSystem().getFogColor());
for(EnemyIntro intro:game.getCurrentMission().getOverworldSystem().getObjectSystem().getDefPlacer().getEnemyIntros()){
final WorldObject wo = intro.getWorldObject();
camera.probeForBehavior(FacingObject.class).setTarget(wo);
camera.probeForBehavior(RotateAroundObject.class).setTarget(wo);
camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.3);
//Roughly center the object (ground objects have their bottom at Y=0)
camera.probeForBehavior(RotateAroundObject.class).setOffset(
new double []{0,wo.getModel().getTriangleList().getMaximumVertexDims().getY()/2,0});
camera.probeForBehavior(RotateAroundObject.class).setDistance(
wo.getModel().getTriangleList().getMaximumVertexDims().getX()*6);
wo.tick(System.currentTimeMillis());//Make sure its position and state is sane.
wo.setRespondToTick(false);//freeze
briefingChars.setScrollPosition(NUM_LINES-2);
setContent(intro.getDescriptionString());
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
wo.setRespondToTick(true);//unfreeze
}//end for(enemyIntros)
camera.probeForBehavior(FacingObject.class).setEnable(false);
camera.probeForBehavior(RotateAroundObject.class).setEnable(false);
camera.probeForBehavior(MatchPosition.class).setEnable(true);
camera.probeForBehavior(MatchDirection.class).setEnable(true);
}//end briefingSequence
private ColorPaletteVectorList getPalette(){
if(palette==null){
try{palette = new ColorPaletteVectorList(tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile()));}
catch(Exception e){tr.showStopper(e);}
}//end if(null)
return palette;
}//end ColorPaletteVectorList
}//end BriefingScreen |
package org.kohsuke.github;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.github.function.InputStreamFunction;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
/**
* An artifact from a workflow run.
*
* @author Guillaume Smet
*/
public class GHArtifact extends GHObject {
// Not provided by the API.
@JsonIgnore
private GHRepository owner;
private String name;
private long sizeInBytes;
private String archiveDownloadUrl;
private boolean expired;
private String expiresAt;
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the size of the artifact in bytes.
*
* @return the size
*/
public long getSizeInBytes() {
return sizeInBytes;
}
/**
* Gets the archive download URL.
*
* @return the archive download URL
*/
public URL getArchiveDownloadUrl() {
return GitHubClient.parseURL(archiveDownloadUrl);
}
/**
* If this artifact has expired.
*
* @return if the artifact has expired
*/
public boolean isExpired() {
return expired;
}
/**
* Gets the date at which this artifact will expire.
*
* @return the date of expiration
*/
public Date getExpiresAt() {
return GitHubClient.parseDate(expiresAt);
}
/**
* @deprecated This object has no HTML URL.
*/
@Override
public URL getHtmlUrl() throws IOException {
return null;
}
/**
* Deletes the artifact.
*
* @throws IOException
* the io exception
*/
public void delete() throws IOException {
root.createRequest().method("DELETE").withUrlPath(getApiRoute()).fetchHttpStatusCode();
}
/**
* Downloads the artifact.
*
* @param <T>
* the type of result
* @param streamFunction
* The {@link InputStreamFunction} that will process the stream
* @throws IOException
* The IO exception.
* @return the result of reading the stream.
*/
public <T> T download(InputStreamFunction<T> streamFunction) throws IOException {
requireNonNull(streamFunction, "Stream function must not be null");
return root.createRequest().method("GET").withUrlPath(getApiRoute(), "zip").fetchStream(streamFunction);
}
private String getApiRoute() {
if (owner == null) {
// Workflow runs returned from search to do not have an owner. Attempt to use url.
final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!");
return StringUtils.prependIfMissing(url.toString().replace(root.getApiUrl(), ""), "/");
}
return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/actions/artifacts/" + getId();
}
GHArtifact wrapUp(GHRepository owner) {
this.owner = owner;
return wrapUp(owner.root);
}
GHArtifact wrapUp(GitHub root) {
this.root = root;
if (owner != null)
owner.wrap(root);
return this;
}
} |
package org.minimalj.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.minimalj.backend.sql.LazyList;
public class CloneHelper {
/*
* With all the security checks getting a constructor is quite expensive.
* So here is a cache for the constructors for the already cloned classes.
*/
private static Map<Class<?>, Constructor<?>> contructors = new HashMap<>(200);
/**
* note: clone works only with special classes validatable through
* ModelTest .
*
* @param object the original object
* @param <T> Type of clazz itself (caller of this method doesn't need to care about this)
* @return a (deep) clone of th original object
*/
public static <T> T clone(T object) {
if (object == null) return null;
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) object.getClass();
try {
T copy = newInstance(clazz);
_deepCopy(object, copy);
return copy;
} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* note: deepCopy works only with special classes validatable through
* ModelTest .
*
* @param from the original object
* @param to an empty object to be filled
*/
public static void deepCopy(Object from, Object to) {
if (from == null) throw new IllegalArgumentException("from must not be null");
if (to == null) throw new IllegalArgumentException("to must not be null");
if (from.getClass() != to.getClass()) throw new IllegalArgumentException("from and to must have exactly same class, from has " + from.getClass() + " to has " + to.getClass());
try {
_deepCopy(from, to);
} catch (IllegalAccessException | IllegalArgumentException x) {
throw new RuntimeException(x);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void _deepCopy(Object from, Object to) throws IllegalArgumentException, IllegalAccessException {
for (Field field : from.getClass().getDeclaredFields()) {
if (FieldUtils.isStatic(field)) continue;
Object fromValue = field.get(from);
Object toValue = field.get(to);
if (fromValue instanceof List) {
List fromList = (List)fromValue;
List toList = (List)toValue;
if (fromList instanceof LazyList) {
// LazyList doesn't need to be cloned
field.set(to, fromList);
} else if (fromList != null) {
if (FieldUtils.isFinal(field)) {
toList.clear();
} else {
toList = new ArrayList<>();
field.set(to, toList);
}
for (Object element : fromList) {
toList.add(clone(element));
}
}
} else if (fromValue instanceof Set) {
Set fromSet = (Set)field.get(from);
Set toSet = (Set)toValue;
// Set can only contain enums. No need for cloning the elements.
toSet.clear();
toSet.addAll(fromSet);
} else if (isPrimitive(field)) {
if (!FieldUtils.isFinal(field)) {
field.set(to, fromValue);
}
} else if (FieldUtils.isFinal(field)) {
if (fromValue != null) {
if (toValue != null) {
deepCopy(fromValue, toValue);
} else {
throw new IllegalStateException("final field is not null in from object but null in to object. Field: " + field);
}
}
} else if (FieldUtils.isTransient(field) || fromValue == null) {
// note: transient fields are copied but not cloned!
field.set(to, toValue);
} else {
toValue = CloneHelper.clone(fromValue);
field.set(to, toValue);
}
}
}
private static boolean isPrimitive(Field field) {
String fieldTypeName = field.getType().getName();
if (field.getType().isPrimitive() || fieldTypeName.startsWith("java")) return true;
if (Enum.class.isAssignableFrom(field.getType())) return true;
return false;
}
public static <T> T newInstance(Class<T> clazz) {
@SuppressWarnings("unchecked")
Constructor<T> constructor = (Constructor<T>) contructors.get(clazz);
if (constructor == null) {
try {
constructor = clazz.getConstructor();
contructors.put(clazz, constructor);
} catch (SecurityException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
try {
T newInstance = constructor.newInstance();
return newInstance;
} catch (IllegalArgumentException |
InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.document.Classification;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.inmoov.LanguagePack;
import org.myrobotlab.inmoov.Utils;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.jme3.InMoov3DApp;
import org.myrobotlab.kinematics.DHLinkType;
import org.myrobotlab.kinematics.GravityCenter;
import org.myrobotlab.kinematics.Point;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.openni.OpenNiData;
import org.myrobotlab.openni.Skeleton;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Pin;
import org.myrobotlab.service.interfaces.IKJointAngleListener;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.myrobotlab.service.interfaces.ServoData;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.slf4j.Logger;
// FIXME - EVERYTHING .. ya EVERYTHING a local top level reference !
// TODO ALL PEERS NEED TO BE PRIVATE - ACCESS THROUGH GETTERS
// TODO ATTACH THINGS ...
// TODO implement generic bodypart to remove lot of things from here
public class InMoov extends Service implements IKJointAngleListener, JoystickListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(InMoov.class);
public InMoov(String n) {
super(n);
}
// start variables declaration
// TODO: inventory all of those vars..
private final String GESTURES_DIRECTORY = "gestures";
public String CALIBRATION_FILE = "calibration.py";
transient HashMap<String, ServoController> arduinos = new HashMap<String, ServoController>();
transient private HashMap<String, InMoovArm> arms = new HashMap<String, InMoovArm>();
transient private HashMap<String, InMoovHand> hands = new HashMap<String, InMoovHand>();
transient public final static String LEFT = "left";
transient public final static String RIGHT = "right";
boolean copyGesture = false;
public double openNiShouldersOffset = -50.0;
public boolean openNiLeftShoulderInverted = true;
public boolean openNiRightShoulderInverted = true;
boolean firstSkeleton = true;
boolean saveSkeletonFrame = false;
boolean speakErrors = false;
String lastInMoovError = "";
int maxInactivityTimeSeconds = 120;
public static int attachPauseMs = 100;
public Set<String> gesturesList = new TreeSet<String>();
private String lastGestureExecuted = "";
public static boolean RobotCanMoveHeadRandom = true;
public static boolean RobotCanMoveEyesRandom = true;
public static boolean RobotCanMoveBodyRandom = true;
public static boolean RobotCanMoveRandom = true;
public static boolean RobotIsSleeping = false;
public static boolean RobotIsStarted = false;
public Integer pirPin = null;
Long startSleep = null;
Long lastPIRActivityTime = null;
boolean useHeadForTracking = true;
boolean useEyesForTracking = false;
transient InMoov3DApp vinMoovApp;
transient LanguagePack languagePack = new LanguagePack();
private PinArrayControl pirArduino;
public static LinkedHashMap<String, String> languages = new LinkedHashMap<String, String>();
public static List<String> languagesIndex = new ArrayList<String>();
String language;
boolean mute;
static String speechService = "MarySpeech";
static String speechRecognizer = "WebkitSpeechRecognition";
// end variables
// services reservations & related extra class for custom methods & configs
transient public OpenCV opencv;
public Vision vision;
transient public SpeechRecognizer ear;
transient public SpeechSynthesis mouth;
transient public Tracking eyesTracking;
transient public Tracking headTracking;
transient public OpenNi openni;
transient public MouthControl mouthControl;
transient public Python python;
transient public InMoovHead head;
transient public InMoovTorso torso;
transient public InMoovArm leftArm;
transient public InMoovHand leftHand;
transient public InMoovArm rightArm;
transient public InMoovHand rightHand;
transient public InMoovEyelids eyelids;
transient public Pid pid;
transient public Relay LeftRelay1;
transient public Relay RightRelay1;
transient public NeoPixel neopixel;
transient public Arduino neopixelArduino;
transient public UltrasonicSensor ultrasonicSensor;
transient public ProgramAB chatBot;
transient private IntegratedMovement integratedMovement;
transient private InverseKinematics3D ik3d;
transient private JMonkeyEngine jme; // TODO - should probably be a Simulator
// interface
transient private Joystick joystick;
// end services reservations
// attach engine, more here !! later ..
public void attach(Attachable attachable) {
// opencv
if (attachable instanceof OpenCV) {
opencv = (OpenCV) attachable;
subscribe(opencv.getName(), "publishClassification");
} else if (attachable instanceof SpeechSynthesis) {
mouth = (SpeechSynthesis) attachable;
if (ear != null) {
ear.addMouth(mouth);
}
} else if (attachable instanceof SpeechRecognizer) {
ear = (SpeechRecognizer) attachable;
if (mouth != null) {
ear.addMouth(mouth);
}
} else if (attachable instanceof ProgramAB) {
chatBot = (ProgramAB) attachable;
}
}
// end attach
// VISION public methods
public void cameraOff() {
if (opencv != null) {
opencv.stopCapture();
opencv.disableAll();
}
// temporary fix overexpand windows
SwingGui gui = (SwingGui) Runtime.getService("gui");
if (gui != null) {
gui.maximize();
}
}
public void cameraOn() {
if (opencv == null) {
startOpenCV();
}
opencv.capture();
vision.enablePreFilters();
}
public boolean isCameraOn() {
if (opencv != null) {
if (opencv.isCapturing()) {
return true;
}
}
return false;
}
public void stopTracking() {
if (eyesTracking != null) {
eyesTracking.stopTracking();
}
if (headTracking != null) {
headTracking.stopTracking();
}
}
public void clearTrackingPoints() {
if (headTracking == null) {
error("attach head before tracking");
} else {
headTracking.clearTrackingPoints();
}
}
@Deprecated
public void startHeadTracking(String port, Integer rothead, Integer neck) {
log.warn("Please use ServoControl : startHeadTracking(YourServoRothead,YourServoNeck), I will try to do it for you...");
startHeadTracking();
}
public void startHeadTracking() {
startHeadTracking(head.rothead, head.neck);
}
public void startHeadTracking(ServoControl rothead, ServoControl neck) {
if (opencv == null) {
log.warn("Tracking needs Opencv activated, I will try to lauch it. It is better if you DIY");
startOpenCV();
}
if (headTracking == null) {
speakBlocking(languagePack.get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.opencv, rothead, neck);
}
}
@Deprecated
public void startEyesTracking(String port, Integer eyeX, Integer eyeY) {
log.warn("Please use ServoControl : startEyesTracking(ServoX,ServoY), I will try to do it for you...");
startEyesTracking();
}
public void startEyesTracking() {
startEyesTracking(head.eyeX, head.eyeY);
}
public void startEyesTracking(ServoControl eyeX, ServoControl eyeY) {
if (opencv == null) {
log.warn("Tracking needs Opencv activated, I will try to lauch it. It is better if you DIY");
startOpenCV();
}
speakBlocking(languagePack.get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.connect(this.opencv, head.eyeX, head.eyeY);
}
public void trackHumans() {
// FIXME can't have 2 PID for tracking
// if (eyesTracking != null) {
// eyesTracking.faceDetect();
vision.enablePreFilters();
startHeadTracking();
if (headTracking != null) {
headTracking.faceDetect();
}
}
// FIXME check / test lk tracking..
public void trackPoint() {
vision.enablePreFilters();
startHeadTracking();
if (headTracking != null) {
headTracking.startLKTracking();
headTracking.trackPoint();
}
}
public void onClassification(TreeMap<String, List<Classification>> classifications) {
vision.yoloInventory(classifications);
}
// END VISION methods
// OPENNI methods
@Deprecated
public boolean RobotIsOpenCvCapturing() {
if (opencv != null)
return opencv.isCapturing();
return false;
}
// TODO:change -> isOpenNiCapturing
@Deprecated
public boolean RobotIsOpenNiCapturing() {
if (openni != null) {
if (openni.capturing) {
return true;
}
}
return false;
}
public void onOpenNIData(OpenNiData data) {
if (data != null) {
Skeleton skeleton = data.skeleton;
if (firstSkeleton) {
speakBlocking("i see you");
firstSkeleton = false;
}
if (copyGesture) {
if (leftArm != null) {
if (!Double.isNaN(skeleton.leftElbow.getAngleXY())) {
if (skeleton.leftElbow.getAngleXY() >= 0) {
leftArm.bicep.moveTo((double)skeleton.leftElbow.getAngleXY());
}
}
if (!Double.isNaN(skeleton.leftShoulder.getAngleXY())) {
if (skeleton.leftShoulder.getAngleXY() >= 0) {
leftArm.omoplate.moveTo((double)skeleton.leftShoulder.getAngleXY());
}
}
if (!Double.isNaN(skeleton.leftShoulder.getAngleYZ())) {
if (skeleton.leftShoulder.getAngleYZ() + openNiShouldersOffset >= 0) {
leftArm.shoulder.moveTo((double)skeleton.leftShoulder.getAngleYZ() - 50);
}
}
}
if (rightArm != null) {
if (!Double.isNaN(skeleton.rightElbow.getAngleXY())) {
if (skeleton.rightElbow.getAngleXY() >= 0) {
rightArm.bicep.moveTo((double)skeleton.rightElbow.getAngleXY());
}
}
if (!Double.isNaN(skeleton.rightShoulder.getAngleXY())) {
if (skeleton.rightShoulder.getAngleXY() >= 0) {
rightArm.omoplate.moveTo((double)skeleton.rightShoulder.getAngleXY());
}
}
if (!Double.isNaN(skeleton.rightShoulder.getAngleYZ())) {
if (skeleton.rightShoulder.getAngleYZ() + openNiShouldersOffset >= 0) {
rightArm.shoulder.moveTo((double)skeleton.rightShoulder.getAngleYZ() - 50);
}
}
}
}
}
// TODO - route data appropriately
// rgb & depth image to OpenCV
// servos & depth image to gui (entire InMoov + references to servos)
}
// END OPENNI methods
// START GESTURES related methods
public void loadGestures() {
loadGestures(GESTURES_DIRECTORY);
}
/**
* This method will try to launch a python command with error handling
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
*/
public boolean loadGestures(String directory) {
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = Utils.makeDirectory(directory);
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (Utils.loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
gesturesList.add(f.getName());
} else {
totalError += 1;
}
} else {
log.warn("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
if (totalError > 0) {
speakAlert(languagePack.get("GESTURE_ERROR"));
return false;
}
return true;
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public String captureGesture() {
return captureGesture(null);
}
public String captureGesture(String gestureName) {
StringBuffer script = new StringBuffer();
Date date = new Date();
String indentSpace = "";
script.append("# - " + date + " - Captured gesture :\n");
if (gestureName != null) {
indentSpace = " ";
script.append(String.format("def %s():\n", gestureName));
}
if (head != null) {
script.append(indentSpace);
script.append(head.getScript(getName()));
}
if (leftArm != null) {
script.append(indentSpace);
script.append(leftArm.getScript(getName()));
}
if (rightArm != null) {
script.append(indentSpace);
script.append(rightArm.getScript(getName()));
}
if (leftHand != null) {
script.append(indentSpace);
script.append(leftHand.getScript(getName()));
}
if (rightHand != null) {
script.append(indentSpace);
script.append(rightHand.getScript(getName()));
}
if (torso != null) {
script.append(indentSpace);
script.append(torso.getScript(getName()));
}
if (eyelids != null) {
script.append(indentSpace);
script.append(eyelids.getScript(getName()));
}
send("python", "appendScript", script.toString());
return script.toString();
}
public boolean copyGesture(boolean b) throws Exception {
log.info("copyGesture {}", b);
if (b) {
if (openni == null) {
openni = startOpenNI();
}
speakBlocking("copying gestures");
openni.startUserTracking();
} else {
speakBlocking("stop copying gestures");
if (openni != null) {
openni.stopCapture();
firstSkeleton = true;
}
}
copyGesture = b;
return b;
}
public void savePose(String poseName) {
// TODO: consider a prefix for the pose name?
captureGesture(poseName);
}
public void saveGesture(String gestureName, String directory) {
// TODO: consider the gestures directory as a property on the inmoov
String gestureMethod = mapGestureNameToPythonMethod(gestureName);
String gestureFilename = directory + File.separator + gestureMethod + ".py";
File gestureFile = new File(gestureFilename);
if (gestureFile.exists()) {
log.warn("Gesture file {} already exists.. not overwiting it.", gestureFilename);
return;
}
FileWriter gestureWriter = null;
try {
gestureWriter = new FileWriter(gestureFile);
// print the first line of the python file
gestureWriter.write("def " + gestureMethod + "():\n");
// now for each servo, we should write out the approperiate moveTo
// statement
// TODO: consider doing this only for the inmoov services.. but for now..
// i think
// we want all servos that are currently in the system?
for (ServiceInterface service : Runtime.getServices()) {
if (ServoControl.class.isAssignableFrom(service.getClass())) {
double pos = ((ServoControl) service).getPos();
gestureWriter.write(" " + service.getName() + ".moveTo(" + pos + ")\n");
}
}
gestureWriter.write("\n");
gestureWriter.close();
} catch (IOException e) {
log.warn("Error writing gestures file {}", gestureFilename);
e.printStackTrace();
return;
}
// TODO: consider writing out cooresponding AIML?
}
private String mapGestureNameToPythonMethod(String gestureName) {
// TODO: some fancier mapping?
String methodName = gestureName.replaceAll(" ", "");
return methodName;
}
public void saveGesture(String gestureName) {
// TODO: allow a user to save a gesture to the gestures directory
saveGesture(gestureName, GESTURES_DIRECTORY);
}
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
// END GESTURES
// SKELETON RELATED METHODS
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
if (eyelids != null) {
eyelids.enable();
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
if (eyelids != null) {
eyelids.disable();
}
}
public void fullSpeed() {
if (head != null) {
head.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (rightHand != null) {
rightHand.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (leftHand != null) {
leftHand.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (rightArm != null) {
rightArm.setVelocity(-1.0, -1.0, -1.0, -1.0);
}
if (leftArm != null) {
leftArm.setVelocity(-1.0, -1.0, -1.0, -1.0);
}
if (torso != null) {
torso.setVelocity(-1.0, -1.0, -1.0);
}
if (eyelids != null) {
eyelids.setVelocity(-1.0, -1.0);
}
}
public void halfSpeed() {
if (head != null) {
head.setVelocity(25.0, 25.0, 25.0, 25.0, -1.0, 25.0);
}
if (rightHand != null) {
rightHand.setVelocity(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setVelocity(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setVelocity(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setVelocity(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setVelocity(20.0, 20.0, 20.0);
}
if (eyelids != null) {
eyelids.setVelocity(30.0, 30.0);
}
}
public boolean isAttached() {
boolean attached = false;
if (leftHand != null) {
attached |= leftHand.isAttached();
}
if (leftArm != null) {
attached |= leftArm.isAttached();
}
if (rightHand != null) {
attached |= rightHand.isAttached();
}
if (rightArm != null) {
attached |= rightArm.isAttached();
}
if (head != null) {
attached |= head.isAttached();
}
if (torso != null) {
attached |= torso.isAttached();
}
if (eyelids != null) {
attached |= eyelids.isAttached();
}
return attached;
}
public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) {
if (!arms.containsKey(which)) {
error("setArmSpeed %s does not exist", which);
} else {
arms.get(which).moveTo(bicep, rotate, shoulder, omoplate);
}
}
public void moveEyes(double eyeX, double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.error("moveEyes - I have a null head");
}
}
public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("moveHand %s does not exist", which);
} else {
hands.get(which).moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
public void moveHead(double neck, double rothead) {
moveHead(neck, rothead, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(neck, rothead, null, null, null, rollNeck);
}
public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void moveEyelids(double eyelidleft, double eyelidright) {
if (eyelids != null) {
eyelids.moveTo(eyelidleft, eyelidright);
} else {
log.error("moveEyelids - I have a null Eyelids");
}
}
public void moveHeadBlocking(double neck, double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(double neck, double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void waitTargetPos() {
if (head != null)
head.waitTargetPos();
if (eyelids != null)
eyelids.waitTargetPos();
if (leftArm != null)
leftArm.waitTargetPos();
if (rightArm != null)
rightArm.waitTargetPos();
if (leftHand != null)
leftHand.waitTargetPos();
if (rightHand != null)
rightHand.waitTargetPos();
if (torso != null)
torso.waitTargetPos();
}
public void rest() {
log.info("InMoov Native Rest Gesture Called");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
if (eyelids != null) {
eyelids.rest();
}
}
@Deprecated
public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
if (!arms.containsKey(which)) {
error("setArmSpeed %s does not exist", which);
} else {
arms.get(which).setSpeed(bicep, rotate, shoulder, omoplate);
}
}
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
if (!arms.containsKey(which)) {
error("setArmVelocity %s does not exist", which);
} else {
arms.get(which).setVelocity(bicep, rotate, shoulder, omoplate);
}
}
@Deprecated
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandVelocity(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("setHandSpeed %s does not exist", which);
} else {
hands.get(which).setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("setHandSpeed %s does not exist", which);
} else {
hands.get(which).setVelocity(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
@Deprecated
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadVelocity(Double rothead, Double neck) {
setHeadVelocity(rothead, neck, null, null, null, null);
}
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadVelocity(rothead, neck, null, null, null, rollNeck);
}
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadVelocity(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
if (head != null) {
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed);
} else {
log.warn("setHeadSpeed - I have no head");
}
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head != null) {
head.setVelocity(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
} else {
log.warn("setHeadVelocity - I have no head");
}
}
@Deprecated
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
public void setEyelidsVelocity(Double eyelidleft, Double eyelidright) {
if (eyelids != null) {
eyelids.setVelocity(eyelidleft, eyelidright);
} else {
log.warn("setEyelidsVelocity - I have no eyelids");
}
}
public InMoovArm startArm(String side, String port, String type) throws Exception {
// TODO rework this...
if (type == "left") {
speakBlocking(languagePack.get("STARTINGLEFTARM") + " " + port);
} else {
speakBlocking(languagePack.get("STARTINGRIGHTARM") + " " + port);
}
InMoovArm arm = (InMoovArm) startPeer(String.format("%sArm", side));
arms.put(side, arm);
arm.setSide(side);// FIXME WHO USES SIDE - THIS SHOULD BE NAME !!!
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// arm.arduino.setBoard(type); FIXME - this is wrong setting to Mega ...
// what if its a USB or I2C ???
arm.connect(port); // FIXME are all ServoControllers "connectable" ?
arduinos.put(port, arm.controller);
return arm;
}
public InMoovHand startHand(String side, String port, String type) throws Exception {
// TODO rework this...
if (type == "left") {
speakBlocking(languagePack.get("STARTINGLEFTHAND") + " " + port);
} else {
speakBlocking(languagePack.get("STARTINGRIGHTHAND") + " " + port);
}
InMoovHand hand = (InMoovHand) startPeer(String.format("%sHand", side));
hand.setSide(side);
hands.put(side, hand);
// FIXME - this is wrong ! its configuratin of an Arduino, (we may not have
// an Arduino !!!)
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// hand.arduino.setBoard(type);
hand.connect(port);
arduinos.put(port, hand.controller);
return hand;
}
public InMoovHead startHead(String port) throws Exception {
return startHead(port, null, 12, 13, 22, 24, 26, 30);
}
public InMoovHead startHead(String port, String type) throws Exception {
return startHead(port, type, 12, 13, 22, 24, 26, 30);
}
public InMoovHead startHead(String port, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) throws Exception {
return startHead(port, null, headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
public InMoovHead startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin)
throws Exception {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
speakBlocking(languagePack.get("STARTINGHEAD") + " " + port);
head = (InMoovHead) startPeer("head");
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// FIXME - !!! => cannot do this "here" ??? head.arduino.setBoard(type);
head.connect(port, headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
arduinos.put(port, head.controller);
return head;
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
if (eyelids != null) {
eyelids.setAutoDisable(param);
}
}
public InMoovArm startLeftArm(String port) throws Exception {
return startLeftArm(port, null);
}
public InMoovArm startLeftArm(String port, String type) throws Exception {
leftArm = startArm(LEFT, port, type);
return leftArm;
}
public InMoovHand startLeftHand(String port) throws Exception {
return startLeftHand(port, null);
}
public InMoovHand startLeftHand(String port, String type) throws Exception {
leftHand = startHand(LEFT, port, type);
return leftHand;
}
public InMoovArm startRightArm(String port) throws Exception {
return startRightArm(port, null);
}
public InMoovArm startRightArm(String port, String type) throws Exception {
if (rightArm != null) {
info("right arm already started");
return rightArm;
}
rightArm = startArm(RIGHT, port, type);
return rightArm;
}
public InMoovHand startRightHand(String port) throws Exception {
return startRightHand(port, null);
}
public InMoovHand startRightHand(String port, String type) throws Exception {
rightHand = startHand(RIGHT, port, type);
return rightHand;
}
/*
* New startEyelids attach method ( for testing );
*/
public InMoovEyelids startEyelids(ServoController controller, Integer eyeLidLeftPin, Integer eyeLidRightPin) throws Exception {
eyelids = (InMoovEyelids) startPeer("eyelids");
eyelids.attach(controller, eyeLidLeftPin, eyeLidRightPin);
return eyelids;
}
// END SKELETON RELATED METHODS
// GENERAL METHODS / TO SORT
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds && isAttached()) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
String getBoardType(String side, String type) {
if (type != null) {
return type;
}
if (RIGHT.equals(side)) {
return Arduino.BOARD_TYPE_MEGA;
}
return Arduino.BOARD_TYPE_MEGA;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (eyelids != null) {
lastActivityTime = Math.max(lastActivityTime, eyelids.getLastActivityTime());
}
if (lastPIRActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPIRActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public Python getPython() {
try {
if (python == null) {
python = (Python) startPeer("python");
}
} catch (Exception e) {
error(e);
}
return python;
}
public boolean isMute() {
return mute;
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
startSleep = System.currentTimeMillis();
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
startSleep = null;
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
// TODO FIX/CHECK this, migrate from python land
public void publishPin(Pin pin) {
log.info("{} - {}", pin.pin, pin.value);
if (pin.value == 1) {
lastPIRActivityTime = System.currentTimeMillis();
}
// if its PIR & PIR is active & was sleeping - then wake up !
if (pirPin == pin.pin && startSleep != null && pin.value == 1) {
// attach(); // good morning / evening / night... asleep for % hours
powerUp();
// Calendar now = Calendar.getInstance();
/*
* FIXME - make a getSalutation String salutation = "hello "; if
* (now.get(Calendar.HOUR_OF_DAY) < 12) { salutation = "good morning "; }
* else if (now.get(Calendar.HOUR_OF_DAY) < 16) { salutation =
* "good afternoon "; } else { salutation = "good evening "; }
*
*
* speakBlocking(String.format("%s. i was sleeping but now i am awake" ,
* salutation));
*/
}
}
@Override
public void purgeTasks() {
speakBlocking("purging all tasks");
super.purgeTasks();
}
@Override
public boolean save() {
super.save();
if (leftHand != null) {
leftHand.save();
}
if (rightHand != null) {
rightHand.save();
}
if (rightArm != null) {
rightArm.save();
}
if (leftArm != null) {
leftArm.save();
}
if (head != null) {
head.save();
}
if (openni != null) {
openni.save();
}
return true;
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
}
public List<AudioData> speakBlocking(String toSpeak) {
if (mouth == null) {
mouth = (SpeechSynthesis)startPeer("mouth");
}
if (mouth == null) {
log.error("speakBlocking is called, but my mouth is NULL...");
return null;
}
if (!mute) {
try {
return mouth.speakBlocking(toSpeak);
} catch (Exception e) {
log.error("speakBlocking threw", e);
}
}
return null;
}
public List<AudioData> speakAlert(String toSpeak) {
speakBlocking(languagePack.get("ALERT"));
return speakBlocking(toSpeak);
}
public List<AudioData> speak(String toSpeak) {
if (mouth == null) {
log.error("Speak is called, but my mouth is NULL...");
return null;
}
if (!mute) {
try {
return mouth.speak(toSpeak);
} catch (Exception e) {
Logging.logError(e);
}
}
return null;
}
public boolean speakErrors(boolean b) {
speakErrors = b;
return b;
}
// FIXME , later ... attach things !
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startHead(leftPort);
startOpenCV();
startEar();
startMouthControl(head.jaw, mouth);
startLeftHand(leftPort);
startRightHand(rightPort);
// startEyelids(rightPort);
startLeftArm(leftPort);
startRightArm(rightPort);
startTorso(leftPort);
startHeadTracking();
startEyesTracking();
// TODO LP
speakBlocking("startup sequence completed");
}
/**
* Start InMoov brain engine And extra stuffs, like "what is you name" ( TODO
* finish migration )
*
* @return started ProgramAB service
*/
public ProgramAB startBrain() {
if (chatBot == null) {
chatBot = (ProgramAB) Runtime.start(this.getIntanceName() + ".brain", "ProgramAB");
}
this.attach(chatBot);
speakBlocking(languagePack.get("CHATBOTACTIVATED"));
chatBot.repetitionCount(10);
chatBot.setPath("InMoov/chatBot");
chatBot.startSession("default", getLanguage());
// reset some parameters to default...
chatBot.setPredicate("topic", "default");
chatBot.setPredicate("questionfirstinit", "");
chatBot.setPredicate("tmpname", "");
chatBot.setPredicate("null", "");
// load last user session
if (!chatBot.getPredicate("name").isEmpty()) {
if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown")) {
chatBot.setPredicate("lastUsername", chatBot.getPredicate("name"));
}
}
chatBot.setPredicate("parameterHowDoYouDo", "");
try {
chatBot.savePredicates();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// start session based on last recognized person
if (!chatBot.getPredicate("default", "lastUsername").isEmpty() && !chatBot.getPredicate("default", "lastUsername").equals("unknown")) {
chatBot.startSession(chatBot.getPredicate("lastUsername"));
}
return chatBot;
}
// TODO TODO TODO - context & status report -
// "current context is right hand"
// FIXME - voice control for all levels (ie just a hand or head !!!!)
public SpeechRecognizer startEar() {
if (ear == null) {
ear = (SpeechRecognizer) startPeer("ear");
}
this.attach((Attachable) ear);
speakBlocking(languagePack.get("STARTINGEAR"));
return ear;
}
public SpeechSynthesis startMouth() {
if (mouth == null) {
mouth = (SpeechSynthesis) startPeer("mouth");
}
this.attach((Attachable) mouth);
speakBlocking(languagePack.get("STARTINGMOUTH"));
speakBlocking(languagePack.get("WHATISTHISLANGUAGE"));
return mouth;
}
@Deprecated
public MouthControl startMouthControl(String port) {
log.warn("Please use ServoControl : startMouthControl(YourServoJaw,mouthService), I will try to do it for you...");
return startMouthControl();
}
public MouthControl startMouthControl() {
return startMouthControl(head.jaw, mouth);
}
public MouthControl startMouthControl(ServoControl jaw, SpeechSynthesis mouth) {
speakBlocking(languagePack.get("STARTINGMOUTHCONTROL"));
if (mouthControl == null) {
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(jaw);
mouthControl.attach((Attachable) mouth);
mouthControl.setmouth(10, 50);
}
return mouthControl;
}
public boolean startOpenCV() {
speakBlocking(languagePack.get("STARTINGOPENCV"));
if (opencv == null) {
opencv = (OpenCV) Runtime.loadAndStart(this.getIntanceName() + ".opencv", "OpenCV");
}
this.attach(opencv);
if (vision.openCVenabled) {
// test for a worky opencv with hardware
// TODO: revisit this test method. , maybe it should go away or be done differently?
// It forces capture
if (vision.test()) {
broadcastState();
return true;
} else {
speakAlert(languagePack.get("OPENCVNOWORKY"));
return false;
}
}
return false;
}
public OpenNi startOpenNI() throws Exception {
if (openni == null) {
speakBlocking(languagePack.get("STARTINGOPENNI"));
openni = (OpenNi) startPeer("openni");
pid = (Pid) startPeer("pid");
pid.setPID("kinect", 10.0, 0.0, 1.0);
pid.setMode("kinect", Pid.MODE_AUTOMATIC);
pid.setOutputRange("kinect", -1, 1);
pid.setControllerDirection("kinect", 0);
// re-mapping of skeleton !
openni.skeleton.leftElbow.mapXY(0, 180, 180, 0);
openni.skeleton.rightElbow.mapXY(0, 180, 180, 0);
if (openNiLeftShoulderInverted) {
openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0);
}
if (openNiRightShoulderInverted) {
openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0);
}
// openni.skeleton.leftShoulder
// openni.addListener("publishOpenNIData", this.getName(),
// "getSkeleton");
// openni.addOpenNIData(this);
subscribe(openni.getName(), "publishOpenNIData");
}
return openni;
}
public void startPIR(String port, int pin) throws IOException {
speakBlocking(String.format("starting pee. eye. are. sensor on port %s pin %d", port, pin));
if (arduinos.containsKey(port)) {
ServoController sc = arduinos.get(port);
if (sc instanceof Arduino) {
Arduino arduino = (Arduino) sc;
// arduino.connect(port);
// arduino.setSampleRate(8000);
arduino.enablePin(pin, 10);
pirArduino = arduino;
pirPin = pin;
arduino.addListener("publishPin", this.getName(), "publishPin");
}
} else {
// FIXME - SHOULD ALLOW STARTUP AND LATER ACCESS VIA PORT ONCE OTHER
// STARTS CHECK MAP FIRST
log.error("{} arduino not found - start some other system first (head, arm, hand)", port);
}
}
@Override
public void preShutdown() {
RobotCanMoveRandom = false;
stopTracking();
speakBlocking(languagePack.get("SHUTDOWN"));
halfSpeed();
rest();
waitTargetPos();
// if relay used, we switch on power
if (LeftRelay1 != null) {
LeftRelay1.on();
}
if (RightRelay1 != null) {
RightRelay1.on();
}
if (eyelids != null) {
eyelids.autoBlink(false);
eyelids.moveToBlocking(180, 180);
}
stopVinMoov();
if (neopixel != null && neopixelArduino != null) {
neopixel.animationStop();
sleep(500);
neopixel.detach(neopixelArduino);
sleep(100);
neopixelArduino.serial.disconnect();
neopixelArduino.serial.stopRecording();
neopixelArduino.disconnect();
}
disable();
if (LeftRelay1 != null) {
LeftRelay1.off();
}
if (RightRelay1 != null) {
RightRelay1.off();
}
}
@Override
public void startService() {
super.startService();
if (vision == null) {
vision = new Vision();
vision.init();
}
vision.instance = this;
// TODO : use locale it-IT,fi-FI
languages.put("en-US", "English - United States");
languages.put("fr-FR", "French - France");
languages.put("es-ES", "Spanish - Spain");
languages.put("de-DE", "German - Germany");
languages.put("nl-NL", "Dutch - Netherlands");
languages.put("ru-RU", "Russian");
languages.put("hi-IN", "Hindi - India");
languages.put("it-IT", "Italian - Italia");
languages.put("fi-FI", "Finnish - Finland");
languages.put("pt-PT", "Portuguese - Portugal");
languagesIndex = new ArrayList<String>(languages.keySet());
this.language = getLanguage();
python = getPython();
languagePack.load(language);
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
}
public InMoovTorso startTorso(String port) throws Exception {
return startTorso(port, null);
}
public InMoovTorso startTorso(String port, String type) throws Exception {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
speakBlocking(languagePack.get("STARTINGTORSO") + " " + port);
torso = (InMoovTorso) startPeer("torso");
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// FIXME - needs to be a ServoController
// torso.arduino.setBoard(type);
torso.connect(port);
arduinos.put(port, torso.controller);
return torso;
}
public void stopPIR() {
if (pirArduino != null && pirPin != null) {
pirArduino.disablePin(pirPin);
pirPin = null;
pirArduino = null;
}
/*
* if (arduinos.containsKey(port)) { Arduino arduino = arduinos.get(port);
* arduino.connect(port); arduino.setSampleRate(8000);
* arduino.digitalReadPollStart(pin); pirPin = pin;
* arduino.addListener("publishPin", this.getName(), "publishPin"); }
*/
}
// This is an in-flight check vs power up or power down
public void systemCheck() {
speakBlocking("starting system check");
speakBlocking("testing");
rest();
sleep(500);
if (rightHand != null) {
speakBlocking("testing right hand");
rightHand.test();
}
if (rightArm != null) {
speakBlocking("testing right arm");
rightArm.test();
}
if (leftHand != null) {
speakBlocking("testing left hand");
leftHand.test();
}
if (leftArm != null) {
speakBlocking("testing left arm");
leftArm.test();
}
if (head != null) {
speakBlocking("testing head");
head.test();
}
if (torso != null) {
speakBlocking("testing torso");
torso.test();
}
if (eyelids != null) {
speakBlocking("testing eyelids");
eyelids.test();
}
sleep(500);
rest();
broadcastState();
speakBlocking("system check completed");
}
public void loadCalibration() {
loadCalibration(CALIBRATION_FILE);
}
public void loadCalibration(String calibrationFilename) {
File calibF = new File(calibrationFilename);
if (calibF.exists()) {
log.info("Loading Calibration Python file {}", calibF.getAbsolutePath());
Python p = (Python) Runtime.getService("python");
try {
p.execFile(calibF.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
log.warn("Error loading calibratoin file {}", calibF.getAbsolutePath());
e.printStackTrace();
}
}
}
public void saveCalibration() {
saveCalibration(CALIBRATION_FILE);
}
public void saveCalibration(String calibrationFilename) {
File calibFile = new File(calibrationFilename);
FileWriter calibrationWriter = null;
try {
calibrationWriter = new FileWriter(calibFile);
calibrationWriter.write("
calibrationWriter.write("# InMoov auto generated calibration \n");
calibrationWriter.write("# " + new Date() + "\n");
calibrationWriter.write("
// String inMoovName = this.getName();
// iterate all the services that are running.
// we want all servos that are currently in the system?
for (ServiceInterface service : Runtime.getServices()) {
if (service instanceof ServoControl) {
ServoControl s = (Servo) service;
if (!s.getName().startsWith(this.getName())) {
continue;
}
calibrationWriter.write("\n");
// first detach the servo.
calibrationWriter.write("# Servo Config : " + s.getName() + "\n");
calibrationWriter.write(s.getName() + ".detach()\n");
calibrationWriter.write(s.getName() + ".setMinMax(" + s.getMin() + "," + s.getMax() + ")\n");
calibrationWriter.write(s.getName() + ".setVelocity(" + s.getSpeed() + ")\n");
calibrationWriter.write(s.getName() + ".setRest(" + s.getRest() + ")\n");
if (s.getPin() != null) {
calibrationWriter.write(s.getName() + ".setPin(" + s.getPin() + ")\n");
} else {
calibrationWriter.write("# " + s.getName() + ".setPin(" + s.getPin() + ")\n");
}
s.map(s.getMin(), s.getMax(), s.getMinOutput(), s.getMaxOutput());
// save the servo map
calibrationWriter.write(s.getName() + ".map(" + s.getMin() + "," + s.getMax() + "," + s.getMinOutput() + "," + s.getMaxOutput() + ")\n");
// if there's a controller reattach it at rest
if (s.getControllerName() != null) {
String controller = s.getControllerName();
calibrationWriter.write(s.getName() + ".attach(\"" + controller + "\"," + s.getPin() + "," + s.getRest() + ")\n");
}
if (s.getAutoDisable()) {
calibrationWriter.write(s.getName() + ".setAutoDisable(True)\n");
}
}
}
calibrationWriter.write("\n");
calibrationWriter.close();
} catch (IOException e) {
log.warn("Error writing calibration file {}", calibrationFilename);
e.printStackTrace();
return;
}
}
// vinmoov cosmetics and optional vinmoov monitor idea ( poc i know nothing
// about jme...)
// just want to use jme as main screen and show some informations
// like batterie / errors / onreconized text etc ...
// i01.VinmoovMonitorActivated=1 before to start vinmoov
public Boolean VinmoovMonitorActivated = false;
public void onListeningEvent() {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setMicro(true);
}
}
public void onPauseListening() {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setMicro(false);
}
}
public void setBatteryLevel(Integer level) {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setBatteryLevel(level);
}
}
public Boolean VinmoovFullScreen = false;
public String VinmoovBackGroundColor = "Grey";
public int VinmoovWidth = 800;
public int VinmoovHeight = 600;
private Boolean debugVinmoov = true;
// show some infos to jme screen
public void setLeftArduinoConnected(boolean param) {
vinMoovApp.setLeftArduinoConnected(param);
}
public void setRightArduinoConnected(boolean param) {
vinMoovApp.setRightArduinoConnected(param);
}
// end vinmoov cosmetics and optional vinmoov monitor
/* use the most recent virtual inmoov */
public void onIKServoEvent(ServoData data) {
if (vinMoovApp != null) {
vinMoovApp.updatePosition(data);
}
}
public void stopVinMoov() {
try {
vinMoovApp.stop();
} catch (NullPointerException e) {
}
vinMoovApp = null;
}
public void startIntegratedMovement() {
integratedMovement = (IntegratedMovement) startPeer("integratedMovement");
IntegratedMovement im = integratedMovement;
// set the DH Links or each arms
im.setNewDHRobotArm("leftArm");
im.setNewDHRobotArm("rightArm");
im.setNewDHRobotArm("kinect");
if (torso != null) {
im.setDHLink("leftArm", torso.midStom, 113, 90, 0, -90);
im.setDHLink("rightArm", torso.midStom, 113, 90, 0, -90);
im.setDHLink("kinect", torso.midStom, 113, 90, 0, -90);
im.setDHLink("leftArm", torso.topStom, 0, 180, 292, 90);
im.setDHLink("rightArm", torso.topStom, 0, 180, 292, 90);
im.setDHLink("kinect", torso.topStom, 0, 180, 110, -90);
} else {
im.setDHLink("leftArm", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("rightArm", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("kinect", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("leftArm", "i01.torso.topStom", 0, 180, 292, 90);
im.setDHLink("rightArm", "i01.torso.topStom", 0, 180, 292, 90);
im.setDHLink("kinect", "i01.torso.topStom", 0, 180, 110, -90);
}
im.setDHLink("leftArm", "leftS", 143, 180, 0, 90);
im.setDHLink("rightArm", "rightS", -143, 180, 0, -90);
if (arms.containsKey(LEFT)) {
InMoovArm arm = arms.get(LEFT);
im.setDHLink("leftArm", arm.omoplate, 0, -5.6, 45, -90);
im.setDHLink("leftArm", arm.shoulder, 77, -30 + 90, 0, 90);
im.setDHLink("leftArm", arm.rotate, 284, 90, 40, 90);
im.setDHLink("leftArm", arm.bicep, 0, -7 + 24.4 + 90, 300, 90);
} else {
im.setDHLink("leftArm", "i01.leftArm.omoplate", 0, -5.6, 45, -90);
im.setDHLink("leftArm", "i01.leftArm.shoulder", 77, -30 + 90, 0, 90);
im.setDHLink("leftArm", "i01.leftArm.rotate", 284, 90, 40, 90);
im.setDHLink("leftArm", "i01.leftArm.bicep", 0, -7 + 24.4 + 90, 300, 90);
}
if (arms.containsKey(RIGHT)) {
InMoovArm arm = arms.get(RIGHT);
im.setDHLink("rightArm", arm.omoplate, 0, -5.6, 45, 90);
im.setDHLink("rightArm", arm.shoulder, -77, -30 + 90, 0, -90);
im.setDHLink("rightArm", arm.rotate, -284, 90, 40, -90);
im.setDHLink("rightArm", arm.bicep, 0, -7 + 24.4 + 90, 300, 0);
} else {
im.setDHLink("rightArm", "i01.rightArm.omoplate", 0, -5.6, 45, 90);
im.setDHLink("rightArm", "i01.rightArm.shoulder", -77, -30 + 90, 0, -90);
im.setDHLink("rightArm", "i01.rightArm.rotate", -284, 90, 40, -90);
im.setDHLink("rightArm", "i01.rightArm.bicep", 0, -7 + 24.4 + 90, 300, 0);
}
if (hands.containsKey(LEFT)) {
InMoovHand hand = hands.get(LEFT);
im.setDHLink("leftArm", hand.wrist, 00, -90, 0, 0);
im.setDHLinkType("i01.leftHand.wrist", DHLinkType.REVOLUTE_ALPHA);
} else {
im.setDHLink("leftArm", "i01.leftHand.wrist", 00, -90, 0, 0);
}
if (hands.containsKey(RIGHT)) {
InMoovHand hand = hands.get(RIGHT);
im.setDHLink("rightArm", hand.wrist, 00, -90, 0, 0);
im.setDHLinkType("i01.rigtHand.wrist", DHLinkType.REVOLUTE_ALPHA);
} else {
im.setDHLink("rightArm", "i01.rightHand.wrist", 00, -90, 0, 0);
}
im.setDHLink("leftArm", "wristup", 0, -5, 90, 0);
im.setDHLink("leftArm", "wristdown", 0, 0, 125, 45);
im.setDHLink("leftArm", "finger", 5, -90, 5, 0);
im.setDHLink("rightArm", "Rwristup", 0, 5, 90, 0);
im.setDHLink("rightArm", "Rwristdown", 0, 0, 125, -45);
im.setDHLink("rightArm", "Rfinger", 5, 90, 5, 0);
im.setDHLink("kinect", "camera", 0, 90, 10, 90);
// log.info("{}",im.createJointPositionMap("leftArm").toString());
// start the kinematics engines
// define object, each dh link are set as an object, but the
// start point and end point will be update by the ik service, but still
// need
// a name and a radius
im.clearObject();
im.addObject(0.0, 0.0, 0.0, 0.0, 0.0, -150.0, "base", 150.0, false);
im.addObject("i01.torso.midStom", 150.0);
im.addObject("i01.torso.topStom", 10.0);
im.addObject("i01.leftArm.omoplate", 10.0);
im.addObject("i01.rightArm.omoplate", 10.0);
im.addObject("i01.leftArm.shoulder", 50.0);
im.addObject("i01.rightArm.shoulder", 50.0);
im.addObject("i01.leftArm.rotate", 50.0);
im.addObject("i01.rightArm.rotate", 50.0);
im.addObject("i01.leftArm.bicep", 60.0);
im.addObject("i01.rightArm.bicep", 60.0);
im.addObject("i01.leftHand.wrist", 70.0);
im.addObject("i01.rightHand.wrist", 70.0);
im.objectAddIgnore("i01.rightArm.omoplate", "i01.leftArm.rotate");
im.objectAddIgnore("i01.rightArm.omoplate", "i01.rightArm.rotate");
im.addObject("leftS", 10);
im.addObject("rightS", 10);
im.objectAddIgnore("leftS", "rightS");
im.objectAddIgnore("rightS", "i01.leftArm.shoulder");
im.objectAddIgnore("leftS", "i01.rightArm.shoulder");
im.addObject("wristup", 70);
im.addObject("wristdown", 70);
im.objectAddIgnore("i01.leftArm.bicep", "wristup");
im.addObject("Rwristup", 70);
im.addObject("Rwristdown", 70);
im.objectAddIgnore("i01.rightArm.bicep", "Rwristup");
im.startEngine("leftArm");
im.startEngine("rightArm");
im.startEngine("kinect");
im.cog = new GravityCenter(im);
im.cog.setLinkMass("i01.torso.midStom", 2.832, 0.5);
im.cog.setLinkMass("i01.torso.topStom", 5.774, 0.5);
im.cog.setLinkMass("i01.leftArm.omoplate", 0.739, 0.5);
im.cog.setLinkMass("i01.rightArm.omoplate", 0.739, 0.5);
im.cog.setLinkMass("i01.leftArm.rotate", 0.715, 0.5754);
im.cog.setLinkMass("i01.rightArm.rotate", 0.715, 0.5754);
im.cog.setLinkMass("i01.leftArm.shoulder", 0.513, 0.5);
im.cog.setLinkMass("i01.rightArm.shoulder", 0.513, 0.5);
im.cog.setLinkMass("i01.leftArm.bicep", 0.940, 0.4559);
im.cog.setLinkMass("i01.rightArm.bicep", 0.940, 0.4559);
im.cog.setLinkMass("i01.leftHand.wrist", 0.176, 0.7474);
im.cog.setLinkMass("i01.rightHand.wrist", 0.176, 0.7474);
im.setJmeApp(vinMoovApp);
im.setOpenni(openni);
}
public Double getUltrasonicSensorDistance() {
if (ultrasonicSensor != null) {
return ultrasonicSensor.range();
} else {
warn("No UltrasonicSensor attached");
return 0.0;
}
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null && neopixelArduino != null) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public void stopNeopixelAnimation() {
if (neopixel != null && neopixelArduino != null) {
neopixel.animationStop();
} else {
warn("No Neopixel attached");
}
}
/**
* TODO : use system locale set language for InMoov service used by chatbot +
* ear + mouth
*
* @param l
* - format : java Locale
*/
public boolean setLanguage(String l) {
if (languages.containsKey(l)) {
this.language = l;
info("Set language to %s", languages.get(l));
Runtime runtime = Runtime.getInstance();
runtime.setLocale(l);
languagePack.load(language);
return true;
// this.broadcastState();
} else {
error("InMoov not yet support {}", l);
return false;
}
}
/**
* get current language
*/
public String getLanguage() {
if (this.language == null) {
// check if default locale supported by inmoov
if (languages.containsKey(Locale.getDefault().toLanguageTag())) {
this.language = Locale.getDefault().toLanguageTag();
} else {
this.language = "en-US";
}
}
// to be sure runtime == inmoov language
if (!Locale.getDefault().toLanguageTag().equals(this.language)) {
setLanguage(this.language);
}
return this.language;
}
/**
* @return the mute startup state ( InMoov vocal startup actions )
*/
public Boolean getMute() {
return mute;
}
// END GENERAL METHODS / TO SORT
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(InMoov.class.getCanonicalName());
meta.addDescription("The InMoov service");
meta.addCategory("robot");
// meta.addDependency("inmoov.fr", "1.0.0");
// meta.addDependency("org.myrobotlab.inmoov", "1.0.0");
meta.addDependency("inmoov.fr", "inmoov", "1.1.11", "zip");
meta.addDependency("inmoov.fr", "jm3-model", "1.0.0", "zip");
meta.sharePeer("head.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("torso.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("leftArm.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("leftHand.arduino", "left", "Arduino", "shared left arduino");
// eyelidsArduino peer for backward compatibility
meta.sharePeer("eyelidsArduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("rightArm.arduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("rightHand.arduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("eyesTracking.opencv", "opencv", "OpenCV", "shared head OpenCV");
meta.sharePeer("eyesTracking.controller", "left", "Arduino", "shared head Arduino");
meta.sharePeer("eyesTracking.x", "head.eyeX", "Servo", "shared servo");
meta.sharePeer("eyesTracking.y", "head.eyeY", "Servo", "shared servo");
meta.sharePeer("mouthControl.mouth", "mouth", speechService, "shared Speech");
meta.sharePeer("headTracking.opencv", "opencv", "OpenCV", "shared head OpenCV");
meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head Arduino");
meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo");
meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo");
// Global - undecorated by self name
meta.addRootPeer("python", "Python", "shared Python service");
// put peer definitions in
meta.addPeer("torso", "InMoovTorso", "torso");
meta.addPeer("eyelids", "InMoovEyelids", "eyelids");
meta.addPeer("leftArm", "InMoovArm", "left arm");
meta.addPeer("leftHand", "InMoovHand", "left hand");
meta.addPeer("rightArm", "InMoovArm", "right arm");
meta.addPeer("rightHand", "InMoovHand", "right hand");
// webkit speech.
meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service");
// meta.addPeer("ear", "Sphinx", "InMoov Sphinx speech recognition
// service");
meta.addPeer("eyesTracking", "Tracking", "Tracking for the eyes");
meta.addPeer("head", "InMoovHead", "the head");
meta.addPeer("headTracking", "Tracking", "Head tracking system");
meta.addPeer("mouth", speechService, "InMoov speech service");
meta.addPeer("mouthControl", "MouthControl", "MouthControl");
meta.addPeer("openni", "OpenNi", "Kinect service");
meta.addPeer("pid", "Pid", "Pid service");
// For VirtualInMoov
meta.addPeer("jme", "JMonkeyEngine", "Virtual inmoov");
meta.addPeer("ik3d", "InverseKinematics3D", "Virtual inmoov");
// For IntegratedMovement
meta.addPeer("integratedMovement", "IntegratedMovement", "Inverse kinematic type movement");
return meta;
}
public void setHead(InMoovHead head) {
this.head = head;
}
public InMoovHead startHead(ServoController controller) {
speakBlocking(languagePack.get("STARTINGHEAD"));
head = (InMoovHead) startPeer("head");
head.setController(controller);
// arduinos.put(port, head.controller); // FIXME - silly used by PIR -
// refactor out ..
return head;
}
public InMoovArm startArm(String side, ServoController controller) throws Exception {
// speakBlocking(languagePack.get("STARTINGLEFTARM"));
InMoovArm arm = (InMoovArm) startPeer(String.format("%sArm", side));
arm.setController(controller);
arms.put(side, arm);
arm.setSide(side);// FIXME WHO USES SIDE - THIS SHOULD BE NAME !!!
if ("left".equals(side)) {
leftArm = arm;
} else if ("right".equals(side)) {
rightArm = arm;
}
return arm;
}
public InMoovHand startHand(String side, ServoController sc) {
InMoovHand hand = (InMoovHand) startPeer(String.format("%sHand", side));
hand.setSide(side);
hands.put(side, hand);
hand.setController(sc);
if ("left".equals(side)) {
leftHand = hand;
} else if ("right".equals(side)) {
rightHand = hand;
}
return hand;
}
public InMoovTorso startTorso(ServoController controller) throws Exception {
torso = (InMoovTorso) startPeer("torso");
torso.setController(controller);
return torso;
}
@Override
public void onJointAngles(Map<String, Double> angleMap) {
// TODO Auto-generated method stub
log.info("onJointAngles {}", angleMap);
// here we can make decisions on what ik sets we want to use and
// what body parts are to move
for (String name : angleMap.keySet()) {
ServiceInterface si = Runtime.getService(name);
if (si instanceof Servo) {
((Servo)si).moveTo(angleMap.get(name));
}
}
}
public void startIK3d() throws Exception {
ik3d = (InverseKinematics3D) Runtime.start("ik3d", "InverseKinematics3D");
ik3d.setCurrentArm("rightArm", InMoovArm.getDHRobotArm(getName(), "left"));
// Runtime.createAndStart("gui", "SwingGui");
// OpenCV cv1 = (OpenCV)Runtime.createAndStart("cv1", "OpenCV");
// OpenCVFilterAffine aff1 = new OpenCVFilterAffine("aff1");
// aff1.setAngle(270);
// aff1.setDx(-80);
// aff1.setDy(-80);
// cv1.addFilter(aff1);
// cv1.setCameraIndex(0);
// cv1.capture();
// cv1.undockDisplay(true);
/*
* SwingGui gui = new SwingGui("gui"); gui.startService();
*/
/*
* Joystick joystick = (Joystick) Runtime.start("joystick", "Joystick");
* joystick.setController(2);
*
* // joystick.startPolling();
*
* // attach the joystick input to the ik3d service. //
* joystick.addInputListener(ik3d); joystick.attach(this);
*/
}
public static void main(String[] args) throws Exception {
LoggingFactory.init(Level.INFO);
String leftPort = "COM3";
String rightPort = "COM4";
Platform.setVirtual(true);
Runtime.start("gui", "SwingGui");
Runtime.start("python", "Python");
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.setLanguage("en-US");
i01.startMouth();
i01.startEar();
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
webgui.startBrowser("http://localhost:8888/#/service/i01.ear");
HtmlFilter htmlFilter = (HtmlFilter) Runtime.start("htmlFilter", "HtmlFilter");
i01.chatBot = (ProgramAB) Runtime.start("i01.chatBot", "ProgramAB");
i01.chatBot.addTextListener(htmlFilter);
htmlFilter.addListener("publishText", "i01", "speak");
i01.chatBot.attach((Attachable) i01.ear);
i01.startBrain();
i01.startHead(leftPort);
i01.startMouthControl(i01.head.jaw, i01.mouth);
i01.loadGestures("InMoov/gestures");
i01.startVinMoov();
i01.startOpenCV();
i01.execGesture("BREAKITdaVinci()");
}
public void startVinMoov() throws Exception {
startSimulator();
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
Point ikPoint = null;
public void startSimulator() throws Exception {
if (jme == null) {
jme = (JMonkeyEngine) startPeer("jme");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
jme.setRotation("i01.head.jaw", "x");
jme.setRotation("i01.head.neck", "x");
jme.setRotation("i01.head.rothead", "y");
jme.setRotation("i01.head.rollNeck", "z");
jme.setRotation("i01.head.eyeY", "x");
jme.setRotation("i01.head.eyeX", "y");
jme.setRotation("i01.torso.topStom", "z");
jme.setRotation("i01.torso.midStom", "y");
jme.setRotation("i01.torso.lowStom", "x");
jme.setRotation("i01.rightArm.bicep", "x");
jme.setRotation("i01.leftArm.bicep", "x");
jme.setRotation("i01.rightArm.shoulder", "x");
jme.setRotation("i01.leftArm.shoulder", "x");
jme.setRotation("i01.rightArm.rotate", "y");
jme.setRotation("i01.leftArm.rotate", "y");
jme.setRotation("i01.rightArm.omoplate", "z");
jme.setRotation("i01.leftArm.omoplate", "z");
jme.setRotation("i01.rightHand.wrist", "y");
jme.setRotation("i01.leftHand.wrist", "y");
// jme.setRotation("i01.rightHand.index", "x");
// jme.setRotation("i01.rightHand.majeure", "x");
// jme.setRotation("i01.leftHand.index", "x");
// jme.setRotation("i01.leftHand.majeure", "x");
jme.setMapper("i01.head.jaw", 0, 180, -5, 80);
jme.setMapper("i01.head.neck", 0, 180, 20, -20);
jme.setMapper("i01.head.rollNeck", 0, 180, 30, -30);
jme.setMapper("i01.head.eyeY", 0, 180, 30, 175);
jme.setMapper("i01.head.eyeX", 0, 180, 30, 175); //TODO need to check the mapping
jme.setMapper("i01.rightArm.bicep", 0, 180, 0, -150);
jme.setMapper("i01.leftArm.bicep", 0, 180, 0, -150);
jme.setMapper("i01.rightArm.shoulder", 0, 180, 30, -150);
jme.setMapper("i01.leftArm.shoulder", 0, 180, 30, -150);
jme.setMapper("i01.rightArm.rotate", 0, 180, 80, -80);
jme.setMapper("i01.leftArm.rotate", 0, 180, -80, 80);
jme.setMapper("i01.rightArm.omoplate", 0, 180, 10, -180);
jme.setMapper("i01.leftArm.omoplate", 0, 180, -10, 180);
/*
jme.setMapper("i01.rightHand.index", 0, 180, 90, -90);
jme.setMapper("i01.rightHand.majeure", 0, 180, 90, -90);
*/
jme.setMapper("i01.rightHand.wrist", 0, 180, -20, 60);
/*
jme.setMapper("i01.leftHand.index", 0, 180, 90, -90);
jme.setMapper("i01.leftHand.majeure", 0, 180, 90, -90);
*/
jme.setMapper("i01.leftHand.wrist", 0, 180, 20, -60);
jme.setMapper("i01.torso.topStom", 0, 180, -30, 30);
jme.setMapper("i01.torso.midStom", 0, 180, 50, 130);
jme.setMapper("i01.torso.lowStom", 0, 180, -30, 30);
jme.attach("i01.leftHand.thumb", "i01.leftHand.thumb", "i01.leftHand.thumb2", "i01.leftHand.thumb3");
jme.setRotation("i01.leftHand.thumb", "y");
jme.setRotation("i01.leftHand.thumb2", "x");
jme.setRotation("i01.leftHand.thumb3", "x");
jme.attach("i01.leftHand.index", "i01.leftHand.index", "i01.leftHand.index2", "i01.leftHand.index3");
jme.setRotation("i01.leftHand.index", "x");
jme.setRotation("i01.leftHand.index2", "x");
jme.setRotation("i01.leftHand.index3", "x");
jme.attach("i01.leftHand.majeure", "i01.leftHand.majeure", "i01.leftHand.majeure2", "i01.leftHand.majeure3");
jme.setRotation("i01.leftHand.majeure", "x");
jme.setRotation("i01.leftHand.majeure2", "x");
jme.setRotation("i01.leftHand.majeure3", "x");
jme.attach("i01.leftHand.ringFinger", "i01.leftHand.ringFinger", "i01.leftHand.ringFinger2", "i01.leftHand.ringFinger3");
jme.setRotation("i01.leftHand.ringFinger", "x");
jme.setRotation("i01.leftHand.ringFinger2", "x");
jme.setRotation("i01.leftHand.ringFinger3", "x");
jme.attach("i01.leftHand.pinky", "i01.leftHand.pinky", "i01.leftHand.pinky2", "i01.leftHand.pinky3");
jme.setRotation("i01.leftHand.pinky", "x");
jme.setRotation("i01.leftHand.pinky2", "x");
jme.setRotation("i01.leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
jme.setMapper("i01.leftHand.index", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.index2", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.index3", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.majeure", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.majeure2", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.majeure3", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.ringFinger", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.ringFinger2", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.ringFinger3", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.pinky", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.pinky2", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.pinky3", 0, 180, -110, -200);
jme.setMapper("i01.leftHand.thumb", 0, 180, -90, -270);
jme.setMapper("i01.leftHand.thumb2", 0, 180, -90, -270); //TODO CHECK THIS MAPPING
jme.setMapper("i01.leftHand.thumb3", 0, 180, -90, -270); //TODO CHECK THIS MAPPING
// right hand
jme.attach("i01.rightHand.thumb", "i01.rightHand.thumb", "i01.rightHand.thumb2", "i01.rightHand.thumb3");
jme.setRotation("i01.rightHand.thumb", "y");
jme.setRotation("i01.rightHand.thumb2", "x");
jme.setRotation("i01.rightHand.thumb3", "x");
jme.attach("i01.rightHand.index", "i01.rightHand.index", "i01.rightHand.index2", "i01.rightHand.index3");
jme.setRotation("i01.rightHand.index", "x");
jme.setRotation("i01.rightHand.index2", "x");
jme.setRotation("i01.rightHand.index3", "x");
jme.attach("i01.rightHand.majeure", "i01.rightHand.majeure", "i01.rightHand.majeure2", "i01.rightHand.majeure3");
jme.setRotation("i01.rightHand.majeure", "x");
jme.setRotation("i01.rightHand.majeure2", "x");
jme.setRotation("i01.rightHand.majeure3", "x");
jme.attach("i01.rightHand.ringFinger", "i01.rightHand.ringFinger", "i01.rightHand.ringFinger2", "i01.rightHand.ringFinger3");
jme.setRotation("i01.rightHand.ringFinger", "x");
jme.setRotation("i01.rightHand.ringFinger2", "x");
jme.setRotation("i01.rightHand.ringFinger3", "x");
jme.attach("i01.rightHand.pinky", "i01.rightHand.pinky", "i01.rightHand.pinky2", "i01.rightHand.pinky3");
jme.setRotation("i01.rightHand.pinky", "x");
jme.setRotation("i01.rightHand.pinky2", "x");
jme.setRotation("i01.rightHand.pinky3", "x");
jme.setMapper("i01.rightHand.index", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.index2", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.index3", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.majeure", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.majeure2", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.majeure3", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.ringFinger", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.ringFinger2", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.ringFinger3", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.pinky", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.pinky2", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.pinky3", 0, 180, 60, -120);
jme.setMapper("i01.rightHand.thumb", 0, 180, -90, -270);
jme.setMapper("i01.rightHand.thumb2", 0, 180, -90, -270); //TODO CHECK THIS MAPPING
jme.setMapper("i01.rightHand.thumb3", 0, 180, -90, -270); //TODO CHECK THIS MAPPING
// additional experimental mappings
/*
* jme.attach("i01.leftHand.pinky", "i01.leftHand.index2");
* jme.attach("i01.leftHand.thumb", "i01.leftHand.index3");
* jme.setRotation("i01.leftHand.index2", "x");
* jme.setRotation("i01.leftHand.index3", "x");
* jme.setMapper("i01.leftHand.index", 0, 180, -90, -270);
* jme.setMapper("i01.leftHand.index2", 0, 180, -90, -270);
* jme.setMapper("i01.leftHand.index3", 0, 180, -90, -270);
*/
// creating a virtual inmoov with virtual servo controller
ServoController sc = jme.getServoController();
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.startHead(sc);
i01.startArm("left", sc);
i01.startArm("right", sc);
i01.startHand("left", sc);
i01.startHand("right", sc);
i01.startTorso(sc);
i01.startMouth();
i01.startMouthControl();
i01.rest();
}
public void setIkPoint(double x, double y, double z) {
if (ikPoint == null) {
ikPoint = new Point(x, y, z);
jme.addBox("ikPoint", x, y, z, "cc0000", true);
}
// move target marker
jme.moveTo("ikPoint", x, y, z);
if (ik3d == null) {
ik3d = (InverseKinematics3D) startPeer("ik3d");
ik3d.setCurrentArm("i01.leftArm", InMoovArm.getDHRobotArm("i01", "left"));
ik3d.attach(this);
}
// move arm to target
ik3d.moveTo("i01.leftArm", ikPoint);
}
public JMonkeyEngine getSimulator() {
if (jme == null) {
jme = (JMonkeyEngine) startPeer("jme");
}
return jme;
}
} |
package com.lukekorth.pebblelocker;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.lukekorth.pebblelocker.events.ActivityResumedEvent;
import com.lukekorth.pebblelocker.events.RequirePurchaseEvent;
import com.lukekorth.pebblelocker.helpers.CustomDeviceAdminReceiver;
import com.lukekorth.pebblelocker.receivers.BaseBroadcastReceiver;
import com.lukekorth.pebblelocker.services.AndroidWearDetectionService;
import com.lukekorth.pebblelocker.services.LockingIntentService;
import com.squareup.otto.Subscribe;
import org.slf4j.LoggerFactory;
import fr.nicolaspomepuy.discreetapprate.AppRate;
import fr.nicolaspomepuy.discreetapprate.RetryPolicy;
public class PebbleLocker extends PremiumFeaturesActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final int REQUEST_CODE_ENABLE_ADMIN = 1;
private static final int REQUEST_GOOGLE_PLAY_SERVICES = 2;
private DevicePolicyManager mDPM;
private ComponentName mDeviceAdmin;
private CheckBoxPreference mAdmin;
private EditTextPreference mPassword;
private CheckBoxPreference mEnable;
private CheckBoxPreference mForceLock;
private SharedPreferences mPrefs;
private AlertDialog requirePassword;
private long timeStamp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.main);
mAdmin = (CheckBoxPreference) findPreference("key_enable_admin");
mPassword = (EditTextPreference) findPreference("key_password");
mEnable = (CheckBoxPreference) findPreference("key_enable_locker");
mForceLock = (CheckBoxPreference) findPreference("key_force_lock");
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdmin = new ComponentName(this, CustomDeviceAdminReceiver.class);
mAdmin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
// Launch the activity to have the user enable our admin.
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Pebble Locker needs device admin access to lock your device on disconnect");
startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
// return false - don't update checkbox until we're really active
return false;
} else {
mDPM.removeActiveAdmin(mDeviceAdmin);
PebbleLocker.this.enableOptions(false);
mEnable.setChecked(false);
removePassword();
return true;
}
}
});
mPassword.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
doResetPassword((String) newValue);
return true;
}
});
mEnable.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(Boolean.parseBoolean(newValue.toString())) {
enableLockOptions(true);
showAlert(R.string.pebble_locker_enabled);
} else {
enableLockOptions(false);
removePassword();
showAlert(R.string.pebble_locker_disabled);
}
return true;
}
});
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
PebbleLockerApplication.getBus().register(this);
AppRate.with(this)
.text("Rate Pebble Locker")
.initialLaunchCount(3)
.retryPolicy(RetryPolicy.EXPONENTIAL)
.checkAndShow();
startService(new Intent(this, AndroidWearDetectionService.class));
}
@Subscribe
public void onRequirePurchaseEvent(RequirePurchaseEvent event) {
requirePurchase();
}
public void onResume() {
super.onResume();
mPrefs.registerOnSharedPreferenceChangeListener(this);
PebbleLockerApplication.getBus().post(new ActivityResumedEvent());
checkForRequiredPasswordByOtherApps();
checkForActiveAdmin();
if(!mPrefs.getString("key_password", "").equals("") &&
timeStamp < (System.currentTimeMillis() - 60000) &&
mPrefs.getBoolean(BaseBroadcastReceiver.LOCKED, true)) {
requestPassword();
} else {
int response = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (response != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(response, this, REQUEST_GOOGLE_PLAY_SERVICES)
.show();
}
}
}
@Override
public void onPause() {
super.onPause();
mPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
PebbleLockerApplication.getBus().unregister(this);
}
/**
* This is dangerous, so we prevent automated tests from doing it, and we
* remind the user after we do it.
*/
private void doResetPassword(String newPassword) {
if (alertIfMonkey()) {
return;
}
// hack because we need the new password to be
// set in shared prefs before this method returns
mPrefs.edit().putString("key_password", newPassword).apply();
if(newPassword.length() == 0) {
LoggerFactory.getLogger("User").debug("Password was set to empty");
mEnable.setChecked(false);
showAlert(R.string.password_cleared);
} else {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(getString(R.string.reset_password_warning, newPassword))
.setPositiveButton("Don't Forget It!", null)
.show();
}
startService(new Intent(
this, LockingIntentService.class).putExtra(LockingIntentService.LOCK, true));
}
private void removePassword() {
mPassword.setText("");
}
private void checkForActiveAdmin() {
if(mDPM.isAdminActive(mDeviceAdmin)) {
mAdmin.setChecked(true);
enableOptions(true);
if (mPrefs.getBoolean("key_enable_locker", false)) {
enableLockOptions(true);
} else {
enableLockOptions(false);
}
} else {
mAdmin.setChecked(false);
enableOptions(false);
}
}
private void enableOptions(boolean enabled) {
mEnable.setEnabled(enabled);
enableLockOptions(enabled);
}
private void enableLockOptions(boolean enabled) {
mPassword.setEnabled(enabled);
mForceLock.setEnabled(enabled);
}
@SuppressLint("NewApi")
private void checkForRequiredPasswordByOtherApps() {
int encryptionStatus = mDPM.getStorageEncryptionStatus();
boolean encryptionEnabled = (
encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING ||
encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
);
if((mDPM.getPasswordMinimumLength(null) > 0 || encryptionEnabled) && !mPrefs.getBoolean("ignore_warning", false)) {
new AlertDialog.Builder(this)
.setMessage(R.string.incompatable_warning)
.setCancelable(false)
.setPositiveButton(R.string.do_not_use, new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
PebbleLocker.this.finish();
}
})
.setNegativeButton(R.string.use_anyway, new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mPrefs.edit().putBoolean("ignore_warning", true).apply();
}
})
.show();
}
}
private void requestPassword() {
if(requirePassword == null || !requirePassword.isShowing()) {
LayoutInflater factory = LayoutInflater.from(this);
View textEntryView = factory.inflate(R.layout.password_prompt, null);
final EditText passwordEditText = (EditText) textEntryView.findViewById(R.id.password_edit);
if(mPrefs.getString("key_password", "").matches("[0-9]+")) {
passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
requirePassword = new AlertDialog.Builder(PebbleLocker.this)
.setTitle("Enter your pin/password to continue")
.setView(textEntryView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = passwordEditText.getText().toString();
dialog.cancel();
if(!mPrefs.getString("key_password", "").equals(password))
requestPassword();
else
timeStamp = System.currentTimeMillis();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
requestPassword();
}
})
.setCancelable(false)
.create();
requirePassword.show();
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String message;
if (key.equals("key_password")) {
if (TextUtils.isEmpty(sharedPreferences.getString("key_password", ""))) {
message = "User changed their password to empty";
} else {
message = "User changed their password";
}
} else {
message = "User changed " + key;
}
LoggerFactory.getLogger("Settings_Changed").debug(message);
}
/**
* If the "user" is a monkey, post an alert and notify the caller. This prevents automated
* test frameworks from stumbling into annoying or dangerous operations.
*/
private boolean alertIfMonkey() {
if (ActivityManager.isUserAMonkey()) {
showAlert(R.string.monkey);
return true;
} else {
return false;
}
}
} |
package org.myrobotlab.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFactory;
import org.atmosphere.nettosphere.Config;
import org.atmosphere.nettosphere.Handler;
import org.atmosphere.nettosphere.Nettosphere;
import org.jboss.netty.handler.ssl.SslContext;
import org.jboss.netty.handler.ssl.util.SelfSignedCertificate;
import org.myrobotlab.codec.Api;
import org.myrobotlab.codec.ApiFactory;
import org.myrobotlab.codec.Codec;
import org.myrobotlab.codec.CodecFactory;
import org.myrobotlab.codec.CodecJson;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.framework.Message;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceEnvironment;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.image.Util;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.net.BareBonesBrowserLaunch;
import org.myrobotlab.net.Connection;
//import org.myrobotlab.service.WebGUI3.Error;
import org.myrobotlab.service.interfaces.AuthorizationProvider;
import org.myrobotlab.service.interfaces.Gateway;
//import org.myrobotlab.webgui.WebGUIServlet;
import org.slf4j.Logger;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.providers.netty.NettyAsyncHttpProvider;
import com.ning.http.client.providers.netty.NettyAsyncHttpProviderConfig;
/**
*
* WebGui - This service is the AngularJS based GUI TODO - messages &
* services are already APIs - perhaps a data API - same as service without the
* message wrapper
*/
public class WebGui extends Service implements AuthorizationProvider, Gateway, Handler {
/**
* Static list of third party dependencies for this service. The list will be
* consumed by Ivy to download and manage the appropriate resources
*/
public static class LiveVideoStreamHandler implements Handler {
@Override
public void handle(AtmosphereResource r) {
// TODO Auto-generated method stub
try {
/*
* OpenCV opencv = (OpenCV) Runtime.start("opencv", "OpenCV");
* OpenCVFilterFFMEG ffmpeg = new OpenCVFilterFFMEG("ffmpeg");
* opencv.addFilter(ffmpeg); opencv.capture(); sleep(1000);
* opencv.removeFilters(); ffmpeg.stopRecording();
*/
AtmosphereResponse response = r.getResponse();
// response.setContentType("video/mp4");
// response.setContentType("video/x-flv");
response.setContentType("video/avi");
// FIXME - mime type of avi ??
ServletOutputStream out = response.getOutputStream();
// response.addHeader(name, value);
// byte[] data = FileIO.fileToByteArray(new
// File("flvTest.flv"));
// byte[] data = FileIO.fileToByteArray(new
// File("src/main/resources/resource/WebGUI/video/ffmpeg.1443989700495.mp4"));
// byte[] data = FileIO.fileToByteArray(new
// File("mp4Test.mp4"));
byte[] data = FileIO.toByteArray(new File("test.avi.h264.mp4"));
log.info("bytes {}", data.length);
out.write(data);
out.flush();
// out.close();
// r.write(data);
// r.writeOnTimeout(arg0)
// r.forceBinaryWrite();
// r.close();
} catch (Exception e) {
Logging.logError(e);
}
}
}
public static class Panel {
String name;
String simpleName;
int posX = 40;
int posY = 20;
int zIndex = 1;
int width = 400;
int height = 400;
int preferredWidth = 800;
int preferredHeight = 600;
boolean hide = false;
public Panel(String panelName) {
this.name = panelName;
}
public Panel(String name, int x, int y, int z) {
this.name = name;
this.posX = x;
this.posY = y;
this.zIndex = z;
}
}
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(WebGui.class);
private static final AtomicBoolean TRUST_SERVER_CERT = new AtomicBoolean(true);
private static final TrustManager DUMMY_TRUST_MANAGER = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (!TRUST_SERVER_CERT.get()) {
throw new CertificateException("Server certificate not trusted.");
}
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
private static SSLContext createSSLContext2() {
try {
InputStream keyStoreStream = Security.class.getResourceAsStream(Util.getResourceDir() + "/keys/selfsigned.jks");
char[] keyStorePassword = "changeit".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreStream, keyStorePassword);
// Set up key manager factory to use our key store
char[] certificatePassword = "changeit".toCharArray();
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, certificatePassword);
// Initialize the SSLContext to work with our key managers.
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManager[] trustManagers = new TrustManager[] { DUMMY_TRUST_MANAGER };
SecureRandom secureRandom = new SecureRandom();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, secureRandom);
return sslContext;
} catch (Exception e) {
throw new Error("Failed to initialize SSLContext", e);
}
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(WebGui.class.getCanonicalName());
meta.addDescription("web display");
meta.addCategory("connectivity", "display");
meta.includeServiceInOneJar(true);
meta.addDependency("org.atmosphere", "nettosphere", "2.3.0");
//meta.addDependency("org.atmosphere", "wasync", "2.1.3"); provided in Runtime now.
// MAKE NOTE !!! - we currently distribute myrobotlab.jar with a webgui
// hence these following dependencies are zipped with myrobotlab.jar !
// and are NOT listed as dependencies, because they are already included
// Its now part of myrobotlab.jar - unzipped in
// build.xml (part of myrobotlab.jar now)
// meta.addDependency("io.netty", "3.10.0"); // netty-3.10.0.Final.jar
// meta.addDependency("org.atmosphere.nettosphere", "2.3.0"); //
// nettosphere-assembly-2.3.0.jar
// meta.addDependency("org.atmosphere.nettosphere", "2.3.0");//
// geronimo-servlet_3.0_spec-1.0.jar
return meta;
}
public Integer port;
String address = "0.0.0.0";
public Integer sslPort;
transient Nettosphere nettosphere;
transient Broadcaster broadcaster;
transient BroadcasterFactory broadcastFactory;
public String root = "root";
boolean useLocalResources = false;
boolean autoStartBrowser = true;
// SHOW INTERFACE
// FIXME - allowAPI1(true|false)
// FIXME - allowAPI2(true|false)
// FIXME - allow Protobuf/Thrift/Avro
// FIXME - NO JSON ENCODING SHOULD BE IN THIS FILE !!!
public String startURL = "http://localhost:%d";
transient final ConcurrentHashMap<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>();
// FIXME might need to change to HashMap<String, HashMap<String,String>> to
// add client session
// TODO - probably should have getters - to publish - currently
// just marking as transient to remove some of the data load 10240 max frame
transient Map<String, Panel> panels;
transient Map<String, Map<String, Panel>> desktops;
transient ApiFactory api = null;
String currentDesktop = "default";
transient LiveVideoStreamHandler stream = new LiveVideoStreamHandler();
public WebGui(String n) {
super(n);
api = ApiFactory.getInstance(this);
if (desktops == null) {
desktops = new HashMap<String, Map<String, Panel>>();
}
if (!desktops.containsKey(currentDesktop)) {
panels = new HashMap<String, Panel>();
desktops.put(currentDesktop, panels);
} else {
panels = desktops.get(currentDesktop);
}
String name = Runtime.getRuntimeName();
subscribe(name, "registered");
// FIXME - "unregistered" / "released"
}
@Override
public void addConnectionListener(String name) {
// TODO Auto-generated method stub
}
@Override
public boolean allowExport(String serviceName) {
// TODO Auto-generated method stub
return false;
}
public void autoStartBrowser(boolean autoStartBrowser) {
this.autoStartBrowser = autoStartBrowser;
}
public void broadcast(Message msg) {
try {
if (broadcaster != null) {
Codec codec = CodecFactory.getCodec(CodecUtils.MIME_TYPE_JSON);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
codec.encode(bos, msg);
bos.close();
broadcaster.broadcast(new String(bos.toByteArray())); // wtf
}
} catch (Exception e) {
Logging.logError(e);
}
}
@Override
public void connect(String uri) throws URISyntaxException {
// TODO Auto-generated method stub
}
SSLContext createSSLContext() {
try {
if (sslPort != null) {
return SSLContext.getInstance("TLS");
}
} catch (Exception e) {
log.warn("can not make ssl context", e);
}
return null;
}
public void extract() throws IOException {
extract(false);
}
public void extract(boolean overwrite) throws IOException {
// TODO - check resource version vs self version
// overwrite if different ?
FileIO.extractResources(overwrite);
}
@Override
public HashMap<URI, Connection> getClients() {
// TODO Auto-generated method stub
return null;
}
public Config.Builder getConfig() {
Config.Builder configBuilder = new Config.Builder();
try {
boolean secureTest = false;
if (secureTest) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
configBuilder.sslContext(createSSLContext());// .sslContext(sslCtx);
}
} catch (Exception e) {
log.error("certificate creation threw", e);
}
configBuilder
/*
* did not work :( .resource(
* "jar:file:/C:/mrl/myrobotlab/dist/myrobotlab.jar!/resource")
* .resource(
* "jar:file:/C:/mrl/myrobotlab/dist/myrobotlab.jar!/resource/WebGui" )
*/
.resource("/stream", stream)
// .resource("/video/ffmpeg.1443989700495.mp4", test)
// for the inmmoov
.resource("../myrobotlab/src/main/resources/resource/WebGui")
// for debugging
.resource("./src/main/resources/resource/WebGui").resource("./src/main/resources/resource")
// for runtime - after extractions
.resource("./resource/WebGui").resource("./resource")
// Support 2 APIs
// synchronous DO NOT SUSPEND
.resource("/api", this)
// if Jetty is in the classpath it will use it by default - we
// want to use Netty
/*org.atmosphere.websocket.maxTextMessageSize*/
/* noWorky :(
.initParam("org.atmosphere.websocket.maxTextMessageSize","-1")
.initParam("org.atmosphere.websocket.maxBinaryMessageSize","-1")
.initParam(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE,"-1")
.initParam(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE,"-1")
.initParam(ApplicationConfig.WEBSOCKET_BUFFER_SIZE,"1000000")
*/
.initParam("org.atmosphere.cpr.asyncSupport", "org.atmosphere.container.NettyCometSupport").initParam(ApplicationConfig.SCAN_CLASSPATH, "false")
.initParam(ApplicationConfig.PROPERTY_SESSION_SUPPORT, "true").port(port).host(address); // all
// ips
SSLContext sslContext = createSSLContext();
if (sslContext != null) {
configBuilder.sslContext(sslContext);
}
// SessionSupport ss = new SessionSupport();
configBuilder.build();
return configBuilder;
}
@Override
public List<Connection> getConnections(URI clientKey) {
// TODO Auto-generated method stub
return null;
}
public Map<String, String> getHeadersInfo(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
/**
* Atmosphere (nearly) always gives a ConcurrentModificationException its
* supposed to be fixed in later versions - but later version have proven
* very unstable
*/
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key.toLowerCase(), value);
}
return map;
}
public String getId(AtmosphereResource r) {
String id = r.getRequest().getHeader("id");
if (id == null) {
id = "anonymous";
}
return id;
}
public Integer getPort() {
return port;
}
@Override
public String getPrefix(URI protocolKey) {
// TODO Auto-generated method stub
return null;
}
/*
* SSLContext createSSLContext() { try { if (sslPort != null) { return
* SSLContext.getInstance("TLS"); } } catch (Exception e) {
* log.warn("can not make ssl context", e); } return null; }
*/
/**
* With a single method Atmosphere does so much !!! It sets up the connection,
* possibly gets a session, turns the request into something like a
* HTTPServletRequest, provides us with input & output streams - and
* manages all the "long polling" or websocket upgrades on its own !
*
* Atmosphere Rocks !
*
* common to all apis is handled here - then delegated to the appropriate api
* handler
*/
@Override
public void handle(AtmosphereResource r) {
String apiKey = Api.getApiKey(r.getRequest().getRequestURI());
AtmosphereRequest request = r.getRequest();
log.debug(">> {} - {} - [{}]", request.getMethod(), request.getRequestURI(), request.body().asString());
try {
// FIXME - maintain single broadcaster for each session ?
// Broadcaster bc = r.getBroadcaster();
// if (bc != null || r.getBroadcaster() != broadcaster){
r.setBroadcaster(broadcaster);
String id = getId(r);
handleSession(r);
// FIXME - header SAS token for authentication ???
// Map<String, String> headers = getHeadersInfo(request);
// GET vs POST - post assumes low-level messaging
// GET is high level synchronous
// String httpMethod = request.getMethod();
// get default encoder
// FIXME FIXME FIXME - this IS A CODEC !!! NOT AN API-TYPE !!! -
// CHANGE to MIME_TYPE_APPLICATION_JSON !!!
// TODO - add handleSwaggerApi
switch (apiKey) {
case ApiFactory.API_TYPE_MESSAGES: {
handleMessagesApi(r);
break;
}
case ApiFactory.API_TYPE_SERVICE: {
handleServiceApi(r);
break;
}
default: {
// handleInvalidApi(r); // TODO - swagger list of apis ?
throw new IOException("invalid api: " + apiKey);
}
}
} catch (Exception e) {
try {
AtmosphereResponse response = r.getResponse();
OutputStream out = response.getOutputStream();
response.addHeader("Content-Type", CodecUtils.MIME_TYPE_JSON);
Codec codec = CodecFactory.getCodec(CodecUtils.MIME_TYPE_JSON);
Status error = Status.error(e);
Message msg = Message.createMessage(this, getName(), CodecUtils.getCallBackName("getStatus"), error);
if (ApiFactory.API_TYPE_SERVICE.equals(apiKey)) {
// for the purpose of only returning the data
// only not the message
if (msg.data == null) {
log.warn("<< {}", CodecJson.encode(null));
codec.encode(out, null);
} else {
// return the return type
log.warn("<< {}", CodecJson.encode(msg.data[0]));
codec.encode(out, msg.data[0]);
}
} else {
// API_TYPE_MESSAGES
// DEPRECATE - FOR LOGGING ONLY REMOVE
log.warn("<< {}", CodecJson.encode(msg)); // FIXME if logTraffic
codec.encode(out, msg);
}
} catch (Exception e2) {
log.error("respond threw", e);
}
}
}
/**
* handleMessagesApi handles all requests sent to /api/messages It
* suspends/upgrades the connection to a websocket It is a asynchronous
* protocol - and all messages are wrapped in a message wrapper.
*
* The ApiFactory will handle the details of de-serializing but its necessary
* to setup some protocol details here for websockets and session management
* which the ApiFactory should not be concerned with.
*
* @param r
* - request and response objects from Atmosphere server
*/
public void handleMessagesApi(AtmosphereResource r) {
try {
AtmosphereResponse response = r.getResponse();
AtmosphereRequest request = r.getRequest();
OutputStream out = response.getOutputStream();
if (!r.isSuspended()) {
r.suspend();
}
response.addHeader("Content-Type", CodecUtils.MIME_TYPE_JSON);
api.process(this, out, r.getRequest().getRequestURI(), request.body().asString());
/*
* // FIXME - GET or POST should work - so this "should" be unnecessary ..
* if ("GET".equals(httpMethod)) { // if post and parts.length < 3 ?? //
* respond(r, apiKey, "getPlatform", new Hello(Runtime.getId()));
* HashMap<URI, ServiceEnvironment> env = Runtime.getEnvironments();
* respond(r, apiKey, "getLocalServices", env); } else {
* doNotUseThisProcessMessageAPI(codec, request.body()); // FIXME data is
* double encoded .. can't put '1st' encoded json // api.process(this,
* out, r.getRequest().getRequestURI(), request.body().asString()); }
*/
} catch (Exception e) {
log.error("handleMessagesApi -", e);
}
}
/**
* This is a middle level method to handle the details of Atmosphere and
* http/ws level of processing request. It will eventually call
* ApiFactory.process which handles the "pure" Jvm Java only processing
*
* @param r
* r
* @throws Exception
* e
*
*/
public void handleServiceApi(AtmosphereResource r) throws Exception {
AtmosphereRequest request = r.getRequest();
AtmosphereResponse response = r.getResponse();
OutputStream out = response.getOutputStream();
response.addHeader("Content-Type", CodecUtils.MIME_TYPE_JSON);
String hack = null;
byte[] data = null;
if (request.body() != null) {
hack = request.body().asString();
// data = request.body().asBytes();
if (hack != null) { // FIXME - hack because request.body().asBytes()
// ALWAYS returns null !!
data = hack.getBytes();
}
}
api.process(out, r.getRequest().getRequestURI(), data);
}
public void handleSession(AtmosphereResource r) {
AtmosphereRequest request = r.getRequest();
HttpSession s = request.getSession(true);
if (s != null) {
log.debug("put session uuid {}", r.uuid());
sessions.put(r.uuid(), request.getSession(true));
}
}
public void hide(String name) {
invoke("publishHide", name);
}
@Override
public boolean isAuthorized(HashMap<String, String> security, String serviceName, String method) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isAuthorized(Message msg) {
// TODO Auto-generated method stub
return false;
}
public boolean isStarted() {
if (nettosphere != null && nettosphere.isStarted()) {
// is running
info("WebGui is started");
return true;
}
return false;
}
public Map<String, Panel> loadPanels() {
return panels;
}
/*
* FIXME - needs to be LogListener interface with
* LogListener.onLogEvent(String logEntry) !!!! THIS SHALL LOG NO ENTRIES OR
* ABANDON ALL HOPE !!!
*
* This is completely out of band - it does not use the regular queues inbox
* or outbox
*
* We want to broadcast this - but THERE CAN NOT BE ANY log.info/warn/error
* etc !!!! or there will be an infinite loop and you will be at the gates of
* hell !
*
*/
public void onLogEvent(Message msg) {
try {
if (broadcaster != null) {
Codec codec = CodecFactory.getCodec(CodecUtils.MIME_TYPE_JSON);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
codec.encode(bos, msg);
bos.close();
broadcaster.broadcast(new String(bos.toByteArray())); // wtf
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
public void onRegistered(ServiceInterface si) {
// new service
// subscribe to the status events
subscribe(si.getName(), "publishStatus");
subscribe(si.getName(), "publishState");
// for distributed Runtimes
if (si.isRuntime()) {
subscribe(si.getName(), "registered");
}
invoke("publishPanel", si.getName());
// broadcast it too
// repackage message
/*
* don't need to do this :) Message m = createMessage(getName(),
* "onRegistered", si); m.sender = Runtime.getInstance().getName();
* broadcast(m);
*/
}
@Override
public boolean preProcessHook(Message m) {
// FIXME - problem with collisions of this service's methods
// and dialog methods ?!?!?
// broadcast
broadcast(m);
// if the method name is == to a method in the WebGui
// process it
if (methodSet.contains(m.method)) {
// process the message like a regular service
return true;
}
// otherwise send the message to the dialog with the senders name
// broadcast(m);
return false;
}
@Override
public String publishConnect() {
// TODO Auto-generated method stub
return null;
}
@Override
public Connection publishConnect(Connection keys) {
// TODO Auto-generated method stub
return null;
}
@Override
public String publishDisconnect() {
// TODO Auto-generated method stub
return null;
}
@Override
public Status publishError() {
// TODO Auto-generated method stub
return null;
}
public String publishHide(String name) {
return name;
}
public Panel publishPanel(String panelName) {
Panel panel = null;
if (panels.containsKey(panelName)) {
panel = panels.get(panelName);
} else {
panel = new Panel(panelName);
panels.put(panelName, panel);
}
return panel;
}
public void publishPanels() {
for (String key : panels.keySet()) {
invoke("publishPanel", key);
}
}
public String publishShow(String name) {
return name;
}
public boolean publishShowAll(boolean b) {
return b;
}
/*
* redirects browser to new url
*/
public String redirect(String url) {
return url;
}
public void restart() {
stop();
start();
}
public boolean save() {
return super.save();
}
/**
* From UI events --to--> MRL request to save panel data typically done
* after user has changed or updated the UI in position, height, width, zIndex
* etc.
*
* If you need MRL changes of position or UI changes use publishPanel to
* remotely control UI
*
* @param panel
* - the panel which has been moved or resized
*/
public void savePanel(Panel panel) {
if (panel.name == null) {
log.error("panel name is null!");
return;
}
panels.put(panel.name, panel);
save();
}
@Override
public void sendRemote(String key, Message msg) throws URISyntaxException {
// TODO Auto-generated method stub
}
@Override
public void sendRemote(URI key, Message msg) {
// TODO Auto-generated method stub
}
public void set(String name, int x, int y) {
set(name, x, y, 0); // or is z -1 ?
}
public void set(String name, int x, int y, int z) {
Panel panel = null;
if (panels.containsKey(name)) {
panel = panels.get(name);
} else {
panel = new Panel(name, x, y, z);
}
invoke("publishPanel", panel);
}
public void setPort(Integer port) {
this.port = port; // restart service ?
}
public void show(String name) {
invoke("publishShow", name);
}
// TODO - refactor next 6+ methods to only us publishPanel
public void showAll(boolean b) {
invoke("publishShowAll", b);
}
public void start() {
try {
if (port == null) {
port = 8888;
}
// Broadcaster b = broadcasterFactory.get();
// a session "might" be nice - but for now we are stateless
// SessionSupport ss = new SessionSupport();
if (nettosphere != null && nettosphere.isStarted()) {
// is running
info("{} currently running on port {} - stop first, then start");
return;
}
nettosphere = new Nettosphere.Builder().config(getConfig().build()).build();
sleep(1000); // needed ?
try {
nettosphere.start();
} catch (Exception e) {
log.error("starting nettosphere failed", e);
}
broadcastFactory = nettosphere.framework().getBroadcasterFactory();
// get default boadcaster
/*
* nettosphere.framework().removeAllAtmosphereHandler();
* nettosphere.framework().resetStates();
* nettosphere.framework().destroy();
*/
nettosphere.stop();
}
}).start();
sleep(1000);
}
}
public void stopService() {
super.stopService();
stop();
}
// FIXME
/**
* UseLocalResources determines if references to JQuery JavaScript library are
* local or if the library is linked to using content delivery network.
* Default (false) is to use the CDN
*
* @param useLocalResources
* - true uses local resources fals uses cdn
*/
public void useLocalResources(boolean useLocalResources) {
this.useLocalResources = useLocalResources;
}
public void setAddress(String address) {
this.address = address;
}
public static void main(String[] args) {
LoggingFactory.init(Level.WARN);
try {
// Double level = Runtime.getBatteryLevel();
// log.info("" + level);
/*
* VirtualArduino virtual = (VirtualArduino)Runtime.start("virtual",
* "VirtualArduino"); virtual.connect("COM5");
*
* Runtime.start("python", "Python");
*/
// Runtime.start("arduino", "Arduino");
// Runtime.start("srf05", "UltrasonicSensor");
// Runtime.setRuntimeName("george");
WebGui webgui = (WebGui) Runtime.start("webgui", "WebGui");
webgui.autoStartBrowser(true);
// Runtime.start("mary", "MarySpeech");
} catch (Exception e) {
Logging.logError(e);
}
}
} |
/**
* This file was automatically generated by the Mule Development Kit
*/
package org.nuxeo.mule;
import org.mule.api.ConnectionException;
import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.Module;
import org.mule.api.annotations.Processor;
import org.mule.api.annotations.display.Password;
import org.mule.api.annotations.display.Placement;
import org.mule.api.annotations.lifecycle.Start;
import org.mule.api.annotations.lifecycle.Stop;
import org.mule.api.annotations.param.Default;
import org.mule.api.annotations.param.Optional;
import org.nuxeo.ecm.automation.client.AutomationClient;
import org.nuxeo.ecm.automation.client.Session;
import org.nuxeo.ecm.automation.client.adapters.DocumentService;
import org.nuxeo.ecm.automation.client.jaxrs.impl.HttpAutomationClient;
import org.nuxeo.ecm.automation.client.model.DocRef;
import org.nuxeo.ecm.automation.client.model.Document;
import org.nuxeo.ecm.automation.client.model.Documents;
import org.nuxeo.ecm.automation.client.model.FileBlob;
import org.nuxeo.ecm.automation.client.model.PropertyMap;
/**
* Connector that uses Nuxeo Automation java client to leverage Nuxeo Rest API
*
* @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
*
*/
@Module(name = "nuxeo", schemaVersion = "1.0-SNAPSHOT")
public class NuxeoConnector {
/**
* Username to connect to Nuxeo Server
*/
@Configurable
@Placement(group = "Authentication")
private String username;
/**
* Password to connect to Nuxeo Server
*/
@Configurable
@Password
@Placement(group = "Authentication")
private String password;
/**
* Nuxeo Server name (IP or DNS name)
*/
@Configurable
@Placement(group = "Connection")
private String serverName = "localhost";
/**
* Port used to connect to Nuxeo Server
*/
@Configurable
@Placement(group = "Connection")
private String port = "8080";
/**
* Context Path for Nuxeo instance
*/
@Configurable
@Placement(group = "Connection")
private String contextPath = "nuxeo";
/**
* get Login used to connect to Nuxeo
*
* @return Login used to connect to Nuxeo
*/
public String getUsername() {
return username;
}
/**
* get Password used to connect to Nuxeo
*
* @return Password used to connect to Nuxeo
*/
public String getPassword() {
return password;
}
/**
* get Nuxeo Server Name
*
* @return Nuxeo Server Name
*/
public String getServerName() {
return serverName;
}
/**
* get Nuxeo Server Port
*
* @return Nuxeo Server Port
*/
public String getPort() {
return port;
}
/**
* get Nuxeo Server Context pat
*
* @return Nuxeo Server Context path
*/
public String getContextPath() {
return contextPath;
}
/**
* set Username used to connect to Nuxeo Server
*
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* set Password used to connect to Nuxeo Server
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* set Nuxeo Server name
*
* @param serverName
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
/**
* set port used to connect to Nuxeo Server
*
* @param port
*/
public void setPort(String port) {
this.port = port;
}
/**
* set Context path of the target Nuxeo Server
*
* @param contextPath
*/
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
private Session session;
protected String getServerUrl() {
return "http://" + serverName + ":" + port + "/" + contextPath
+ "/site/automation";
}
protected DocumentService docService;
/**
* Connect to Nuxeo Server via Automation java client
*
* @throws ConnectionException
*/
// @Connect
@Start
public void connect() throws ConnectionException {
AutomationClient client = new HttpAutomationClient(getServerUrl());
session = client.getSession(this.username, this.password);
docService = session.getAdapter(DocumentService.class);
}
/**
* Disconnect
*/
// @Disconnect
@Stop
public void disconnect() {
if (session != null) {
session.close();
}
}
/**
* Are we connected
*/
// @ValidateConnection
public boolean isConnected() {
return (session != null);
}
/**
* Are we connected
*/
// @ConnectionIdentifier
public String connectionId() {
return getServerUrl() + username;
}
/**
* Get a Document from Nuxeo repository
*
* @param ref the DocumentRef
* @return a Document Object
* @throws Exception in case of error
*/
@Processor
public Document getDocument(String ref) throws Exception {
return docService.getDocument(ref);
}
/**
* Get the root Document of Nuxeo Repository
*
* @return a Document Object
* @throws Exception
*/
@Processor
public Document getRootDocument() throws Exception {
return getDocument("/");
}
/**
* Create a Document
*
* @param parent reference of the Parent document
* @param type Document Type
* @param docName name of the target Document
* @param properties Metadata
* @return a Document Object
* @throws Exception
*/
@Processor
public Document createDocument(String parent, String type, String docName,
PropertyMap properties) throws Exception {
return docService.createDocument(new DocRef(parent), type, docName,
properties);
}
/**
* Deletes a Document
*
* @param ref reference of the Document to delete
* @throws Exception
*/
@Processor
public void remove(String ref) throws Exception {
docService.remove(ref);
}
/**
* Copy a Document
*
* @param src reference of the source document
* @param targetParent reference of the destination document
* @param docName name of the copied document
* @return a Document Object
* @throws Exception
*/
@Processor
public Document copy(String src, String targetParent, @Optional
@Default("")
String docName) throws Exception {
if (docName == null || docName.isEmpty()) {
return docService.copy(new DocRef(src), new DocRef(targetParent));
} else {
return docService.copy(new DocRef(src), new DocRef(targetParent),
docName);
}
}
/**
* Move a Document
*
* @param src the reference of the document to move
* @param targetParent the reference of thr target parent
* @param docName the name of the document after move
* @return a Document Object
* @throws Exception
*/
@Processor
public Document move(String src, String targetParent, @Optional
@Default("")
String docName) throws Exception {
if (docName == null || docName.isEmpty()) {
return docService.move(new DocRef(src), new DocRef(targetParent));
} else {
return docService.move(new DocRef(src), new DocRef(targetParent),
docName);
}
}
/**
* Retrieves children of a Document
*
* @param docRef Reference of the parent Document
* @return a Documents List
* @throws Exception
*/
@Processor
public Documents getChildren(String docRef) throws Exception {
return docService.getChildren(new DocRef(docRef));
}
/**
* Get a children
*
* @param docRef reference of the parent Document
* @param docName name of the child to fetch
* @return a Document Objects
* @throws Exception
*/
@Processor
public Document getChild(String docRef, String docName) throws Exception {
return docService.getChild(new DocRef(docRef), docName);
}
/**
* Get Parent Document
*
* @param docRef reference of the Document
* @return a Document Object
* @throws Exception
*/
@Processor
public Document getParent(String docRef) throws Exception {
return docService.getParent(new DocRef(docRef));
}
/**
* Runs a NXQL Query against repository
*
* @param query NXQL Query
* @return a Documents List
* @throws Exception
*/
@Processor
public Documents query(String query) throws Exception {
return docService.query(query);
}
@Processor
public Document setPermission(String doc, String user, String permission,
String acl, boolean granted) throws Exception {
return docService.setPermission(new DocRef(doc), user, permission, acl,
granted);
}
/**
* Removes an ACL
*
* @param doc reference of the target Document
* @param acl ACL
* @return a Document Object
* @throws Exception
*/
@Processor
public Document removeAcl(String doc, String acl) throws Exception {
return docService.removeAcl(new DocRef(doc), acl);
}
/**
* Set Lifecycle State
*
* @param doc reference to the target Document
* @param state LifeCycle State
* @return a Document Object
* @throws Exceptions
*/
@Processor
public Document setState(String doc, String state) throws Exception {
return docService.setState(new DocRef(doc), state);
}
/**
* Locks a Document
*
* @param doc target Document
* @param lock lock info (can be null)
* @return a Document Object
* @throws Exception
*/
@Processor
public Document lock(String doc, String lock) throws Exception {
if (lock == null || lock.isEmpty()) {
return docService.lock(new DocRef(doc));
} else {
return docService.lock(new DocRef(doc), lock);
}
}
/**
* Unlocks a Document
*
* @param doc reference to the target Document
* @return a Document Object
* @throws Exception
*/
@Processor
public Document unlock(String doc) throws Exception {
return docService.unlock(new DocRef(doc));
}
/**
* Change a property on a Document
*
* @param doc reference to the target Document
* @param key property Name
* @param value property Value
* @return a Document Object
* @throws Exception
*/
@Processor
public Document setProperty(String doc, String key, String value)
throws Exception {
return docService.setProperty(new DocRef(doc), key, value);
}
/**
* Remove a Property on a Document
*
* @param doc reference to the target Document
* @param key property name
* @return a Document Object
* @throws Exception
*/
@Processor
public Document removeProperty(String doc, String key) throws Exception {
return docService.removeProperty(new DocRef(doc), key);
}
/**
* Updates a Document
*
* @param doc reference to the target Document
* @param properties Map of properties to set on document
* @return a Document Object
* @throws Exception
*/
@Processor
public Document update(String doc, PropertyMap properties) throws Exception {
return docService.update(new DocRef(doc), properties);
}
/**
* Publish a Document
*
* @param doc reference to the target Document
* @param section reference of the publish target
* @param override flag to control override
* @return a Document Object
* @throws Exception
*/
@Processor
public Document publish(String doc, String section, @Optional
@Default("false")
boolean override) throws Exception {
return docService.publish(new DocRef(doc), new DocRef(section),
override);
}
/**
* Create a Relation
*
* @param subject reference to the target Document
* @param predicate predicate of the relation
* @param object reference on the target related Document
* @return a Document Object
* @throws Exception
*/
@Processor
public Document createRelation(String subject, String predicate,
DocRef object) throws Exception {
return docService.createRelation(new DocRef(subject), predicate, object);
}
/**
* get Relations
*
* @param doc reference to the target Document
* @param predicate predicate to search for
* @param outgoing flag to indicate of relations processed must be outgoing
* or incoming
* @return list of linked Document Objects
* @throws Exception
*/
@Processor
public Documents getRelations(String doc, String predicate, boolean outgoing)
throws Exception {
return docService.getRelations(new DocRef(doc), predicate, outgoing);
}
/**
* Attach a Blob to a Document
*
* @param doc reference to the target Document
* @param blob Blob to attach
* @param xpath Xpath of the target property
* @throws Exception
*/
@Processor
public void setBlob(String doc, FileBlob blob, @Optional
@Default("")
String xpath) throws Exception {
if (xpath == null || xpath.isEmpty()) {
docService.setBlob(new DocRef(doc), blob);
} else {
docService.setBlob(new DocRef(doc), blob, xpath);
}
}
/**
* Remove a Blob from a Document
*
* @param doc reference to the target Document
* @param xpath xpath of the target Blob
* @throws Exception
*/
@Processor
public void removeBlob(String doc, @Optional
@Default("")
String xpath) throws Exception {
if (xpath == null || xpath.isEmpty()) {
docService.removeBlob(new DocRef(doc));
} else {
docService.removeBlob(new DocRef(doc), xpath);
}
}
/**
* get the Blob associated to a Document
*
* @param doc reference to the target Document
* @param xpath xpath of the target Blob
* @return a FileBlob object
* @throws Exception
*/
@Processor
public FileBlob getBlob(String doc, @Optional
@Default("")
String xpath) throws Exception {
if (xpath == null || xpath.isEmpty()) {
return docService.getBlob(new DocRef(doc));
} else {
return docService.getBlob(new DocRef(doc), xpath);
}
}
/**
* get the Blobs associated to a Document
*
* @param doc
* @param xpath
* @return a list of Blobs
* @throws Exception
*/
// @Processor
/*
* public Blobs getBlobs(String doc, @Optional
*
* @Default("") String xpath) throws Exception {
*
* if (xpath == null || xpath.isEmpty()) { return docService.getBlobs(new
* DocRef(doc)); } else { return docService.getBlobs(new DocRef(doc),
* xpath); } }
*/
/**
* Creates a version
*
* @param doc reference to the target Document
* @param increment increment policy (minor/major)
* @return a Document Object
* @throws Exception
*/
@Processor
public Document createVersion(String doc, @Optional
@Default("")
String increment) throws Exception {
if (increment == null || increment.isEmpty()) {
return docService.createVersion(new DocRef(doc));
} else {
return docService.createVersion(new DocRef(doc), increment);
}
}
/**
* Fire an Event
*
* @param event name of the event to raise
* @param doc reference to the document to attach to the event
* @throws Exception
*/
@Processor
public void fireEvent(String event, @Optional
@Default("")
String doc) throws Exception {
if (doc == null || doc.isEmpty()) {
docService.fireEvent(event);
} else {
docService.fireEvent(new DocRef(doc), event);
}
}
} |
package api.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import actions.scoringActions.ScoringSummStAction;
import api.ApiInterface;
import application.AppBean;
import beans.relation.summary.SummaryStatement;
import beans.scoring.LearningAnalyticsBean;
import beans.scoring.PeerContainer;
import beans.scoring.ScoreBean;
import beans.scoring.ScoreContainer;
import beans.scripts.PatientIllnessScript;
import controller.NavigationController;
import controller.PeerSyncController;
import controller.SummaryStatementController;
import database.DBClinReason;
import net.casus.util.CasusConfiguration;
import net.casus.util.StringUtilities;
import net.casus.util.Utility;
import util.CRTLogger;
/**
* simple JSON Webservice for simple API JSON framework
*
* <base>/crt/src/html/api/api.xhtml?impl=peerSync
* should either start a new thread, or return basic running thread data!
*
* @author Gulpi (=Martin Adler)
*/
public class SummaryStatementAPI implements ApiInterface {
public SummaryStatementAPI() {
}
@SuppressWarnings("unchecked")
@Override
public synchronized String handle() {
String result = null;
@SuppressWarnings("rawtypes")
Map resultObj = new HashMap();
long id = StringUtilities.getLongFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("id"), -1);
if (id > 0) {
SummaryStatement st = null;
PatientIllnessScript userPatientIllnesScript = new DBClinReason().selectLearnerPatIllScript(id, "id");
PatientIllnessScript expScript = (PatientIllnessScript) new DBClinReason().selectExpertPatIllScriptByVPId(userPatientIllnesScript.getVpId());
expScript.getSummStStage();
ScoreBean scoreBean = new ScoreBean(userPatientIllnesScript, userPatientIllnesScript.getSummStId(), ScoreBean.TYPE_SUMMST, userPatientIllnesScript.getStage());
if(expScript!=null && expScript.getSummSt()!=null){
ScoringSummStAction action = new ScoringSummStAction();
st = new SummaryStatementController().initSummStRating(expScript, userPatientIllnesScript, action);
}
if (st != null) {
resultObj.put("status", "ok");
resultObj.put("SummaryStatement", st);
}
else {
resultObj.put("status", "error");
resultObj.put("errorMsg", "no SummaryStatement object ?");
}
}
else {
resultObj.put("status", "error");
resultObj.put("errorMsg", "userPatientIllnesScriptID invalid! " + id);
}
ObjectMapper mapper = new ObjectMapper();
try {
if (CasusConfiguration.getGlobalBooleanValue("SummaryStatementAPI.prettyJSON", true)) {
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultObj);
}
else {
result = mapper.writeValueAsString(resultObj);
}
} catch (JsonProcessingException e) {
result = e.getMessage();
}
return result;
}
} |
package org.tarrio.debloat;
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 org.tarrio.debloat.Codec.Decoder;
import org.tarrio.debloat.registry.CompressionAlgorithmRegistry;
/**
* Example command-line utility to compress and decompress files using the
* Debloat library.
*
* @author Jacobo Tarrio
*/
public class DebloatCmd {
private final InputStream inputStream;
private final OutputStream outputStream;
private final String algorithm;
private final Operation operation;
public enum Operation {
COMPRESS, DECOMPRESS;
}
public DebloatCmd(String inputFileName, String outputFileName,
String algorithm, Operation operation) throws FileNotFoundException {
this.inputStream = inputFileName == null ? System.in
: new FileInputStream(inputFileName);
this.outputStream = outputFileName == null ? System.out
: new FileOutputStream(outputFileName);
this.algorithm = algorithm;
this.operation = operation;
}
private void run() throws IOException {
Codec codec = CodecFactory.getCodec();
if (operation == Operation.COMPRESS) {
CompressionAlgorithm compressor = CompressionAlgorithmRegistry.getInstance().get(
algorithm);
compressor.compress(inputStream, codec.getEncoder(outputStream));
} else {
Decoder decoder = codec.getDecoder(inputStream);
CompressionAlgorithm compressor = CompressionAlgorithmRegistry.getInstance()
.get(decoder);
compressor.decompress(decoder, outputStream);
}
}
private static void showHelp() {
System.err
.println("Arguments: [<command>] <inputFilename> <outputFilename>");
System.err.println("");
System.err
.println("If the input or output file names are not specified, or if they are \"-\",");
System.err.println("the standard input/output will be used.");
System.err.println("");
System.err.println("Commands:");
System.err.println(" -c : Compress (default)");
System.err.println(" -d : Decompress");
System.err
.println(" -a=<algorithm> : Select algorithm (default: LZ77)");
System.err.println(" Available algorithms:");
for (String algorithm : CompressionAlgorithmRegistry.getInstance().getAlgorithms()) {
System.err.println(" - " + algorithm);
}
}
public static DebloatCmd parseArgs(String[] args) throws FileNotFoundException {
String input = null;
String output = null;
String algorithm = "LZ77";
Operation operation = Operation.COMPRESS;
for (String arg : args) {
if (arg.startsWith("-") && !"-".equals(arg)) {
if ("-d".equals(arg)) {
operation = Operation.DECOMPRESS;
} else if ("-c".equals(arg)) {
operation = Operation.COMPRESS;
} else if (arg.startsWith("-a=")) {
algorithm = arg.substring(3);
} else {
showHelp();
}
} else {
if (input == null) {
input = "-".equals(arg) ? null : arg;
} else if (output == null) {
output = "-".equals(arg) ? null : arg;
} else {
showHelp();
}
}
}
return new DebloatCmd(input, output, algorithm, operation);
}
public static void main(String[] args) throws IOException {
parseArgs(args).run();
}
} |
package org.znerd.util.text;
public class TextUtils {
public static final String quote(Object o) {
return o == null ? "(null)" : quote(o.toString());
}
public static final boolean isEmpty(String s) {
return s == null || "".trim().equals(s);
}
private TextUtils() {
}
} |
package org.jetbrains.plugins.groovy.lang.psi.impl.javaView;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileEvent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.plugins.groovy.caches.GroovyCachesManager;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import java.util.*;
/**
* @author ven
*/
public class GroovyClassFinder implements ProjectComponent, PsiElementFinder {
private Project myProject;
private Map<GroovyFile, GrJavaFile> myJavaFiles = new WeakHashMap<GroovyFile, GrJavaFile>();
private GroovyClassFinder.MyVFSListener myVfsListener;
public GroovyClassFinder(Project project) {
myProject = project;
}
@Nullable
public PsiClass findClass(@NotNull String qualifiedName, GlobalSearchScope scope) {
GrTypeDefinition typeDef = GroovyCachesManager.getInstance(myProject).getClassByName(qualifiedName, scope);
if (typeDef == null) return null;
return new GrJavaClass(getJavaFile((GroovyFile) typeDef.getContainingFile()), typeDef);
}
private GrJavaFile getJavaFile(GroovyFile file) {
GrJavaFile javaFile = myJavaFiles.get(file);
if (javaFile == null) {
javaFile = new GrJavaFile(file);
myJavaFiles.put(file, javaFile);
}
return javaFile;
}
@NotNull
public PsiClass[] findClasses(String qualifiedName, GlobalSearchScope scope) {
GrTypeDefinition[] typeDefs = GroovyCachesManager.getInstance(myProject).getClassesByName(qualifiedName, scope);
if (typeDefs.length == 0) return PsiClass.EMPTY_ARRAY;
PsiClass[] result = new PsiClass[typeDefs.length];
for (int i = 0; i < result.length; i++) {
GrTypeDefinition typeDef = typeDefs[i];
result[i] = new GrJavaClass(getJavaFile((GroovyFile) typeDef.getContainingFile()), typeDef);
}
return result;
}
@Nullable
public PsiPackage findPackage(String qualifiedName) {
return null;
}
@NotNull
public PsiPackage[] getSubPackages(PsiPackage psiPackage, GlobalSearchScope scope) {
return new PsiPackage[0];
}
@NotNull
public PsiClass[] getClasses(PsiPackage psiPackage, GlobalSearchScope scope) {
List<PsiClass> result = new ArrayList<PsiClass>();
for (final PsiDirectory dir : psiPackage.getDirectories(scope)) {
for (final PsiFile file : dir.getFiles()) {
if (file instanceof GroovyFile) {
result.addAll(Arrays.asList(getJavaFile((GroovyFile) file).getClasses()));
}
}
}
return result.toArray(new PsiClass[result.size()]);
}
public void projectOpened() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
myVfsListener = new MyVFSListener();
VirtualFileManager.getInstance().addVirtualFileListener(myVfsListener);
}
});
}
public void projectClosed() {
VirtualFileManager.getInstance().addVirtualFileListener(myVfsListener);
}
@NonNls
@NotNull
public String getComponentName() {
return "Groovy class finder";
}
public void initComponent() {
}
public void disposeComponent() {
}
class MyVFSListener extends VirtualFileAdapter {
public void beforeFileDeletion(VirtualFileEvent event) {
VirtualFile vFile = event.getFile();
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
if (psiFile instanceof GroovyFile) {
GroovyFile groovyFile = (GroovyFile) psiFile;
myJavaFiles.remove(groovyFile);
}
}
}
} |
package pirateboat.torrent;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import pirateboat.info.TheFilmDataBaseService;
import pirateboat.utilities.HttpHelper;
import pirateboat.utilities.PropertiesHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class Premiumize extends HttpUser {
private final TheFilmDataBaseService theFilmDataBaseService;
private static final Logger log = LoggerFactory.getLogger(Premiumize.class);
public Premiumize(HttpHelper httpHelper, TheFilmDataBaseService theFilmDataBaseService) {
super(httpHelper);
this.theFilmDataBaseService = theFilmDataBaseService;
}
public String addTorrentToQueue(Torrent toBeAddedTorrent) {
String response;
String addTorrenntUrl = "https:
PropertiesHelper.getProperty("customer_id") + "&pin=" + PropertiesHelper.getProperty("pin") +
"&type=hello.torrent&src=" + cleanMagnetUri(toBeAddedTorrent.magnetUri);
response = httpHelper.getPage(addTorrenntUrl);
return response;
}
private String cleanMagnetUri(String magnetUri) {
return magnetUri.replaceAll(" ", "_");
}
public ArrayList<Torrent> getRemoteTorrents() {
ArrayList<Torrent> remoteTorrentList;
String responseTorrents;
responseTorrents = httpHelper.getPage("https:
PropertiesHelper.getProperty("customer_id") + "&pin=" + PropertiesHelper.getProperty("pin"));
remoteTorrentList = parseRemoteTorrents(responseTorrents);
return remoteTorrentList;
}
public String getMainFileURLFromTorrent(Torrent torrent) {
List<TorrentFile> tfList = getFilesFromTorrent(torrent);
String remoteURL = null;
// iterate over and check for One File Torrent
long biggestFileYet = 0;
for (TorrentFile tf : tfList) {
if (tf.filesize > biggestFileYet) {
biggestFileYet = tf.filesize;
remoteURL = tf.url;
}
}
return remoteURL;
}
public List<TorrentFile> getFilesFromTorrent(Torrent torrent) {
List<TorrentFile> returnList = new ArrayList<>();
String responseFiles = httpHelper.getPage("https:
"&customer_id=" +
PropertiesHelper.getProperty("customer_id") + "&pin=" + PropertiesHelper.getProperty("pin"));
ObjectMapper m = new ObjectMapper();
try {
JsonNode rootNode = m.readTree(responseFiles);
JsonNode localNodes = rootNode.path("content");
List<JsonNode> fileList = localNodes.findParents("type");
for (JsonNode jsonFile : fileList) {
if (jsonFile.get("type").asText().equals("file")) {
extractTorrentFileFromJSON(torrent, returnList, jsonFile, "");
} else if (jsonFile.get("type").asText().equals("folder")) {
extractTorrentFilesFromJSONFolder(torrent, returnList, jsonFile, "");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return returnList;
}
private void extractTorrentFilesFromJSONFolder(Torrent torrent, List<TorrentFile> returnList, JsonNode jsonFolder, String prefix) {
String responseFiles = httpHelper.getPage("https:
"&customer_id=" +
PropertiesHelper.getProperty("customer_id") + "&pin=" + PropertiesHelper.getProperty("pin"));
String folderName = prefix + String.valueOf(jsonFolder.get("name").asText()) + "/";
ObjectMapper m = new ObjectMapper();
JsonNode rootNode = null;
try {
rootNode = m.readTree(responseFiles);
JsonNode localNodes = rootNode.path("content");
List<JsonNode> fileList = localNodes.findParents("type");
for (JsonNode jsonFile : fileList) {
if (jsonFile.get("type").asText().equals("file")) {
extractTorrentFileFromJSON(torrent, returnList, jsonFile, folderName);
} else if (jsonFile.get("type").asText().equals("folder")) {
extractTorrentFilesFromJSONFolder(torrent, returnList, jsonFile, folderName);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void extractTorrentFileFromJSON(Torrent torrent, List<TorrentFile> returnList, JsonNode jsonFile, String prefix) {
TorrentFile tf = new TorrentFile();
// check if hello.torrent is onefile and is located in root
if (torrent.file_id != null && torrent.folder_id != null) {
if (String.valueOf(jsonFile.get("id").asText()).equals(torrent.file_id)) {
tf.name = prefix + jsonFile.get("name").asText();
tf.filesize = jsonFile.get("size").asLong();
tf.url = jsonFile.get("link").asText();
returnList.add(tf);
}
} else {
tf.name = prefix + jsonFile.get("name").asText();
tf.filesize = jsonFile.get("size").asLong();
tf.url = jsonFile.get("link").asText();
returnList.add(tf);
}
}
private ArrayList<Torrent> parseRemoteTorrents(String pageContent) {
ArrayList<Torrent> remoteTorrentList = new ArrayList<>();
ObjectMapper m = new ObjectMapper();
try {
JsonNode rootNode = m.readTree(pageContent);
JsonNode localNodes = rootNode.path("transfers");
for (JsonNode localNode : localNodes) {
Torrent tempTorrent = new Torrent(toString());
tempTorrent.name = localNode.get("name").asText();
tempTorrent.folder_id = localNode.get("folder_id").asText();
tempTorrent.file_id = localNode.get("file_id").asText();
tempTorrent.folder_id = cleanJsonNull(tempTorrent.folder_id);
tempTorrent.file_id = cleanJsonNull(tempTorrent.file_id);
tempTorrent.remoteId = localNode.get("id").toString().replace("\"", "");
tempTorrent.status = localNode.get("status").asText();
String src = localNode.get("src").asText();
if(src.contains("btih")) {
tempTorrent.magnetUri = src;
}
String[] messages = localNode.get("message").asText().split(",");
if (messages.length == 3) {
tempTorrent.eta = messages[2];
}
tempTorrent.progress = localNode.get("progress").toString();
remoteTorrentList.add(tempTorrent);
}
} catch (IOException e) {
e.printStackTrace();
}
return remoteTorrentList;
}
private String cleanJsonNull(String inputString) {
return inputString.equals("null") ? null : inputString;
}
public void delete(Torrent remoteTorrent) {
String removeTorrenntUrl = "https:
PropertiesHelper.getProperty("customer_id") + "&pin=" + PropertiesHelper.getProperty("pin") +
"&type=hello.torrent&src=" + remoteTorrent.magnetUri;
httpHelper.getPage(removeTorrenntUrl);
}
public boolean isSingleFileDownload(Torrent remoteTorrent) {
List<TorrentFile> tfList = getFilesFromTorrent(remoteTorrent);
// getMaxFilesize
// getSumSize
long sumFileSize = 0L;
long biggestFileYet = 0L;
for (TorrentFile tf : tfList) {
if (tf.filesize > biggestFileYet) {
biggestFileYet = tf.filesize;
}
sumFileSize += tf.filesize;
}
// if maxfilesize >90% sumSize --> Singlefile
return biggestFileYet > (0.9d * sumFileSize);
}
public List<Torrent> getCacheStateOfTorrents(List<Torrent> torrents) {
String requestUrl = "https:
PropertiesHelper.getProperty("pin") + "%s";
String urlEncodedBrackets = TorrentHelper.urlEncode("[]");
String collected = torrents.stream().map(Torrent::getTorrentId).collect(Collectors.joining("&items" + urlEncodedBrackets + "=", "&items" + urlEncodedBrackets + "=", ""));
String checkUrl = String.format(requestUrl, collected);
String pageContent = httpHelper.getPage(checkUrl);
JsonParser parser = new JsonParser();
JsonElement jsonRoot = parser.parse(pageContent);
if (jsonRoot == null || !jsonRoot.isJsonObject()) {
log.error("couldn't retrieve cache for:" + checkUrl);
log.error(pageContent);
} else {
JsonElement reponse = jsonRoot.getAsJsonObject().get("response");
JsonArray reponseArray = reponse.getAsJsonArray();
AtomicInteger index = new AtomicInteger();
if (reponseArray.size() == torrents.size()) {
reponseArray.forEach(jsonElement -> {
torrents.get(index.get()).isCached = jsonElement.getAsBoolean();
index.getAndIncrement();
});
}
}
return torrents;
}
} |
package org.jkiss.dbeaver.ext.exasol.model;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.exasol.model.cache.ExasolTableCache;
import org.jkiss.dbeaver.ext.exasol.model.cache.ExasolTableForeignKeyCache;
import org.jkiss.dbeaver.ext.exasol.model.cache.ExasolTableUniqueKeyCache;
import org.jkiss.dbeaver.ext.exasol.model.cache.ExasolViewCache;
import org.jkiss.dbeaver.ext.exasol.tools.ExasolUtils;
import org.jkiss.dbeaver.model.DBPRefreshableObject;
import org.jkiss.dbeaver.model.DBPScriptObject;
import org.jkiss.dbeaver.model.DBPSystemObject;
import org.jkiss.dbeaver.model.impl.DBSObjectCache;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectSimpleCache;
import org.jkiss.dbeaver.model.meta.Association;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureContainer;
import org.jkiss.dbeaver.model.struct.rdb.DBSSchema;
public class ExasolSchema extends ExasolGlobalObject implements DBSSchema, DBPRefreshableObject, DBPSystemObject, DBSProcedureContainer, DBPScriptObject {
private static final List<String> SYSTEM_SCHEMA = Arrays.asList("SYS","EXA_STATISTICS");
private String name;
private String owner;
private Timestamp createTime;
private String remarks;
// ExasolSchema's children
private DBSObjectCache<ExasolSchema, ExasolScript> scriptCache;
private ExasolViewCache viewCache = new ExasolViewCache();
private ExasolTableCache tableCache = new ExasolTableCache();
// ExasolTable's children
private final ExasolTableUniqueKeyCache constraintCache = new ExasolTableUniqueKeyCache(tableCache);
private final ExasolTableForeignKeyCache associationCache = new ExasolTableForeignKeyCache(tableCache);
public ExasolSchema(ExasolDataSource exasolDataSource, String name) {
super(exasolDataSource, true);
this.name = name;
this.scriptCache = new JDBCObjectSimpleCache<>(
ExasolScript.class,
"select "
+ "script_name,script_owner,script_language,script_type,script_result_type,script_text,script_comment,b.created "
+ "from EXA_ALL_SCRIPTS a inner join EXA_ALL_OBJECTS b "
+ "on a.script_name = b.object_name and a.script_schema = b.root_name where a.script_schema = ? order by script_name",
name);
}
public ExasolSchema(ExasolDataSource exasolDataSource, ResultSet dbResult) throws DBException {
this(exasolDataSource, JDBCUtils.safeGetStringTrimmed(dbResult, "OBJECT_NAME"));
this.owner = JDBCUtils.safeGetString(dbResult, "OWNER");
this.createTime = JDBCUtils.safeGetTimestamp(dbResult, "CREATED");
this.remarks = JDBCUtils.safeGetString(dbResult, "OBJECT_COMMENT");
this.name = JDBCUtils.safeGetString(dbResult, "OBJECT_NAME");
}
@NotNull
@Override
@Property(viewable = true, editable = false, order = 1)
public String getName() {
return this.name;
}
@Override
public Collection<ExasolTableBase> getChildren(DBRProgressMonitor monitor) throws DBException {
List<ExasolTableBase> allChildren = new ArrayList<>();
allChildren.addAll(tableCache.getAllObjects(monitor, this));
allChildren.addAll(viewCache.getAllObjects(monitor, this));
return allChildren;
}
@Override
public ExasolTableBase getChild(DBRProgressMonitor monitor, String childName) throws DBException {
ExasolTableBase child = tableCache.getObject(monitor, this, childName);
if (child == null) {
child = viewCache.getObject(monitor, this, childName);
}
return child;
}
@Override
public Class<ExasolTableBase> getChildType(DBRProgressMonitor monitor) throws DBException {
return ExasolTableBase.class;
}
@Override
public void cacheStructure(DBRProgressMonitor monitor, int scope) throws DBException {
if (((scope & STRUCT_ENTITIES) != 0)) {
monitor.subTask("Cache tables");
tableCache.getAllObjects(monitor, this);
monitor.subTask("Cache Views");
viewCache.getAllObjects(monitor, this);
}
if (((scope & STRUCT_ATTRIBUTES) != 0)) {
monitor.subTask("Cache table columns");
tableCache.loadChildren(monitor, this, null);
monitor.subTask("Cache Views");
viewCache.loadChildren(monitor, this, null);
}
if ((scope & STRUCT_ASSOCIATIONS) != 0) {
monitor.subTask("Cache table unique keys");
constraintCache.getObjects(monitor, this, null);
monitor.subTask("Cache table foreign keys");
associationCache.getObjects(monitor, this, null);
}
}
// Associations
@Association
public Collection<ExasolTable> getTables(DBRProgressMonitor monitor) throws DBException {
return tableCache.getTypedObjects(monitor, this, ExasolTable.class);
}
public ExasolTable getTable(DBRProgressMonitor monitor, String name) throws DBException {
return tableCache.getObject(monitor, this, name, ExasolTable.class);
}
@Association
public Collection<ExasolView> getViews(DBRProgressMonitor monitor) throws DBException {
return viewCache.getTypedObjects(monitor, this, ExasolView.class);
}
public ExasolView getView(DBRProgressMonitor monitor, String name) throws DBException {
return viewCache.getObject(monitor, this, name, ExasolView.class);
}
@Override
public boolean isSystem() {
// TODO Auto-generated method stub
return SYSTEM_SCHEMA.contains(name);
}
@Override
public Collection<ExasolScript> getProcedures(DBRProgressMonitor monitor) throws DBException {
return scriptCache.getAllObjects(monitor, this);
}
@Override
public ExasolScript getProcedure(DBRProgressMonitor monitor, String uniqueName) throws DBException {
return scriptCache.getObject(monitor, this, uniqueName);
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
scriptCache.clearCache();
tableCache.clearCache();
viewCache.clearCache();
constraintCache.clearCache();
associationCache.clearCache();
return this;
}
@Override
public String toString() {
return "Schema " + name;
}
@Property(viewable = true, editable = false, order = 2)
public Timestamp getCreateTime() {
return createTime;
}
@Property(viewable = true, editable = false, order = 3)
public String getDescription() {
return remarks;
}
@Property(viewable = true, editable = false, order = 4)
public String getOwner() {
return owner;
}
public ExasolTableCache getTableCache() {
return tableCache;
}
public ExasolViewCache getViewCache() {
return viewCache;
}
public ExasolTableUniqueKeyCache getConstraintCache() {
return constraintCache;
}
public ExasolTableForeignKeyCache getAssociationCache() {
return associationCache;
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor)
throws DBException
{
return ExasolUtils.generateDDLforSchema(monitor, this);
}
} |
package uk.gov.register.core;
import uk.gov.mint.Item;
public class FatEntry {
public final Entry entry;
public final Item item;
public FatEntry(Entry entry, Item item) {
this.entry = entry;
this.item = item;
}
} |
package org.jkiss.dbeaver.ext.mysql.edit;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.IDatabasePersistAction;
import org.jkiss.dbeaver.ext.mysql.MySQLMessages;
import org.jkiss.dbeaver.ext.mysql.model.MySQLCatalog;
import org.jkiss.dbeaver.ext.mysql.model.MySQLDataSource;
import org.jkiss.dbeaver.model.edit.DBECommandContext;
import org.jkiss.dbeaver.model.edit.DBEObjectRenamer;
import org.jkiss.dbeaver.model.impl.DBSObjectCache;
import org.jkiss.dbeaver.model.impl.edit.AbstractDatabasePersistAction;
import org.jkiss.dbeaver.model.impl.jdbc.edit.struct.JDBCObjectEditor;
import org.jkiss.dbeaver.ui.dialogs.EnterNameDialog;
import org.jkiss.utils.CommonUtils;
/**
* MySQLCatalogManager
*/
public class MySQLCatalogManager extends JDBCObjectEditor<MySQLCatalog, MySQLDataSource> implements DBEObjectRenamer<MySQLCatalog> {
@Override
public long getMakerOptions()
{
return FEATURE_SAVE_IMMEDIATELY;
}
@Override
protected DBSObjectCache<MySQLDataSource, MySQLCatalog> getObjectsCache(MySQLCatalog object)
{
return object.getDataSource().getCatalogCache();
}
@Override
protected MySQLCatalog createDatabaseObject(IWorkbenchWindow workbenchWindow, IEditorPart activeEditor, DBECommandContext context, MySQLDataSource parent, Object copyFrom)
{
String schemaName = EnterNameDialog.chooseName(workbenchWindow.getShell(), MySQLMessages.edit_catalog_manager_dialog_schema_name);
if (CommonUtils.isEmpty(schemaName)) {
return null;
}
MySQLCatalog newCatalog = new MySQLCatalog(parent, null);
newCatalog.setName(schemaName);
return newCatalog;
}
@Override
protected IDatabasePersistAction[] makeObjectCreateActions(ObjectCreateCommand command)
{
return new IDatabasePersistAction[] {
new AbstractDatabasePersistAction("Create schema", "CREATE SCHEMA `" + command.getObject().getName() + "`") //$NON-NLS-2$
};
}
@Override
protected IDatabasePersistAction[] makeObjectDeleteActions(ObjectDeleteCommand command)
{
return new IDatabasePersistAction[] {
new AbstractDatabasePersistAction("Drop schema", "DROP SCHEMA `" + command.getObject().getName() + "`") //$NON-NLS-2$
};
}
@Override
public void renameObject(DBECommandContext commandContext, MySQLCatalog catalog, String newName) throws DBException
{
throw new DBException("Direct database rename is not yet implemented in MySQL. You should use export/import functions for that.");
//super.addCommand(new CommandRenameCatalog(newName), null);
//saveChanges(monitor);
}
/*
private class CommandRenameCatalog extends DBECommandAbstract<MySQLCatalog> {
private String newName;
protected CommandRenameCatalog(MySQLCatalog catalog, String newName)
{
super(catalog, "Rename catalog");
this.newName = newName;
}
public IDatabasePersistAction[] getPersistActions()
{
return new IDatabasePersistAction[] {
new AbstractDatabasePersistAction("Rename catalog", "RENAME SCHEMA " + getObject().getName() + " TO " + newName)
};
}
@Override
public void updateModel()
{
getObject().setName(newName);
getObject().getDataSource().getContainer().fireEvent(
new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, getObject()));
}
}
*/
} |
package org.opencps.backend.util;
import java.util.Calendar;
import java.util.Random;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.processmgt.model.ServiceProcess;
import org.opencps.processmgt.model.WorkflowOutput;
import org.opencps.util.PortletConstants;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
/**
* @author khoavd
*
*/
public class DossierNoGenerator {
public static String genaratorNoReceptionOption(String pattern,
long dossierId, String option, boolean isReset , long idGenerateOption) {
return StringUtil.upperCase(_genaratorNoReceptionOption(pattern,
dossierId, option, isReset, idGenerateOption));
}
private static String _genaratorNoReceptionOption(String pattern,
long dossierId, String option, boolean isReset, long idGenerateOption) {
String noReception = StringPool.BLANK;
pattern = StringUtil.lowerCase(pattern);
pattern = StringUtil.trim(pattern, ' ');
StringBuffer sbNoReception = new StringBuffer(pattern);
Calendar cal = Calendar.getInstance();
String strYearTypeOne = Integer.toString(cal.get(Calendar.YEAR));
String strYearTypeTwo = Integer.toString(cal.get(Calendar.YEAR))
.substring(2);
String strMonth = (cal.get(Calendar.MONTH) + 1) < 10 ? "0"
+ Integer.toString(cal.get(Calendar.MONTH) + 1) : Integer
.toString(cal.get(Calendar.MONTH) + 1);
String strDay = cal.get(Calendar.DAY_OF_MONTH) < 10 ? "0"
+ Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) : Integer
.toString(cal.get(Calendar.DAY_OF_MONTH));
if (_validateParttern(pattern)) {
String specialChar = _getSpecicalChar(pattern);
String serialNumber = _serialNumberAutoIncrementOption(pattern,
dossierId, option, isReset, idGenerateOption);
String subPattern = pattern.substring(pattern.indexOf('('), pattern.lastIndexOf(')') + 1);
if (pattern.contains(FIX_MONTH_PATTERN_RESET)
|| pattern.contains(FIX_YEAR_PATTERN_RESET)) {
sbNoReception.replace(subPattern.indexOf('n') - 1,
subPattern.lastIndexOf('n') + 1, serialNumber);
String patternTemp = sbNoReception.toString();
if (patternTemp.contains(FIX_MONTH_PATTERN_RESET)) {
sbNoReception.replace(patternTemp.indexOf('m') - 1,
patternTemp.indexOf('m') + 2, StringPool.BLANK);
} else if(patternTemp.contains(FIX_YEAR_PATTERN_RESET)) {
sbNoReception.replace(patternTemp.indexOf('y') - 1,
patternTemp.indexOf('y') + 2, StringPool.BLANK);
}
if(pattern.contains(subPattern)) {
pattern = StringUtil.replace(pattern, subPattern, sbNoReception.toString());
}
} else {
sbNoReception.replace(subPattern.indexOf('n') - 1,
subPattern.lastIndexOf('n') + 2, serialNumber);
if(pattern.contains(subPattern)) {
pattern = StringUtil.replace(pattern, subPattern, sbNoReception.toString());
}
}
//pattern = sbNoReception.toString();
try {
sbNoReception.replace(pattern.indexOf('%') - 1,
pattern.lastIndexOf('%') + 2, specialChar);
} catch (Exception e) {
}
pattern = sbNoReception.toString();
if (pattern.contains(FIX_YEAR_PATTERN_TYPE_1)) {
pattern = StringUtil.replace(pattern, FIX_YEAR_PATTERN_TYPE_1,
strYearTypeOne);
}
if (pattern.contains(FIX_YEAR_PATTERN_TYPE_2)) {
pattern = StringUtil.replace(pattern, FIX_YEAR_PATTERN_TYPE_2,
strYearTypeTwo);
}
if (pattern.contains(FIX_MONTH_PATTERN)) {
pattern = StringUtil.replace(pattern, FIX_MONTH_PATTERN,
strMonth);
}
if (pattern.contains(FIX_DAY_PATTERN)) {
pattern = StringUtil.replace(pattern, FIX_DAY_PATTERN, strDay);
}
noReception = pattern;
} else {
StringBuffer sbNoReceptionDefault = new StringBuffer();
String serialNumber = noGenarator(FIX_DEFAULT_SERIAL_NUMBER);
sbNoReceptionDefault.append(strYearTypeOne);
sbNoReceptionDefault.append(strMonth);
sbNoReceptionDefault.append(strDay);
sbNoReceptionDefault.append(serialNumber);
noReception = sbNoReceptionDefault.toString();
}
return noReception;
}
private static String _serialNumberAutoIncrementOption(String pattern,
long dossierId, String option, boolean isReset, long idGenerateOption) {
long dossierCounter = 0;
try {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
switch (option) {
case PortletConstants.DOSSIER_PART_RESULT_PATTERN:
if (isReset) {
CounterLocalServiceUtil
.reset(WorkflowOutput.class.getName()
+ StringPool.POUND
+ String.valueOf(idGenerateOption));
}
dossierCounter = CounterLocalServiceUtil
.increment(WorkflowOutput.class.getName()
+ StringPool.POUND
+ String.valueOf(idGenerateOption));
break;
default:
dossierCounter = CounterLocalServiceUtil
.increment(ServiceProcess.class.getName()
+ StringPool.PERIOD
+ Long.toString(dossier.getServiceConfigId()));
break;
}
} catch (Exception e) {
dossierCounter = dossierId;
}
String subPattern = pattern.substring(pattern.indexOf('('), pattern.indexOf(')'));
int numberSerial = StringUtil.count(subPattern, "n");
String strNumSerial = intToString(dossierCounter, numberSerial);
return strNumSerial;
}
/**
* @param pattern
* @return
*/
public static String genaratorNoReception(String pattern, long dossierId) {
return StringUtil.upperCase(_genaratorNoReception(pattern, dossierId));
/*
* Dossier dossier = null;
*
* try { dossier =
* DossierLocalServiceUtil.getDossierByReceptionNo(noReception); } catch
* (Exception e) {
*
* }
*
* if (Validator.isNotNull(dossier)) { noReception =
* genaratorNoReception(pattern, dossierId); }
*
* return noReception;
*/}
/**
* Generate noReception with pattern
*
* @param pattern
* @return
*/
private static String _genaratorNoReception(String pattern, long dossierId) {
String noReception = StringPool.BLANK;
pattern = StringUtil.lowerCase(pattern);
pattern = StringUtil.trim(pattern, ' ');
StringBuffer sbNoReception = new StringBuffer(pattern);
Calendar cal = Calendar.getInstance();
String strYearTypeOne = Integer.toString(cal.get(Calendar.YEAR));
String strYearTypeTwo = Integer.toString(cal.get(Calendar.YEAR))
.substring(2);
String strMonth = (cal.get(Calendar.MONTH) + 1) < 10 ? "0"
+ Integer.toString(cal.get(Calendar.MONTH) + 1) : Integer
.toString(cal.get(Calendar.MONTH) + 1);
String strDay = cal.get(Calendar.DAY_OF_MONTH) < 10 ? "0"
+ Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) : Integer
.toString(cal.get(Calendar.DAY_OF_MONTH));
if (_validateParttern(pattern)) {
String specialChar = _getSpecicalChar(pattern);
String serialNumber = _serialNumberAutoIncrement(pattern, dossierId);
sbNoReception.replace(pattern.indexOf('n') - 1,
pattern.lastIndexOf('n') + 2, serialNumber);
pattern = sbNoReception.toString();
try {
sbNoReception.replace(pattern.indexOf('%') - 1,
pattern.lastIndexOf('%') + 2, specialChar);
} catch (Exception e) {
}
pattern = sbNoReception.toString();
if (pattern.contains(FIX_YEAR_PATTERN_TYPE_1)) {
pattern = StringUtil.replace(pattern, FIX_YEAR_PATTERN_TYPE_1,
strYearTypeOne);
}
if (pattern.contains(FIX_YEAR_PATTERN_TYPE_2)) {
pattern = StringUtil.replace(pattern, FIX_YEAR_PATTERN_TYPE_2,
strYearTypeTwo);
}
if (pattern.contains(FIX_MONTH_PATTERN)) {
pattern = StringUtil.replace(pattern, FIX_MONTH_PATTERN,
strMonth);
}
if (pattern.contains(FIX_DAY_PATTERN)) {
pattern = StringUtil.replace(pattern, FIX_DAY_PATTERN, strDay);
}
noReception = pattern;
} else {
StringBuffer sbNoReceptionDefault = new StringBuffer();
String serialNumber = noGenarator(FIX_DEFAULT_SERIAL_NUMBER);
sbNoReceptionDefault.append(strYearTypeOne);
sbNoReceptionDefault.append(strMonth);
sbNoReceptionDefault.append(strDay);
sbNoReceptionDefault.append(serialNumber);
noReception = sbNoReceptionDefault.toString();
}
return noReception;
}
private static boolean _validateParttern(String pattern) {
boolean isValidator = true;
// pattern = StringUtil.lowerCase(pattern);
int countSpecial = StringUtil.count(pattern, "%");
if (countSpecial > 2) {
isValidator = false;
}
/*
* if (!pattern.contains(FIX_YEAR_PATTERN_TYPE_1) &&
* !pattern.contains(FIX_YEAR_PATTERN_TYPE_2)) { isValidator = false; }
*
* if (!pattern.contains(FIX_MONTH_PATTERN)) { isValidator = false; }
*
* if (!pattern.contains(FIX_DAY_PATTERN)) { isValidator = false; }
*
* if (!pattern.contains(FIX_SERIAL_PATERN)) { isValidator = false; }
*/
return isValidator;
}
/**
* @return
*/
public static String noGenarator(int lengNumber) {
char[] chars = "012346789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < lengNumber; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
/**
* @param pattern
* @param dossierId
* @return
*/
private static String _serialNumberAutoIncrement(String pattern,
long dossierId) {
long dossierCounter = 0;
try {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
dossierCounter = CounterLocalServiceUtil
.increment(ServiceProcess.class.getName()
+ StringPool.PERIOD
+ Long.toString(dossier.getServiceConfigId()));
} catch (Exception e) {
dossierCounter = dossierId;
}
int numberSerial = StringUtil.count(pattern, "n");
String strNumSerial = intToString(dossierCounter, numberSerial);
return strNumSerial;
}
private static String _getSpecicalChar(String pattern) {
String special = StringPool.BLANK;
try {
special = pattern.substring(pattern.indexOf('%') + 1,
pattern.lastIndexOf('%'));
} catch (Exception e) {
// TODO: handle exception
}
return special;
}
/**
* @param number
* @param stringLength
* @return
*/
public static String intToString(long number, int stringLength) {
int numberOfDigits = String.valueOf(number).length();
int numberOfLeadingZeroes = stringLength - numberOfDigits;
StringBuilder sb = new StringBuilder();
if (numberOfLeadingZeroes > 0) {
for (int i = 0; i < numberOfLeadingZeroes; i++) {
sb.append("0");
}
}
sb.append(number);
return sb.toString();
}
public static final String FIX_YEAR_PATTERN_TYPE_1 = "{yyyy}";
public static final String FIX_YEAR_PATTERN_TYPE_2 = "{yy}";
public static final String FIX_MONTH_PATTERN = "{mm}";
public static final String FIX_DAY_PATTERN = "{dd}";
public static final String FIX_MONTH_PATTERN_RESET = "-m";
public static final String FIX_YEAR_PATTERN_RESET = "-y";
public static final String FIX_SERIAL_PATERN = "{nn";
public static final int FIX_DEFAULT_SERIAL_NUMBER = 6;
} |
package com.liferay.webform.portlet;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.captcha.CaptchaTextException;
import com.liferay.portal.kernel.captcha.CaptchaUtil;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.LocalizationUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.expando.model.ExpandoRow;
import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoValueLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.portlet.PortletResponseUtil;
import com.liferay.webform.util.WebFormUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.internet.InternetAddress;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
/**
* @author Daniel Weisser
* @author Jorge Ferrer
* @author Alberto Montero
* @author Julio Camarero
* @author Brian Wing Shun Chan
*/
public class WebFormPortlet extends MVCPortlet {
public void deleteData(
ActionRequest actionRequest, ActionResponse actionResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
WebKeys.THEME_DISPLAY);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(actionRequest);
String databaseTableName = preferences.getValue(
"databaseTableName", StringPool.BLANK);
if (Validator.isNotNull(databaseTableName)) {
ExpandoTableLocalServiceUtil.deleteTable(
themeDisplay.getCompanyId(), WebFormUtil.class.getName(),
databaseTableName);
}
}
public void saveData(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(
WebKeys.THEME_DISPLAY);
String portletId = (String)resourceRequest.getAttribute(
WebKeys.PORTLET_ID);
String tempURL = ParamUtil.getString(resourceRequest, "referUrl");
String tempUsrName = ParamUtil.getString(resourceRequest, "usrName");
String tempScreenName = ParamUtil.getString(resourceRequest, "screenName");
String tempUsrDateStamp = ParamUtil.getString(resourceRequest, "dateStamp");
String tempSuccess = ParamUtil.getString(resourceRequest, "successURL");
System.out.println(">>>>>>>>>>>>>>>>>"+tempSuccess);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(
resourceRequest, portletId);
preferences.setValue("tempURL", tempURL);
preferences.setValue("tempUsrName",tempUsrName);
preferences.setValue("tempUsrDateStamp", tempUsrDateStamp);
preferences.setValue("tempScreenName", tempScreenName);
preferences.setValue("successURL", tempSuccess);
boolean requireCaptcha = GetterUtil.getBoolean(
preferences.getValue("requireCaptcha", StringPool.BLANK));
String successURL = GetterUtil.getString(
preferences.getValue("successURL", StringPool.BLANK));
System.out.println(">>>>>>>>>>>>>>>>>"+successURL);
boolean sendAsEmail = GetterUtil.getBoolean(
preferences.getValue("sendAsEmail", StringPool.BLANK));
boolean saveToDatabase = GetterUtil.getBoolean(
preferences.getValue("saveToDatabase", StringPool.BLANK));
String databaseTableName = GetterUtil.getString(
preferences.getValue("databaseTableName", StringPool.BLANK));
boolean saveToFile = GetterUtil.getBoolean(
preferences.getValue("saveToFile", StringPool.BLANK));
String fileName = GetterUtil.getString(
preferences.getValue("fileName", StringPool.BLANK));
if (requireCaptcha) {
try {
CaptchaUtil.check(resourceRequest);
}
catch (CaptchaTextException cte) {
SessionErrors.add(
resourceRequest, CaptchaTextException.class.getName());
return;
}
}
Map<String,String> fieldsMap = new LinkedHashMap<String,String>();
for (int i = 1; true; i++) {
String fieldLabel = preferences.getValue(
"fieldLabel" + i, StringPool.BLANK);
if (Validator.isNull(fieldLabel)) {
break;
}
fieldsMap.put(fieldLabel, resourceRequest.getParameter("field" + i));
}
Set<String> validationErrors = null;
try {
validationErrors = validate(fieldsMap, preferences);
}
catch (Exception e) {
SessionErrors.add(
resourceRequest, "validation-script-error",
e.getMessage().trim());
return;
}
if (validationErrors.isEmpty()) {
boolean emailSuccess = true;
boolean databaseSuccess = true;
boolean fileSuccess = true;
if (sendAsEmail) {
emailSuccess = sendEmail(fieldsMap, preferences);
}
if (saveToDatabase) {
if (Validator.isNull(databaseTableName)) {
databaseTableName = WebFormUtil.getNewDatabaseTableName(
portletId);
preferences.setValue(
"databaseTableName", databaseTableName);
preferences.store();
}
databaseSuccess = saveDatabase(
themeDisplay.getCompanyId(), fieldsMap, preferences,
databaseTableName);
}
if (saveToFile) {
fileSuccess = saveFile(fieldsMap, fileName);
}
if (emailSuccess && databaseSuccess && fileSuccess) {
SessionMessages.add(resourceRequest, "success");
}
else {
SessionErrors.add(resourceRequest, "error");
}
}
else {
for (String badField : validationErrors) {
SessionErrors.add(resourceRequest, "error" + badField);
}
}
if (SessionErrors.isEmpty(resourceRequest) &&
Validator.isNotNull(successURL)) {
System.out.println(">>>>>>>>>>>>>>>>>!!!update d"+successURL);
getPortletContext().getRequestDispatcher(resourceResponse.encodeURL("/success.jsp")).include(resourceRequest, resourceResponse);
}
}
public void serveResource(
ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
String cmd = ParamUtil.getString(resourceRequest, Constants.CMD);
try {
if (cmd.equals("captcha")) {
serveCaptcha(resourceRequest, resourceResponse);
}
else if (cmd.equals("export")) {
exportData(resourceRequest, resourceResponse);
}else if (cmd.equals("saveData")) {
saveData(resourceRequest, resourceResponse);
}
}
catch (Exception e) {
_log.error(e, e);
}
}
protected void exportData(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(
WebKeys.THEME_DISPLAY);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(resourceRequest);
String databaseTableName = preferences.getValue(
"databaseTableName", StringPool.BLANK);
String title = preferences.getValue("title", "no-title");
StringBuilder sb = new StringBuilder();
List<String> fieldLabels = new ArrayList<String>();
for (int i = 1; true; i++) {
String fieldLabel = preferences.getValue(
"fieldLabel" + i, StringPool.BLANK);
String localizedfieldLabel = LocalizationUtil.getPreferencesValue(
preferences, "fieldLabel" + i, themeDisplay.getLanguageId());
if (Validator.isNull(fieldLabel)) {
break;
}
fieldLabels.add(fieldLabel);
sb.append("\"");
sb.append(localizedfieldLabel.replaceAll("\"", "\\\""));
sb.append("\";");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
if (Validator.isNotNull(databaseTableName)) {
List<ExpandoRow> rows = ExpandoRowLocalServiceUtil.getRows(
themeDisplay.getCompanyId(), WebFormUtil.class.getName(),
databaseTableName, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (ExpandoRow row : rows) {
for (String fieldName : fieldLabels) {
String data = ExpandoValueLocalServiceUtil.getData(
themeDisplay.getCompanyId(),
WebFormUtil.class.getName(), databaseTableName,
fieldName, row.getClassPK(), StringPool.BLANK);
data = data.replaceAll("\"", "\\\"");
sb.append("\"");
sb.append(data);
sb.append("\";");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
}
String fileName = title + ".csv";
byte[] bytes = sb.toString().getBytes();
String contentType = ContentTypes.APPLICATION_TEXT;
PortletResponseUtil.sendFile(
resourceResponse, fileName, bytes, contentType);
}
protected String getMailBody(Map<String,String> fieldsMap) {
StringBuilder sb = new StringBuilder();
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
sb.append(fieldLabel);
sb.append(" : ");
sb.append(fieldValue);
sb.append("\n");
}
return sb.toString();
}
protected boolean saveDatabase(
long companyId, Map<String,String> fieldsMap,
PortletPreferences preferences, String databaseTableName)
throws Exception {
WebFormUtil.checkTable(companyId, databaseTableName, preferences);
long classPK = CounterLocalServiceUtil.increment(
WebFormUtil.class.getName());
try {
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
ExpandoValueLocalServiceUtil.addValue(
companyId, WebFormUtil.class.getName(), databaseTableName,
fieldLabel, classPK, fieldValue);
}
return true;
}
catch (Exception e) {
_log.error(
"The web form data could not be saved to the database", e);
return false;
}
}
protected boolean saveFile(Map<String,String> fieldsMap, String fileName) {
// Save the file as a standard Excel CSV format. Use ; as a delimiter,
// quote each entry with double quotes, and escape double quotes in
// values a two double quotes.
StringBuilder sb = new StringBuilder();
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
sb.append("\"");
sb.append(StringUtil.replace(fieldValue, "\"", "\"\""));
sb.append("\";");
}
String s = sb.substring(0, sb.length() - 1) + "\n";
try {
FileUtil.write(fileName, s, false, true);
return true;
}
catch (Exception e) {
_log.error("The web form data could not be saved to a file", e);
return false;
}
}
protected boolean sendEmail(
Map<String,String> fieldsMap, PortletPreferences preferences) {
try {
String subject = preferences.getValue("subject", StringPool.BLANK);
String emailAddress = preferences.getValue(
"emailAddress", StringPool.BLANK);
if (Validator.isNull(emailAddress)) {
_log.error(
"The web form email cannot be sent because no email " +
"address is configured");
return false;
}
String body="Dear Administrator: \n"+"\nA user in your school(s) or district has reported the following problem:\n\nUser Name : "+preferences.getValue("tempUsrName" ,StringPool.BLANK)+"\nScreen Name : "+preferences.getValue("tempScreenName",StringPool.BLANK);
body+="\n"+getMailBody(fieldsMap);
body+="URL : "+preferences.getValue("tempURL",StringPool.BLANK)+"\nDate : "+preferences.getValue("tempUsrDateStamp",StringPool.BLANK)+"\nThis email has been automatically generated by the SLC.PLEASE DO NOT RESPOND TO THIS EMAIL.\n\nYours,\nSLC Operations TeamURL";
InternetAddress fromAddress = null;
try {
String smtpUser = PropsUtil.get(
PropsKeys.MAIL_SESSION_MAIL_SMTP_USER);
if (Validator.isNotNull(smtpUser)) {
fromAddress = new InternetAddress(smtpUser);
}
}
catch (Exception e) {
_log.error(e, e);
}
if (fromAddress == null) {
fromAddress = new InternetAddress(emailAddress);
}
InternetAddress toAddress = new InternetAddress(emailAddress);
MailMessage mailMessage = new MailMessage(
fromAddress, toAddress, subject, body, false);
MailServiceUtil.sendEmail(mailMessage);
return true;
}
catch (Exception e) {
_log.error("The web form email could not be sent", e);
return false;
}
}
protected void serveCaptcha(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
CaptchaUtil.serveImage(resourceRequest, resourceResponse);
}
protected Set<String> validate(
Map<String,String> fieldsMap, PortletPreferences preferences)
throws Exception {
Set<String> validationErrors = new HashSet<String>();
for (int i = 0; i < fieldsMap.size(); i++) {
String fieldType = preferences.getValue(
"fieldType" + (i + 1), StringPool.BLANK);
String fieldLabel = preferences.getValue(
"fieldLabel" + (i + 1), StringPool.BLANK);
String fieldValue = fieldsMap.get(fieldLabel);
boolean fieldOptional = GetterUtil.getBoolean(
preferences.getValue(
"fieldOptional" + (i + 1), StringPool.BLANK));
if (Validator.equals(fieldType, "paragraph")) {
continue;
}
if (!fieldOptional && Validator.isNotNull(fieldLabel) &&
Validator.isNull(fieldValue)) {
validationErrors.add(fieldLabel);
continue;
}
String validationScript = GetterUtil.getString(
preferences.getValue(
"fieldValidationScript" + (i + 1), StringPool.BLANK));
if (Validator.isNotNull(validationScript) &&
!WebFormUtil.validate(
fieldValue, fieldsMap, validationScript)) {
validationErrors.add(fieldLabel);
continue;
}
}
return validationErrors;
}
private static Log _log = LogFactoryUtil.getLog(WebFormPortlet.class);
} |
package gov.nih.nci.cabig.caaers.api.impl;
import gov.nih.nci.cabig.caaers.api.AdverseEventService;
import gov.nih.nci.cabig.caaers.dao.AdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.GridIdentifiableDao;
import gov.nih.nci.cabig.caaers.dao.ParticipantDao;
import gov.nih.nci.cabig.caaers.dao.SiteDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.DomainObject;
import gov.nih.nci.cabig.caaers.domain.GridIdentifiable;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.Lab;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.Site;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import java.util.List;
public class DefaultAdverseEventService implements AdverseEventService {
private StudyDao studyDao;
private SiteDao siteDao;
private ParticipantDao participantDao;
private StudyParticipantAssignmentDao studyParticipantAssignmentDao;
private AdverseEventReportDao adverseEventReportDao;
public DefaultAdverseEventService() {
}
public String createCandidateAdverseEvent(Study study,
Participant participant, Site site, AdverseEvent ae, List<Lab> labs) {
ParameterLoader loader = new ParameterLoader(study, site, participant);
StudyParticipantAssignment studyParticipantAssignment = getStudyParticipantAssignmentDao()
.getAssignment(loader.participant, loader.study);
AdverseEventReport adverseEventReport = new AdverseEventReport();
adverseEventReport.setAssignment(studyParticipantAssignment);
adverseEventReport.setPrimaryAdverseEvent(ae);
adverseEventReport.setLabs(labs);
getAdverseEventReportDao().save(adverseEventReport);
return adverseEventReport.getGridId();
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public StudyDao getStudyDao() {
return studyDao;
}
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
public SiteDao getSiteDao() {
return siteDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public ParticipantDao getParticipantDao() {
return participantDao;
}
private <T extends DomainObject & GridIdentifiable> T load(T param, GridIdentifiableDao<T> dao, boolean required) {
T loaded = null;
boolean hasGridId = checkForGridId(param);
boolean hasIdentifiers = this.checkForIdentifiers(param);
if (!hasGridId && !hasIdentifiers){
throw new IllegalArgumentException(param.getClass().getSimpleName() + " doesn't have grid identifiers or identifiers");
}
if(hasGridId){
loaded = dao.getByGridId(param.getGridId());
if (loaded != null){
return loaded;
}
}
if (hasIdentifiers){
// load based on identifiers
loaded = loadByIdentifiers(param);
}
if(loaded == null){
throw new IllegalArgumentException(param.getClass().getSimpleName() + " doesn't exist.");
}
return loaded;
}
@SuppressWarnings("unchecked")
private <T extends DomainObject> T loadByIdentifiers(T param) {
DomainObject returnObject = null;
if(param instanceof Participant) {
returnObject = (DomainObject)getParticipantDao().getByIdentifier(((Participant)param).getIdentifiers().get(0));
} else if(param instanceof Study) {
returnObject = (DomainObject)getStudyDao().getByIdentifier(((Study)param).getIdentifiers().get(0));
}
return (T)returnObject;
//getByExample(param, {"identifiers"}, )
}
private boolean checkForGridId(GridIdentifiable gridIdentifiable) {
if (!gridIdentifiable.hasGridId()) {
return false;
// "No gridId on " + gridIdentifiable.getClass().getSimpleName().toLowerCase() + " parameter");
}
return true;
}
private boolean checkForIdentifiers(DomainObject obj){
List<Identifier> identifiers = null;
if (obj instanceof Study ){
Study study = (Study)obj;
identifiers = study.getIdentifiers();
}
if (obj instanceof Participant ){
Participant subject = (Participant)obj;
identifiers = subject.getIdentifiers();
}
if (identifiers == null){
return false;
}
return true;
}
public void setStudyParticipantAssignmentDao(StudyParticipantAssignmentDao studyParticipantAssignmentDao) {
this.studyParticipantAssignmentDao = studyParticipantAssignmentDao;
}
public StudyParticipantAssignmentDao getStudyParticipantAssignmentDao() {
return studyParticipantAssignmentDao;
}
public AdverseEventReportDao getAdverseEventReportDao() {
return adverseEventReportDao;
}
public void setAdverseEventReportDao(AdverseEventReportDao adverseEventReportDao) {
this.adverseEventReportDao = adverseEventReportDao;
}
private class ParameterLoader{
private Study study;
private Site site;
private Participant participant;
public ParameterLoader(Study study, Site site){
loadStudy(study);
loadSite(site);
}
public ParameterLoader(Study study, Site site, Participant participant){
this(study,site);
loadParticipant(participant);
}
public StudySite validateSiteInStudy() {
StudySite studySite = null;
for (StudySite aStudySite : getStudy().getStudySites()) {
if (aStudySite.getSite().equals(getSite())) {
studySite = aStudySite;
}
}
if(studySite == null){
throw new IllegalArgumentException("Site " + getSite().getId() + " not associated with study " + getStudy().getId());
}
return studySite;
}
private void loadSite(Site param) {
if(param == null) {
this.site = getSiteDao().getDefaultSite();
} else {
this.site = load(param, getSiteDao(), true);
if(this.site == null) {
if(this.site == null) {
this.site = getSiteDao().getDefaultSite();
}
}
}
}
private void loadStudy(Study param) {
this.study = load(param, getStudyDao(), true);
}
private void loadParticipant(Participant param) {
this.participant = load(param, getParticipantDao(), true);
}
public Study getStudy() {
return study;
}
public void setStudy(Study study) {
this.study = study;
}
public Site getSite() {
return site;
}
public void setSite(Site site) {
this.site = site;
}
public Participant getParticipant() {
return participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
}
}
} |
package com.exedio.cope.pattern;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.exedio.cope.Attribute;
import com.exedio.cope.BooleanAttribute;
import com.exedio.cope.ConstraintViolationException;
import com.exedio.cope.DataAttribute;
import com.exedio.cope.Item;
import com.exedio.cope.MandatoryViolationException;
import com.exedio.cope.Model;
import com.exedio.cope.NestingRuntimeException;
import com.exedio.cope.NoSuchIDException;
import com.exedio.cope.ObjectAttribute;
import com.exedio.cope.Pattern;
import com.exedio.cope.StringAttribute;
import com.exedio.cope.Transaction;
import com.exedio.cope.Attribute.Option;
public final class Media extends HttpPath
{
final boolean notNull;
final String fixedMimeMajor;
final String fixedMimeMinor;
final DataAttribute data;
final StringAttribute mimeMajor;
final StringAttribute mimeMinor;
final BooleanAttribute exists;
final ObjectAttribute isNull;
public Media(final Option option, final String fixedMimeMajor, final String fixedMimeMinor)
{
if(option==null)
throw new NullPointerException("option must not be null");
if(fixedMimeMajor==null)
throw new NullPointerException("fixedMimeMajor must not be null");
if(fixedMimeMinor==null)
throw new NullPointerException("fixedMimeMinor must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = fixedMimeMajor;
this.fixedMimeMinor = fixedMimeMinor;
registerSource(this.data = Item.dataAttribute(option));
this.mimeMajor = null;
this.mimeMinor = null;
this.exists = option.mandatory ? null : Item.booleanAttribute(Item.OPTIONAL);
this.isNull = exists;
if(data==null)
throw new NullPointerException("data must not be null");
if(this.exists!=null)
registerSource(this.exists);
}
public Media(final Option option, final String fixedMimeMajor)
{
if(option==null)
throw new NullPointerException("option must not be null");
if(fixedMimeMajor==null)
throw new NullPointerException("fixedMimeMajor must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = fixedMimeMajor;
this.fixedMimeMinor = null;
registerSource(this.data = Item.dataAttribute(option));
this.mimeMajor = null;
registerSource(this.mimeMinor = Item.stringAttribute(option, 1, 30));
this.exists = null;
this.isNull = mimeMinor;
if(data==null)
throw new NullPointerException("data must not be null");
if(mimeMinor==null)
throw new NullPointerException("mimeMinor must not be null");
if(mimeMinor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMinor cannot be unique");
if(mimeMinor.isMandatory())
throw new RuntimeException("mimeMinor cannot be mandatory");
if(mimeMinor.isReadOnly())
throw new RuntimeException("mimeMinor cannot be read-only");
}
public Media(final Option option)
{
if(option==null)
throw new NullPointerException("option must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = null;
this.fixedMimeMinor = null;
registerSource(this.data = Item.dataAttribute(option));
registerSource(this.mimeMajor = Item.stringAttribute(option, 1, 30));
registerSource(this.mimeMinor = Item.stringAttribute(option, 1, 30));
this.exists = null;
this.isNull = mimeMajor;
if(data==null)
throw new NullPointerException("data must not be null");
if(mimeMajor==null)
throw new NullPointerException("mimeMajor must not be null");
if(mimeMajor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMajor cannot be unique");
if(mimeMajor.isMandatory())
throw new RuntimeException("mimeMajor cannot be mandatory");
if(mimeMajor.isReadOnly())
throw new RuntimeException("mimeMajor cannot be read-only");
if(mimeMinor==null)
throw new NullPointerException("mimeMinor must not be null");
if(mimeMinor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMinor cannot be unique");
if(mimeMinor.isMandatory())
throw new RuntimeException("mimeMinor cannot be mandatory");
if(mimeMinor.isReadOnly())
throw new RuntimeException("mimeMinor cannot be read-only");
}
public final String getFixedMimeMajor()
{
return fixedMimeMajor;
}
public final String getFixedMimeMinor()
{
return fixedMimeMinor;
}
public final DataAttribute getData()
{
return data;
}
public final StringAttribute getMimeMajor()
{
return mimeMajor;
}
public final StringAttribute getMimeMinor()
{
return mimeMinor;
}
public final BooleanAttribute getExists()
{
return exists;
}
public void initialize()
{
super.initialize();
final String name = getName();
if(data!=null && !data.isInitialized())
initialize(data, name+"Data");
if(mimeMajor!=null && !mimeMajor.isInitialized())
initialize(mimeMajor, name+"Major");
if(mimeMinor!=null && !mimeMinor.isInitialized())
initialize(mimeMinor, name+"Minor");
if(exists!=null && !exists.isInitialized())
initialize(exists, name+"Exists");
}
public boolean isNull(final Item item)
{
return notNull ? false : (item.get(isNull)==null);
}
/**
* Returns the major mime type of this media.
* Returns null, if there is no data for this media.
*/
public final String getMimeMajor(final Item item)
{
if(isNull(item))
return null;
return (mimeMajor!=null) ? (String)item.get(mimeMajor) : fixedMimeMajor;
}
/**
* Returns the minor mime type of this media.
* Returns null, if there is no data for this media.
*/
public final String getMimeMinor(final Item item)
{
if(isNull(item))
return null;
return (mimeMinor!=null) ? (String)item.get(mimeMinor) : fixedMimeMinor;
}
/**
* Returns the content type of this media.
* Returns null, if there is no data for this media.
*/
public final String getContentType(final Item item)
{
if(isNull(item))
return null;
return getMimeMajor(item) + '/' + getMimeMinor(item);
}
private final RuntimeException newNoDataException(final Item item)
{
return new RuntimeException("missing data for "+this.toString()+" on "+item.toString());
}
/**
* Returns a stream for fetching the data of this media.
* <b>You are responsible for closing the stream, when you are finished!</b>
* Returns null, if there is no data for this media.
*/
public final InputStream getData(final Item item)
{
if(isNull(item))
return null;
final InputStream result = item.get(data);
if(result==null)
throw newNoDataException(item);
return result;
}
/**
* Returns the length of the data of this media.
* Returns -1, if there is no data for this media.
*/
public final long getDataLength(final Item item)
{
if(isNull(item))
return -1;
final long result = item.getDataLength(data);
if(result<0)
throw newNoDataException(item);
return result;
}
/**
* Returns the date of the last modification
* of the data of this media.
* Returns -1, if there is no data for this media.
*/
public final long getDataLastModified(final Item item)
{
if(isNull(item))
return -1;
final long result = item.getDataLastModified(data);
if(result<=0)
throw newNoDataException(item);
return result;
}
/**
* Returns a URL pointing to the data of this media.
* Returns null, if there is no data for this media.
*/
public final String getURL(final Item item)
{
if(isNull(item))
return null;
final StringBuffer bf = new StringBuffer(getMediaRootUrl());
appendDataPath(item, bf);
appendExtension(item, bf);
return bf.toString();
}
/**
* Provides data for this persistent media.
* Closes <data>data</data> after reading the contents of the stream.
* @param data give null to remove data.
* @throws MandatoryViolationException
* if data is null and attribute is {@link Attribute#isMandatory() mandatory}.
* @throws IOException if reading data throws an IOException.
*/
public final void set(final Item item, final InputStream data, final String mimeMajor, final String mimeMinor)
throws IOException
{
try
{
if(data!=null)
{
if((mimeMajor==null&&fixedMimeMajor==null) ||
(mimeMinor==null&&fixedMimeMinor==null))
throw new RuntimeException("if data is not null, mime types must also be not null");
}
else
{
if(mimeMajor!=null||mimeMinor!=null)
throw new RuntimeException("if data is null, mime types must also be null");
}
// TODO use Item.set(AttributeValue[])
if(this.mimeMajor!=null)
item.set(this.mimeMajor, mimeMajor);
if(this.mimeMinor!=null)
item.set(this.mimeMinor, mimeMinor);
if(this.exists!=null)
item.set(this.exists, (data!=null) ? Boolean.TRUE : null);
item.set(this.data, data);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
finally
{
if(data!=null)
data.close();
}
}
private final void appendDataPath(final Item item, final StringBuffer bf)
{
final String id = item.getCopeID();
final int dot = id.indexOf('.');
if(dot<0)
throw new RuntimeException(id);
bf.append(getUrlPath()).
append(id.substring(dot+1));
}
private final void appendExtension(final Item item, final StringBuffer bf)
{
final String major = getMimeMajor(item);
final String minor = getMimeMinor(item);
final String compactExtension = getCompactExtension(major, minor);
if(compactExtension==null)
{
bf.append('.').
append(major).
append('.').
append(minor);
}
else
bf.append(compactExtension);
}
private static final String getCompactExtension(final String mimeMajor, final String mimeMinor)
{
if("image".equals(mimeMajor))
{
if("jpeg".equals(mimeMinor) || "pjpeg".equals(mimeMinor))
return ".jpg";
else if("gif".equals(mimeMinor))
return ".gif";
else if("png".equals(mimeMinor))
return ".png";
else
return null;
}
else if("text".equals(mimeMajor))
{
if("html".equals(mimeMinor))
return ".html";
else if("plain".equals(mimeMinor))
return ".txt";
else if("css".equals(mimeMinor))
return ".css";
else
return null;
}
else
return null;
}
public final static Media get(final DataAttribute attribute)
{
for(Iterator i = attribute.getPatterns().iterator(); i.hasNext(); )
{
final Pattern pattern = (Pattern)i.next();
if(pattern instanceof Media)
{
final Media media = (Media)pattern;
if(media.getData()==attribute)
return media;
}
}
throw new NullPointerException(attribute.toString());
}
private long start = System.currentTimeMillis();
private final Object startLock = new Object();
public final Log mediumFound = new Log();
public final Log itemFound = new Log();
public final Log dataNotNull = new Log();
public final Log modified = new Log();
public final Log fullyDelivered = new Log();
public final Date getStart()
{
final long startLocal;
synchronized(startLock)
{
startLocal = this.start;
}
return new Date(startLocal);
}
public final void resetLogs()
{
final long now = System.currentTimeMillis();
synchronized(startLock)
{
start = now;
}
mediumFound.reset();
itemFound.reset();
dataNotNull.reset();
modified.reset();
fullyDelivered.reset();
}
/**
* Sets the offset, the Expires http header is set into the future.
* Together with a http reverse proxy this ensures,
* that for that time no request for that data will reach the servlet.
* This may reduce the load on the server.
*
* TODO: make this configurable, at best per media.
*/
private static final long EXPIRES_OFFSET = 1000 * 5; // 5 seconds
private static final String REQUEST_IF_MODIFIED_SINCE = "If-Modified-Since";
private static final String RESPONSE_EXPIRES = "Expires";
private static final String RESPONSE_LAST_MODIFIED = "Last-Modified";
private static final String RESPONSE_CONTENT_LENGTH = "Content-Length";
final boolean serveContent(
final HttpServletRequest request, final HttpServletResponse response,
final String pathInfo, final int trailingSlash)
throws ServletException, IOException
{
//System.out.println("entity="+this);
Log state = mediumFound;
final int dotAfterSlash = pathInfo.indexOf('.', trailingSlash);
//System.out.println("trailingDot="+trailingDot);
final String pkString =
(dotAfterSlash>=0)
? pathInfo.substring(trailingSlash+1, dotAfterSlash)
: pathInfo.substring(trailingSlash+1);
//System.out.println("pkString="+pkString);
final String id = getType().getID() + '.' + pkString;
//System.out.println("ID="+id);
try
{
final Model model = getType().getModel();
model.startTransaction("DataServlet");
final Item item = model.findByID(id);
//System.out.println("item="+item);
state = itemFound;
final String contentType = getContentType(item);
//System.out.println("contentType="+contentType);
if(contentType!=null)
{
state = dataNotNull;
response.setContentType(contentType);
final long lastModified = getDataLastModified(item);
//System.out.println("lastModified="+formatHttpDate(lastModified));
response.setDateHeader(RESPONSE_LAST_MODIFIED, lastModified);
final long now = System.currentTimeMillis();
response.setDateHeader(RESPONSE_EXPIRES, now+EXPIRES_OFFSET);
final long ifModifiedSince = request.getDateHeader(REQUEST_IF_MODIFIED_SINCE);
//System.out.println("ifModifiedSince="+request.getHeader(REQUEST_IF_MODIFIED_SINCE));
//System.out.println("ifModifiedSince="+ifModifiedSince);
if(ifModifiedSince>=0 && ifModifiedSince>=lastModified)
{
//System.out.println("not modified");
response.setStatus(response.SC_NOT_MODIFIED);
System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" NOT modified");
}
else
{
state = modified;
final long contentLength = getDataLength(item);
//System.out.println("contentLength="+String.valueOf(contentLength));
response.setHeader(RESPONSE_CONTENT_LENGTH, String.valueOf(contentLength));
//response.setHeader("Cache-Control", "public");
System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" modified: "+contentLength);
ServletOutputStream out = null;
InputStream in = null;
try
{
out = response.getOutputStream();
in = getData(item);
final byte[] buffer = new byte[Math.max((int)contentLength, 50*1024)];
for(int len = in.read(buffer); len != -1; len = in.read(buffer))
out.write(buffer, 0, len);
}
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
state = fullyDelivered;
}
Transaction.commit();
return true;
}
else
{
Transaction.commit();
return false;
}
}
catch(NoSuchIDException e)
{
return false;
}
finally
{
Transaction.rollbackIfNotCommitted();
state.increment();
}
}
private final static String format(final long date)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
return df.format(new Date(date));
}
} |
package io.github.benas.randombeans.randomizers.text;
import io.github.benas.randombeans.randomizers.AbstractRandomizer;
import io.github.benas.randombeans.util.Constants;
import java.nio.charset.Charset;
/**
* Generate a random {@link String}.
*
* @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*/
public class StringRandomizer extends AbstractRandomizer<String> {
private final CharacterRandomizer characterRandomizer;
private int maxLength = Constants.MAX_STRING_LENGTH;
private int minLength = Constants.MIN_STRING_LENGTH;
/**
* Create a new {@link StringRandomizer}.
*/
public StringRandomizer() {
super();
characterRandomizer = new CharacterRandomizer();
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
*/
public StringRandomizer(final Charset charset) {
characterRandomizer = new CharacterRandomizer(charset);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
*/
public StringRandomizer(int maxLength) {
super();
this.maxLength = maxLength;
characterRandomizer = new CharacterRandomizer();
}
/**
* Create a new {@link StringRandomizer}.
*
* @param seed initial seed
*/
public StringRandomizer(long seed) {
super(seed);
characterRandomizer = new CharacterRandomizer(seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param seed initial seed
*/
public StringRandomizer(final Charset charset, final long seed) {
super(seed);
characterRandomizer = new CharacterRandomizer(charset, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
* @param seed initial seed
*/
public StringRandomizer(final int maxLength, final long seed) {
super(seed);
this.maxLength = maxLength;
characterRandomizer = new CharacterRandomizer(seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
* @param minLength of the String to generate
* @param seed initial seed
*/
public StringRandomizer(final int minLength, final int maxLength, final long seed) {
super(seed);
this.maxLength = maxLength;
this.minLength = minLength;
characterRandomizer = new CharacterRandomizer(seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param maxLength of the String to generate
* @param seed initial seed
*/
public StringRandomizer(final Charset charset, final int maxLength, final long seed) {
super(seed);
this.maxLength = maxLength;
characterRandomizer = new CharacterRandomizer(charset, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param maxLength of the String to generate
* @param minLength of the String to generate
* @param seed initial seed
*/
public StringRandomizer(final Charset charset, final int minLength, final int maxLength, final long seed) {
super(seed);
if (minLength > maxLength) {
throw new IllegalArgumentException("minLength should be less than or equal to maxLength");
}
this.maxLength = maxLength;
this.minLength = minLength;
characterRandomizer = new CharacterRandomizer(charset, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer() {
return new StringRandomizer();
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final Charset charset) {
return new StringRandomizer(charset);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final int maxLength) {
return new StringRandomizer(maxLength);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final long seed) {
return new StringRandomizer(seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final Charset charset, final long seed) {
return new StringRandomizer(charset, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final int maxLength, final long seed) {
return new StringRandomizer(maxLength, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param maxLength of the String to generate
* @param minLength of the String to generate
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final int minLength, final int maxLength, final long seed) {
if (minLength > maxLength) {
throw new IllegalArgumentException("minLength should be less than or equal to maxLength");
}
return new StringRandomizer(minLength, maxLength, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param maxLength of the String to generate
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final Charset charset, final int maxLength, final long seed) {
return new StringRandomizer(charset, maxLength, seed);
}
/**
* Create a new {@link StringRandomizer}.
*
* @param charset to use
* @param maxLength of the String to generate
* @param minLength of the String to generate
* @param seed initial seed
* @return a new {@link StringRandomizer}.
*/
public static StringRandomizer aNewStringRandomizer(final Charset charset, final int minLength, final int maxLength, final long seed) {
if (minLength > maxLength) {
throw new IllegalArgumentException("minLength should be less than or equal to maxLength");
}
return new StringRandomizer(charset, minLength, maxLength, seed);
}
@Override
public String getRandomValue() {
StringBuilder stringBuilder = new StringBuilder();
int length = minLength + random.nextInt(maxLength - minLength + 1);
for (int i = 0; i < length; i++) {
stringBuilder.append(characterRandomizer.getRandomValue());
}
return stringBuilder.toString();
}
} |
package scal.io.liger;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.gson.stream.MalformedJsonException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import scal.io.liger.adapter.CardAdapter;
import scal.io.liger.model.Card;
import scal.io.liger.model.ClipCard;
import scal.io.liger.model.Dependency;
import scal.io.liger.model.InstanceIndexItem;
import scal.io.liger.model.MediaFile;
import scal.io.liger.model.StoryPath;
import scal.io.liger.model.StoryPathLibrary;
public class MainActivity extends Activity implements StoryPathLibrary.StoryPathLibraryListener{
private static final String TAG = "MainActivity";
public static final String INTENT_KEY_WINDOW_TITLE = "window_title";
public static final String INTENT_KEY_STORYPATH_LIBRARY_ID = "storypath_library_id";
public static final String INTENT_KEY_STORYPATH_INSTANCE_PATH = "storypath_instance_path";
public static final int INTENT_CODE = 16328;
RecyclerView mRecyclerView;
StoryPathLibrary mStoryPathLibrary;
public CardAdapter mCardAdapter = null;
String language = null;
/** Preferences received via launching intent */
String mRequestedLanguage;
int mPhotoSlideDuration;
// new, store info to minimize file access
public HashMap<String, InstanceIndexItem> instanceIndex;
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// copy index files
IndexManager.copyAvailableIndex(MainActivity.this);
IndexManager.copyInstalledIndex(MainActivity.this);
// check expansion files, initiate downloads if necessary
DownloadHelper.checkAndDownload(MainActivity.this);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//// if (DEVELOPER_MODE) {
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectNetwork() // or .detectAll() for all detectable problems
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());
Log.d("MainActivity", "onCreate");
if (savedInstanceState == null) {
Log.d(TAG, "onCreate called with no savedInstanceState");
JsonHelper.setupFileStructure(this);
MediaHelper.setupFileStructure(this);
// NEW: load instance index
// only fill on startup to minimize disk access
instanceIndex = IndexManager.loadInstanceIndex(MainActivity.this);
instanceIndex = IndexManager.fillInstanceIndex(MainActivity.this, instanceIndex);
// TEMP
if (instanceIndex.size() > 0) {
Log.d(TAG, "ONCREATE - FOUND INSTANCE INDEX WITH " + instanceIndex.size() + " ITEMS");
} else {
Log.d(TAG, "ONCREATE - FOUND INSTANCE INDEX WITH NO ITEMS");
}
Intent i = getIntent();
if (i.hasExtra("lang")) {
language = i.getExtras().getString("lang");
Log.d("LANGUAGE", "Found language code " + language + " in intent");
} else {
Log.d("LANGUAGE", "Found no language code in intent");
}
final ActionBar actionBar = getActionBar();
if (i.hasExtra(INTENT_KEY_WINDOW_TITLE)) {
actionBar.setTitle(i.getStringExtra(INTENT_KEY_WINDOW_TITLE));
}
actionBar.setDisplayHomeAsUpEnabled(true);
// TODO : Should these be serialized with StoryPathLibrary?
mPhotoSlideDuration = i.getIntExtra(Constants.EXTRA_PHOTO_SLIDE_DURATION, 0);
mRequestedLanguage = i.getStringExtra(Constants.EXTRA_LANG);
String jsonFilePath = null;
String json = null;
if (i.hasExtra(INTENT_KEY_STORYPATH_LIBRARY_ID)) {
jsonFilePath = JsonHelper.getJsonPathByKey(i.getStringExtra(INTENT_KEY_STORYPATH_LIBRARY_ID));
json = JsonHelper.loadJSONFromZip(jsonFilePath, this, language);
} else if (i.hasExtra(INTENT_KEY_STORYPATH_INSTANCE_PATH)) {
jsonFilePath = i.getStringExtra(INTENT_KEY_STORYPATH_INSTANCE_PATH);
json = JsonHelper.loadJSON(new File(jsonFilePath), language);
}
if (json != null) {
initFromJson(json, jsonFilePath);
} else {
showJsonSelectorPopup();
}
} else {
// NEW: load instance index
// if there is no file, this should be an empty hash map
instanceIndex = IndexManager.loadInstanceIndex(MainActivity.this);
// TEMP
if (instanceIndex.size() > 0) {
Log.d(TAG, "ONCREATE(STATE) - FOUND INSTANCE INDEX WITH " + instanceIndex.size() + " ITEMS");
} else {
Log.d(TAG, "ONCREATE(STATE) - FOUND INSTANCE INDEX WITH NO ITEMS");
}
if (savedInstanceState.containsKey("storyPathLibraryJson")) {
Log.d(TAG, "LOAD STORY PATH LIBRARY FROM SAVED INSTANCE STATE");
String jsonSPL = savedInstanceState.getString("storyPathLibraryJson");
if (jsonSPL != null) {
// fyi: story path (if any) is restored from saved instance, not saved state
initFromJson(jsonSPL, "SAVED_STATE");
} else {
Log.e(TAG, "SAVED INSTANCE STATE DOES NOT CONTAIN A VALID STORY PATH LIBRARY");
}
} else {
Log.e(TAG, "SAVED INSTANCE STATE DOES NOT CONTAIN STORY PATH LIBRARY");
}
}
}
/**
* Apply user preferences delivered via Intent extras to StoryPathLibrary
*/
private void configureStoryPathLibrary() {
mStoryPathLibrary.language = mRequestedLanguage;
mStoryPathLibrary.photoSlideDurationMs = mPhotoSlideDuration;
}
public void activateCard(Card card) {
mCardAdapter.addCardAtPosition(card, findSpot(card));
}
public void inactivateCard(Card card) {
mCardAdapter.removeCard(card);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState called");
if (mStoryPathLibrary == null) {
Log.d(TAG, "data not yet loaded, no state to save");
} else {
outState.putString("storyPathLibraryJson", JsonHelper.serializeStoryPathLibrary(mStoryPathLibrary));
if (mStoryPathLibrary.getCurrentStoryPath() != null) {
outState.putString("storyPathJson", JsonHelper.serializeStoryPath(mStoryPathLibrary.getCurrentStoryPath()));
}
}
super.onSaveInstanceState(outState);
}
private void showJsonSelectorPopup() {
SharedPreferences sp = getSharedPreferences("appPrefs", Context.MODE_PRIVATE);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String[] jsonFiles = JsonHelper.getJSONFileList();
//should never happen
if(jsonFiles.length == 0) {
jsonFiles = new String[1];
jsonFiles[0] = "Please add JSON files to the 'Liger' Folder and restart app\n(Located on root of SD card)";
builder.setTitle("No JSON files found")
.setItems(jsonFiles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
}
});
}
else {
builder.setTitle("Choose Story File(SdCard/Liger/)").setItems(jsonFiles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
File jsonFile = JsonHelper.setSelectedJSONFile(index);
String jsonPath = JsonHelper.setSelectedJSONPath(index);
// TEMP - unsure how to best determine new story vs. existing story
String json = JsonHelper.loadJSON(MainActivity.this, language);
initFromJson(json, jsonPath);
}
});
}
AlertDialog alert = builder.create();
alert.show();
}
private void initFromJson(String json, String jsonPath) {
if (json == null || json.equals("")) {
Toast.makeText(MainActivity.this, "Was not able to load this lesson, content was missing!", Toast.LENGTH_LONG).show();
finish();
return;
}
ArrayList<String> referencedFiles = null;
// should not need to insert dependencies into a saved instance or state
if (jsonPath.contains("instance")) {
Log.d(TAG, "INIT FROM SAVED INSTANCE");
referencedFiles = new ArrayList<String>();
} else if (jsonPath.equals("SAVED_STATE")) {
Log.d(TAG, "INIT FROM SAVED STATE");
referencedFiles = new ArrayList<String>();
} else {
Log.d(TAG, "INIT FROM TEMPLATE");
referencedFiles = new ArrayList<String>();
// referenced instances should be passed in with the intent somehow
// referencedFiles = JsonHelper.getInstancePaths();
Intent i = getIntent();
if (i.hasExtra("referenced_files")) {
String referencedFilesString = i.getExtras().getString("referenced_files");
// support multiple referenced files?
String[] referencedFilesArray = referencedFilesString.split(":");
Log.d(TAG, "Found " + referencedFilesArray.length + " referenced files in intent");
for (String referencedFile : referencedFilesArray) {
referencedFiles.add(referencedFile);
}
} else {
Log.d(TAG, "Found no referenced files in intent");
}
}
mStoryPathLibrary = JsonHelper.deserializeStoryPathLibrary(json, jsonPath, referencedFiles, MainActivity.this);
configureStoryPathLibrary();
mStoryPathLibrary.setStoryPathLibraryListener(MainActivity.this);
setupCardView();
if ((mStoryPathLibrary != null) && (mStoryPathLibrary.getCurrentStoryPathFile() != null)) {
mStoryPathLibrary.loadStoryPathTemplate("CURRENT");
}
// TEMP METADATA CHECK
/*
Log.d("METADATA", "TITLE: " + mStoryPathLibrary.getMetaTitle());
Log.d("METADATA", "DESCRIPTION: " + mStoryPathLibrary.getMetaDescription());
Log.d("METADATA", "THUMBNAIL: " + mStoryPathLibrary.getMetaThumbnail());
Log.d("METADATA", "SECTION: " + mStoryPathLibrary.getMetaSection());
Log.d("METADATA", "LOCATION: " + mStoryPathLibrary.getMetaLocation());
if (mStoryPathLibrary.getMetaTags() != null) {
for (String metaTag : mStoryPathLibrary.getMetaTags()) {
Log.d("METADATA", "TAG: " + metaTag);
}
}
*/
}
// MNB - IS THIS METHOD NEEDED?
public void refreshCardList() {
Log.d(TAG, "refreshCardList called");
if (mRecyclerView == null)
return;
refreshCardViewXXX();
}
public void setupCardView () {
Log.d(TAG, "setupCardView called");
if (mRecyclerView == null)
return;
if (mCardAdapter == null) {
//add valid cards to view
ArrayList<Card> cards = new ArrayList<Card>();
if (mStoryPathLibrary != null) {
cards = mStoryPathLibrary.getValidCards();
StoryPath storyPath = mStoryPathLibrary.getCurrentStoryPath();
if (storyPath != null) {
cards.addAll(storyPath.getValidCards());
}
}
mCardAdapter = new CardAdapter(cards);
mRecyclerView.setAdapter(mCardAdapter);
}
}
public void refreshCardViewXXX () {
Log.d(TAG, "refreshCardViewXXX called");
if (mRecyclerView == null) {
return;
}
if (mCardAdapter == null) {
setupCardView();
return;
}
//add valid cards to view
ArrayList<Card> cards = new ArrayList<Card>();
if (mStoryPathLibrary != null) {
cards = mStoryPathLibrary.getValidCards();
StoryPath storyPath = mStoryPathLibrary.getCurrentStoryPath();
if (storyPath != null) {
cards.addAll(storyPath.getValidCards());
}
}
mCardAdapter = new CardAdapter(cards);
mRecyclerView.setAdapter(mCardAdapter);
}
public void goToCard(StoryPath currentPath, String cardPath) throws MalformedJsonException {
Log.d(TAG, "goToCard: " + cardPath);
// assumes the format story::card::field::value
String[] pathParts = cardPath.split("::");
StoryPathLibrary storyPathLibrary = null;
StoryPath storyPath = null;
boolean newStoryPath = false;
if ((mStoryPathLibrary.getId().equals(pathParts[0])) ||
((mStoryPathLibrary.getCurrentStoryPath() != null) &&
(mStoryPathLibrary.getCurrentStoryPath().getId().equals(pathParts[0])))) {
// reference targets this story path or library
storyPathLibrary = mStoryPathLibrary;
storyPath = mStoryPathLibrary.getCurrentStoryPath();
} else {
// reference targets a serialized story path
for (Dependency dependency : currentPath.getDependencies()) {
if (dependency.getDependencyId().equals(pathParts[0])) {
// ASSUMES DEPENDENCIES ARE CORRECT RELATIVE TO PATH OF CURRENT LIBRARY
// check for file
// paths to actual files should fully qualified
// paths within zip files should be relative
// (or at least not resolve to actual files)
String checkPath = currentPath.buildZipPath(dependency.getDependencyFile());
File checkFile = new File(checkPath);
// add reference to previous path and gather references from that path
// (not sure it makes sense to add reference to previous path automatically?)
ArrayList<String> referencedFiles = new ArrayList<String>();
if (currentPath.getSavedFileName() != null) {
Log.d("DEPENDENCIES", "ADDING REFERENCE TO CURRENT PATH " + currentPath.getSavedFileName());
referencedFiles.add(currentPath.getSavedFileName());
}
if (currentPath.getDependencies() != null) {
for (Dependency currentDependency : currentPath.getDependencies()) {
if (currentDependency.getDependencyId().contains("instance")) {
Log.d("DEPENDENCIES", "ADDING REFERENCE TO CURRENT PATH DEPENDENCY " + currentDependency.getDependencyFile());
referencedFiles.add(currentDependency.getDependencyFile());
}
}
}
if (checkFile.exists()) {
if (dependency.getDependencyFile().contains("-library-instance")) {
storyPath = JsonHelper.loadStoryPathLibrary(checkPath, referencedFiles, this, language);
} else {
storyPath = JsonHelper.loadStoryPath(checkPath, mStoryPathLibrary, referencedFiles, this, language);
}
Log.d("FILES", "LOADED FROM FILE: " + dependency.getDependencyFile());
} else {
if (dependency.getDependencyFile().contains("-library-instance")) {
storyPath = JsonHelper.loadStoryPathLibraryFromZip(checkPath, referencedFiles, this, language);
} else {
storyPath = JsonHelper.loadStoryPathFromZip(checkPath, mStoryPathLibrary, referencedFiles, this, language);
}
Log.d("FILES", "LOADED FROM ZIP: " + dependency.getDependencyFile());
}
// need to account for references pointing to either a path or a library
if (storyPath instanceof StoryPath) {
Log.d("REFERENCES", "LOADED A PATH, NOW LOADING A LIBRARY");
checkPath = storyPath.buildZipPath(storyPath.getStoryPathLibraryFile());
checkFile = new File(checkPath);
if (checkFile.exists()) {
storyPathLibrary = JsonHelper.loadStoryPathLibrary(checkPath, referencedFiles, this, language);
Log.d("FILES", "LOADED FROM FILE: " + storyPath.getStoryPathLibraryFile());
} else {
storyPathLibrary = JsonHelper.loadStoryPathLibraryFromZip(checkPath, referencedFiles, this, language);
Log.d("FILES", "LOADED FROM ZIP: " + storyPath.getStoryPathLibraryFile());
}
} else {
storyPathLibrary = (StoryPathLibrary)storyPath;
if (storyPathLibrary.getCurrentStoryPathFile() == null) {
Log.d("REFERENCES", "LOADED A LIBRARY, NO PATH");
storyPath = null;
} else {
Log.d("REFERENCES", "LOADED A LIBRARY, NOW LOADING A PATH");
checkPath = storyPathLibrary.buildZipPath(storyPathLibrary.getCurrentStoryPathFile());
checkFile = new File(checkPath);
if (checkFile.exists()) {
storyPath = JsonHelper.loadStoryPath(checkPath, storyPathLibrary, referencedFiles, this, language);
Log.d("FILES", "LOADED FROM FILE: " + storyPathLibrary.getCurrentStoryPathFile());
} else {
storyPath = JsonHelper.loadStoryPathFromZip(checkPath, storyPathLibrary, referencedFiles, this, language);
Log.d("FILES", "LOADED FROM ZIP: " + storyPathLibrary.getCurrentStoryPathFile());
}
}
}
// loaded in reverse order, so need to set these references
if (storyPath != null) {
storyPath.setStoryPathLibrary(storyPathLibrary);
storyPath.setStoryPathLibraryFile(storyPathLibrary.getFileLocation());
storyPathLibrary.setCurrentStoryPath(storyPath);
storyPathLibrary.setCurrentStoryPathFile(storyPath.getFileLocation()); // VERIFY THIS
}
newStoryPath = true;
break;
}
}
}
Card card = null;
if ((storyPathLibrary != null) && storyPathLibrary.getId().equals(pathParts[0])) {
card = storyPathLibrary.getCardById(cardPath);
}
if ((storyPath != null) && storyPath.getId().equals(pathParts[0])) {
card = storyPath.getCardById(cardPath);
}
if (card == null) {
Log.e("REFERENCES", "CARD ID " + pathParts[1] + " WAS NOT FOUND");
return;
}
if (newStoryPath) {
// TODO: need additional code to save current story path
// serialize current story path
// add to story path files
mStoryPathLibrary = storyPathLibrary;
refreshCardViewXXX();
}
int cardIndex = mCardAdapter.mDataset.indexOf(card);
if (cardIndex < 0) {
System.err.println("CARD ID " + pathParts[1] + " IS NOT VISIBLE");
return;
}
mRecyclerView.scrollToPosition(cardIndex);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Log.d(TAG, "onActivityResult, requestCode:" + requestCode + ", resultCode: " + resultCode);
if (resultCode == RESULT_OK) {
// TODO : Remove this and allow Card View Controllers to be notified of data changes
if(requestCode == Constants.REQUEST_VIDEO_CAPTURE) {
Uri uri = intent.getData();
String path = Utility.getRealPathFromURI(getApplicationContext(), uri);
if (Utility.isNullOrEmpty(path)) {
Log.e(TAG, "onActivityResult got null path");
return;
}
Log.d(TAG, "onActivityResult, video path:" + path);
String pathId = this.getSharedPreferences("prefs", Context.MODE_PRIVATE).getString(Constants.PREFS_CALLING_CARD_ID, null); // FIXME should be done off the ui thread
if (null == pathId || null == uri) {
return;
}
Card c = null;
if (mStoryPathLibrary.getCurrentStoryPath() != null) {
c = mStoryPathLibrary.getCurrentStoryPath().getCardById(pathId);
}
if (c == null) {
c = mStoryPathLibrary.getCardById(pathId); // FIXME temporarily routing around this to test clipcard
}
if (c instanceof ClipCard) {
ClipCard cc = (ClipCard)c;
MediaFile mf = new MediaFile(path, Constants.VIDEO);
cc.saveMediaFile(mf);
// SEEMS LIKE A REASONABLE TIME TO SAVE
mStoryPathLibrary.save(true);
mCardAdapter.changeCard(cc);
scrollRecyclerViewToCard(cc);
} else {
if (c != null) {
Log.e(TAG, "card type " + c.getClass().getName() + " has no method to save " + Constants.VIDEO + " files");
} else {
Log.e(TAG, "c is null!");
}
}
} else if(requestCode == Constants.REQUEST_IMAGE_CAPTURE) {
String path = this.getSharedPreferences("prefs", Context.MODE_PRIVATE).getString(Constants.EXTRA_FILE_LOCATION, null);
Log.d(TAG, "onActivityResult, path:" + path);
String pathId = this.getSharedPreferences("prefs", Context.MODE_PRIVATE).getString(Constants.PREFS_CALLING_CARD_ID, null); // FIXME should be done off the ui thread
if (null == pathId || null == path) {
return;
}
Card c = null;
if (mStoryPathLibrary.getCurrentStoryPath() != null) {
c = mStoryPathLibrary.getCurrentStoryPath().getCardById(pathId);
}
if (c == null) {
c = mStoryPathLibrary.getCardById(pathId); // FIXME temporarily routing around this to test clipcard
}
if (c instanceof ClipCard) {
ClipCard cc = (ClipCard)c;
MediaFile mf = new MediaFile(path, Constants.PHOTO);
cc.saveMediaFile(mf);
// SEEMS LIKE A REASONABLE TIME TO SAVE
mStoryPathLibrary.save(true);
mCardAdapter.changeCard(cc);
scrollRecyclerViewToCard(cc);
} else {
Log.e(TAG, "card type " + c.getClass().getName() + " has no method to save " + Constants.PHOTO + " files");
}
} else if(requestCode == Constants.REQUEST_AUDIO_CAPTURE) {
Uri uri = intent.getData();
String path = Utility.getRealPathFromURI(getApplicationContext(), uri);
Log.d(TAG, "onActivityResult, audio path:" + path);
String pathId = this.getSharedPreferences("prefs", Context.MODE_PRIVATE).getString(Constants.PREFS_CALLING_CARD_ID, null); // FIXME should be done off the ui thread
if (null == pathId || null == uri) {
return;
}
Card c = null;
if (mStoryPathLibrary.getCurrentStoryPath() != null) {
c = mStoryPathLibrary.getCurrentStoryPath().getCardById(pathId);
}
if (c == null) {
c = mStoryPathLibrary.getCardById(pathId); // FIXME temporarily routing around this to test clipcard
}
if (c instanceof ClipCard) {
ClipCard cc = (ClipCard)c;
MediaFile mf = new MediaFile(path, Constants.AUDIO);
cc.saveMediaFile(mf);
// SEEMS LIKE A REASONABLE TIME TO SAVE
mStoryPathLibrary.save(true);
mCardAdapter.changeCard(cc);
scrollRecyclerViewToCard(cc);
} else {
Log.e(TAG, "card class " + c.getClass().getName() + " has no method to save " + Constants.AUDIO + " files");
}
} else if (requestCode == Constants.REQUEST_FILE_IMPORT) {
Uri uri = intent.getData();
// Will only allow stream-based access to files
if (Build.VERSION.SDK_INT >= 19) {
getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
String path = Utility.getRealPathFromURI(getApplicationContext(), uri);
Log.d(TAG, "onActivityResult, imported file path:" + path);
String pathId = this.getSharedPreferences("prefs", Context.MODE_PRIVATE).getString(Constants.PREFS_CALLING_CARD_ID, null); // FIXME should be done off the ui thread
Card c = mStoryPathLibrary.getCurrentStoryPath().getCardById(pathId);
if (c instanceof ClipCard) {
ClipCard cc = (ClipCard)c;
MediaFile mf = new MediaFile(uri.toString(), cc.getMedium());
cc.saveMediaFile(mf);
// SEEMS LIKE A REASONABLE TIME TO SAVE
mStoryPathLibrary.save(true);
mCardAdapter.changeCard(cc);
scrollRecyclerViewToCard(cc);
} else {
Log.e(TAG, "card type " + c.getClass().getName() + " has no method to save " + Constants.VIDEO + " files");
}
}
}
}
/**
* Deprecated. Remove after testing that we have no issues with devices not storing
* image files where specified via the EXTRA_OUTPUT extra of the ACTION_IMAGE_CAPTURE intent.
*/
@Deprecated
private String getLastImagePath() {
final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
String imagePath = null;
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
imagePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageCursor.close();
imageCursor = null;
}
return imagePath;
}
public int findSpot(Card card) {
int newIndex = 0;
if (mStoryPathLibrary.getCards().contains(card)) {
int baseIndex = mStoryPathLibrary.getCards().indexOf(card);
for (int i = (baseIndex - 1); i >= 0; i
Card previousCard = mStoryPathLibrary.getCards().get(i);
if (mCardAdapter.mDataset.contains(previousCard)) {
newIndex = mCardAdapter.mDataset.indexOf(previousCard) + 1;
break;
}
}
}
if ((mStoryPathLibrary.getCurrentStoryPath() != null) && (mStoryPathLibrary.getCurrentStoryPath().getCards().contains(card))) {
int baseIndex = mStoryPathLibrary.getCurrentStoryPath().getCards().indexOf(card);
for (int i = (baseIndex - 1); i >= 0; i
Card previousCard = mStoryPathLibrary.getCurrentStoryPath().getCards().get(i);
if (mCardAdapter.mDataset.contains(previousCard)) {
newIndex = mCardAdapter.mDataset.indexOf(previousCard) + 1;
break;
}
}
}
return newIndex;
}
public String checkCard(Card updatedCard) {
if (updatedCard.getStateVisiblity()) {
// new or updated
if (mCardAdapter.mDataset.contains(updatedCard)) {
return "UPDATE";
} else {
return "ADD";
}
} else {
// deleted
if (mCardAdapter.mDataset.contains(updatedCard)) {
return "DELETE";
}
}
return "ERROR";
}
/**
* Scroll {@link #mRecyclerView} so that card is the
* first visible item
*/
public void scrollRecyclerViewToCard(Card card) {
int position = mCardAdapter.getPositionForCard(card);
mRecyclerView.scrollToPosition(position);
}
@Override
public void onCardAdded(Card newCard) {
Log.i(TAG, "Card added " + newCard.getId());
mCardAdapter.appendCard(newCard);
}
@Override
public void onCardChanged(Card changedCard) {
Log.i(TAG, "Card changed " + changedCard.getId());
mCardAdapter.changeCard(changedCard);
}
@Override
public void onCardsSwapped(Card cardOne, Card cardTwo) {
Log.i(TAG, String.format("Cards swapped %s <-> %s ", cardOne.getId(), cardTwo.getId()));
mCardAdapter.swapCards(cardOne, cardTwo);
}
@Override
public void onCardRemoved(Card removedCard) {
Log.i(TAG, "Card removed " + removedCard.getId());
mCardAdapter.removeCard(removedCard);
}
@Override
public void onStoryPathLoaded() {
refreshCardList();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finishActivity(INTENT_CODE);
return true;
}
return true;
}
} |
package com.networknt.restrans;
import com.networknt.handler.BuffersUtils;
import com.networknt.handler.MiddlewareHandler;
import com.networknt.handler.ResponseInterceptor;
import com.networknt.httpstring.AttachmentConstants;
import com.networknt.rule.RuleConstants;
import com.networknt.rule.RuleEngine;
import com.networknt.rule.RuleLoaderStartupHook;
import com.networknt.utility.Constants;
import com.networknt.utility.ModuleRegistry;
import io.undertow.Handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a generic middleware handler to manipulate response based on rule-engine rules so that it can be much more
* flexible than any other handlers like the header handler to manipulate the headers. The rules will be loaded from
* the configuration or from the light-portal if portal is implemented.
*
* @author Steve Hu
*/
public class ResponseTransformerInterceptor implements ResponseInterceptor {
static final Logger logger = LoggerFactory.getLogger(ResponseTransformerInterceptor.class);
private static final String RESPONSE_HEADERS = "responseHeaders";
private static final String REQUEST_HEADERS = "requestHeaders";
private static final String RESPONSE_BODY = "responseBody";
private static final String REMOVE = "remove";
private static final String UPDATE = "update";
private static final String QUERY_PARAMETERS = "queryParameters";
private static final String PATH_PARAMETERS = "pathParameters";
private static final String METHOD = "method";
private static final String REQUEST_URL = "requestURL";
private static final String REQUEST_URI = "requestURI";
private static final String REQUEST_PATH = "requestPath";
private static final String POST = "post";
private static final String PUT = "put";
private static final String PATCH = "patch";
private static final String REQUEST_BODY = "requestBody";
private static final String AUDIT_INFO = "auditInfo";
private static final String STATUS_CODE = "statusCode";
private static final String STARTUP_HOOK_NOT_LOADED = "ERR11019";
private static final String RESPONSE_TRANSFORM = "response-transform";
private ResponseTransformerConfig config;
private volatile HttpHandler next;
private RuleEngine engine;
public ResponseTransformerInterceptor() {
if (logger.isInfoEnabled()) logger.info("ResponseManipulatorHandler is loaded");
config = ResponseTransformerConfig.load();
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(ResponseTransformerInterceptor.class.getName(), config.getMappedConfig(), null);
}
@Override
public void reload() {
config.reload();
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (logger.isTraceEnabled())
logger.trace("ResponseTransformerHandler.handleRequest is called.");
String requestPath = exchange.getRequestPath();
if (config.getAppliedPathPrefixes() != null && config.getAppliedPathPrefixes().stream().anyMatch(requestPath::startsWith)) {
if (engine == null) {
engine = new RuleEngine(RuleLoaderStartupHook.rules, null);
}
String responseBody = BuffersUtils.toString(getBuffer(exchange), StandardCharsets.UTF_8);
if (logger.isTraceEnabled())
logger.trace("original response body = " + responseBody);
// call the rule engine to transform the response body and response headers. The input contains all the request
// and response elements.
HttpString method = exchange.getRequestMethod();
Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
Map<String, Object> objMap = this.createExchangeInfoMap(exchange, method, responseBody, auditInfo);
// need to get the rule/rules to execute from the RuleLoaderStartupHook. First, get the endpoint.
String endpoint;
if (auditInfo != null) {
if (logger.isDebugEnabled())
logger.debug("auditInfo exists. Grab endpoint from it.");
endpoint = (String) auditInfo.get("endpoint");
} else {
if (logger.isDebugEnabled())
logger.debug("auditInfo is NULL. Grab endpoint from exchange.");
endpoint = exchange.getRequestPath() + "@" + method.toString().toLowerCase();
}
if (logger.isDebugEnabled())
logger.debug("request endpoint: " + endpoint);
// checked the RuleLoaderStartupHook to ensure it is loaded. If not, return an error to the caller.
if (RuleLoaderStartupHook.endpointRules == null) {
logger.error("RuleLoaderStartupHook endpointRules is null");
}
// get the rules (maybe multiple) based on the endpoint.
Map<String, List> endpointRules = (Map<String, List>) RuleLoaderStartupHook.endpointRules.get(endpoint);
if (endpointRules == null) {
if (logger.isDebugEnabled())
logger.debug("endpointRules iS NULL");
} else {
if (logger.isDebugEnabled())
logger.debug("endpointRules: " + endpointRules.get(RESPONSE_TRANSFORM).size());
}
boolean finalResult = true;
List<Map<String, Object>> responseTransformRules = endpointRules.get(RESPONSE_TRANSFORM);
Map<String, Object> result = null;
String ruleId = null;
// iterate the rules and execute them in sequence. Break only if one rule is successful.
for(Map<String, Object> ruleMap: responseTransformRules) {
ruleId = (String)ruleMap.get(Constants.RULE_ID);
result = engine.executeRule(ruleId, objMap);
boolean res = (Boolean)result.get(RuleConstants.RESULT);
if(!res) {
finalResult = false;
break;
}
}
if(finalResult) {
for (Map.Entry<String, Object> entry : result.entrySet()) {
if (logger.isTraceEnabled())
logger.trace("key = " + entry.getKey() + " value = " + entry.getValue());
// you can only update the response headers and response body in the transformation.
switch (entry.getKey()) {
case RESPONSE_HEADERS:
// if responseHeaders object is null, ignore it.
Map<String, Object> responseHeaders = (Map) result.get(RESPONSE_HEADERS);
if (responseHeaders != null) {
// manipulate the response headers.
List<String> removeList = (List) responseHeaders.get(REMOVE);
if (removeList != null) {
removeList.forEach(s -> exchange.getResponseHeaders().remove(s));
}
Map<String, Object> updateMap = (Map) responseHeaders.get(UPDATE);
if (updateMap != null) {
updateMap.forEach((k, v) -> exchange.getResponseHeaders().put(new HttpString(k), (String) v));
}
}
break;
case RESPONSE_BODY:
responseBody = (String) result.get(RESPONSE_BODY);
if (responseBody != null) {
// copy transformed buffer to the attachment
var dest = exchange.getAttachment(AttachmentConstants.BUFFERED_RESPONSE_DATA_KEY);
BuffersUtils.transfer(ByteBuffer.wrap(responseBody.getBytes()), dest, exchange);
}
break;
}
}
}
}
}
private Map<String, Object> executeRules(Map<String, Object> objMap, Map<String, List> endpointRules) throws Exception {
// if there is no access rule for this endpoint, check the default deny flag in the config.
List<Map<String, Object>> responseTransformRules = endpointRules.get(RESPONSE_TRANSFORM);
Map<String, Object> result = null;
String ruleId;
// iterate the rules and execute them in sequence. Break only if one rule is successful.
for (Map<String, Object> ruleMap : responseTransformRules) {
ruleId = (String) ruleMap.get(Constants.RULE_ID);
result = engine.executeRule(ruleId, objMap);
boolean res = (Boolean) result.get(RuleConstants.RESULT);
if (!res) {
return null;
}
}
return result;
}
private Map<String, Object> createExchangeInfoMap(HttpServerExchange exchange, HttpString method, String responseBody, Map<String, Object> auditInfo) {
Map<String, Object> objMap = new HashMap<>();
objMap.put(REQUEST_HEADERS, exchange.getRequestHeaders());
objMap.put(RESPONSE_HEADERS, exchange.getResponseHeaders());
objMap.put(QUERY_PARAMETERS, exchange.getQueryParameters());
objMap.put(PATH_PARAMETERS, exchange.getPathParameters());
objMap.put(METHOD, method.toString());
objMap.put(REQUEST_URL, exchange.getRequestURL());
objMap.put(REQUEST_URI, exchange.getRequestURI());
objMap.put(REQUEST_PATH, exchange.getRequestPath());
if (method.toString().equalsIgnoreCase(POST)
|| method.toString().equalsIgnoreCase(PUT)
|| method.toString().equalsIgnoreCase(PATCH)) {
Object bodyMap = exchange.getAttachment(AttachmentConstants.REQUEST_BODY);
objMap.put(REQUEST_BODY, bodyMap);
}
if (responseBody != null) {
objMap.put(RESPONSE_BODY, responseBody);
}
objMap.put(AUDIT_INFO, auditInfo);
objMap.put(STATUS_CODE, exchange.getStatusCode());
return objMap;
}
@Override
public boolean isRequiredContent() {
return config.isRequiredContent();
}
} |
package org.runningdinner.frontend;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.runningdinner.admin.RunningDinnerService;
import org.runningdinner.admin.rest.BasicSettingsTO;
import org.runningdinner.common.IssueKeys;
import org.runningdinner.common.exception.DinnerNotFoundException;
import org.runningdinner.common.exception.ValidationException;
import org.runningdinner.core.RegistrationType;
import org.runningdinner.core.RunningDinner;
import org.runningdinner.frontend.rest.RegistrationDataV2TO;
import org.runningdinner.participant.Participant;
import org.runningdinner.participant.ParticipantAddress;
import org.runningdinner.test.util.ApplicationTest;
import org.runningdinner.test.util.TestHelperService;
import org.runningdinner.test.util.TestUtil;
import org.runningdinner.wizard.BasicDetailsTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ApplicationTest
public class FrontendRunningDinnerTest {
@Autowired
private FrontendRunningDinnerService frontendRunningDinnerService;
@Autowired
private RunningDinnerService runningDinnerService;
@Autowired
private TestHelperService testHelperService;
private LocalDate todayIn30Days;
private RunningDinner runningDinner;
private String publicDinnerId;
@Before
public void setUp() {
todayIn30Days = LocalDate.now().plusDays(30);
runningDinner = testHelperService.createPublicRunningDinner(todayIn30Days, 2);
publicDinnerId = runningDinner.getPublicSettings().getPublicId();
}
@Test
public void testFindRunningDinnerByPublicId() {
RunningDinner foundRunningDinner = frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now());
assertThat(foundRunningDinner).isNotNull();
assertThat(foundRunningDinner.getPublicSettings().getPublicId()).isEqualTo(runningDinner.getPublicSettings().getPublicId());
}
@Test(expected = DinnerNotFoundException.class)
public void testFindRunningDinnerByPublicIdFailsForClosedRegistration() {
BasicSettingsTO basicSettings = TestUtil.newBasicSettings(new BasicDetailsTO(runningDinner));
basicSettings.getBasicDetails().setRegistrationType(RegistrationType.CLOSED);
runningDinnerService.updateBasicSettings(runningDinner.getAdminId(), basicSettings);
frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now());
}
@Test
public void testRegistrationValidationSuccessful() {
RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "max@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6);
RegistrationSummary result = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true);
assertThat(result).isNotNull();
}
@Test
public void testRegistrationInvalidName() {
RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "max@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6);
registrationData.setFirstnamePart(null);
registrationData.setLastname("Mustermann");
try {
frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true);
Assert.fail("Expected ValidationException to be thrown");
} catch (IllegalArgumentException expectedEx) {
// NOP
// assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.FULLNAME_NOT_VALID);
}
}
@Test
public void testRegistrationInvalidRegistrationDate() {
// set end of registration date back to day before yesterday
LocalDate tomorrow = LocalDate.now().plusDays(1);
runningDinner = testHelperService.createPublicRunningDinner(tomorrow, 2);
RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "max@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6);
try {
frontendRunningDinnerService.performRegistration(runningDinner.getPublicSettings().getPublicId(), registrationData, true);
Assert.fail("Expected ValidationException to be thrown");
} catch (ValidationException expectedEx) {
assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.REGISTRATION_DATE_EXPIRED);
}
}
@Test
public void testRegistrationSuccess() {
RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "max@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6);
RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId,
registrationData, false);
checkRegistrationSummary(firstParticipant, 1);
registrationData = TestUtil.createRegistrationData("Maria Musterfrau", "maria@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2);
RegistrationSummary secondParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false);
checkRegistrationSummary(secondParticipant, 2);
registrationData = TestUtil.createRegistrationData("Third Participant", "third@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2);
RegistrationSummary thirdParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false);
checkRegistrationSummary(thirdParticipant, 3);
}
protected void checkRegistrationSummary(RegistrationSummary registrationSummary, int expectedParticipantNumber) {
Participant participant = registrationSummary.getParticipant();
assertThat(participant).isNotNull();
assertThat(participant.getParticipantNumber()).isEqualTo(expectedParticipantNumber);
assertThat(participant.isNew()).isFalse();
}
@Test
public void testDuplicatedRegistration() {
RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "max@muster.de",
ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6);
RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false);
checkRegistrationSummary(firstParticipant, 1);
try {
frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false);
Assert.fail("Expected ValidationException to be thrown");
} catch (ValidationException ex) {
assertThat(ex.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.PARTICIPANT_ALREADY_REGISTERED);
}
}
@Test
public void testFindPublicRunningDinnersSimple() {
LocalDate todayIn29Days = todayIn30Days.minusDays(1);
List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days);
assertDinnerFound(publicRunningDinners);
}
@Test
public void testFindPublicDinnersSeveral() {
LocalDate now = LocalDate.now();
LocalDate todayIn35Days = now.plusDays(35);
LocalDate todayIn40Days = now.plusDays(40);
LocalDate todayIn41Days = now.plusDays(41);
RunningDinner firstPublicDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3);
RunningDinner secondPublicDinner = testHelperService.createPublicRunningDinner(todayIn41Days, 3);
RunningDinner closedRunningDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3, RegistrationType.OPEN);
List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn35Days);
assertThat(publicRunningDinners).contains(firstPublicDinner, secondPublicDinner);
assertThat(publicRunningDinners).doesNotContain(closedRunningDinner);
}
@Test
public void cancelledDinnerNotFound() {
LocalDate todayIn29Days = todayIn30Days.minusDays(1);
List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days);
assertDinnerFound(publicRunningDinners);
runningDinnerService.cancelRunningDinner(runningDinner.getAdminId(), todayIn29Days.atTime(10, 10));
publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days);
assertDinnerNotFound(publicRunningDinners);
}
private void assertDinnerFound(List<RunningDinner> publicRunningDinners) {
Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet());
assertThat(publicIds).contains(runningDinner.getPublicSettings().getPublicId());
}
private void assertDinnerNotFound(List<RunningDinner> publicRunningDinners) {
Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet());
assertThat(publicIds).doesNotContain(runningDinner.getPublicSettings().getPublicId());
}
} |
package wei.mark.standout;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
* Extend this class to easily create and manage floating StandOut windows.
*
* @author Mark Wei <markwei@gmail.com>
*
* Contributors: Jason <github.com/jasonconnery>
*
*/
public abstract class StandOutWindow extends Service {
static final String TAG = "StandOutWindow";
/**
* StandOut window id: You may use this sample id for your first window.
*/
public static final int DEFAULT_ID = 0;
/**
* Special StandOut window id: You may NOT use this id for any windows.
*/
public static final int ONGOING_NOTIFICATION_ID = -1;
/**
* StandOut window id: You may use this id when you want it to be
* disregarded. The system makes no distinction for this id; it is only used
* to improve code readability.
*/
public static final int DISREGARD_ID = -2;
/**
* Intent action: Show a new window corresponding to the id.
*/
public static final String ACTION_SHOW = "SHOW";
/**
* Intent action: Restore a previously hidden window corresponding to the
* id. The window should be previously hidden with {@link #ACTION_HIDE}.
*/
public static final String ACTION_RESTORE = "RESTORE";
/**
* Intent action: Close an existing window with an existing id.
*/
public static final String ACTION_CLOSE = "CLOSE";
/**
* Intent action: Close all existing windows.
*/
public static final String ACTION_CLOSE_ALL = "CLOSE_ALL";
/**
* Intent action: Send data to a new or existing window.
*/
public static final String ACTION_SEND_DATA = "SEND_DATA";
/**
* Intent action: Hide an existing window with an existing id. To enable the
* ability to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*/
public static final String ACTION_HIDE = "HIDE";
/**
* Show a new window corresponding to the id, or restore a previously hidden
* window.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
*
* @see #show(int)
*/
public static void show(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Hide the existing window corresponding to the id. To enable the ability
* to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #hide(int)
*/
public static void hide(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Close an existing window with an existing id.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #close(int)
*/
public static void close(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getCloseIntent(context, cls, id));
}
/**
* Close all existing windows.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @see #closeAll()
*/
public static void closeAll(Context context,
Class<? extends StandOutWindow> cls) {
context.startService(getCloseAllIntent(context, cls));
}
/**
* This allows windows of different applications to communicate with each
* other.
*
* <p>
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the class and id of the
* sender.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window, or DISREGARD_ID.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* Provide the class of the sending window if you want a result.
* @param fromId
* Provide the id of the sending window if you want a result.
* @see #sendData(int, Class, int, int, Bundle)
*/
public static void sendData(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
context.startService(getSendDataIntent(context, toCls, toId,
requestCode, data, fromCls, fromId));
}
/**
* See {@link #show(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getShowIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
boolean cached = sWindowCache.isCached(id, cls);
String action = cached ? ACTION_RESTORE : ACTION_SHOW;
Uri uri = cached ? Uri.parse("standout://" + cls + '/' + id) : null;
return new Intent(context, cls).putExtra("id", id).setAction(action)
.setData(uri);
}
/**
* See {@link #hide(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getHideIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_HIDE);
}
/**
* See {@link #close(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_CLOSE);
}
/**
* See {@link #closeAll(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseAllIntent(Context context,
Class<? extends StandOutWindow> cls) {
return new Intent(context, cls).setAction(ACTION_CLOSE_ALL);
}
/**
* See {@link #sendData(Context, Class, int, int, Bundle, Class, int)}.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* If the sending window wants a result, provide the class of the
* sending window.
* @param fromId
* If the sending window wants a result, provide the id of the
* sending window.
* @return An {@link Intnet} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getSendDataIntent(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
return new Intent(context, toCls).putExtra("id", toId)
.putExtra("requestCode", requestCode)
.putExtra("wei.mark.standout.data", data)
.putExtra("wei.mark.standout.fromCls", fromCls)
.putExtra("fromId", fromId).setAction(ACTION_SEND_DATA);
}
// internal map of ids to shown/hidden views
static WindowCache sWindowCache;
static Window sFocusedWindow;
// static constructors
static {
sWindowCache = new WindowCache();
sFocusedWindow = null;
}
// internal system services
WindowManager mWindowManager;
private NotificationManager mNotificationManager;
LayoutInflater mLayoutInflater;
// internal state variables
private boolean startedForeground;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
startedForeground = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// intent should be created with
// getShowIntent(), getHideIntent(), getCloseIntent()
if (intent != null) {
String action = intent.getAction();
int id = intent.getIntExtra("id", DEFAULT_ID);
// this will interfere with getPersistentNotification()
if (id == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException(
"ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(id);
} else if (ACTION_HIDE.equals(action)) {
hide(id);
} else if (ACTION_CLOSE.equals(action)) {
close(id);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (!isExistingId(id) && id != DISREGARD_ID) {
Log.w(TAG,
"Sending data to non-existant window. If this is not intended, make sure toId is either an existing window's id or DISREGARD_ID.");
}
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent
.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(id, requestCode, data, fromCls, fromId);
}
} else {
Log.w(TAG, "Tried to onStartCommand() with a null intent.");
}
// the service is started in foreground in show()
// so we don't expect Android to kill this service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closes all windows
closeAll();
}
/**
* Return the name of every window in this implementation. The name will
* appear in the default implementations of the system window decoration
* title and notification titles.
*
* @return The name.
*/
public abstract String getAppName();
/**
* Return the icon resource for every window in this implementation. The
* icon will appear in the default implementations of the system window
* decoration and notifications.
*
* @return The icon.
*/
public abstract int getAppIcon();
/**
* Create a new {@link View} corresponding to the id, and add it as a child
* to the frame. The view will become the contents of this StandOut window.
* The view MUST be newly created, and you MUST attach it to the frame.
*
* <p>
* If you are inflating your view from XML, make sure you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)} to attach your
* view to frame. Set the ViewGroup to be frame, and the boolean to true.
*
* <p>
* If you are creating your view programmatically, make sure you use
* {@link FrameLayout#addView(View)} to add your view to the frame.
*
* @param id
* The id representing the window.
* @param frame
* The {@link FrameLayout} to attach your view as a child to.
*/
public abstract void createAndAttachView(int id, FrameLayout frame);
/**
* Return the {@link StandOutWindow#LayoutParams} for the corresponding id.
* The system will set the layout params on the view for this StandOut
* window. The layout params may be reused.
*
*
* @param id
* The id of the window.
* @param window
* The window corresponding to the id. Given as courtesy, so you
* may get the existing layout params.
* @return The {@link StandOutWindow#LayoutParams} corresponding to the id.
* The layout params will be set on the window. The layout params
* returned will be reused whenever possible, minimizing the number
* of times getParams() will be called.
*/
public abstract StandOutLayoutParams getParams(int id, Window window);
/**
* Implement this method to change modify the behavior and appearance of the
* window corresponding to the id.
*
* <p>
* You may use any of the flags defined in {@link StandOutFlags}. This
* method will be called many times, so keep it fast.
*
* <p>
* Use bitwise OR (|) to set flags, and bitwise XOR (^) to unset flags. To
* test if a flag is set, use {@link Utils#isSet(int, int)}.
*
* @param id
* The id of the window.
* @return A combination of flags.
*/
public int getFlags(int id) {
return 0;
}
/**
* Implement this method to set a custom title for the window corresponding
* to the id.
*
* @param id
* The id of the window.
* @return The title of the window.
*/
public String getTitle(int id) {
return getAppName();
}
/**
* Implement this method to set a custom icon for the window corresponding
* to the id.
*
* @param id
* The id of the window.
* @return The icon of the window.
*/
public int getIcon(int id) {
return getAppIcon();
}
/**
* Return the title for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The title for the persistent notification.
*/
public String getPersistentNotificationTitle(int id) {
return getAppName() + " Running";
}
/**
* Return the message for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The message for the persistent notification.
*/
public String getPersistentNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the window shown.
* @return The intent for the persistent notification.
*/
public Intent getPersistentNotificationIntent(int id) {
return null;
}
/**
* Return the icon resource for every hidden window in this implementation.
* The icon will appear in the default implementations of the hidden
* notifications.
*
* @return The icon.
*/
public int getHiddenIcon() {
return getAppIcon();
}
/**
* Return the title for the hidden notification corresponding to the window
* being hidden.
*
* @param id
* The id of the hidden window.
* @return The title for the hidden notification.
*/
public String getHiddenNotificationTitle(int id) {
return getAppName() + " Hidden";
}
/**
* Return the message for the hidden notification corresponding to the
* window being hidden.
*
* @param id
* The id of the hidden window.
* @return The message for the hidden notification.
*/
public String getHiddenNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the hidden notification corresponding to the window
* being hidden.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the hidden window.
* @return The intent for the hidden notification.
*/
public Intent getHiddenNotificationIntent(int id) {
return null;
}
/**
* Return a persistent {@link Notification} for the corresponding id. You
* must return a notification for AT LEAST the first id to be requested.
* Once the persistent notification is shown, further calls to
* {@link #getPersistentNotification(int)} may return null. This way Android
* can start the StandOut window service in the foreground and will not kill
* the service on low memory.
*
* <p>
* As a courtesy, the system will request a notification for every new id
* shown. Your implementation is encouraged to include the
* {@link PendingIntent#FLAG_UPDATE_CURRENT} flag in the notification so
* that there is only one system-wide persistent notification.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getPersistentNotification(int)} that keeps one system-wide
* persistent notification that creates a new window on every click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id, or null if
* you've previously returned a notification.
*/
public Notification getPersistentNotification(int id) {
// basic notification stuff
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// getPersistentNotification() is called for every new window
// so we replace the old notification with a new one that has
// a bigger id
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return a hidden {@link Notification} for the corresponding id. The system
* will request a notification for every id that is hidden.
*
* <p>
* If null is returned, StandOut will assume you do not wish to support
* hiding this window, and will {@link #close(int)} it for you.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getHiddenNotification(int)} that for every hidden window keeps a
* notification which restores that window upon user's click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id or null.
*/
public Notification getHiddenNotification(int id) {
// same basics as getPersistentNotification()
int icon = getHiddenIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getHiddenNotificationTitle(id);
String contentText = getHiddenNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// the difference here is we are providing the same id
Intent notificationIntent = getHiddenNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return the animation to play when the window corresponding to the id is
* shown.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getShowAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
}
/**
* Return the animation to play when the window corresponding to the id is
* hidden.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getHideAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Return the animation to play when the window corresponding to the id is
* closed.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getCloseAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Implement this method to set a custom theme for all windows in this
* implementation.
*
* @return The theme to set on the window, or 0 for device default.
*/
public int getThemeStyle() {
return 0;
}
/**
* You probably want to leave this method alone and implement
* {@link #getDropDownItems(int)} instead. Only implement this method if you
* want more control over the drop down menu.
*
* <p>
* Implement this method to set a custom drop down menu when the user clicks
* on the icon of the window corresponding to the id. The icon is only shown
* when {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set.
*
* @param id
* The id of the window.
* @return The drop down menu to be anchored to the icon, or null to have no
* dropdown menu.
*/
public PopupWindow getDropDown(final int id) {
final List<DropDownListItem> items;
List<DropDownListItem> dropDownListItems = getDropDownItems(id);
if (dropDownListItems != null) {
items = dropDownListItems;
} else {
items = new ArrayList<StandOutWindow.DropDownListItem>();
}
// add default drop down items
items.add(new DropDownListItem(
android.R.drawable.ic_menu_close_clear_cancel, "Quit "
+ getAppName(), new Runnable() {
@Override
public void run() {
closeAll();
}
}));
// turn item list into views in PopupWindow
LinearLayout list = new LinearLayout(this);
list.setOrientation(LinearLayout.VERTICAL);
final PopupWindow dropDown = new PopupWindow(list,
StandOutLayoutParams.WRAP_CONTENT,
StandOutLayoutParams.WRAP_CONTENT, true);
for (final DropDownListItem item : items) {
ViewGroup listItem = (ViewGroup) mLayoutInflater.inflate(
R.layout.drop_down_list_item, null);
list.addView(listItem);
ImageView icon = (ImageView) listItem.findViewById(R.id.icon);
icon.setImageResource(item.icon);
TextView description = (TextView) listItem
.findViewById(R.id.description);
description.setText(item.description);
listItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
item.action.run();
dropDown.dismiss();
}
});
}
Drawable background = getResources().getDrawable(
android.R.drawable.editbox_dropdown_dark_frame);
dropDown.setBackgroundDrawable(background);
return dropDown;
}
/**
* Implement this method to populate the drop down menu when the user clicks
* on the icon of the window corresponding to the id. The icon is only shown
* when {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set.
*
* @param id
* The id of the window.
* @return The list of items to show in the drop down menu, or null or empty
* to have no dropdown menu.
*/
public List<DropDownListItem> getDropDownItems(int id) {
return null;
}
/**
* Implement this method to be alerted to touch events in the body of the
* window corresponding to the id.
*
* <p>
* Note that even if you set {@link #FLAG_DECORATION_SYSTEM}, you will not
* receive touch events from the system window decorations.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
public boolean onTouchBody(int id, Window window, View view,
MotionEvent event) {
return false;
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is moved.
*
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
* @see {@link #onTouchHandleMove(int, Window, View, MotionEvent)}
*/
public void onMove(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is resized.
*
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
* @see {@link #onTouchHandleResize(int, Window, View, MotionEvent)}
*/
public void onResize(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be shown. This callback will occur before the view is
* added to the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be shown.
* @return Return true to cancel the view from being shown, or false to
* continue.
* @see #show(int)
*/
public boolean onShow(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be hidden. This callback will occur before the view is
* removed from the window manager and {@link #getHiddenNotification(int)}
* is called.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be hidden.
* @return Return true to cancel the view from being hidden, or false to
* continue.
* @see #hide(int)
*/
public boolean onHide(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be closed. This callback will occur before the view is
* removed from the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @return Return true to cancel the view from being closed, or false to
* continue.
* @see #close(int)
*/
public boolean onClose(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when all windows are about to be
* closed. This callback will occur before any views are removed from the
* window manager.
*
* @return Return true to cancel the views from being closed, or false to
* continue.
* @see #closeAll()
*/
public boolean onCloseAll() {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id has received some data. The sender is described by fromCls and fromId
* if the sender wants a result. To send a result, use
* {@link #sendData(int, Class, int, int, Bundle)}.
*
* @param id
* The id of your receiving window.
* @param requestCode
* The sending window provided this request code to declare what
* kind of data is being sent.
* @param data
* A bundle of parceleable data that was sent to your receiving
* window.
* @param fromCls
* The sending window's class. Provided if the sender wants a
* result.
* @param fromId
* The sending window's id. Provided if the sender wants a
* result.
*/
public void onReceiveData(int id, int requestCode, Bundle data,
Class<? extends StandOutWindow> fromCls, int fromId) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be updated in the layout. This callback will occur before
* the view is updated by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be updated.
* @param params
* The updated layout params.
* @return Return true to cancel the window from being updated, or false to
* continue.
* @see #updateViewLayout(int, Window, StandOutLayoutParams)
*/
public boolean onUpdate(int id, Window window, StandOutLayoutParams params) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be bought to the front. This callback will occur before
* the window is brought to the front by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @return Return true to cancel the window from being brought to the front,
* or false to continue.
* @see #bringToFront(int)
*/
public boolean onBringToFront(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to have its focus changed. This callback will occur before
* the window's focus is changed.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @param focus
* Whether the window is gaining or losing focus.
* @return Return true to cancel the window's focus from being changed, or
* false to continue.
* @see #focus(int)
*/
public boolean onFocusChange(int id, Window window, boolean focus) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id receives a key event. This callback will occur before the window
* handles the event with {@link Window#dispatchKeyEvent(KeyEvent)}.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to receive the key event.
* @param event
* The key event.
* @return Return true to cancel the window from handling the key event, or
* false to let the window handle the key event.
* @see {@link Window#dispatchKeyEvent(KeyEvent)}
*/
public boolean onKeyEvent(int id, Window window, KeyEvent event) {
return false;
}
/**
* Show or restore a window corresponding to the id. Return the window that
* was shown/restored.
*
* @param id
* The id of the window.
* @return The window shown.
*/
public final synchronized Window show(int id) {
// get the window corresponding to the id
Window cachedWindow = getWindow(id);
final Window window;
// check cache first
if (cachedWindow != null) {
window = cachedWindow;
} else {
window = new Window(this, id);
}
// alert callbacks and cancel if instructed
if (onShow(id, window)) {
Log.d(TAG, "Window " + id + " show cancelled by implementation.");
return null;
}
// focus an already shown window
if (window.visibility == Window.VISIBILITY_VISIBLE) {
Log.d(TAG, "Window " + id + " is already shown.");
focus(id);
return window;
}
window.visibility = Window.VISIBILITY_VISIBLE;
// get animation
Animation animation = getShowAnimation(id);
// get the params corresponding to the id
StandOutLayoutParams params = window.getLayoutParams();
try {
// add the view to the window manager
mWindowManager.addView(window, params);
// animate
if (animation != null) {
window.getChildAt(0).startAnimation(animation);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// add view to internal map
sWindowCache.putCache(id, getClass(), window);
// get the persistent notification
Notification notification = getPersistentNotification(id);
// show the notification
if (notification != null) {
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR;
// only show notification if not shown before
if (!startedForeground) {
// tell Android system to show notification
startForeground(
getClass().hashCode() + ONGOING_NOTIFICATION_ID,
notification);
startedForeground = true;
} else {
// update notification if shown before
mNotificationManager.notify(getClass().hashCode()
+ ONGOING_NOTIFICATION_ID, notification);
}
} else {
// notification can only be null if it was provided before
if (!startedForeground) {
throw new RuntimeException("Your StandOutWindow service must"
+ "provide a persistent notification."
+ "The notification prevents Android"
+ "from killing your service in low"
+ "memory situations.");
}
}
focus(id);
return window;
}
/**
* Hide a window corresponding to the id. Show a notification for the hidden
* window.
*
* @param id
* The id of the window.
*/
public final synchronized void hide(int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to hide(" + id
+ ") a null window.");
}
// alert callbacks and cancel if instructed
if (onHide(id, window)) {
Log.d(TAG, "Window " + id + " hide cancelled by implementation.");
return;
}
// ignore if window is already hidden
if (window.visibility == Window.VISIBILITY_GONE) {
Log.d(TAG, "Window " + id + " is already hidden.");
}
// check if hide enabled
if (Utils.isSet(window.flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
window.visibility = Window.VISIBILITY_TRANSITION;
// get the hidden notification for this view
Notification notification = getHiddenNotification(id);
// get animation
Animation animation = getHideAnimation(id);
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
window.visibility = Window.VISIBILITY_GONE;
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// display the notification
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR
| Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(getClass().hashCode() + id,
notification);
} else {
// if hide not enabled, close window
close(id);
}
}
/**
* Close a window corresponding to the id.
*
* @param id
* The id of the window.
*/
public final synchronized void close(final int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to close(" + id
+ ") a null window.");
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onClose(id, window)) {
Log.w(TAG, "Window " + id + " close cancelled by implementation.");
return;
}
// remove hidden notification
mNotificationManager.cancel(getClass().hashCode() + id);
unfocus(window);
window.visibility = Window.VISIBILITY_TRANSITION;
// get animation
Animation animation = getCloseAnimation(id);
// remove window
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
window.visibility = Window.VISIBILITY_GONE;
// remove view from internal map
sWindowCache.removeCache(id,
StandOutWindow.this.getClass());
// if we just released the last window, quit
if (getExistingIds().size() == 0) {
// tell Android to remove the persistent
// notification
// the Service will be shutdown by the system on low
// memory
startedForeground = false;
stopForeground(true);
}
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
// remove view from internal map
sWindowCache.removeCache(id, getClass());
// if we just released the last window, quit
if (sWindowCache.getCacheSize(getClass()) == 0) {
// tell Android to remove the persistent notification
// the Service will be shutdown by the system on low memory
startedForeground = false;
stopForeground(true);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Close all existing windows.
*/
public final synchronized void closeAll() {
// alert callbacks and cancel if instructed
if (onCloseAll()) {
Log.w(TAG, "Windows close all cancelled by implementation.");
return;
}
// add ids to temporary set to avoid concurrent modification
LinkedList<Integer> ids = new LinkedList<Integer>();
for (int id : getExistingIds()) {
ids.add(id);
}
// close each window
for (int id : ids) {
close(id);
}
}
/**
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the id of the sender.
*
* @param fromId
* Provide the id of the sending window if you want a result.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
*/
public final void sendData(int fromId,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data) {
StandOutWindow.sendData(this, toCls, toId, requestCode, data,
getClass(), fromId);
}
/**
* Bring the window corresponding to this id in front of all other windows.
* The window may flicker as it is removed and restored by the system.
*
* @param id
* The id of the window to bring to the front.
*/
public final synchronized void bringToFront(int id) {
Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to bringToFront(" + id
+ ") a null window.");
}
if (window.visibility == Window.VISIBILITY_GONE) {
throw new IllegalStateException("Tried to bringToFront(" + id
+ ") a window that is not shown.");
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onBringToFront(id, window)) {
Log.w(TAG, "Window " + id
+ " bring to front cancelled by implementation.");
return;
}
StandOutLayoutParams params = window.getLayoutParams();
// remove from window manager then add back
try {
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
mWindowManager.addView(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Request focus for the window corresponding to this id. A maximum of one
* window can have focus, and that window will receive all key events,
* including Back and Menu.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
public final synchronized boolean focus(int id) {
// check if that window is focusable
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to focus(" + id
+ ") a null window.");
}
if (!Utils.isSet(window.flags,
StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
// remove focus from previously focused window
if (sFocusedWindow != null) {
unfocus(sFocusedWindow);
}
return window.onFocus(true);
}
return false;
}
/**
* Remove focus for the window corresponding to this id. Once a window is
* unfocused, it will stop receiving key events.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
public final synchronized boolean unfocus(int id) {
Window window = getWindow(id);
return unfocus(window);
}
/**
* Courtesy method for your implementation to use if you want to. Gets a
* unique id to assign to a new window.
*
* @return The unique id.
*/
public final int getUniqueId() {
int unique = DEFAULT_ID;
for (int id : getExistingIds()) {
unique = Math.max(unique, id + 1);
}
return unique;
}
/**
* Return whether the window corresponding to the id exists. This is useful
* for testing if the id is being restored (return true) or shown for the
* first time (return false).
*
* @param id
* The id of the window.
* @return True if the window corresponding to the id is either shown or
* hidden, or false if it has never been shown or was previously
* closed.
*/
public final boolean isExistingId(int id) {
return sWindowCache.isCached(id, getClass());
}
/**
* Return the ids of all shown or hidden windows.
*
* @return A set of ids, or an empty set.
*/
public final Set<Integer> getExistingIds() {
return sWindowCache.getCacheIds(getClass());
}
/**
* Return the window corresponding to the id, if it exists in cache. The
* window will not be created with
* {@link #createAndAttachView(int, ViewGroup)}. This means the returned
* value will be null if the window is not shown or hidden.
*
* @param id
* The id of the window.
* @return The window if it is shown/hidden, or null if it is closed.
*/
public final Window getWindow(int id) {
return sWindowCache.getCache(id, getClass());
}
/**
* Return the window that currently has focus.
*
* @return The window that has focus.
*/
public final Window getFocusedWindow() {
return sFocusedWindow;
}
/**
* Sets the window that currently has focus.
*/
public final void setFocusedWindow(Window window) {
sFocusedWindow = window;
}
/**
* Change the title of the window, if such a title exists. A title exists if
* {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set, or if your own view
* contains a TextView with id R.id.title.
*
* @param id
* The id of the window.
* @param text
* The new title.
*/
public final void setTitle(int id, String text) {
Window window = getWindow(id);
if (window != null) {
View title = window.findViewById(R.id.title);
if (title instanceof TextView) {
((TextView) title).setText(text);
}
}
}
/**
* Change the icon of the window, if such a icon exists. A icon exists if
* {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set, or if your own view
* contains a TextView with id R.id.window_icon.
*
* @param id
* The id of the window.
* @param drawableRes
* The new icon.
*/
public final void setIcon(int id, int drawableRes) {
Window window = getWindow(id);
if (window != null) {
View icon = window.findViewById(R.id.window_icon);
if (icon instanceof ImageView) {
((ImageView) icon).setImageResource(drawableRes);
}
}
}
/**
* Internal touch handler for handling moving the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
public boolean onTouchHandleMove(int id, Window window, View view,
MotionEvent event) {
StandOutLayoutParams params = window.getLayoutParams();
// how much you have to move in either direction in order for the
// gesture to be a move and not tap
int totalDeltaX = window.touchInfo.lastX - window.touchInfo.firstX;
int totalDeltaY = window.touchInfo.lastY - window.touchInfo.firstY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
if (window.touchInfo.moving
|| Math.abs(totalDeltaX) >= params.threshold
|| Math.abs(totalDeltaY) >= params.threshold) {
window.touchInfo.moving = true;
// if window is moveable
if (Utils.isSet(window.flags,
StandOutFlags.FLAG_BODY_MOVE_ENABLE)) {
// update the position of the window
if (event.getPointerCount() == 1) {
params.x += deltaX;
params.y += deltaY;
}
window.edit().setPosition(params.x, params.y).commit();
}
}
break;
case MotionEvent.ACTION_UP:
window.touchInfo.moving = false;
if (event.getPointerCount() == 1) {
// bring to front on tap
boolean tap = Math.abs(totalDeltaX) < params.threshold
&& Math.abs(totalDeltaY) < params.threshold;
if (tap
&& Utils.isSet(
window.flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP)) {
StandOutWindow.this.bringToFront(id);
}
}
// bring to front on touch
else if (Utils.isSet(window.flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH)) {
StandOutWindow.this.bringToFront(id);
}
break;
}
onMove(id, window, view, event);
return true;
}
/**
* Internal touch handler for handling resizing the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
public boolean onTouchHandleResize(int id, Window window, View view,
MotionEvent event) {
StandOutLayoutParams params = (StandOutLayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
// update the size of the window
params.width += deltaX;
params.height += deltaY;
// keep window between min/max width/height
if (params.width >= params.minWidth
&& params.width <= params.maxWidth) {
window.touchInfo.lastX = (int) event.getRawX();
}
if (params.height >= params.minHeight
&& params.height <= params.maxHeight) {
window.touchInfo.lastY = (int) event.getRawY();
}
window.edit().setSize(params.width, params.height).commit();
break;
case MotionEvent.ACTION_UP:
break;
}
onResize(id, window, view, event);
return true;
}
/**
* Remove focus for the window, which could belong to another application.
* Since we don't allow windows from different applications to directly
* interact with each other, except for
* {@link #sendData(Context, Class, int, int, Bundle, Class, int)}, this
* method is private.
*
* @param window
* The window to unfocus.
* @return True if focus changed successfully, false if it failed.
*/
public synchronized boolean unfocus(Window window) {
if (window == null) {
throw new IllegalArgumentException(
"Tried to unfocus a null window.");
}
return window.onFocus(false);
}
/**
* Update the window corresponding to this id with the given params.
*
* @param id
* The id of the window.
* @param params
* The updated layout params to apply.
*/
public void updateViewLayout(int id, StandOutLayoutParams params) {
Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to updateViewLayout("
+ id + ") a null window.");
}
if (window.visibility == Window.VISIBILITY_GONE) {
return;
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onUpdate(id, window, params)) {
Log.w(TAG, "Window " + id + " update cancelled by implementation.");
return;
}
try {
window.setLayoutParams(params);
mWindowManager.updateViewLayout(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* LayoutParams specific to floating StandOut windows.
*
* @author Mark Wei <markwei@gmail.com>
*
*/
public class StandOutLayoutParams extends WindowManager.LayoutParams {
/**
* Special value for x position that represents the left of the screen.
*/
public static final int LEFT = 0;
/**
* Special value for y position that represents the top of the screen.
*/
public static final int TOP = 0;
/**
* Special value for x position that represents the right of the screen.
*/
public static final int RIGHT = Integer.MAX_VALUE;
/**
* Special value for y position that represents the bottom of the
* screen.
*/
public static final int BOTTOM = Integer.MAX_VALUE;
/**
* Special value for x or y position that represents the center of the
* screen.
*/
public static final int CENTER = Integer.MIN_VALUE;
/**
* Special value for x or y position which requests that the system
* determine the position.
*/
public static final int AUTO_POSITION = Integer.MIN_VALUE + 1;
/**
* The distance that distinguishes a tap from a drag.
*/
public int threshold;
/**
* Optional constraints of the window.
*/
public int minWidth, minHeight, maxWidth, maxHeight;
/**
* @param id
* The id of the window.
*/
public StandOutLayoutParams(int id) {
super(200, 200, TYPE_PHONE,
StandOutLayoutParams.FLAG_NOT_TOUCH_MODAL
| StandOutLayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
int windowFlags = getFlags(id);
setFocusFlag(false);
if (!Utils.isSet(windowFlags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
// windows may be moved beyond edges
flags |= FLAG_LAYOUT_NO_LIMITS;
}
x = getX(id, width);
y = getY(id, height);
gravity = Gravity.TOP | Gravity.LEFT;
threshold = 10;
minWidth = minHeight = 0;
maxWidth = maxHeight = Integer.MAX_VALUE;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
*/
public StandOutLayoutParams(int id, int w, int h) {
this(id);
width = w;
height = h;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos) {
this(id, w, h);
if (xpos != AUTO_POSITION) {
x = xpos;
}
if (ypos != AUTO_POSITION) {
y = ypos;
}
Display display = mWindowManager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
if (x == RIGHT) {
x = width - w;
} else if (x == CENTER) {
x = (width - w) / 2;
}
if (y == BOTTOM) {
y = height - h;
} else if (y == CENTER) {
y = (height - h) / 2;
}
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
* @param minWidth
* The minimum width of the window.
* @param minHeight
* The mininum height of the window.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos,
int minWidth, int minHeight) {
this(id, w, h, xpos, ypos);
this.minWidth = minWidth;
this.minHeight = minHeight;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
* @param minWidth
* The minimum width of the window.
* @param minHeight
* The mininum height of the window.
* @param threshold
* The touch distance threshold that distinguishes a tap from
* a drag.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos,
int minWidth, int minHeight, int threshold) {
this(id, w, h, xpos, ypos, minWidth, minHeight);
this.threshold = threshold;
}
// helper to create cascading windows
private int getX(int id, int width) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int types = sWindowCache.size();
int initialX = 100 * types;
int variableX = 100 * id;
int rawX = initialX + variableX;
return rawX % (displayWidth - width);
}
// helper to create cascading windows
private int getY(int id, int height) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
int types = sWindowCache.size();
int initialY = 100 * types;
int variableY = x + 200 * (100 * id) / (displayWidth - width);
int rawY = initialY + variableY;
return rawY % (displayHeight - height);
}
public void setFocusFlag(boolean focused) {
if (focused) {
flags = flags ^ StandOutLayoutParams.FLAG_NOT_FOCUSABLE;
} else {
flags = flags | StandOutLayoutParams.FLAG_NOT_FOCUSABLE;
}
}
}
protected class DropDownListItem {
public int icon;
public String description;
public Runnable action;
public DropDownListItem(int icon, String description, Runnable action) {
super();
this.icon = icon;
this.description = description;
this.action = action;
}
@Override
public String toString() {
return description;
}
}
} |
package wei.mark.standout;
import java.util.LinkedList;
import java.util.WeakHashMap;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
/**
* Extend this class to easily create and manage floating StandOut windows.
*
* @author Mark Wei <markwei@gmail.com>
*
*/
public abstract class StandOutWindow extends Service {
/**
* StandOut window id: You may use this sample id for your first window.
*/
public static final int DEFAULT_ID = 0;
/**
* StandOut window id: You may NOT use this id for any windows.
*/
public static final int RESERVED_ID = -1;
/**
* Intent action: Show a new window corresponding to the id.
*/
public static final String ACTION_SHOW = "SHOW";
/**
* Intent action: Restore a previously hidden window corresponding to the
* id. The window should be previously hidden with {@link #ACTION_HIDE}.
*/
public static final String ACTION_RESTORE = "RESTORE";
/**
* Intent action: Close an existing window with an existing id.
*/
public static final String ACTION_CLOSE = "CLOSE";
/**
* Intent action: Close all existing windows.
*/
public static final String ACTION_CLOSE_ALL = "CLOSE_ALL";
/**
* Intent action: Hide an existing window with an existing id. To enable the
* ability to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*/
public static final String ACTION_HIDE = "HIDE";
/**
* This default flag indicates that the window requires no window
* decorations (titlebar, hide/close buttons, resize handle, etc).
*/
public static final int FLAG_DECORATION_NONE = 0x00000000;
/**
* Setting this flag indicates that the window wants the system provided
* window decorations (titlebar, hide/close buttons, resize handle, etc).
*/
public static final int FLAG_DECORATION_SYSTEM = 0x00000001;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag indicates
* that the window decorator should NOT provide a hide button.
*/
public static final int FLAG_DECORATION_HIDE_DISABLE = 0x00000002;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag indicates
* that the window decorator should NOT provide a close button.
*/
public static final int FLAG_DECORATION_CLOSE_DISABLE = 0x00000004;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag indicates
* that the window decorator should NOT provide a resize handle.
*/
public static final int FLAG_DECORATION_RESIZE_DISABLE = 0x00000008;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag indicates
* that the window decorator should NOT provide a resize handle.
*/
public static final int FLAG_DECORATION_MOVE_DISABLE = 0x00000010;
/**
* Setting this flag indicates that the window can be moved by dragging the
* body.
*
* <p>
* Note that if {@link #FLAG_DECORATION_SYSTEM} is set, the window can
* always be moved by dragging the titlebar.
*/
public static final int FLAG_BODY_MOVE_ENABLE = 0x00000020;
// internal map of ids to shown/hidden views
private static WeakHashMap<Integer, View> views;
// static constructor
static {
views = new WeakHashMap<Integer, View>();
}
/**
* Show a new window corresponding to the id, or restore a previously hidden
* window.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
*/
public static void show(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Hide the existing window corresponding to the id. To enable the ability
* to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
*/
public static void hide(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Close an existing window with an existing id.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
*/
public static void close(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getCloseIntent(context, cls, id));
}
/**
* Close all existing windows.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
*/
public static void closeAll(Context context,
Class<? extends StandOutWindow> cls) {
context.startService(getCloseAllIntent(context, cls));
}
/**
* See {@link #show(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getShowIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
// Show or restore window depending on whether the id exists
String action = views.containsKey(id) ? ACTION_RESTORE : ACTION_SHOW;
Uri uri = views.containsKey(id) ? Uri.parse("standout://" + id) : null;
return new Intent(context, cls).putExtra("id", id).setAction(action)
.setData(uri);
}
/**
* See {@link #hide(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getHideIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_HIDE);
}
/**
* See {@link #close(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_CLOSE);
}
/**
* See {@link #closeAll(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseAllIntent(Context context,
Class<? extends StandOutWindow> cls) {
return new Intent(context, cls).setAction(ACTION_CLOSE_ALL);
}
// internal system services
private WindowManager mWindowManager;
private NotificationManager mNotificationManager;
private LayoutInflater mLayoutInflater;
// internal state variables
private boolean startedForeground;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
startedForeground = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// intent should be created with
// getShowIntent(), getHideIntent(), getCloseIntent()
if (intent != null) {
String action = intent.getAction();
int id = intent.getIntExtra("id", DEFAULT_ID);
Log.d("StandOutWindow", "Intent id: " + id);
// this will interfere with getPersistentNotification()
if (id == RESERVED_ID) {
throw new RuntimeException(
"ID cannot equals StandOutWindow.RESERVED_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(id);
} else if (ACTION_HIDE.equals(action)) {
hide(id);
} else if (ACTION_CLOSE.equals(action)) {
close(id);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
}
} else {
Log.w("StandOutWindow",
"Tried to onStartCommand() with a null intent");
}
// the service is started in foreground in show()
// so we don't expect Android to kill this service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closes all windows
closeAll();
}
/**
* Create a new {@link View} corresponding to the id, and add it as a child
* to the root. The view will become the contents of this StandOut window.
* The view MUST be newly created, and you MUST attach it to root.
*
* <p>
* If you are inflating your view from XML, make sure you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)} to attach your
* view to root. Set the ViewGroup to be root, and the boolean to true.
*
* <p>
* If you are creating your view programmatically, make sure you use
* {@link ViewGroup#addView(View)} to add your view to root.
*
* @param id
* The id representing the window.
* @param root
* The {@link ViewGroup} to attach your view as a child to.
* @return A new {@link View} corresponding to the id. The view will be the
* content of this StandOut window. The view MUST be newly created.
*/
protected abstract View createAndAttachView(int id, ViewGroup root);
/**
* Return the {@link StandOutWindow#LayoutParams} for the corresponding id.
* The system will set the layout params on the view for this StandOut
* window. The layout params may be reused.
*
*
* @param id
* The id of the window.
* @param view
* The view corresponding to the id. Given as courtesy, so you
* may get the existing layout params.
* @return The {@link StandOutWindow#LayoutParams} corresponding to the id.
* The layout params will be set on the view. The layout params may
* be reused.
*/
protected abstract StandOutWindow.LayoutParams getParams(int id, View view);
/**
* Implement this method to change modify the behavior and appearance of the
* window corresponding to the id.
*
* <p>
* You may use any of the flags defined in {@link StandOutWindow} such as
* {@link #FLAG_DECORATION_NONE}.
*
* <p>
* Use bitwise OR (|) to set flags, and bitwise XOR (^) to unset flags. To
* test if a flag is set, use (getFlags(id) & flag) != 0.
*
* @param id
* The id of the window.
* @return Bitwise OR'd flags
*/
protected int getFlags(int id) {
return FLAG_DECORATION_NONE;
}
/**
* Return a persistent {@link Notification} for the corresponding id. You
* must return a notification for AT LEAST the first id to be requested.
* Once the persistent notification is shown, further calls to
* {@link #getPersistentNotification(int)} may return null. This way Android
* can start the StandOut window service in the foreground and will not kill
* the service on low memory.
*
* <p>
* As a courtesy, the system will request a notification for every new id
* shown. Your implementation is encouraged to include the
* {@link PendingIntent#FLAG_UPDATE_CURRENT} flag in the notification so
* that there is only one system-wide persistent notification.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getPersistentNotification(int)} that keeps one system-wide
* persistent notification that creates a new window on every click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id, or null if
* you've previously returned a notification.
*/
protected abstract Notification getPersistentNotification(int id);
/**
* Return a hidden {@link Notification} for the corresponding id. The system
* will request a notification for every id that is hidden.
*
* <p>
* If null is returned, StandOut will assume you do not wish to support
* hiding this window, and will {@link #close(int)} it for you.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getHiddenNotification(int)} that for every hidden window keeps a
* notification which restores that window upon user's click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id or null.
*/
protected Notification getHiddenNotification(int id) {
return null;
}
/**
* Implement this method to be alerted to touch events on the window
* corresponding to the id. The events are passed directly from
* {@link View.OnTouchListener#onTouch(View, MotionEvent)}
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected boolean onTouch(int id, View window, View view, MotionEvent event) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be shown. This callback will occur before the view is
* added to the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be shown.
* @return Return true to cancel the view from being shown, or false to
* continue.
* @see #show(int)
*/
protected boolean onShow(int id, View window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be hidden. This callback will occur before the view is
* removed from the window manager and {@link #getHiddenNotification(int)}
* is called.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be hidden.
* @return Return true to cancel the view from being hidden, or false to
* continue.
* @see #hide(int)
*/
protected boolean onHide(int id, View window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be closed. This callback will occur before the view is
* removed from the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @return Return true to cancel the view from being closed, or false to
* continue.
* @see #close(int)
*/
protected boolean onClose(int id, View window) {
return false;
}
/**
* Implement this callback to be alerted when all windowsare about to be
* closed. This callback will occur before any views are removed from the
* window manager.
*
* @return Return true to cancel the views from being closed, or false to
* continue.
* @see #closeAll()
*/
protected boolean onCloseAll() {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be updated in the layout. This callback will occur before
* the view is updated by the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @param params
* The updated layout params.
* @return Return true to cancel the view from being updated, or false to
* continue.
* @see #updateViewLayout(int, View, LayoutParams)
*/
protected boolean onUpdate(int id, View window,
StandOutWindow.LayoutParams params) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be bought to the front. This callback will occur before
* the view is brought to the front by the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be brought to the front.
* @return Return true to cancel the view from being brought to the front,
* or false to continue.
* @see #bringToFront(int)
*/
protected boolean onBringToFront(int id, View window) {
return false;
}
/**
* Show or restore a window corresponding to the id.
*
* @param id
* The id of the window.
*/
protected final void show(int id) {
// get the view corresponding to the id
View window = getWrappedView(id);
if (window == null) {
Log.w("StandOutWindow", "Tried to show(" + id + ") a null view");
return;
}
// alert callbacks and cancel if instructed
if (onShow(id, window))
return;
WrappedTag tag = (WrappedTag) window.getTag();
tag.shown = true;
// add view to internal map
views.put(id, window);
// get the params corresponding to the id
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
if (params == null) {
params = getParams(id, window);
}
try {
// add the view to the window manager
mWindowManager.addView(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
// get the persistent notification
Notification notification = getPersistentNotification(id);
// show the notification
if (notification != null) {
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR;
// only show notification if not shown before
if (!startedForeground) {
// tell Android system to show notification
startForeground(RESERVED_ID, notification);
startedForeground = true;
}
} else {
// notification can only be null if it was provided before
if (!startedForeground) {
throw new RuntimeException("Your StandOutWindow service must"
+ "provide a persistent notification."
+ "The notification prevents Android"
+ "from killing your service in low"
+ "memory situations.");
}
}
}
/**
* Hide a window corresponding to the id. Show a notification for the hidden
* window.
*
* @param id
* The id of the window.
*/
protected final void hide(int id) {
// get the hidden notification for this view
Notification notification = getHiddenNotification(id);
if (notification == null) {
close(id);
return;
}
// get the view corresponding to the id
View window = getWrappedView(id);
if (window == null) {
Log.w("StandOutWindow", "Tried to hide(" + id + ") a null view");
return;
}
// alert callbacks and cancel if instructed
if (onHide(id, window))
return;
WrappedTag tag = (WrappedTag) window.getTag();
tag.shown = false;
try {
// remove the view from the window manager
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
// display the notification
notification.flags = notification.flags | Notification.FLAG_NO_CLEAR
| Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(id, notification);
}
/**
* Close a window corresponding to the id.
*
* @param id
* The id of the window.
*/
protected final void close(int id) {
// get the view corresponding to the id
View window = getWrappedView(id);
if (window == null) {
Log.w("StandOutWindow", "Tried to close(" + id + ") a null view");
return;
}
// alert callbacks and cancel if instructed
if (onClose(id, window))
return;
WrappedTag tag = (WrappedTag) window.getTag();
if (tag.shown) {
try {
// remove the view from the window manager
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
tag.shown = false;
// cancel hidden notification
mNotificationManager.cancel(id);
}
// remove view from internal map
views.remove(id);
// if we just released the last view, quit
if (views.isEmpty()) {
// tell Android to remove the persistent notification
// the Service will be shutdown by the system on low memory
startedForeground = false;
stopForeground(true);
}
}
/**
* Close all existing windows.
*/
protected final void closeAll() {
// alert callbacks and cancel if instructed
if (onCloseAll())
return;
// add ids to temporary set to avoid concurrent modification
LinkedList<Integer> ids = new LinkedList<Integer>();
for (int id : views.keySet()) {
ids.add(id);
}
// close each window
for (int id : ids) {
close(id);
}
}
/**
* Update the window corresponding to this view with the given params.
*
* @param window
* The window to update.
* @param params
* The updated layout params to apply.
*/
protected final void updateViewLayout(int id, View window,
StandOutWindow.LayoutParams params) {
// alert callbacks and cancel if instructed
if (onUpdate(id, window, params))
return;
if (window == null) {
Log.w("StandOutWindow", "Tried to updateViewLayout() a null window");
return;
}
mWindowManager.updateViewLayout(window, params);
}
/**
* Bring the window corresponding to this id in front of all other windows.
* The window may flicker as it is removed and restored by the system.
*
* @param id
* The id of the window to bring to the front.
*/
protected final void bringToFront(int id) {
View window = getWrappedView(id);
if (window == null) {
Log.w("StandOutWindow", "Tried to bringToFront() a null view");
return;
}
// alert callbacks and cancel if instructed
if (onBringToFront(id, window))
return;
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
if (params == null) {
params = getParams(id, window);
}
mWindowManager.removeView(window);
mWindowManager.addView(window, params);
}
// wraps the view from getView() into a frame that is easier to manage.
// the frame allows us to pass touch input to implementations
// and set a WrappedTag to keep track of the id and visibility
private View getWrappedView(int id) {
// try get the wrapped view from the internal map
View cachedView = views.get(id);
// if the wrapped view exists, then return it rather than creating one
if (cachedView != null) {
return cachedView;
}
// create the wrapping frame and body
final View window;
FrameLayout body;
int flags = getFlags(id);
if ((flags & FLAG_DECORATION_SYSTEM) != 0) {
// requested system window decorations
window = getSystemWindow(id);
body = (FrameLayout) window.findViewById(R.id.body);
} else {
// did not request decorations. will provide own implementation
window = new FrameLayout(this);
body = (FrameLayout) window;
}
// attach the view corresponding to the id from the implementation
View view = createAndAttachView(id, body);
// make sure the implemention created a view
if (view == null) {
throw new RuntimeException(
"Your view must not be null in createAndAttachView()");
}
// make sure the implementation attached the view
if (view.getParent() == null) {
throw new RuntimeException(
"You must attach your view to the given root ViewGroup in createAndAttachView()");
}
// wrap the existing tag and attach it to the frame
window.setTag(new WrappedTag(id, false, view.getTag()));
return window;
}
/**
* Returns the system window decorations if the implementation sets
* {@link #FLAG_DECORATION_SYSTEM}.
*
* <p>
* The system window decorations support hiding, closing, moving, and
* resizing.
*
* @param id
* The id of the window.
* @return The frame view containing the system window decorations.
*/
private View getSystemWindow(final int id) {
final View window = mLayoutInflater.inflate(R.layout.window, null);
// hide
Button hide = (Button) window.findViewById(R.id.hide);
hide.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("StandOutHelloWorld", "Minimize button clicked");
hide(id);
}
});
// close
Button close = (Button) window.findViewById(R.id.close);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("StandOutHelloWorld", "Close button clicked");
close(id);
}
});
// move
final OnTouchListener moveTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (id) {
default:
WindowTouchInfo touchInfo = ((WrappedTag) window
.getTag()).touchInfo;
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchInfo.x = params.x;
touchInfo.y = params.y;
touchInfo.downX = (int) event.getRawX();
touchInfo.downY = (int) event.getRawY();
touchInfo.deltaX = touchInfo.deltaY = 0;
break;
case MotionEvent.ACTION_MOVE:
touchInfo.deltaX = (int) event.getRawX()
- touchInfo.downX;
touchInfo.deltaY = (int) event.getRawY()
- touchInfo.downY;
break;
case MotionEvent.ACTION_UP:
touchInfo.x = touchInfo.x + touchInfo.deltaX;
touchInfo.y = touchInfo.y + touchInfo.deltaY;
// tap
if (touchInfo.deltaX == 0
&& touchInfo.deltaY == 0) {
bringToFront(id);
}
touchInfo.deltaX = touchInfo.deltaY = 0;
touchInfo.downX = touchInfo.downY = 0;
break;
}
Log.d("StandOutWindow", "Titlebar handle touch: "
+ event);
// update the position of the window
params.x = touchInfo.x + touchInfo.deltaX;
params.y = touchInfo.y + touchInfo.deltaY;
updateViewLayout(id, window, params);
return true;
}
}
};
final View titlebar = window.findViewById(R.id.titlebar);
titlebar.setOnTouchListener(moveTouchListener);
// resize
View corner = window.findViewById(R.id.corner);
corner.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (id) {
default:
WindowTouchInfo touchInfo = ((WrappedTag) window
.getTag()).touchInfo;
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchInfo.width = params.width;
touchInfo.height = params.height;
touchInfo.downX = (int) event.getRawX();
touchInfo.downY = (int) event.getRawY();
touchInfo.deltaX = touchInfo.deltaY = 0;
break;
case MotionEvent.ACTION_MOVE:
touchInfo.deltaX = (int) event.getRawX()
- touchInfo.downX;
touchInfo.deltaY = (int) event.getRawY()
- touchInfo.downY;
break;
case MotionEvent.ACTION_UP:
touchInfo.width = touchInfo.width
+ touchInfo.deltaX;
touchInfo.height = touchInfo.height
+ touchInfo.deltaY;
touchInfo.deltaX = touchInfo.deltaY = 0;
touchInfo.downX = touchInfo.downY = 0;
break;
}
Log.d("StandOutWindow", "Corner handle touch: " + event);
// update the position of the window
params.width = Math.max(0, touchInfo.width
+ touchInfo.deltaX);
params.height = Math.max(0, touchInfo.height
+ touchInfo.deltaY);
updateViewLayout(id, window, params);
return true;
}
}
});
// set window appearance and behavior based on flags
int flags = getFlags(id);
if ((flags & FLAG_DECORATION_HIDE_DISABLE) != 0) {
hide.setVisibility(View.GONE);
}
if ((flags & FLAG_DECORATION_CLOSE_DISABLE) != 0) {
close.setVisibility(View.GONE);
}
if ((flags & FLAG_DECORATION_MOVE_DISABLE) != 0) {
titlebar.setOnTouchListener(null);
}
if ((flags & FLAG_DECORATION_RESIZE_DISABLE) != 0) {
corner.setVisibility(View.GONE);
}
// body should always send touch events
final boolean bodyMoveEnabled = (flags & FLAG_BODY_MOVE_ENABLE) != 0;
View body = window.findViewById(R.id.body);
body.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// pass all touch events to the implementation
int id = ((WrappedTag) window.getTag()).id;
boolean consumed = StandOutWindow.this.onTouch(id, window, v,
event);
// if set FLAG_BODY_MOVE_ENABLE, move the window
if (bodyMoveEnabled) {
consumed = consumed || moveTouchListener.onTouch(v, event);
}
return consumed;
}
});
return window;
}
/**
* WrappedTag will be attached to views from
* {@link StandOutWindow#getWrappedView(int)}
*
* @author Mark Wei <markwei@gmail.com>
*
*/
public class WrappedTag {
/**
* Id of the window
*/
public int id;
/**
* Whether the window is shown or hidden/closed
*/
public boolean shown;
/**
* Touch information of the window
*/
public WindowTouchInfo touchInfo;
/**
* Original tag of the wrapped view
*/
public Object tag;
public WrappedTag(int id, boolean shown, Object tag) {
super();
this.id = id;
this.shown = shown;
this.touchInfo = new WindowTouchInfo();
this.tag = tag;
}
}
public class WindowTouchInfo {
public int x, y, width, height;
public int downX, downY;
public int deltaX, deltaY;
}
/**
* LayoutParams specific to floating StandOut windows.
*
* @author Mark Wei <markwei@gmail.com>
*
*/
protected class LayoutParams extends
android.view.WindowManager.LayoutParams {
public LayoutParams() {
super(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
TYPE_SYSTEM_ALERT, FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
width = height = 200;
x = y = 50 + (50 * views.size()) % 300;
gravity = Gravity.TOP | Gravity.LEFT;
}
public LayoutParams(int w, int h) {
this();
width = w;
height = h;
}
public LayoutParams(int w, int h, int xpos, int ypos, int gravityFlag) {
this(w, h);
x = xpos;
y = ypos;
gravity = gravityFlag;
}
public LayoutParams(int xpos, int ypos, int gravityFlag) {
this();
x = xpos;
y = ypos;
gravity = gravityFlag;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.