answer stringlengths 17 10.2M |
|---|
package com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.controlTables;
import com.google.common.collect.Sets;
import com.net2plan.gui.plugins.GUINetworkDesign;
import com.net2plan.gui.plugins.networkDesign.AttributeEditor;
import com.net2plan.gui.plugins.networkDesign.ElementSelection;
import com.net2plan.gui.plugins.networkDesign.interfaces.ITableRowFilter;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.controlTables.specificTables.AdvancedJTable_forwardingRule;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.controlTables.specificTables.AdvancedJTable_layer;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableStateFiles.TableState;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableVisualizationFilters.TBFSelectionBased;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableVisualizationFilters.TBFTagBased;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableVisualizationFilters.TBFToFromCarriedTraffic;
import com.net2plan.gui.utils.AdvancedJTable;
import com.net2plan.gui.utils.ColumnHeaderToolTips;
import com.net2plan.gui.utils.FixedColumnDecorator;
import com.net2plan.interfaces.networkDesign.*;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.internal.ErrorHandling;
import com.net2plan.utils.Constants.RoutingType;
import com.net2plan.utils.Pair;
import com.net2plan.utils.StringUtils;
import javax.annotation.Nonnull;
import javax.swing.*;
import javax.swing.RowSorter.SortKey;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.xml.stream.XMLStreamException;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import static com.net2plan.gui.plugins.networkDesign.ElementSelection.SelectionType;
import static com.net2plan.gui.plugins.networkDesign.ElementSelection.getElementType;
import static com.net2plan.gui.plugins.networkDesign.interfaces.ITableRowFilter.FilterCombinationType;
@SuppressWarnings("unchecked")
public abstract class AdvancedJTable_networkElement extends AdvancedJTable
{
protected final TableModel model;
protected final GUINetworkDesign callback;
protected final NetworkElementType networkElementType;
protected final JTable mainTable;
protected final JTable fixedTable;
private final JPopupMenu fixedTableMenu, mainTableMenu;
private final JMenu showMenu;
private final JMenuItem showAllItem, hideAllItem, resetItem, saveStateItem, loadStateItem;
private final ArrayList<TableColumn> hiddenColumns, shownColumns, removedColumns;
private ArrayList<String> hiddenColumnsNames, hiddenColumnsAux;
private final Map<String, Integer> indexForEachColumn, indexForEachHiddenColumn;
private final Map<Integer, String> mapToSaveState;
private JCheckBoxMenuItem lockColumn, unfixCheckBox, attributesItem, hideColumn;
private ArrayList<JMenuItem> hiddenHeaderItems;
private final JScrollPane scroll;
private final FixedColumnDecorator decorator;
private ArrayList<String> attributesColumnsNames;
private boolean expandAttributes = false;
/**
* Constructor that allows to set the table model.
*
* @param model Table model
* @param networkViewer Network callback
* @param networkElementType Network element type
* @since 0.2.0
*/
public AdvancedJTable_networkElement(TableModel model, final GUINetworkDesign networkViewer, NetworkElementType networkElementType, boolean canExpandAttributes)
{
super(model);
this.model = model;
this.callback = networkViewer;
this.networkElementType = networkElementType;
/* configure the tips */
String[] columnTips = getTableTips();
String[] columnHeader = getTableHeaders();
ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
for (int c = 0; c < columnHeader.length; c++)
{
TableColumn col = getColumnModel().getColumn(c);
tips.setToolTip(col, columnTips[c]);
}
getTableHeader().addMouseMotionListener(tips);
/* add the popup menu listener (this) */
addMouseListener(new PopupMenuAdapter());
this.getTableHeader().setReorderingAllowed(true);
scroll = new JScrollPane(this);
this.decorator = new FixedColumnDecorator(scroll, getNumberOfDecoratorColumns());
mainTable = decorator.getMainTable();
fixedTable = decorator.getFixedTable();
hiddenColumnsNames = new ArrayList<>();
hiddenColumns = new ArrayList<>();
shownColumns = new ArrayList<>();
removedColumns = new ArrayList<>();
indexForEachColumn = new HashMap<>();
indexForEachHiddenColumn = new HashMap<>();
mapToSaveState = new HashMap<>();
for (int j = 0; j < mainTable.getColumnModel().getColumnCount(); j++)
{
shownColumns.add(mainTable.getColumnModel().getColumn(j));
}
fixedTableMenu = new JPopupMenu();
mainTableMenu = new JPopupMenu();
showMenu = new JMenu("Show column");
lockColumn = new JCheckBoxMenuItem("Lock column", false);
unfixCheckBox = new JCheckBoxMenuItem("Unlock column", true);
showAllItem = new JMenuItem("Unhide all columns");
hideColumn = new JCheckBoxMenuItem("Hide column", false);
hideAllItem = new JMenuItem("Hide all columns");
hideAllItem.setToolTipText("All columns will be hidden except for the first one.");
attributesItem = new JCheckBoxMenuItem("Attributes in different columns", false);
resetItem = new JMenuItem("Reset columns positions");
loadStateItem = new JMenuItem("Load tables visualization profile");
saveStateItem = new JMenuItem("Save tables visualization profile");
if (canExpandAttributes)
{
this.getModel().addTableModelListener(new TableModelListener()
{
@Override
public void tableChanged(TableModelEvent e)
{
int changedColumn = e.getColumn();
int selectedRow = mainTable.getSelectedRow();
Object value = null;
if (changedColumn > getAttributesColumnIndex())
{
attributesColumnsNames = getAttributesColumnsHeaders();
for (String title : attributesColumnsNames)
{
if (getModel().getColumnName(changedColumn).equals("Att: " + title))
{
value = getModel().getValueAt(selectedRow, changedColumn);
if (value != null)
callback.getDesign().getNetworkElement((Long) getModel().getValueAt(selectedRow, 0)).setAttribute(title, (String) value);
}
}
callback.updateVisualizationJustTables();
}
}
});
}
if (!(this instanceof AdvancedJTable_layer))
{
mainTable.getTableHeader().addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent ev)
{
if (SwingUtilities.isRightMouseButton(ev))
{
// Building menu
mainTableMenu.removeAll();
mainTableMenu.repaint();
mainTableMenu.add(hideColumn);
mainTableMenu.add(lockColumn);
updateShowMenu();
checkNewIndexes();
TableColumn clickedColumn = mainTable.getColumnModel().getColumn(mainTable.columnAtPoint(ev.getPoint()));
String clickedColumnName = clickedColumn.getHeaderValue().toString();
int clickedColumnIndex = indexForEachColumn.get(clickedColumnName);
lockColumn.setEnabled(true);
hideColumn.setEnabled(true);
if (mainTable.getColumnModel().getColumnCount() <= 1)
{
lockColumn.setEnabled(false);
hideColumn.setEnabled(false);
}
// Individual column options
final int col = tableHeader.columnAtPoint(ev.getPoint());
final String columnName = mainTable.getColumnName(col);
switch (columnName)
{
case "Attributes":
mainTableMenu.add(new JPopupMenu.Separator());
mainTableMenu.add(attributesItem);
break;
default:
if (columnName.startsWith("Att:"))
{
mainTableMenu.add(new JPopupMenu.Separator());
mainTableMenu.add(attributesItem);
}
break;
}
mainTableMenu.show(ev.getComponent(), ev.getX(), ev.getY());
lockColumn.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (lockColumn.isSelected() == true)
{
shownColumns.remove(mainTable.getColumnModel().getColumn(clickedColumnIndex));
fromMainTableToFixedTable(clickedColumnIndex);
updateShowMenu();
checkNewIndexes();
mainTableMenu.setVisible(false);
lockColumn.setSelected(false);
}
}
});
hideColumn.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (hideColumn.isSelected())
{
hideColumn(clickedColumnIndex);
checkNewIndexes();
hideColumn.setSelected(false);
}
}
});
}
}
});
fixedTable.getTableHeader().addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
//Checking if right button is clicked
if (SwingUtilities.isRightMouseButton(e))
{
// Build menu
fixedTableMenu.removeAll();
fixedTableMenu.repaint();
fixedTableMenu.add(unfixCheckBox);
fixedTableMenu.add(new JPopupMenu.Separator());
//fixedTableMenu.add(loadStateItem);
//fixedTableMenu.add(saveStateItem);
//fixedTableMenu.add(new JPopupMenu.Separator());
fixedTableMenu.add(resetItem);
fixedTableMenu.add(new JPopupMenu.Separator());
fixedTableMenu.add(showMenu);
fixedTableMenu.add(new JPopupMenu.Separator());
fixedTableMenu.add(showAllItem);
fixedTableMenu.add(hideAllItem);
checkNewIndexes();
updateShowMenu();
TableColumn clickedColumn = fixedTable.getColumnModel().getColumn(fixedTable.columnAtPoint(e.getPoint()));
int clickedColumnIndex = fixedTable.getColumnModel().getColumnIndex(clickedColumn.getIdentifier());
showMenu.setEnabled(true);
unfixCheckBox.setEnabled(true);
if (hiddenColumns.size() == 0)
{
showMenu.setEnabled(false);
}
if (fixedTable.getColumnModel().getColumnCount() <= 1)
{
unfixCheckBox.setEnabled(false);
}
fixedTableMenu.show(e.getComponent(), e.getX(), e.getY());
unfixCheckBox.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (unfixCheckBox.isSelected() == false)
{
shownColumns.add(fixedTable.getColumnModel().getColumn(clickedColumnIndex));
fromFixedTableToMainTable(clickedColumnIndex);
updateShowMenu();
checkNewIndexes();
fixedTableMenu.setVisible(false);
unfixCheckBox.setSelected(true);
}
}
});
for (int j = 0; j < hiddenColumns.size(); j++)
{
JMenuItem currentItem = hiddenHeaderItems.get(j);
String currentColumnName = hiddenColumns.get(j).getHeaderValue().toString();
currentItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
showColumn(currentColumnName, indexForEachHiddenColumn.get(currentColumnName), true);
checkNewIndexes();
}
});
}
}
}
});
this.buildAttributeControls();
}
this.setRowSelectionAllowed(true);
this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
private void buildAttributeControls()
{
showAllItem.addActionListener(e ->
{
showAllColumns();
checkNewIndexes();
});
hideAllItem.addActionListener(e ->
{
hideAllColumns();
checkNewIndexes();
});
resetItem.addActionListener(e ->
{
resetColumnsPositions();
checkNewIndexes();
});
loadStateItem.addActionListener(e -> loadTableState());
saveStateItem.addActionListener(e ->
{
try
{
saveTableState();
} catch (XMLStreamException ex)
{
ErrorHandling.showErrorDialog("Error");
ex.printStackTrace();
}
});
attributesItem.addItemListener(e ->
{
if (attributesItem.isSelected())
{
if (!isAttributeCellExpanded())
{
attributesInDifferentColumns();
}
} else
{
if (isAttributeCellExpanded())
{
attributesInOneColumn();
}
}
});
mainTable.getColumnModel().addColumnModelListener(new TableColumnModelListener()
{
@Override
public void columnAdded(TableColumnModelEvent e)
{
}
@Override
public void columnRemoved(TableColumnModelEvent e)
{
}
@Override
public void columnMoved(TableColumnModelEvent e)
{
checkNewIndexes();
}
@Override
public void columnMarginChanged(ChangeEvent e)
{
}
@Override
public void columnSelectionChanged(ListSelectionEvent e)
{
}
});
}
/**
* Re-configures the menu to show hidden columns
*/
private void updateShowMenu()
{
showMenu.removeAll();
hiddenHeaderItems = new ArrayList<>();
for (int i = 0; i < hiddenColumns.size(); i++)
{
hiddenHeaderItems.add(new JMenuItem(hiddenColumns.get(i).getHeaderValue().toString()));
showMenu.add(hiddenHeaderItems.get(i));
}
}
/**
* Show all columns which are hidden
*/
private void showAllColumns()
{
while (hiddenColumnsNames.size() > 0)
{
String s = hiddenColumnsNames.get(hiddenColumnsNames.size() - 1);
showColumn(s, indexForEachHiddenColumn.get(s), true);
}
checkNewIndexes();
hiddenColumns.clear();
hiddenColumnsNames.clear();
shownColumns.clear();
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
shownColumns.add(mainTable.getColumnModel().getColumn(i));
}
}
/**
* Hide all columns unless the first one of mainTable which are shown
*/
private void hideAllColumns()
{
TableColumn columnToHide = null;
String hiddenColumnHeader = null;
while (mainTable.getColumnModel().getColumnCount() > 1)
{
columnToHide = mainTable.getColumnModel().getColumn(1);
hiddenColumnHeader = columnToHide.getHeaderValue().toString();
hiddenColumns.add(columnToHide);
hiddenColumnsNames.add(columnToHide.getHeaderValue().toString());
indexForEachHiddenColumn.put(hiddenColumnHeader, 1);
mainTable.getColumnModel().removeColumn(columnToHide);
shownColumns.remove(columnToHide);
}
checkNewIndexes();
}
/**
* Show one column which is hidden
*
* @param columnName Name of the column which we want to show
* @param columnIndex Index which the column had when it was shown
* @param move true if column will be moved, false if column will be shown at the end
* @return The column to be shown
*/
private void showColumn(String columnName, int columnIndex, boolean move)
{
String hiddenColumnName;
TableColumn columnToShow = null;
for (TableColumn tc : hiddenColumns)
{
hiddenColumnName = tc.getHeaderValue().toString();
if (columnName.equals(hiddenColumnName))
{
mainTable.getColumnModel().addColumn(tc);
if (move)
mainTable.getColumnModel().moveColumn(mainTable.getColumnCount() - 1, columnIndex);
shownColumns.add(tc);
indexForEachHiddenColumn.remove(columnName, columnIndex);
columnToShow = tc;
break;
}
}
hiddenColumns.remove(columnToShow);
hiddenColumnsNames.clear();
for (TableColumn tc : hiddenColumns)
{
hiddenColumnsNames.add(tc.getHeaderValue().toString());
}
}
/**
* Hide one column which is shown
*
* @param columnIndex Index which the column has in the current Table
* @return The column to be hidden
*/
private void hideColumn(int columnIndex)
{
TableColumn columnToHide = mainTable.getColumnModel().getColumn(columnIndex);
String hiddenColumnHeader = columnToHide.getHeaderValue().toString();
hiddenColumns.add(columnToHide);
hiddenColumnsNames.add(hiddenColumnHeader);
shownColumns.remove(columnToHide);
indexForEachHiddenColumn.put(hiddenColumnHeader, columnIndex);
mainTable.getColumnModel().removeColumn(columnToHide);
}
/**
* Move one column from mainTable to fixedTable
*
* @param columnIndex Index which the column has in mainTable
*/
private void fromMainTableToFixedTable(int columnIndex)
{
TableColumn columnToFix = mainTable.getColumnModel().getColumn(columnIndex);
mainTable.getColumnModel().removeColumn(columnToFix);
fixedTable.getColumnModel().addColumn(columnToFix);
}
/**
* Move one column from fixedTable to mainTable
*
* @param columnIndex Index which the column has in fixedTable
*/
private void fromFixedTableToMainTable(int columnIndex)
{
TableColumn columnToUnfix = fixedTable.getColumnModel().getColumn(columnIndex);
fixedTable.getColumnModel().removeColumn(columnToUnfix);
mainTable.getColumnModel().addColumn(columnToUnfix);
mainTable.getColumnModel().moveColumn(mainTable.getColumnModel().getColumnCount() - 1, 0);
}
/**
* When a new column is added, update the tables
*
* @param
*/
private void updateTables()
{
String fixedTableColumn = null;
String mainTableColumn = null;
ArrayList<Integer> columnIndexesToRemove = new ArrayList<>();
for (int i = 0; i < fixedTable.getColumnModel().getColumnCount(); i++)
{
fixedTableColumn = fixedTable.getColumnModel().getColumn(i).getHeaderValue().toString();
for (int j = 0; j < mainTable.getColumnModel().getColumnCount(); j++)
{
mainTableColumn = mainTable.getColumnModel().getColumn(j).getHeaderValue().toString();
if (mainTableColumn.equals(fixedTableColumn))
{
columnIndexesToRemove.add(j);
}
}
}
int counter = 0;
for (int i = 0; i < columnIndexesToRemove.size(); i++)
{
if (i > 0)
{
for (int j = 0; j < i; j++)
{
if (columnIndexesToRemove.get(j) < columnIndexesToRemove.get(i))
{
counter++;
}
}
}
mainTable.getColumnModel().removeColumn(mainTable.getColumnModel().getColumn(columnIndexesToRemove.get(i) - counter));
counter = 0;
}
if (removedColumns.size() > 0)
{
TableColumn columnRemoved = null;
String mainTableColumnToCheck = null;
for (int j = 0; j < removedColumns.size(); j++)
{
columnRemoved = removedColumns.get(j);
for (int k = 0; k < mainTable.getColumnModel().getColumnCount(); k++)
{
mainTableColumnToCheck = mainTable.getColumnModel().getColumn(k).getHeaderValue().toString();
if (mainTableColumnToCheck.equals(columnRemoved.getHeaderValue().toString()))
{
mainTable.getColumnModel().removeColumn(mainTable.getColumnModel().getColumn(k));
}
}
}
}
if (hiddenColumns.size() > 0)
{
String hiddenColumnName = null;
String mainTableColumnName = null;
for (TableColumn tc : hiddenColumns)
{
hiddenColumnName = tc.getHeaderValue().toString();
for (int k = 0; k < mainTable.getColumnModel().getColumnCount(); k++)
{
mainTableColumnName = mainTable.getColumnModel().getColumn(k).getHeaderValue().toString();
if (hiddenColumnName.equals(mainTableColumnName))
{
mainTable.getColumnModel().removeColumn(mainTable.getColumnModel().getColumn(k));
}
}
}
}
}
/**
* Saves the current positions of the columns
*
* @param
*/
private void saveColumnsPositions()
{
mapToSaveState.clear();
String currentColumnName = "";
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
currentColumnName = mainTable.getColumnModel().getColumn(i).getHeaderValue().toString();
mapToSaveState.put(i, currentColumnName);
}
}
/**
* Restore for each column its previous position
*
* @param
*/
private void restoreColumnsPositions()
{
TableColumn columnToHide = null;
String hiddenColumnHeader = null;
while (mainTable.getColumnModel().getColumnCount() > 0)
{
columnToHide = mainTable.getColumnModel().getColumn(0);
hiddenColumnHeader = columnToHide.getHeaderValue().toString();
hiddenColumns.add(columnToHide);
hiddenColumnsNames.add(columnToHide.getHeaderValue().toString());
indexForEachHiddenColumn.put(hiddenColumnHeader, 0);
mainTable.getColumnModel().removeColumn(columnToHide);
shownColumns.remove(columnToHide);
}
checkNewIndexes();
String currentColumnName = "";
for (int j = 0; j < mapToSaveState.size(); j++)
{
currentColumnName = mapToSaveState.get(j);
showColumn(currentColumnName, j, false);
}
}
/**
* Loads a table state from a external file
*
* @param
*/
private void loadTableState()
{
// Map<NetworkElementType, AdvancedJTable_networkElement> currentTables = callback.getTables();
// HashMap<NetworkElementType, TableState> tStateMap = null;
// try
// tStateMap = TableStateController.loadTableState(currentTables);
// } catch (XMLStreamException e)
// e.printStackTrace();
// for (Map.Entry<NetworkElementType, AdvancedJTable_networkElement> entry : currentTables.entrySet())
// entry.getValue().updateTableFromTableState(tStateMap.get(entry.getValue().getNetworkElementType()));
// JOptionPane.showMessageDialog(null, "Tables visualization profile successfully loaded!");
}
/**
* Saves the current table state on a external file
*/
private void saveTableState() throws XMLStreamException
{
// Map<NetworkElementType, AdvancedJTable_networkElement> currentTables = callback.getTables();
// TableStateController.saveTableState(currentTables);
}
/**
* Update columns positions from a table state
*
* @param state TableState where the table configuration is saved
*/
private void updateTableFromTableState(TableState state)
{
resetColumnsPositions();
TableColumn fixedTableCol = null;
while (fixedTable.getColumnModel().getColumnCount() > 0)
{
fixedTableCol = fixedTable.getColumnModel().getColumn(0);
fixedTable.getColumnModel().removeColumn(fixedTableCol);
}
createDefaultColumnsFromModel();
ArrayList<String> fixedTableColumns = state.getFixedTableColumns();
ArrayList<String> mainTableColumns = state.getMainTableColumns();
HashMap<String, Integer> hiddenColumnsMap = state.getHiddenTableColumns();
boolean areAttributesExpanded = state.getExpandAttributes();
String[] currentHeaders = getCurrentTableHeaders();
ArrayList<String> currentHeadersList = new ArrayList<>();
for (int i = 0; i < currentHeaders.length; i++)
{
currentHeadersList.add(currentHeaders[i]);
}
if (areAttributesExpanded && getAttributesColumnsHeaders().size() > 0)
{
attributesInDifferentColumns();
attributesItem.setSelected(true);
}
for (String col : fixedTableColumns)
{
if (!currentHeadersList.contains(col))
continue;
TableColumn mainTableCol = null;
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
mainTableCol = mainTable.getColumnModel().getColumn(i);
if (col.equals(mainTableCol.getHeaderValue().toString()))
{
mainTable.getColumnModel().removeColumn(mainTableCol);
fixedTable.getColumnModel().addColumn(mainTableCol);
break;
}
}
}
while (mainTable.getColumnModel().getColumnCount() > 0)
{
hideColumn(0);
}
for (String col : mainTableColumns)
{
if (!currentHeadersList.contains(col))
continue;
showColumn(col, 0, false);
}
indexForEachHiddenColumn.clear();
for (Map.Entry<String, Integer> entry : hiddenColumnsMap.entrySet())
{
if (!currentHeadersList.contains(entry.getKey()))
continue;
indexForEachHiddenColumn.put(entry.getKey(), entry.getValue());
}
}
/**
* Reset the column positions
*
* @param
*/
private void resetColumnsPositions()
{
hiddenColumns.clear();
removedColumns.clear();
hiddenColumnsNames.clear();
indexForEachHiddenColumn.clear();
TableColumn tc = null;
while (fixedTable.getColumnModel().getColumnCount() > 0)
{
tc = fixedTable.getColumnModel().getColumn(0);
fixedTable.getColumnModel().removeColumn(tc);
}
mainTable.createDefaultColumnsFromModel();
for (int i = 0; i < getNumberOfDecoratorColumns(); i++)
{
tc = mainTable.getColumnModel().getColumn(0);
mainTable.getColumnModel().removeColumn(tc);
fixedTable.getColumnModel().addColumn(tc);
}
for (String s : getAttributesColumnsHeaders())
{
removeNewColumn("Att: " + s);
}
expandAttributes = false;
attributesItem.setSelected(false);
updateTables();
checkNewIndexes();
}
/**
* When a column is moved into mainTable,
* we have to know which are the new indexes and update indexForEachColumn
*
* @param
*/
private void checkNewIndexes()
{
indexForEachColumn.clear();
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
indexForEachColumn.put(mainTable.getColumnModel().getColumn(i).getHeaderValue().toString(), i);
}
}
/**
* Remove a column from mainTable
*
* @param columnToRemoveName name of the column which is going to be removed
*/
private void removeNewColumn(String columnToRemoveName)
{
TableColumn columnToRemove = null;
for (int j = 0; j < getColumnModel().getColumnCount(); j++)
{
if (columnToRemoveName.equals(getColumnModel().getColumn(j).getHeaderValue().toString()))
{
columnToRemove = getColumnModel().getColumn(j);
mainTable.getColumnModel().removeColumn(getColumnModel().getColumn(j));
break;
}
}
removedColumns.add(columnToRemove);
TableColumn columnToRemoveFromShownColumns = null;
for (TableColumn tc : shownColumns)
{
if (columnToRemoveName.equals(tc.getHeaderValue().toString()))
{
columnToRemoveFromShownColumns = tc;
}
}
shownColumns.remove(columnToRemoveFromShownColumns);
}
/**
* Recover a removed column and adds it in mainTable
*
* @param columnToRecoverName column of the column which is going to be recovered
*/
private void recoverRemovedColumn(String columnToRecoverName)
{
TableColumn columnToRecover = null;
for (TableColumn tc : removedColumns)
{
if (tc.getHeaderValue().toString().equals(columnToRecoverName))
{
columnToRecover = tc;
}
}
removedColumns.remove(columnToRecover);
shownColumns.add(columnToRecover);
mainTable.getColumnModel().addColumn(columnToRecover);
}
/**
* Gets the index of a column
*
* @param columnName name of the column whose index we want to know
*/
private int getColumnIndexByName(String columnName)
{
return indexForEachColumn.get(columnName);
}
/**
* Expands attributes in different columns, one for each attribute
*/
private void attributesInDifferentColumns()
{
saveColumnsPositions();
attributesColumnsNames = getAttributesColumnsHeaders();
boolean attributesColumnInMainTable = false;
String currentColumnName = null;
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
currentColumnName = mainTable.getColumnModel().getColumn(i).getHeaderValue().toString();
if (currentColumnName.equals("Attributes"))
{
attributesColumnInMainTable = true;
break;
}
}
if (!attributesColumnInMainTable)
{
JOptionPane.showMessageDialog(null, "Attributes column must " +
"be unlocked and visible to expand attributes into different columns");
attributesItem.setSelected(false);
} else
{
if (attributesColumnsNames.size() > 0)
{
callback.updateVisualizationJustTables();
createDefaultColumnsFromModel();
removedColumns.clear();
removeNewColumn("Attributes");
updateTables();
expandAttributes = true;
restoreColumnsPositions();
for (String att : getAttributesColumnsHeaders())
{
showColumn("Att: " + att, 0, false);
}
checkNewIndexes();
} else
{
attributesItem.setSelected(false);
}
}
}
/**
* Contracts attributes in different columns, one for each attribute
*/
private void attributesInOneColumn()
{
saveColumnsPositions();
attributesColumnsNames = getAttributesColumnsHeaders();
int attributesCounter = 0;
String columnToCheck = null;
for (String att : attributesColumnsNames)
{
for (int j = 0; j < mainTable.getColumnModel().getColumnCount(); j++)
{
columnToCheck = mainTable.getColumnModel().getColumn(j).getHeaderValue().toString();
if (columnToCheck.equals("Att: " + att))
{
attributesCounter++;
break;
}
}
}
if (!(attributesCounter == attributesColumnsNames.size()))
{
JOptionPane.showMessageDialog(null, "All attributes columns must be unlocked and visible to contract them in one column");
attributesItem.setSelected(true);
} else
{
if (attributesColumnsNames.size() > 0)
{
callback.updateVisualizationJustTables();
createDefaultColumnsFromModel();
removedColumns.clear();
for (String att : attributesColumnsNames)
{
removeNewColumn("Att: " + att);
}
updateTables();
expandAttributes = false;
restoreColumnsPositions();
showColumn("Attributes", 0, false);
checkNewIndexes();
} else
{
attributesItem.setSelected(true);
}
}
}
public ArrayList<String> getMainTableColumns()
{
ArrayList<String> mainTableColumns = new ArrayList<>();
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++)
{
mainTableColumns.add(mainTable.getColumnModel().getColumn(i).getHeaderValue().toString());
}
return mainTableColumns;
}
public ArrayList<String> getFixedTableColumns()
{
ArrayList<String> fixedTableColumns = new ArrayList<>();
for (int i = 0; i < fixedTable.getColumnModel().getColumnCount(); i++)
{
fixedTableColumns.add(fixedTable.getColumnModel().getColumn(i).getHeaderValue().toString());
}
return fixedTableColumns;
}
public HashMap<String, Integer> getHiddenColumns()
{
HashMap<String, Integer> hiddenTableColumns = new HashMap<>();
for (TableColumn hiddenColumn : hiddenColumns)
{
String col = hiddenColumn.getHeaderValue().toString();
hiddenTableColumns.put(col, indexForEachHiddenColumn.get(col));
}
return hiddenTableColumns;
}
public boolean isAttributeCellExpanded()
{
return expandAttributes;
}
public JScrollPane getScroll()
{
return scroll;
}
public NetworkElementType getNetworkElementType()
{
return networkElementType;
}
public FixedColumnDecorator getDecorator()
{
return decorator;
}
public JTable getMainTable()
{
return mainTable;
}
public JTable getFixedTable()
{
return fixedTable;
}
public void updateView(NetPlan currentState)
{
saveColumnsPositions();
setEnabled(false);
String[] header = getCurrentTableHeaders();
((DefaultTableModel) getModel()).setDataVector(new Object[1][header.length], header);
if (currentState.getRoutingType() == RoutingType.SOURCE_ROUTING && networkElementType.equals(NetworkElementType.FORWARDING_RULE))
return;
if (currentState.getRoutingType() == RoutingType.HOP_BY_HOP_ROUTING && (networkElementType.equals(NetworkElementType.ROUTE)))
return;
if (hasElements())
{
String[] tableHeaders = getCurrentTableHeaders();
ArrayList<String> attColumnsHeaders = getAttributesColumnsHeaders();
List<Object[]> allData = getAllData(currentState, attColumnsHeaders);
setEnabled(true);
((DefaultTableModel) getModel()).setDataVector(allData.toArray(new Object[allData.size()][tableHeaders.length]), tableHeaders);
if (attColumnsHeaders != null && networkElementType != NetworkElementType.FORWARDING_RULE)
{
createDefaultColumnsFromModel();
final String[] columnTips = getTableTips();
final String[] columnHeader = getTableHeaders();
final ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
for (int c = 0; c < columnHeader.length; c++)
tips.setToolTip(getColumnModel().getColumn(c), columnTips[c]);
getTableHeader().addMouseMotionListener(tips);
if (isAttributeCellExpanded())
{
removeNewColumn("Attributes");
} else
{
if (attColumnsHeaders.size() > 0)
{
for (String att : attColumnsHeaders)
{
removeNewColumn("Att: " + att);
}
}
}
updateTables();
restoreColumnsPositions();
hiddenColumnsAux = new ArrayList<>();
if (isAttributeCellExpanded())
{
for (TableColumn col : hiddenColumns)
{
hiddenColumnsAux.add(col.getHeaderValue().toString());
}
for (String hCol : hiddenColumnsAux)
{
for (String att : getAttributesColumnsHeaders())
{
if (hCol.equals("Att: " + att))
{
showColumn("Att: " + att, 0, false);
break;
}
}
}
}
}
setColumnRowSortingFixedAndNonFixedTable();
// for (int columnId : getColumnsOfSpecialComparatorForSorting())
// ((DefaultRowSorter) getRowSorter()).setComparator(columnId, new ColumnComparator());
}
// here update the number of entries label
}
public class PopupMenuAdapter extends MouseAdapter
{
@Override
public void mouseClicked(final MouseEvent e)
{
try
{
final Pair<List<NetworkElement>, List<Pair<Demand, Link>>> selection = getSelectedElements();
final boolean nothingSelected = selection.getFirst().isEmpty() && selection.getSecond().isEmpty();
// Checking for selection type
final ElementSelection elementHolder;
if (!nothingSelected)
{
if (!selection.getFirst().isEmpty())
elementHolder = new ElementSelection(getElementType(selection.getFirst()), selection.getFirst());
else if (!selection.getSecond().isEmpty())
elementHolder = new ElementSelection(selection.getSecond());
else elementHolder = new ElementSelection();
} else
{
elementHolder = new ElementSelection();
}
if (SwingUtilities.isRightMouseButton(e))
{
doPopup(e, elementHolder);
return;
}
if (SwingUtilities.isLeftMouseButton(e))
{
if (nothingSelected)
callback.resetPickedStateAndUpdateView();
else
SwingUtilities.invokeLater(() -> showInCanvas(e, elementHolder));
}
} catch (Exception ex)
{
ErrorHandling.showErrorDialog("The GUI has suffered a problem. Please see the console for more information.", "Error");
ex.printStackTrace();
}
}
private JTable getTable(MouseEvent e)
{
Object src = e.getSource();
if (src instanceof JTable)
{
JTable table = (JTable) src;
if (table.getModel() != model) throw new RuntimeException("Table model is not valid");
return table;
}
throw new RuntimeException("Bad - Event source is not a JTable");
}
}
final protected void addPopupMenuAttributeOptions(final MouseEvent e, ElementSelection selection, JPopupMenu popup)
{
assert popup != null;
assert selection != null;
assert networkElementType != NetworkElementType.FORWARDING_RULE;
assert selection.getElementType() != NetworkElementType.FORWARDING_RULE;
if (networkElementType == NetworkElementType.FORWARDING_RULE) return;
final List<? extends NetworkElement> selectedElements = selection.getNetworkElements();
if (!selectedElements.isEmpty())
{
popup.addSeparator();
// Tags controls
JMenuItem addTag = new JMenuItem("Add tag" + (networkElementType == NetworkElementType.LAYER ? "" : " to selected elements"));
addTag.addActionListener(e1 ->
{
JTextField txt_name = new JTextField(20);
JPanel pane = new JPanel();
pane.add(new JLabel("Tag: "));
pane.add(txt_name);
while (true)
{
int result = JOptionPane.showConfirmDialog(null, pane, "Please enter tag name", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
String tag;
try
{
if (txt_name.getText().isEmpty()) continue;
tag = txt_name.getText();
for (NetworkElement selectedElement : selectedElements)
selectedElement.addTag(tag);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Error adding/editing tag");
}
break;
}
});
popup.add(addTag);
JMenuItem removeTag = new JMenuItem("Remove tag" + (networkElementType == NetworkElementType.LAYER ? "" : " from selected elements"));
removeTag.addActionListener(e1 ->
{
try
{
final Set<String> tags = new HashSet<>();
for (NetworkElement selectedElement : selectedElements)
{
final Set<String> elementTags = selectedElement.getTags();
tags.addAll(elementTags);
}
String[] tagList = StringUtils.toArray(tags);
if (tagList.length == 0) throw new Exception("No tag to remove");
Object out = JOptionPane.showInputDialog(null, "Please, select a tag to remove", "Remove tag", JOptionPane.QUESTION_MESSAGE, null, tagList, tagList[0]);
if (out == null) return;
String tagToRemove = out.toString();
for (NetworkElement selectedElement : selectedElements)
selectedElement.removeTag(tagToRemove);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error removing tag");
}
});
popup.add(removeTag);
JMenuItem addAttribute = new JMenuItem("Add/Update attribute" + (networkElementType == NetworkElementType.LAYER ? "" : " to selected elements"));
popup.add(new JPopupMenu.Separator());
addAttribute.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JTextField txt_key = new JTextField(20);
JTextField txt_value = new JTextField(20);
JPanel pane = new JPanel();
pane.add(new JLabel("Attribute: "));
pane.add(txt_key);
pane.add(Box.createHorizontalStrut(15));
pane.add(new JLabel("Value: "));
pane.add(txt_value);
while (true)
{
int result = JOptionPane.showConfirmDialog(null, pane, "Please enter an attribute name and its value", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
String attribute, value;
try
{
if (txt_key.getText().isEmpty())
{
ErrorHandling.showWarningDialog("Please, insert an attribute name.", "Message");
continue;
}
attribute = txt_key.getText();
value = txt_value.getText();
for (NetworkElement selectedElement : selectedElements)
selectedElement.setAttribute(attribute, value);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Error adding/editing attribute");
}
break;
}
}
});
popup.add(addAttribute);
JMenuItem removeAttribute = new JMenuItem("Remove attribute" + (networkElementType == NetworkElementType.LAYER ? "" : " from selected elements"));
removeAttribute.addActionListener(e1 ->
{
try
{
final Set<String> attributes = new HashSet<>();
for (NetworkElement selectedElement : selectedElements)
{
attributes.addAll(selectedElement.getAttributes().keySet());
}
String[] attributeList = StringUtils.toArray(attributes);
if (attributeList.length == 0) throw new Exception("No attribute to remove");
Object out = JOptionPane.showInputDialog(null, "Please, select an attribute to remove", "Remove attribute", JOptionPane.QUESTION_MESSAGE, null, attributeList, attributeList[0]);
if (out == null) return;
String attributeToRemove = out.toString();
for (NetworkElement selectedElement : selectedElements)
selectedElement.removeAttribute(attributeToRemove);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error removing attribute");
}
});
popup.add(removeAttribute);
JMenuItem removeAttributes = new JMenuItem("Remove all attributes" + (networkElementType == NetworkElementType.LAYER ? "" : " from selected elements"));
removeAttributes.addActionListener(e1 ->
{
try
{
for (NetworkElement selectedElement : selectedElements)
selectedElement.removeAllAttributes();
if (isAttributeCellExpanded())
{
recoverRemovedColumn("Attributes");
expandAttributes = false;
attributesItem.setSelected(false);
}
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error removing attributes");
}
});
popup.add(removeAttributes);
popup.addSeparator();
JMenuItem editAttributes = new JMenuItem("Edit attributes" + (networkElementType == NetworkElementType.LAYER ? "" : " from selected elements"));
editAttributes.addActionListener(e1 ->
{
try
{
JDialog dialog = new AttributeEditor(callback, selection);
dialog.setVisible(true);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ex.printStackTrace();
ErrorHandling.showErrorDialog(ex.getMessage(), "Error modifying attributes");
}
});
popup.add(editAttributes);
}
}
public static class ColumnComparator implements Comparator<Object>
{
private final boolean isDoubleWithParenthesis;
private final RowSorter rs;
public ColumnComparator(RowSorter rs, boolean isDoubleWithParenthesis)
{
this.rs = rs;
this.isDoubleWithParenthesis = isDoubleWithParenthesis;
}
@Override
public int compare(Object o1, Object o2)
{
if (o1 instanceof LastRowAggregatedValue)
{
final boolean ascending = ((List<? extends SortKey>) rs.getSortKeys()).get(0).getSortOrder() == SortOrder.ASCENDING;
return ascending ? 1 : -1;
}
if (o2 instanceof LastRowAggregatedValue)
{
final boolean ascending = ((List<? extends SortKey>) rs.getSortKeys()).get(0).getSortOrder() == SortOrder.ASCENDING;
return ascending ? -1 : 1;
}
if (o1 instanceof Boolean)
{
final Boolean oo1 = (Boolean) o1;
final Boolean oo2 = (Boolean) o2;
return oo1.compareTo(oo2);
}
if (o1 instanceof Number)
{
final Number oo1 = (Number) o1;
final Number oo2 = (Number) o2;
return new Double(oo1.doubleValue()).compareTo(new Double(oo2.doubleValue()));
}
String oo1 = (String) o1;
String oo2 = (String) o2;
if (!isDoubleWithParenthesis)
return oo1.compareTo(oo2);
int pos1 = oo1.indexOf(" (");
if (pos1 != -1) oo1 = oo1.substring(0, pos1);
int pos2 = oo2.indexOf(" (");
if (pos2 != -1) oo2 = oo2.substring(0, pos2);
try
{
Double d1, d2;
d1 = Double.parseDouble(oo1);
d2 = Double.parseDouble(oo2);
return d1.compareTo(d2);
} catch (Throwable e)
{
return oo1.compareTo(oo2);
}
}
}
public static class LastRowAggregatedValue
{
private String value;
public LastRowAggregatedValue()
{
value = "
}
public LastRowAggregatedValue(int val)
{
value = "" + val;
}
public LastRowAggregatedValue(double val)
{
value = String.format("%.2f", val);
}
public LastRowAggregatedValue(String value)
{
this.value = value;
}
String getValue()
{
return value;
}
public String toString()
{
return value;
}
}
/**
* Gets the selected elements in this table.
*
* @return
*/
public Pair<List<NetworkElement>, List<Pair<Demand, Link>>> getSelectedElements()
{
final int[] rowIndexes = this.getSelectedRows();
final NetPlan np = callback.getDesign();
final List<NetworkElement> elementList = new ArrayList<>();
final List<Pair<Demand, Link>> frList = new ArrayList<>();
if (rowIndexes.length == 0) return Pair.of(elementList, frList);
final int maxValidRowIndex = model.getRowCount() - 1 - (hasAggregationRow() ? 1 : 0);
final List<Integer> validRows = new ArrayList<Integer>();
for (int a : rowIndexes) if ((a >= 0) && (a <= maxValidRowIndex)) validRows.add(a);
if (networkElementType == NetworkElementType.FORWARDING_RULE)
{
for (int rowIndex : validRows)
{
final String demandInfo = (String) ((DefaultTableModel) getModel()).getValueAt(rowIndex, AdvancedJTable_forwardingRule.COLUMN_DEMAND);
final String linkInfo = (String) ((DefaultTableModel) getModel()).getValueAt(rowIndex, AdvancedJTable_forwardingRule.COLUMN_OUTGOINGLINK);
final int demandIndex = Integer.parseInt(demandInfo.substring(0, demandInfo.indexOf("(")).trim());
final int linkIndex = Integer.parseInt(linkInfo.substring(0, linkInfo.indexOf("(")).trim());
frList.add(Pair.of(np.getDemand(demandIndex), np.getLink(linkIndex)));
}
} else
{
for (int rowIndex : validRows)
{
final long id = (long) ((DefaultTableModel) getModel()).getValueAt(rowIndex, 0);
elementList.add(np.getNetworkElement(id));
}
}
return Pair.of(elementList, frList);
}
public boolean hasAggregationRow()
{
return !networkElementType.equals(NetworkElementType.LAYER) && !networkElementType.equals(NetworkElementType.NETWORK);
}
/* Dialog for filtering by tag */
protected void dialogToFilterByTag(boolean onlyInActiveLayer, FilterCombinationType filterCombinationType)
{
JTextField txt_tagContains = new JTextField(30);
JTextField txt_tagDoesNotContain = new JTextField(30);
JPanel pane = new JPanel(new GridLayout(-1, 1));
pane.add(new JLabel("Has tag (could be empty): "));
pane.add(txt_tagContains);
pane.add(new JLabel("AND does not have tag (could be empty): "));
pane.add(txt_tagDoesNotContain);
while (true)
{
int result = JOptionPane.showConfirmDialog(null, pane, "Filter elements by tag", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
try
{
if (txt_tagContains.getText().isEmpty() && txt_tagDoesNotContain.getText().isEmpty())
{
ErrorHandling.showErrorDialog("At least one input tag is required", "Invalid input");
continue;
}
final ITableRowFilter filter = new TBFTagBased(
callback.getDesign(), onlyInActiveLayer ? callback.getDesign().getNetworkLayerDefault() : null,
txt_tagContains.getText(), txt_tagDoesNotContain.getText());
callback.getVisualizationState().updateTableRowFilter(filter, filterCombinationType);
callback.updateVisualizationJustTables();
} catch (Throwable ex)
{
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Error adding filter");
}
break;
}
}
protected void addFilterOptions(MouseEvent e, ElementSelection selection, JPopupMenu popup)
{
final NetPlan netPlan = callback.getDesign();
final boolean isMultilayerDesign = netPlan.isMultilayer();
for (boolean applyJustToThisLayer : isMultilayerDesign ? new boolean[]{true, false} : new boolean[]{true})
{
final JMenu submenuFilters;
if (applyJustToThisLayer)
submenuFilters = new JMenu("Filters: Apply to this layer");
else
submenuFilters = new JMenu("Filters: Apply to all layers");
for (FilterCombinationType filterCombinationType : FilterCombinationType.values())
{
final JMenu filterCombinationSubMenu;
switch (filterCombinationType)
{
case INCLUDEIF_AND:
filterCombinationSubMenu = new JMenu("Add elements that...");
break;
case INCLUDEIF_OR:
filterCombinationSubMenu = new JMenu("Keep elements that...");
break;
default:
throw new RuntimeException();
}
final JMenuItem trafficBasedFilterMenu = new JMenuItem("Are affected by these " + networkElementType + "s");
filterCombinationSubMenu.add(trafficBasedFilterMenu);
trafficBasedFilterMenu.addActionListener(e1 ->
{
if (selection.getSelectionType() == SelectionType.EMPTY) return;
TBFToFromCarriedTraffic filter = null;
if (selection.getSelectionType() == SelectionType.NETWORK_ELEMENT)
{
final List<? extends NetworkElement> selectedElements = selection.getNetworkElements();
final NetworkLayer layer = callback.getDesign().getNetworkLayerDefault();
for (NetworkElement element : selectedElements)
{
switch (NetworkElementType.getType(element))
{
case NODE:
if (filter == null)
filter = new TBFToFromCarriedTraffic((Node) element, layer, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((Node) element, layer, applyJustToThisLayer));
break;
case LINK:
if (filter == null)
filter = new TBFToFromCarriedTraffic((Link) element, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((Link) element, applyJustToThisLayer));
break;
case DEMAND:
if (filter == null)
filter = new TBFToFromCarriedTraffic((Demand) element, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((Demand) element, applyJustToThisLayer));
break;
case MULTICAST_DEMAND:
if (filter == null)
filter = new TBFToFromCarriedTraffic((MulticastDemand) element, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((MulticastDemand) element, applyJustToThisLayer));
break;
case ROUTE:
if (filter == null)
filter = new TBFToFromCarriedTraffic((Route) element, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((Route) element, applyJustToThisLayer));
break;
case MULTICAST_TREE:
if (filter == null)
filter = new TBFToFromCarriedTraffic((MulticastTree) element, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((MulticastTree) element, applyJustToThisLayer));
break;
case RESOURCE:
if (filter == null)
filter = new TBFToFromCarriedTraffic((Resource) element, layer, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((Resource) element, layer, applyJustToThisLayer));
break;
case SRG:
if (filter == null)
filter = new TBFToFromCarriedTraffic((SharedRiskGroup) element);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic((SharedRiskGroup) element));
break;
default:
// TODO: Control exceptions on filters.
throw new RuntimeException();
}
}
} else
{
final List<Pair<Demand, Link>> forwardingRules = selection.getForwardingRules();
for (Pair<Demand, Link> forwardingRule : forwardingRules)
{
if (filter == null)
filter = new TBFToFromCarriedTraffic(forwardingRule, applyJustToThisLayer);
else
filter.recomputeApplyingShowIf_ThisOrThat(new TBFToFromCarriedTraffic(forwardingRule, applyJustToThisLayer));
}
}
callback.getVisualizationState().updateTableRowFilter(filter, filterCombinationType);
callback.updateVisualizationJustTables();
});
final JMenuItem tagFilterMenu = new JMenuItem("Have tag...");
filterCombinationSubMenu.add(tagFilterMenu);
tagFilterMenu.addActionListener(e1 -> dialogToFilterByTag(applyJustToThisLayer, filterCombinationType));
submenuFilters.add(filterCombinationSubMenu);
}
if (applyJustToThisLayer)
{
final JMenuItem submenuFilters_filterIn = new JMenuItem("Keep only selected elements in this table");
submenuFilters_filterIn.addActionListener(e1 ->
{
TBFSelectionBased filter = new TBFSelectionBased(callback.getDesign(), selection);
callback.getVisualizationState().updateTableRowFilter(filter, FilterCombinationType.INCLUDEIF_AND);
callback.updateVisualizationJustTables();
});
final JMenuItem submenuFilters_filterOut = new JMenuItem("Filter-out selected elements in this table");
submenuFilters_filterOut.addActionListener(e1 ->
{
final ElementSelection invertedSelection = selection.invertSelection();
if (invertedSelection == null)
throw new Net2PlanException("Could not invert selection for the given elements.");
TBFSelectionBased filter = new TBFSelectionBased(callback.getDesign(), invertedSelection);
callback.getVisualizationState().updateTableRowFilter(filter, FilterCombinationType.INCLUDEIF_AND);
callback.updateVisualizationJustTables();
});
submenuFilters.add(submenuFilters_filterIn);
submenuFilters.add(submenuFilters_filterOut);
}
popup.add(submenuFilters);
}
if (networkElementType != NetworkElementType.FORWARDING_RULE && networkElementType != NetworkElementType.NETWORK && networkElementType != NetworkElementType.LAYER)
{
popup.addSeparator();
popup.add(new MenuItem_RemovedFiltered(callback, networkElementType));
if (networkElementType == NetworkElementType.NODE || networkElementType == NetworkElementType.LINK)
popup.add(new MenuItem_HideFiltered(callback, networkElementType));
}
}
public abstract List<Object[]> getAllData(NetPlan currentState, ArrayList<String> attributesTitles);
public abstract String getTabName();
public abstract String[] getTableHeaders();
public abstract String[] getCurrentTableHeaders();
public abstract String[] getTableTips();
public abstract boolean hasElements();
public abstract int getAttributesColumnIndex();
public abstract void setColumnRowSortingFixedAndNonFixedTable();
public abstract int getNumberOfDecoratorColumns();
public abstract ArrayList<String> getAttributesColumnsHeaders();
@Nonnull
protected abstract List<JComponent> getExtraAddOptions();
@Nonnull
protected abstract JMenuItem getAddOption();
@Nonnull
protected abstract List<JComponent> getForcedOptions(ElementSelection selection);
@Nonnull
protected abstract List<JComponent> getExtraOptions(ElementSelection selection);
protected abstract void doPopup(final MouseEvent e, ElementSelection selection);
protected abstract void showInCanvas(MouseEvent e, ElementSelection selection);
static class MenuItem_RemovedFiltered extends JMenuItem
{
MenuItem_RemovedFiltered(@Nonnull GUINetworkDesign callback, @Nonnull NetworkElementType networkElementType)
{
final NetPlan netPlan = callback.getDesign();
this.setText("Remove all filtered out " + networkElementType + "s");
this.addActionListener(e1 ->
{
try
{
final ITableRowFilter tableRowFilter = callback.getVisualizationState().getTableRowFilter();
if (tableRowFilter != null)
{
switch (networkElementType)
{
case NODE:
final List<Node> visibleNodes = tableRowFilter.getVisibleNodes(netPlan.getNetworkLayerDefault());
for (Node node : new ArrayList<>(netPlan.getNodes()))
if (!visibleNodes.contains(node)) node.remove();
break;
case LINK:
final List<Link> visibleLinks = tableRowFilter.getVisibleLinks(netPlan.getNetworkLayerDefault());
for (Link link : new ArrayList<>(netPlan.getLinks()))
if (!visibleLinks.contains(link)) link.remove();
break;
case DEMAND:
final List<Demand> visibleDemands = tableRowFilter.getVisibleDemands(netPlan.getNetworkLayerDefault());
for (Demand demand : new ArrayList<>(netPlan.getDemands()))
if (!visibleDemands.contains(demand)) demand.remove();
break;
case MULTICAST_DEMAND:
final List<MulticastDemand> visibleMulticastDemands = tableRowFilter.getVisibleMulticastDemands(netPlan.getNetworkLayerDefault());
for (MulticastDemand multicastDemand : new ArrayList<>(netPlan.getMulticastDemands()))
if (!visibleMulticastDemands.contains(multicastDemand))
multicastDemand.remove();
break;
case ROUTE:
final List<Route> visibleRoutes = tableRowFilter.getVisibleRoutes(netPlan.getNetworkLayerDefault());
for (Route route : new ArrayList<>(netPlan.getRoutes()))
if (!visibleRoutes.contains(route)) route.remove();
break;
case MULTICAST_TREE:
final List<MulticastTree> visibleMulticastTrees = tableRowFilter.getVisibleMulticastTrees(netPlan.getNetworkLayerDefault());
for (MulticastTree tree : new ArrayList<>(netPlan.getMulticastTrees()))
if (!visibleMulticastTrees.contains(tree)) tree.remove();
break;
case RESOURCE:
final List<Resource> visibleResources = tableRowFilter.getVisibleResources(netPlan.getNetworkLayerDefault());
for (Resource resource : new ArrayList<>(netPlan.getResources()))
if (!visibleResources.contains(resource)) resource.remove();
break;
case SRG:
final List<SharedRiskGroup> visibleSRGs = tableRowFilter.getVisibleSRGs(netPlan.getNetworkLayerDefault());
for (SharedRiskGroup sharedRiskGroup : new ArrayList<>(netPlan.getSRGs()))
if (!visibleSRGs.contains(sharedRiskGroup)) sharedRiskGroup.remove();
break;
default:
// TODO: Error message?
return;
}
}
callback.getVisualizationState().recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
callback.updateVisualizationAfterChanges(Sets.newHashSet(networkElementType));
callback.addNetPlanChange();
} catch (Throwable ex)
{
ex.printStackTrace();
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to complete this action");
}
});
}
}
static class MenuItem_HideFiltered extends JMenuItem
{
MenuItem_HideFiltered(@Nonnull GUINetworkDesign callback, @Nonnull NetworkElementType networkElementType)
{
final NetPlan netPlan = callback.getDesign();
this.setText("Hide all filtered out " + networkElementType + "s");
this.addActionListener(e1 ->
{
final ITableRowFilter tableRowFilter = callback.getVisualizationState().getTableRowFilter();
if (tableRowFilter != null)
{
switch (networkElementType)
{
case NODE:
final List<Node> visibleNodes = tableRowFilter.getVisibleNodes(netPlan.getNetworkLayerDefault());
for (Node node : netPlan.getNodes())
if (!visibleNodes.contains(node))
callback.getVisualizationState().hideOnCanvas(node);
break;
case LINK:
final List<Link> visibleLinks = tableRowFilter.getVisibleLinks(netPlan.getNetworkLayerDefault());
for (Link link : netPlan.getLinks())
if (!visibleLinks.contains(link))
callback.getVisualizationState().hideOnCanvas(link);
break;
default:
return;
}
}
callback.updateVisualizationAfterChanges(Sets.newHashSet(networkElementType));
callback.addNetPlanChange();
});
}
}
} |
package info.tregmine.listeners;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.event.*;
import org.bukkit.event.player.PlayerMoveEvent;
public class WorldPortalListener implements Listener{
private Tregmine plugin;
public WorldPortalListener(Tregmine instance)
{
this.plugin = instance;
}
@EventHandler
public void portalHandler(PlayerMoveEvent event)
{
final TregminePlayer player = plugin.getPlayer(event.getPlayer());
Block under = player.getLocation().subtract(0, 1, 0).getBlock();
Block in = event.getTo().getBlock();
// Simply add another line changing frame, under, world and name to add a new portal! (Similar to end portal)
handlePortal(player, Material.OBSIDIAN, Material.OBSIDIAN, plugin.getRulelessWorld(), "anarchy", in, under);
}
public void handlePortal(TregminePlayer player, Material underType, Material frame, World newWorld, String worldName, Block in, Block under)
{
if (under.getType() != underType || !in.isLiquid()) {
return;
}
if ( !(frameCheck(player, -1, 3, -1, 3, frame) ||
frameCheck(player, -1, 3, -2, 2, frame) ||
frameCheck(player, -1, 3, -3, 1, frame) ||
frameCheck(player, -2, 2, -1, 3, frame) ||
frameCheck(player, -2, 2, -2, 2, frame) ||
frameCheck(player, -2, 2, -3, 1, frame) ||
frameCheck(player, -3, 1, -1, 3, frame) ||
frameCheck(player, -3, 1, -2, 2, frame) ||
frameCheck(player, -3, 1, -3, 1, frame))) {
return;
}
if (player.getWorld().getName().equalsIgnoreCase(newWorld.getName())) {
player.teleportWithHorse(plugin.getServer().getWorld("world").getSpawnLocation());
player.sendMessage(ChatColor.GOLD + "[PORTAL] " + ChatColor.GREEN + "Teleporting to main world!");
} else {
player.teleportWithHorse(newWorld.getSpawnLocation());
player.sendMessage(ChatColor.GOLD + "[PORTAL] " + ChatColor.GREEN + "Teleporting to " + worldName + " world!");
}
}
public boolean frameCheck(TregminePlayer p, int x1, int x2, int z1, int z2, Material portal)
{
if( p.getLocation().add(x1, 0, 0).getBlock().getType().equals(portal) &&
p.getLocation().add(0, 0, z1).getBlock().getType().equals(portal) &&
p.getLocation().add(x2, 0, 0).getBlock().getType().equals(portal) &&
p.getLocation().add(0, 0, z2).getBlock().getType().equals(portal)) {
return true;
} else {
return false;
}
}
} |
package jade.core.management;
import jade.core.ServiceFinder;
import jade.core.VerticalCommand;
import jade.core.GenericCommand;
import jade.core.Service;
import jade.core.BaseService;
import jade.core.ServiceException;
import jade.core.Filter;
import jade.core.Node;
import jade.core.Profile;
import jade.core.Agent;
import jade.core.AgentState;
import jade.core.AID;
import jade.core.ContainerID;
import jade.core.AgentContainer;
import jade.core.MainContainer;
import jade.core.ProfileException;
import jade.core.IMTPException;
import jade.core.NameClashException;
import jade.core.NotFoundException;
import jade.core.UnreachableException;
import jade.security.Authority;
import jade.security.CertificateFolder;
import jade.security.AgentPrincipal;
import jade.security.IdentityCertificate;
import jade.security.AuthException;
/**
The JADE service to manage the basic agent life cycle: creation,
destruction, suspension and resumption.
@author Giovanni Rimassa - FRAMeTech s.r.l.
*/
public class AgentManagementService extends BaseService {
/**
The name of this service.
*/
public static final String NAME = "jade.core.management.AgentManagement";
/**
This command name represents the <code>create-agent</code>
action. The target agent identifier in this command is set to
<code>null</code>, because no agent exists yet.
This command object represents only the <i>first half</i> of
the complete agent creation process. Even if this command is
accepted by the kernel, there is no guarantee that the
requested creation will ever happen. Only when the
<code>InformCreated</code> command is issued can one assume
that the agent creation has taken place.
*/
public static final String REQUEST_CREATE = "Request-Create";
/**
This command name represents the <code>start-agent</code>
action. The target agent identifier in this command has already
been created, but its internal thread was not started at
creation time.
*/
public static final String REQUEST_START = "Request-Start";
/**
This command name represents the <code>kill-agent</code>
action.
This command object represents only the <i>first half</i> of
the complete agent destruction process. Even if this command is
accepted by the kernel, there is no guarantee that the
requested destruction will ever happen. Only when the
<code>InformKilled</code> command is issued can one assume that
the agent destruction has taken place.
*/
public static final String REQUEST_KILL = "Request-Kill";
/**
This command name represents all agent management actions requesting
a change in the life cycle state of their target agent
(suspend, resume, etc.).
This command object represents only the <i>first half</i> of
the complete agent state change process. Even if this command
is accepted by the kernel, there is no guarantee that the
requested state change will ever happen. Only when the
<code>InformStateChanged</code> command is issued can one
assume that the state change has taken place.
*/
public static final String REQUEST_STATE_CHANGE = "Request-State-Change";
// private AgentState myNewState;
/**
This command is issued by an agent that has just been created,
and causes JADE runtime to actually start up the agent thread.
The agent creation can be the outcome of a previously issued
<code>RequestCreate</code> command. In that case, this command
represents only the <i>second half</i> of the complete agent
creation process.
*/
public static final String INFORM_CREATED = "Inform-Created";
/**
This command is issued by an agent that has just been destroyed
and whose thread is terminating.
The agent destruction can either be an autonomous move of the
agent or the outcome of a previously issued
<code>RequestKill</code> command. In the second case, this
command represents only the <i>second half</i> of the complete
agent destruction process.
*/
public static final String INFORM_KILLED = "Inform-Killed";
/**
This command is issued by an agent that has just changed its
life-cycle state.
The agent state change can either be an autonomous move of the
agent or the outcome of a previously issued
<code>RequestStateChange</code> command. In that case, this
command represents only the <i>second half</i> of the complete
agent state tansition process.
*/
public static final String INFORM_STATE_CHANGED = "Inform-State-Changed";
/**
This command name represents the <code>kill-container</code>
action.
*/
public static final String KILL_CONTAINER = "Kill-Container";
// public static final String MAIN_SLICE = "Main-Slice";
public static final String MAIN_SLICE = "Main-Container";
public static final boolean CREATE_AND_START = true;
public static final boolean CREATE_ONLY = false;
public AgentManagementService(AgentContainer ac, Profile p) throws ProfileException {
super(p);
myContainer = ac;
// Create a local slice
localSlice = new ServiceComponent();
}
public String getName() {
return NAME;
}
public Class getHorizontalInterface() {
try {
return Class.forName(NAME + "Slice");
}
catch(ClassNotFoundException cnfe) {
return null;
}
}
public Service.Slice getLocalSlice() {
return localSlice;
}
public Filter getCommandFilter() {
return localSlice;
}
/**
Inner mix-in class for this service: this class receives
commands through its <code>Filter</code> interface and serves
them, coordinating with remote parts of this service through
the <code>Slice</code> interface (that extends the
<code>Service.Slice</code> interface).
*/
private class ServiceComponent implements Filter, AgentManagementSlice {
// Implementation of the Filter interface
public void accept(VerticalCommand cmd) {
try {
String name = cmd.getName();
if(name.equals(REQUEST_CREATE)) {
handleRequestCreate(cmd);
}
else if(name.equals(REQUEST_START)) {
handleRequestStart(cmd);
}
else if(name.equals(REQUEST_KILL)) {
handleRequestKill(cmd);
}
else if(name.equals(REQUEST_STATE_CHANGE)) {
handleRequestStateChange(cmd);
}
else if(name.equals(INFORM_KILLED)) {
handleInformKilled(cmd);
}
else if(name.equals(INFORM_STATE_CHANGED)) {
handleInformStateChanged(cmd);
}
else if(name.equals(INFORM_CREATED)) {
handleInformCreated(cmd);
}
else if(name.equals(KILL_CONTAINER)) {
handleKillContainer(cmd);
}
}
catch(IMTPException imtpe) {
cmd.setReturnValue(new UnreachableException("Remote container is unreachable", imtpe));
}
catch(NotFoundException nfe) {
cmd.setReturnValue(nfe);
}
catch(NameClashException nce) {
cmd.setReturnValue(nce);
}
catch(AuthException ae) {
cmd.setReturnValue(ae);
}
catch(ServiceException se) {
cmd.setReturnValue(new UnreachableException("A Service Exception occurred", se));
}
}
public void setBlocking(boolean newState) {
// Do nothing. Blocking and Skipping not supported
}
public boolean isBlocking() {
return false; // Blocking and Skipping not implemented
}
public void setSkipping(boolean newState) {
// Do nothing. Blocking and Skipping not supported
}
public boolean isSkipping() {
return false; // Blocking and Skipping not implemented
}
// Implementation of the Service.Slice interface
public Service getService() {
return AgentManagementService.this;
}
public Node getNode() throws ServiceException {
try {
return AgentManagementService.this.getLocalNode();
}
catch(IMTPException imtpe) {
throw new ServiceException("Problem in contacting the IMTP Manager", imtpe);
}
}
public void serve(VerticalCommand cmd) {
try {
String cmdName = cmd.getName();
Object[] params = cmd.getParams();
if(cmdName.equals(H_CREATEAGENT)) {
AID agentID = (AID)params[0];
String className = (String)params[1];
Object[] arguments = (Object[])params[2];
String ownership = (String)params[3];
CertificateFolder certs = (CertificateFolder)params[4];
boolean startIt = ((Boolean)params[5]).booleanValue();
createAgent(agentID, className, arguments, ownership, certs, startIt);
}
else if(cmdName.equals(H_KILLAGENT)) {
AID agentID = (AID)params[0];
killAgent(agentID);
}
else if(cmdName.equals(H_CHANGEAGENTSTATE)) {
AID agentID = (AID)params[0];
int newState = ((Integer)params[1]).intValue();
changeAgentState(agentID, newState);
}
else if(cmdName.equals(H_BORNAGENT)) {
AID agentID = (AID)params[0];
ContainerID cid = (ContainerID)params[1];
CertificateFolder certs = (CertificateFolder)params[2];
bornAgent(agentID, cid, certs);
}
else if(cmdName.equals(H_DEADAGENT)) {
AID agentID = (AID)params[0];
deadAgent(agentID);
}
else if(cmdName.equals(H_SUSPENDEDAGENT)) {
AID agentID = (AID)params[0];
suspendedAgent(agentID);
}
else if(cmdName.equals(H_RESUMEDAGENT)) {
AID agentID = (AID)params[0];
resumedAgent(agentID);
}
else if(cmdName.equals(H_EXITCONTAINER)) {
exitContainer();
}
}
catch(Throwable t) {
cmd.setReturnValue(t);
}
}
// Implementation of the service-specific horizontal interface AgentManagementSlice
public void createAgent(AID agentID, String className, Object arguments[], String ownership, CertificateFolder certs, boolean startIt) throws IMTPException, NotFoundException, NameClashException, AuthException {
Agent agent = null;
try {
agent = (Agent)Class.forName(new String(className)).newInstance();
agent.setArguments(arguments);
//#MIDP_EXCLUDE_BEGIN
// Set agent principal and certificates
if(certs != null) {
agent.setPrincipal(certs);
}
// Set agent ownership
if(ownership != null)
agent.setOwnership(ownership);
else if(certs.getIdentityCertificate() != null)
agent.setOwnership(((AgentPrincipal)certs.getIdentityCertificate().getSubject()).getOwnership());
//#MIDP_EXCLUDE_END
// Execute the second half of the creation process
initAgent(agentID, agent, startIt);
}
catch(ClassNotFoundException cnfe) {
throw new IMTPException("Class " + className + " for agent " + agentID + " not found in createAgent()", cnfe);
}
catch(InstantiationException ie) {
throw new IMTPException("Instantiation exception in createAgent()", ie);
}
catch(IllegalAccessException iae) {
throw new IMTPException("Illegal access exception in createAgent()", iae);
}
catch(ServiceException se) {
throw new IMTPException("Service exception in createAgent()", se);
}
}
public void killAgent(AID agentID) throws IMTPException, NotFoundException {
Agent a = myContainer.acquireLocalAgent(agentID);
if(a == null)
throw new NotFoundException("Kill-Agent failed to find " + agentID);
a.doDelete();
myContainer.releaseLocalAgent(agentID);
}
public void changeAgentState(AID agentID, int newState) throws IMTPException, NotFoundException {
Agent a = myContainer.acquireLocalAgent(agentID);
if(a == null)
throw new NotFoundException("Change-Agent-State failed to find " + agentID);
if(newState == Agent.AP_SUSPENDED) {
a.doSuspend();
}
else if(newState == Agent.AP_WAITING) {
a.doWait();
}
else if(newState == Agent.AP_ACTIVE) {
int oldState = a.getState();
if(oldState == Agent.AP_SUSPENDED) {
a.doActivate();
}
else {
a.doWake();
}
}
myContainer.releaseLocalAgent(agentID);
}
public void bornAgent(AID name, ContainerID cid, CertificateFolder certs) throws IMTPException, NameClashException, NotFoundException, AuthException {
MainContainer impl = myContainer.getMain();
if(impl != null) {
try {
// If the name is already in the GADT, throws NameClashException
impl.bornAgent(name, cid, certs, false);
}
catch(NameClashException nce) {
try {
ContainerID oldCid = impl.getContainerID(name);
Node n = impl.getContainerNode(oldCid);
// Perform a non-blocking ping to check...
n.ping(false);
// Ping succeeded: rethrow the NameClashException
throw nce;
}
catch(NameClashException nce2) {
throw nce2; // Let this one through...
}
catch(Exception e) {
// Ping failed: forcibly replace the dead agent...
impl.bornAgent(name, cid, certs, true);
}
}
}
}
public void deadAgent(AID name) throws IMTPException, NotFoundException {
MainContainer impl = myContainer.getMain();
if(impl != null) {
impl.deadAgent(name);
}
}
public void suspendedAgent(AID name) throws IMTPException, NotFoundException {
MainContainer impl = myContainer.getMain();
if(impl != null) {
impl.suspendedAgent(name);
}
}
public void resumedAgent(AID name) throws IMTPException, NotFoundException {
MainContainer impl = myContainer.getMain();
if(impl != null) {
impl.resumedAgent(name);
}
}
public void exitContainer() throws IMTPException, NotFoundException {
myContainer.shutDown();
}
} // End of AgentManagementSlice class
// Vertical command handler methods
private void handleRequestCreate(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, NameClashException, ServiceException {
Object[] params = cmd.getParams();
String name = (String)params[0];
String className = (String)params[1];
String[]args = (String[])params[2];
ContainerID cid = (ContainerID)params[3];
String ownership = (String)params[4];
CertificateFolder certs = (CertificateFolder)params[5];
MainContainer impl = myContainer.getMain();
if(impl != null) {
AID agentID = new AID(name, AID.ISLOCALNAME);
AgentManagementSlice targetSlice = (AgentManagementSlice)getSlice(cid.getName());
targetSlice.createAgent(agentID, className, args, ownership, certs, CREATE_AND_START);
}
else {
// Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication
}
}
private void handleRequestStart(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, NameClashException, ServiceException {
Object[] params = cmd.getParams();
AID target = (AID)params[0];
Agent instance = myContainer.acquireLocalAgent(target);
if(instance == null)
throw new NotFoundException("Start-Agent failed to find " + target);
//#MIDP_EXCLUDE_BEGIN
CertificateFolder agentCerts = instance.getCertificateFolder();
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
CertificateFolder agentCerts = new CertificateFolder();
Authority authority = myContainer.getAuthority();
if(agentCerts.getIdentityCertificate() == null) {
AgentPrincipal principal = authority.createAgentPrincipal(target, AgentPrincipal.NONE);
IdentityCertificate identity = authority.createIdentityCertificate();
identity.setSubject(principal);
authority.sign(identity, agentCerts);
agentCerts.setIdentityCertificate(identity);
}
#MIDP_INCLUDE_END*/
// Notify the main container through its slice
AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE);
mainSlice.bornAgent(target, myContainer.getID(), agentCerts);
// Actually start the agent thread
myContainer.powerUpLocalAgent(target, instance);
myContainer.releaseLocalAgent(target);
}
private void handleRequestKill(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, ServiceException {
Object[] params = cmd.getParams();
AID agentID = (AID)params[0];
MainContainer impl = myContainer.getMain();
if(impl != null) {
ContainerID cid = impl.getContainerID(agentID);
AgentManagementSlice targetSlice = (AgentManagementSlice)getSlice(cid.getName());
targetSlice.killAgent(agentID);
}
else {
// Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication
}
}
private void handleRequestStateChange(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, ServiceException {
Object[] params = cmd.getParams();
AID agentID = (AID)params[0];
AgentState as = (AgentState)params[1];
int newState = Agent.AP_MIN;
if(as.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) {
newState = Agent.AP_SUSPENDED;
}
else if(as.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.WAITING)) {
newState = Agent.AP_WAITING;
}
else if(as.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.ACTIVE)) {
newState = Agent.AP_ACTIVE;
}
MainContainer impl = myContainer.getMain();
if(impl != null) {
ContainerID cid = impl.getContainerID(agentID);
AgentManagementSlice targetSlice = (AgentManagementSlice)getSlice(cid.getName());
targetSlice.changeAgentState(agentID, newState);
}
else {
// Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication
}
}
private void handleInformCreated(VerticalCommand cmd) throws IMTPException, NotFoundException, NameClashException, AuthException, ServiceException {
Object[] params = cmd.getParams();
AID target = (AID)params[0];
Agent instance = (Agent)params[1];
boolean startIt = ((Boolean)params[2]).booleanValue();
initAgent(target, instance, startIt);
}
private void handleInformKilled(VerticalCommand cmd) throws IMTPException, NotFoundException, ServiceException {
Object[] params = cmd.getParams();
AID target = (AID)params[0];
// Remove the dead agent from the LADT of the container
myContainer.removeLocalAgent(target);
// Notify the main container through its slice
AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE);
mainSlice.deadAgent(target);
}
private void handleInformStateChanged(VerticalCommand cmd) {
Object[] params = cmd.getParams();
AID target = (AID)params[0];
AgentState from = (AgentState)params[1];
AgentState to = (AgentState)params[2];
if (to.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) {
try {
// Notify the main container through its slice
AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE);
mainSlice.suspendedAgent(target);
}
catch(IMTPException re) {
re.printStackTrace();
}
catch(NotFoundException nfe) {
nfe.printStackTrace();
}
catch(ServiceException se) {
se.printStackTrace();
}
}
else if (from.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) {
try {
// Notify the main container through its slice
AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE);
mainSlice.resumedAgent(target);
}
catch(IMTPException re) {
re.printStackTrace();
}
catch(NotFoundException nfe) {
nfe.printStackTrace();
}
catch(ServiceException se) {
se.printStackTrace();
}
}
}
private void handleKillContainer(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException {
Object[] params = cmd.getParams();
ContainerID cid = (ContainerID)params[0];
// Forward to the correct slice
AgentManagementSlice targetSlice = (AgentManagementSlice)getSlice(cid.getName());
targetSlice.exitContainer();
}
private void initAgent(AID target, Agent instance, boolean startIt) throws IMTPException, AuthException, NameClashException, NotFoundException, ServiceException {
// Connect the new instance to the local container
Agent old = myContainer.addLocalAgent(target, instance);
try {
//#MIDP_EXCLUDE_BEGIN
CertificateFolder agentCerts = instance.getCertificateFolder();
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
CertificateFolder agentCerts = new CertificateFolder();
Authority authority = myContainer.getAuthority();
if(agentCerts.getIdentityCertificate() == null) {
AgentPrincipal principal = authority.createAgentPrincipal(target, AgentPrincipal.NONE);
IdentityCertificate identity = authority.createIdentityCertificate();
identity.setSubject(principal);
authority.sign(identity, agentCerts);
agentCerts.setIdentityCertificate(identity);
}
#MIDP_INCLUDE_END*/
if(startIt) {
// Notify the main container through its slice
AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE);
mainSlice.bornAgent(target, myContainer.getID(), agentCerts);
// Actually start the agent thread
myContainer.powerUpLocalAgent(target, instance);
}
}
catch(NameClashException nce) {
myContainer.removeLocalAgent(target);
if(old != null) {
myContainer.addLocalAgent(target, old);
}
throw nce;
}
catch(IMTPException imtpe) {
myContainer.removeLocalAgent(target);
throw imtpe;
}
catch(NotFoundException nfe) {
myContainer.removeLocalAgent(target);
throw nfe;
}
catch(AuthException ae) {
myContainer.removeLocalAgent(target);
throw ae;
}
}
// The concrete agent container, providing access to LADT, etc.
private AgentContainer myContainer;
// The local slice for this service
private ServiceComponent localSlice;
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.DatabaseLiaison;
import com.samskivert.jdbc.JDBCUtil;
import com.samskivert.jdbc.depot.clause.QueryClause;
import com.samskivert.jdbc.depot.clause.SelectClause;
/**
* The implementation of {@link DepotRepository#find) functionality.
*/
public class FindOneQuery<T extends PersistentRecord>
implements Query<T>
{
public FindOneQuery (PersistenceContext ctx, Class<T> type, QueryClause[] clauses)
throws PersistenceException
{
_marsh = ctx.getMarshaller(type);
_select = new SelectClause<T>(type, _marsh.getFieldNames(), clauses);
WhereClause where = _select.getWhereClause();
if (where != null) {
_select.getWhereClause().validateQueryType(type); // sanity check
}
_builder = ctx.getSQLBuilder(DepotTypes.getDepotTypes(ctx, _select));
_builder.newQuery(_select);
}
// from Query
public CacheKey getCacheKey ()
{
WhereClause where = _select.getWhereClause();
if (where != null && where instanceof CacheKey) {
return (CacheKey) where;
}
return null;
}
// from Query
public T invoke (Connection conn, DatabaseLiaison liaison) throws SQLException
{
PreparedStatement stmt = _builder.prepare(conn);
try {
T result = null;
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
result = _marsh.createObject(rs);
}
// TODO: if (rs.next()) issue warning?
rs.close();
return result;
} finally {
JDBCUtil.close(stmt);
}
}
// from Query
public void updateCache (PersistenceContext ctx, T result)
{
CacheKey key = getCacheKey();
if (key == null) {
// no row-specific cache key was given
if (result == null || !_marsh.hasPrimaryKey()) {
return;
}
// if we can, create a key from what was actually returned
key = _marsh.getPrimaryKey(result);
}
ctx.cacheStore(key, (result != null) ? result.clone() : null);
}
// from Query
public T transformCacheHit (CacheKey key, T value)
{
if (value == null) {
return null;
}
// we do not want to return a reference to the actual cached entity so we clone it
@SuppressWarnings("unchecked") T cvalue = (T) value.clone();
return cvalue;
}
protected DepotMarshaller<T> _marsh;
protected SelectClause<T> _select;
protected SQLBuilder _builder;
} |
// $Id: GameManager.java,v 1.30 2002/06/01 21:21:20 ray Exp $
package com.threerings.parlor.game;
import com.threerings.presents.dobj.AttributeChangeListener;
import com.threerings.presents.dobj.AttributeChangedEvent;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.server.PlaceManager;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.crowd.server.PlaceManagerDelegate;
import com.threerings.parlor.Log;
import com.threerings.parlor.data.ParlorCodes;
/**
* The game manager handles the server side management of a game. It
* manipulates the game state in accordance with the logic of the game
* flow and generally manages the whole game playing process.
*
* <p> The game manager extends the place manager because games are
* implicitly played in a location, the players of the game implicitly
* bodies in that location.
*/
public class GameManager extends PlaceManager
implements ParlorCodes, GameCodes, AttributeChangeListener
{
// documentation inherited
protected Class getPlaceObjectClass ()
{
return GameObject.class;
}
// documentation inherited
protected void didInit ()
{
super.didInit();
// cast our configuration object (do we need to do this?)
_gconfig = (GameConfig)_config;
// register our message handlers
MessageHandler handler = new PlayerReadyHandler();
registerMessageHandler(PLAYER_READY_NOTIFICATION, handler);
}
/**
* Initializes the game manager with the supplied game configuration
* object. This happens before startup and before the game object has
* been created.
*
* @param players the usernames of all of the players in this game or
* null if the game has no specific set of players.
*/
public void setPlayers (String[] players)
{
// keep this around for now, we'll need it later
_players = players;
// instantiate a player oid array which we'll fill in later
_playerOids = new int[players.length];
}
/**
* Sets the specified player as an AI with the specified skill.
* It is assumed that this will be set soon after the player names for all
* AIs present in the game. (It should be done before human players start
* trickling into the game.)
*
* @param pidx the player index of the AI.
* @param skill the skill level, from 0 to 100 inclusive.
*/
public void setAI (int pidx, byte skill)
{
if (_AIs == null) {
_AIs = new byte[_players.length];
for (int ii=0; ii < _players.length; ii++) {
_AIs[ii] = -1;
}
// set up a delegate op for AI ticking
_tickAIOp = new TickAIDelegateOp();
}
_AIs[pidx] = skill;
}
/**
* Sets whether this game is to be rated. All games are unrated by
* default.
*/
// TODO: obsolete this method? It's used by SailingVessel in the yocode.
public void setRateGame (boolean rated)
{
_gconfig.rated = rated;
}
/**
* Returns an array of the usernames of the players in this game.
*/
public String[] getPlayers ()
{
return _players;
}
/**
* Returns whether the game is over.
*/
public boolean isGameOver ()
{
return (_gameobj.state == GameObject.GAME_OVER);
}
// documentation inherited
protected void didStartup ()
{
super.didStartup();
// obtain a casted reference to our game object
_gameobj = (GameObject)_plobj;
// stick the players into the game object
_gameobj.setPlayers(_players);
// let the players of this game know that we're ready to roll (if
// we have a specific set of players)
if (_players != null) {
Object[] args = new Object[] {
new Integer(_gameobj.getOid()) };
for (int i = 0; i < _players.length; i++) {
BodyObject bobj = CrowdServer.lookupBody(_players[i]);
if (bobj == null) {
Log.warning("Unable to deliver game ready to " +
"non-existent player " +
"[gameOid=" + _gameobj.getOid() +
", player=" + _players[i] + "].");
continue;
}
// deliver a game ready notification to the player
CrowdServer.invmgr.sendNotification(
bobj.getOid(), MODULE_NAME, GAME_READY_NOTIFICATION, args);
}
}
}
// documentation inherited
protected void bodyLeft (int bodyOid)
{
super.bodyLeft(bodyOid);
// deal with disappearing players
}
/**
* When a game room becomes empty, we cancel the game if it's still in
* progress and close down the game room.
*/
protected void placeBecameEmpty ()
{
Log.info("Game room empty. Going away. " +
"[gameOid=" + _gameobj.getOid() + "].");
// cancel the game if it wasn't over.
if (_gameobj.state != GameObject.GAME_OVER) {
_gameobj.setState(GameObject.CANCELLED);
}
// shut down the place (which will destroy the game object and
// clean up after everything)
shutdown();
}
/**
* Called when all players have arrived in the game room. By default,
* this starts up the game, but a manager may wish to override this
* and start the game according to different criterion.
*/
protected void playersAllHere ()
{
// start up the game (if we haven't already)
if (_gameobj.state == GameObject.AWAITING_PLAYERS) {
startGame();
}
}
/**
* This is called when the game is ready to start (all players
* involved have delivered their "am ready" notifications). It calls
* {@link #gameWillStart}, sets the necessary wheels in motion and
* then calls {@link #gameDidStart}. Derived classes should override
* one or both of the calldown functions (rather than this function)
* if they need to do things before or after the game starts.
*/
public void startGame ()
{
// complain if we're already started
if (_gameobj.state == GameObject.IN_PLAY) {
Log.warning("Requested to start an already in-play game " +
"[game=" + _gameobj + "].");
return;
}
// let the derived class do its pre-start stuff
gameWillStart();
// transition the game to started
_gameobj.setState(GameObject.IN_PLAY);
// do post-start processing
gameDidStart();
}
/**
* Called when the game is about to start, but before the game start
* notification has been delivered to the players. Derived classes
* should override this if they need to perform some pre-start
* activities.
*/
protected void gameWillStart ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameWillStart();
}
});
}
/**
* Called after the game start notification was dispatched. Derived
* classes can override this to put whatever wheels they might need
* into motion now that the game is started (if anything other than
* transitioning the game to <code>IN_PLAY</code> is necessary).
*/
protected void gameDidStart ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidStart();
}
});
// and register ourselves to receive AI ticks
if (_AIs != null) {
AIGameTicker.registerAIGame(this);
}
}
/**
* Called by the AIGameTicker if we're registered as an AI game.
*/
protected void tickAIs ()
{
for (int ii=0; ii < _AIs.length; ii++) {
byte level = _AIs[ii];
if (level != -1) {
tickAI(ii, level);
}
}
}
/**
* Called by tickAIs to tick each AI in the game.
*/
protected void tickAI (int pidx, byte level)
{
_tickAIOp.setAI(pidx, level);
applyToDelegates(_tickAIOp);
}
/**
* Called when the game is known to be over. This will call some
* calldown functions to determine the winner of the game and then
* transition the game to the <code>GAME_OVER</code> state.
*/
public void endGame ()
{
// figure out who won...
// transition to the game over state
_gameobj.setState(GameObject.GAME_OVER);
// wait until we hear the game state transition on the game object
// to invoke our game over code so that we can be sure that any
// final events dispatched on the game object prior to the call to
// endGame() have been dispatched
}
/**
* Called after the game has transitioned to the
* <code>GAME_OVER</code> state. Derived classes should override this
* to perform any post-game activities.
*/
protected void gameDidEnd ()
{
// remove ourselves from the AIticker, if applicable
if (_AIs != null) {
AIGameTicker.unregisterAIGame(this);
}
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidEnd();
}
});
// calculate ratings and all that...
}
/**
* Called when the game is to be reset to its starting state in
* preparation for a new game without actually ending the current
* game. It calls {@link #gameWillReset} and {@link #gameDidReset}.
* The standard game start processing ({@link #gameWillStart} and
* {@link #gameDidStart}) will also be called (in between the calls to
* will and did reset). Derived classes should override one or both of
* the calldown functions (rather than this function) if they need to
* do things before or after the game resets.
*/
public void resetGame ()
{
// let the derived class do its pre-reset stuff
gameWillReset();
// do the standard game start processing
gameWillStart();
_gameobj.setState(GameObject.IN_PLAY);
gameDidStart();
// let the derived class do its post-reset stuff
gameDidReset();
}
/**
* Called when the game is about to reset, but before the board has
* been re-initialized or any other clearing out of game data has
* taken place. Derived classes should override this if they need to
* perform some pre-reset activities.
*/
protected void gameWillReset ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameWillReset();
}
});
}
/**
* Called after the game has been reset. Derived classes can override
* this to put whatever wheels they might need into motion now that
* the game is reset.
*/
protected void gameDidReset ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidReset();
}
});
}
// documentation inherited
public void attributeChanged (AttributeChangedEvent event)
{
if (event.getName().equals(GameObject.STATE)) {
switch (event.getIntValue()) {
case GameObject.CANCELLED:
// fall through to GAME_OVER case
case GameObject.GAME_OVER:
// now we do our end of game processing
gameDidEnd();
break;
}
}
}
/** Handles player ready notifications. */
protected class PlayerReadyHandler implements MessageHandler
{
public void handleEvent (MessageEvent event, PlaceManager pmgr)
{
int cloid = event.getSourceOid();
BodyObject body = (BodyObject)CrowdServer.omgr.getObject(cloid);
if (body == null) {
Log.warning("Player sent am ready notification and then " +
"disappeared [event=" + event + "].");
return;
}
// make a note of this player's oid and check to see if we're
// all set at the same time
boolean allSet = true;
for (int i = 0; i < _players.length; i++) {
if (_players[i].equals(body.username)) {
_playerOids[i] = body.getOid();
}
if ((_playerOids[i] == 0) &&
((_AIs == null) || (_AIs[i] == -1))) {
allSet = false;
}
}
// if everyone is now ready to go, make a note of it
if (allSet) {
playersAllHere();
}
}
}
/**
* A helper operation to distribute AI ticks to our delegates.
*/
protected class TickAIDelegateOp implements DelegateOp
{
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate) delegate).tickAI(_pidx, _level);
}
public void setAI (int pidx, byte level)
{
_pidx = pidx;
_level = level;
}
protected int _pidx;
protected byte _level;
}
/** A reference to our game configuration. */
protected GameConfig _gconfig;
/** A reference to our game object. */
protected GameObject _gameobj;
/** The usernames of the players of this game. */
protected String[] _players;
/** The oids of our player and AI body objects. */
protected int[] _playerOids;
/** If AIs are present, contains their skill levels, or -1 at human
* player indexes.. */
protected byte[] _AIs;
/** Our delegate operator to tick AIs. */
protected TickAIDelegateOp _tickAIOp;
} |
package org.carlspring.strongbox.cron.jobs;
import org.carlspring.strongbox.config.NugetLayoutProviderCronTasksTestConfig;
import org.carlspring.strongbox.cron.domain.CronTaskConfiguration;
import org.carlspring.strongbox.cron.services.CronTaskConfigurationService;
import org.carlspring.strongbox.cron.services.JobManager;
import org.carlspring.strongbox.event.cron.CronTaskEventTypeEnum;
import org.carlspring.strongbox.repository.RepositoryManagementStrategyException;
import org.carlspring.strongbox.resource.ConfigurationResourceResolver;
import org.carlspring.strongbox.services.ConfigurationManagementService;
import org.carlspring.strongbox.services.RepositoryManagementService;
import org.carlspring.strongbox.services.StorageManagementService;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.repository.RepositoryLayoutEnum;
import org.carlspring.strongbox.storage.repository.RepositoryPolicyEnum;
import org.carlspring.strongbox.util.FileUtils;
import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Kate Novik.
*/
@ContextConfiguration(classes = NugetLayoutProviderCronTasksTestConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
@Ignore
public class RegenerateNugetChecksumCronJobTestIT
extends BaseCronJobWithNugetIndexingTestCase
{
private static final String STORAGE1 = "nuget-common-storage";
private static final String STORAGE2 = "nuget-checksum-test";
private static final String REPOSITORY_RELEASES = "rnccj-releases";
private static final String REPOSITORY_ALPHA = "rnccj-alpha";
private static final File REPOSITORY_RELEASES_BASEDIR_1 = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE1 + "/" +
REPOSITORY_RELEASES);
private static final File REPOSITORY_ALPHA_BASEDIR = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE1 + "/" +
REPOSITORY_ALPHA);
private static final File REPOSITORY_RELEASES_BASEDIR_2 = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE2 + "/" +
REPOSITORY_RELEASES);
@Inject
private CronTaskConfigurationService cronTaskConfigurationService;
@Inject
private ConfigurationManagementService configurationManagementService;
@Inject
private RepositoryManagementService repositoryManagementService;
@Inject
protected StorageManagementService storageManagementService;
@Inject
private JobManager jobManager;
@BeforeClass
public static void cleanUp()
throws Exception
{
cleanUp(getRepositoriesToClean());
}
@Before
public void initialize()
throws Exception
{
createStorage(STORAGE1);
createRepository(STORAGE1, REPOSITORY_RELEASES, RepositoryPolicyEnum.RELEASE.getPolicy(), false);
//Create released nuget package in the repository rnccj-releases (storage1)
generateNugetPackage(REPOSITORY_RELEASES_BASEDIR_1.getAbsolutePath(),
"org.carlspring.strongbox.checksum-second", "1.0");
createRepository(STORAGE1, REPOSITORY_ALPHA, RepositoryPolicyEnum.SNAPSHOT.getPolicy(), false);
//Create pre-released nuget package in the repository rnccj-alpha
generateAlphaNugetPackage(REPOSITORY_ALPHA_BASEDIR.getAbsolutePath(), "org.carlspring.strongbox.checksum-one",
"1.0.1");
createStorage(STORAGE2);
createRepository(STORAGE2, REPOSITORY_RELEASES, RepositoryPolicyEnum.RELEASE.getPolicy(), false);
//Create released nuget package in the repository rnccj-releases (storage2)
generateNugetPackage(REPOSITORY_RELEASES_BASEDIR_2.getAbsolutePath(), "org.carlspring.strongbox.checksum-one",
"1.0");
}
@After
public void removeRepositories()
throws IOException, JAXBException
{
removeRepositories(getRepositoriesToClean());
}
public static Set<Repository> getRepositoriesToClean()
{
Set<Repository> repositories = new LinkedHashSet<>();
repositories.add(createRepositoryMock(STORAGE1, REPOSITORY_RELEASES));
repositories.add(createRepositoryMock(STORAGE1, REPOSITORY_ALPHA));
repositories.add(createRepositoryMock(STORAGE2, REPOSITORY_RELEASES));
return repositories;
}
public void addRegenerateCronJobConfig(String name,
String storageId,
String repositoryId,
String basePath,
boolean forceRegeneration)
throws Exception
{
CronTaskConfiguration cronTaskConfiguration = new CronTaskConfiguration();
cronTaskConfiguration.setOneTimeExecution(true);
cronTaskConfiguration.setImmediateExecution(true);
cronTaskConfiguration.setName(name);
cronTaskConfiguration.addProperty("jobClass", RegenerateChecksumCronJob.class.getName());
cronTaskConfiguration.addProperty("cronExpression", "0 11 11 11 11 ? 2100");
cronTaskConfiguration.addProperty("storageId", storageId);
cronTaskConfiguration.addProperty("repositoryId", repositoryId);
cronTaskConfiguration.addProperty("basePath", basePath);
cronTaskConfiguration.addProperty("forceRegeneration", String.valueOf(forceRegeneration));
cronTaskConfigurationService.saveConfiguration(cronTaskConfiguration);
CronTaskConfiguration obj = cronTaskConfigurationService.findOne(name);
assertNotNull(obj);
}
@Test
public void testRegenerateNugetPackageChecksum()
throws Exception
{
String jobName = "RegenerateNuget-1";
String artifactPath = REPOSITORY_RELEASES_BASEDIR_1 + "/org.carlspring.strongbox.checksum-second";
FileUtils.deleteIfExists(
new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
FileUtils.deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
assertTrue("The checksum file for artifact exist!",
!new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists());
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (jobName1.equals(jobName) && statusExecuted)
{
try
{
assertTrue("The checksum file for artifact doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists());
assertTrue("The checksum file for artifact is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").length() >
0);
assertTrue("The checksum file for metadata file doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512").exists());
assertTrue("The checksum file for metadata file is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512").length() > 0);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, REPOSITORY_RELEASES,
properties ->
{
properties.put("basePath", "org.carlspring.strongbox.checksum-second");
properties.put("forceRegeneration","false");
});
assertTrue("Failed to execute task!",
expectEvent(jobName, CronTaskEventTypeEnum.EVENT_CRON_TASK_EXECUTION_COMPLETE.getType()));
}
@Test
public void testRegenerateNugetChecksumInRepository()
throws Exception
{
String jobName = "RegenerateNuget-2";
String artifactPath = REPOSITORY_ALPHA_BASEDIR + "/org.carlspring.strongbox.checksum-one";
FileUtils.deleteIfExists(
new File(artifactPath, "/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512"));
FileUtils.deleteIfExists(
new File(artifactPath, "/1.0.1-alpha/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
assertTrue("The checksum file for artifact exist!",
!new File(artifactPath,
"/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512").exists());
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (jobName1.equals(jobName) && statusExecuted)
{
try
{
assertTrue("The checksum file for artifact doesn't exist!",
new File(artifactPath,
"/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512").exists());
assertTrue("The checksum file for artifact is empty!",
new File(artifactPath,
"/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512").length() >
0);
assertTrue("The checksum file for metadata file doesn't exist!",
new File(artifactPath,
"/1.0.1-alpha/org.carlspring.strongbox.checksum-one.nuspec.sha512").exists());
assertTrue("The checksum file for metadata file is empty!",
new File(artifactPath,
"/1.0.1-alpha/org.carlspring.strongbox.checksum-one.nuspec.sha512").length() >
0);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, REPOSITORY_ALPHA,
properties -> properties.put("forceRegeneration","false"));
assertTrue("Failed to execute task!",
expectEvent(jobName, CronTaskEventTypeEnum.EVENT_CRON_TASK_EXECUTION_COMPLETE.getType()));
}
@Test
public void testRegenerateNugetChecksumInStorage()
throws Exception
{
String jobName = "RegenerateNuget-3";
String artifactPath = REPOSITORY_RELEASES_BASEDIR_1 + "/org.carlspring.strongbox.checksum-second";
FileUtils.deleteIfExists(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
FileUtils.deleteIfExists(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
assertTrue("The checksum file for artifact exist!",
!new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists());
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (jobName1.equals(jobName) && statusExecuted)
{
try
{
assertTrue("The checksum file for artifact doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists());
assertTrue("The checksum file for artifact is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").length() > 0);
assertTrue("The checksum file for metadata file doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512").exists());
assertTrue("The checksum file for metadata file is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512").length() > 0);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, null,
properties -> properties.put("forceRegeneration","false"));
assertTrue("Failed to execute task!",
expectEvent(jobName, CronTaskEventTypeEnum.EVENT_CRON_TASK_EXECUTION_COMPLETE.getType()));
}
@Test
public void testRegenerateNugetChecksumInStorages()
throws Exception
{
String jobName = "RegenerateNuget-4";
String artifactPath = REPOSITORY_RELEASES_BASEDIR_2 + "/org.carlspring.strongbox.checksum-one";
FileUtils.deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512"));
FileUtils.deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
assertTrue("The checksum file for artifact exist!",
!new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512").exists());
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (jobName1.equals(jobName) && statusExecuted)
{
try
{
assertTrue("The checksum file for artifact doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512").exists());
assertTrue("The checksum file for artifact is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512").length() > 0);
assertTrue("The checksum file for metadata file doesn't exist!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.nuspec.sha512").exists());
assertTrue("The checksum file for metadata file is empty!",
new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.nuspec.sha512").length() > 0);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, null, null,
properties -> properties.put("forceRegeneration","false"));
assertTrue("Failed to execute task!",
expectEvent(jobName, CronTaskEventTypeEnum.EVENT_CRON_TASK_EXECUTION_COMPLETE.getType()));
}
private void createRepository(String storageId,
String repositoryId,
String policy,
boolean indexing)
throws IOException,
JAXBException,
RepositoryManagementStrategyException
{
Repository repository = new Repository(repositoryId);
repository.setPolicy(policy);
repository.setLayout(RepositoryLayoutEnum.NUGET_HIERARCHICAL.getLayout());
repository.setStorage(configurationManagementService.getStorage(storageId));
createRepository(repository);
}
private void createRepository(Repository repository)
throws IOException,
JAXBException,
RepositoryManagementStrategyException
{
configurationManagementService.saveRepository(repository.getStorage().getId(), repository);
// Create the repository
repositoryManagementService.createRepository(repository.getStorage().getId(), repository.getId());
}
private void createStorage(String storageId)
throws IOException, JAXBException
{
createStorage(new Storage(storageId));
}
private void createStorage(Storage storage)
throws IOException, JAXBException
{
configurationManagementService.saveStorage(storage);
storageManagementService.createStorage(storage);
}
public static void cleanUp(Set<Repository> repositoriesToClean)
throws Exception
{
if (repositoriesToClean != null)
{
for (Repository repository : repositoriesToClean)
{
removeRepositoryDirectory(repository.getStorage().getId(), repository.getId());
}
}
}
private static void removeRepositoryDirectory(String storageId,
String repositoryId)
throws IOException
{
File repositoryBaseDir = new File(ConfigurationResourceResolver.getVaultDirectory(),
"/storages/" + storageId + "/" + repositoryId);
if (repositoryBaseDir.exists())
{
org.apache.commons.io.FileUtils.deleteDirectory(repositoryBaseDir);
}
}
public void removeRepositories(Set<Repository> repositoriesToClean)
throws IOException, JAXBException
{
for (Repository repository : repositoriesToClean)
{
configurationManagementService.removeRepository(repository.getStorage()
.getId(), repository.getId());
}
}
public static Repository createRepositoryMock(String storageId,
String repositoryId)
{
// This is no the real storage, but has a matching ID.
// We're mocking it, as the configurationManager is not available at the the static methods are invoked.
Storage storage = new Storage(storageId);
Repository repository = new Repository(repositoryId);
repository.setStorage(storage);
return repository;
}
} |
package io.compgen.ngsutils.cli.bed;
import java.io.IOException;
import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.ngsutils.annotation.GenomeSpan;
import io.compgen.ngsutils.bam.Strand;
import io.compgen.ngsutils.bed.BedPEReader;
import io.compgen.ngsutils.bed.BedPERecord;
import io.compgen.ngsutils.bed.BedRecord;
@Command(name="bedpe-tobed", desc="Convert a BEDPE file to a BED file by combining coordinates (default) or splitting the coordinates", category="bed", doc="Note: only non-discordant records can be combined.")
public class BedPEToBed extends AbstractOutputCommand {
private String filename = null;
private int maxDistance = 0;
private boolean split = false;
private boolean first = false;
private boolean second = false;
@Option(desc = "Split records into two BED lines", name="split")
public void setSplit(boolean split) {
this.split = split;
}
@Option(desc = "Write the first record only", name="first")
public void setFirst(boolean first) {
this.first = first;
}
@Option(desc = "Write the second record only", name="second")
public void setSecond(boolean second) {
this.second = second;
}
@Option(desc = "Maximum allowed distance between records (-1 to disable)", name="max", defaultValue="10000")
public void setMaxDistance(int maxDistance) {
this.maxDistance = maxDistance;
}
@UnnamedArg(name = "FILE")
public void setFilename(String filename) {
this.filename = filename;
}
@Exec
public void exec() throws IOException, CommandArgumentException {
int i = 0;
if (first) {
i++;
}
if (second) {
i++;
}
if (split) {
i++;
}
if (i > 1) {
throw new CommandArgumentException("You can only specify one of: --first --second --split");
}
for (BedPERecord record: IterUtils.wrap(BedPEReader.readFile(filename))) {
GenomeSpan coord1 = record.getCoord1();
GenomeSpan coord2 = record.getCoord2();
if (split) {
new BedRecord(new GenomeSpan(coord1.ref, coord1.start, coord1.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
new BedRecord(new GenomeSpan(coord2.ref, coord2.start, coord2.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
} else if (first) {
new BedRecord(new GenomeSpan(coord1.ref, coord1.start, coord1.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
} else if (second) {
new BedRecord(new GenomeSpan(coord2.ref, coord2.start, coord2.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
} else {
if (isDiscordant(coord1, coord2, maxDistance)) {
continue;
}
if (coord1.compareTo(coord2) < 0) { // coord1 is less
new BedRecord(new GenomeSpan(coord1.ref, coord1.start, coord2.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
} else {
new BedRecord(new GenomeSpan(coord1.ref, coord2.start, coord1.end), record.getName(), record.getScoreAsDouble(), record.getExtras()).write(out);
}
}
}
}
public static boolean isDiscordant(GenomeSpan coord1, GenomeSpan coord2, int maxDist) {
if (coord1.ref.equals(coord2.ref)) {
if (coord1.compareTo(coord2) < 0) { // coord1 is less
if (maxDist == -1 || coord2.start - coord1.end <= maxDist) {
// concordant reads are on different strands
return coord1.strand != Strand.NONE && coord2.strand != Strand.NONE && coord2.strand.equals(coord1.strand);
}
} else {
if (maxDist == -1 || coord1.start - coord2.end <= maxDist) { // coord2 is less or equal
// concordant reads are on different strands
return coord1.strand != Strand.NONE && coord2.strand != Strand.NONE && coord2.strand.equals(coord1.strand);
}
}
}
return true;
}
} |
package net.sf.jabref.export;
import net.sf.jabref.Globals;
import net.sf.jabref.BibtexDatabase;
import net.sf.jabref.msbib.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import java.util.Set;
import java.io.IOException;
import java.io.File;
/**
* ExportFormat for exporting in MSBIB XML format.
*/
class MSBibExportFormat extends ExportFormat {
public MSBibExportFormat() {
super(Globals.lang("MS Office 2007"), "MSBib", null, null, ".xml");
}
public void performExport(final BibtexDatabase database, final String file, final String encoding, Set keySet) throws IOException {
// forcing to use UTF8 output format for some problems with
// xml export in other encodings
SaveSession ss = getSaveSession("UTF8", new File(file));
VerifyingWriter ps = ss.getWriter();
MSBibDatabase md = new MSBibDatabase(database, keySet);
// PS: DOES NOT SUPPORT EXPORTING ONLY A SET OF ENTRIES
try {
DOMSource source = new DOMSource(md.getDOMrepresentation());
StreamResult result = new StreamResult(ps);
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.transform(source, result);
}
catch (Exception e) {
throw new Error(e);
}
try {
finalizeSaveSession(ss);
} catch (SaveException ex) {
throw new IOException(ex.getMessage());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return;
}
} |
package ru.stqa.pft.homework;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTests {
@Test
public void test1() {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
Assert.assertEquals(p1.distanceTo(p2), 5.0);
}
@Test
public void test2() {
Point p1 = new Point(-3, 0.2);
Point p2 = new Point(0, -3);
Assert.assertEquals((int) p1.distanceTo(p2), 4);
}
} |
package org.apache.fop.fo.flow;
// XML
import org.xml.sax.Attributes;
// FOP
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.FONode;
import org.apache.fop.fo.FObj;
import org.apache.fop.fo.FOTreeVisitor;
import org.apache.fop.fo.properties.TextAlign;
import org.apache.fop.fo.properties.Overflow;
import org.apache.fop.fo.properties.DisplayAlign;
import org.apache.fop.fo.properties.Scaling;
import org.apache.fop.image.ImageFactory;
import org.apache.fop.image.FopImage;
import org.apache.fop.datatypes.Length;
import org.apache.fop.datatypes.LengthRange;
// Java
import java.awt.geom.Rectangle2D;
/**
* External graphic formatting object.
* This FO node handles the external graphic. It creates an image
* inline area that can be added to the area tree.
*/
public class ExternalGraphic extends FObj {
private String url;
private int breakAfter;
private int breakBefore;
private int align;
private int startIndent;
private int endIndent;
private int spaceBefore;
private int spaceAfter;
private int viewWidth = -1;
private int viewHeight = -1;
private boolean clip = false;
private Rectangle2D placement = null;
/**
* Create a new External graphic node.
*
* @param parent the parent of this node
*/
public ExternalGraphic(FONode parent) {
super(parent);
}
/**
* Setup this image.
* This gets the sizes for the image and the dimensions and clipping.
*/
public void setup() {
url = this.propertyList.get(PR_SRC).getString();
if (url == null) {
return;
}
url = ImageFactory.getURL(url);
// assume lr-tb for now and just use the .optimum value of the range
Length ipd = propertyList.get(PR_INLINE_PROGRESSION_DIMENSION).
getLengthRange().getOptimum().getLength();
if (!ipd.isAuto()) {
viewWidth = ipd.getValue();
} else {
ipd = propertyList.get(PR_WIDTH).getLength();
if (!ipd.isAuto()) {
viewWidth = ipd.getValue();
}
}
Length bpd = propertyList.get(PR_BLOCK_PROGRESSION_DIMENSION | CP_OPTIMUM).getLength();
if (!bpd.isAuto()) {
viewHeight = bpd.getValue();
} else {
bpd = propertyList.get(PR_HEIGHT).getLength();
if (!bpd.isAuto()) {
viewHeight = bpd.getValue();
}
}
// if we need to load this image to get its size
FopImage fopimage = null;
int cwidth = -1;
int cheight = -1;
Length ch = propertyList.get(PR_CONTENT_HEIGHT).getLength();
if (!ch.isAuto()) {
/*if (ch.scaleToFit()) {
if (viewHeight != -1) {
cheight = viewHeight;
}
} else {*/
cheight = ch.getValue();
}
Length cw = propertyList.get(PR_CONTENT_WIDTH).getLength();
if (!cw.isAuto()) {
/*if (cw.scaleToFit()) {
if (viewWidth != -1) {
cwidth = viewWidth;
}
} else {*/
cwidth = cw.getValue();
}
int scaling = propertyList.get(PR_SCALING).getEnum();
if ((scaling == Scaling.UNIFORM) || (cwidth == -1) || cheight == -1) {
ImageFactory fact = ImageFactory.getInstance();
fopimage = fact.getImage(url, getUserAgent());
if (fopimage == null) {
// error
url = null;
return;
}
// load dimensions
if (!fopimage.load(FopImage.DIMENSIONS, getUserAgent())) {
// error
url = null;
return;
}
if (cwidth == -1 && cheight == -1) {
cwidth = (int)(fopimage.getWidth() * 1000);
cheight = (int)(fopimage.getHeight() * 1000);
} else if (cwidth == -1) {
cwidth = (int)(fopimage.getWidth() * cheight) / fopimage.getHeight();
} else if (cheight == -1) {
cheight = (int)(fopimage.getHeight() * cwidth) / fopimage.getWidth();
} else {
// adjust the larger
double rat1 = cwidth / (fopimage.getWidth() * 1000f);
double rat2 = cheight / (fopimage.getHeight() * 1000f);
if (rat1 < rat2) {
// reduce cheight
cheight = (int)(rat1 * fopimage.getHeight() * 1000);
} else {
cwidth = (int)(rat2 * fopimage.getWidth() * 1000);
}
}
}
if (viewWidth == -1) {
viewWidth = cwidth;
}
if (viewHeight == -1) {
viewHeight = cheight;
}
if (cwidth > viewWidth || cheight > viewHeight) {
int overflow = propertyList.get(PR_OVERFLOW).getEnum();
if (overflow == Overflow.HIDDEN) {
clip = true;
} else if (overflow == Overflow.ERROR_IF_OVERFLOW) {
getLogger().error("Image: " + url
+ " overflows the viewport, clipping to viewport");
clip = true;
}
}
int xoffset = 0;
int yoffset = 0;
int da = propertyList.get(PR_DISPLAY_ALIGN).getEnum();
switch(da) {
case DisplayAlign.BEFORE:
break;
case DisplayAlign.AFTER:
yoffset = viewHeight - cheight;
break;
case DisplayAlign.CENTER:
yoffset = (viewHeight - cheight) / 2;
break;
case DisplayAlign.AUTO:
default:
break;
}
int ta = propertyList.get(PR_TEXT_ALIGN).getEnum();
switch(ta) {
case TextAlign.CENTER:
xoffset = (viewWidth - cwidth) / 2;
break;
case TextAlign.END:
xoffset = viewWidth - cwidth;
break;
case TextAlign.START:
break;
case TextAlign.JUSTIFY:
default:
break;
}
placement = new Rectangle2D.Float(xoffset, yoffset, cwidth, cheight);
}
/**
* @return the ViewHeight (in millipoints??)
*/
public int getViewHeight() {
return viewHeight;
}
/**
* This is a hook for an FOTreeVisitor subclass to be able to access
* this object.
* @param fotv the FOTreeVisitor subclass that can access this object.
* @see org.apache.fop.fo.FOTreeVisitor
*/
public void acceptVisitor(FOTreeVisitor fotv) {
fotv.serveExternalGraphic(this);
}
public String getURL() {
return url;
}
public int getViewWidth() {
return viewWidth;
}
public boolean getClip() {
return clip;
}
public Rectangle2D getPlacement() {
return placement;
}
/**
* @see org.apache.fop.fo.FObj#handleAttrs
*/
public void handleAttrs(Attributes attlist) throws FOPException {
super.handleAttrs(attlist);
getFOTreeControl().getFOInputHandler().image(this);
}
} |
package hu.sch.domain;
import hu.sch.domain.user.User;
import hu.sch.domain.util.DateInterval;
import hu.sch.domain.interfaces.MembershipTableEntry;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@Table(name = "grp_membership")
@NamedQueries(value = {
@NamedQuery(name = Membership.getMembership,
query = "SELECT ms FROM Membership ms WHERE ms.user = :user AND ms.group.isSvie = true"),
@NamedQuery(name = Membership.getActiveSvieMemberships,
query = "SELECT ms FROM Membership ms WHERE ms.user = :user AND ms.group.isSvie = true AND ms.end IS null"),
@NamedQuery(name = Membership.getMembers,
query = "SELECT u FROM User u WHERE u.svieMembershipType <> :msType"),
@NamedQuery(name = Membership.getDelegatedMemberForGroup,
query = "SELECT ms.user FROM Membership ms "
+ "WHERE ms.group.id=:groupId AND ms.user.sviePrimaryMembership = ms AND ms.user.delegated = true"),
@NamedQuery(name = Membership.getAllDelegated,
query = "SELECT u FROM User u WHERE u.delegated = true "
+ "ORDER BY u.lastName, u.firstName"),
@NamedQuery(name = Membership.findMembershipsForGroup, query =
"SELECT ms FROM Membership ms "
+ "WHERE ms.groupId = :id"),
@NamedQuery(name = Membership.findMembershipForUserAndGroup, query =
"SELECT ms FROM Membership ms WHERE ms.groupId = :groupId AND ms.userId = :userId")
})
@SequenceGenerator(name = "grp_members_seq", sequenceName = "grp_members_seq",
allocationSize = 1)
public class Membership implements MembershipTableEntry {
public static final String SORT_BY_GROUP = "group";
public static final String SORT_BY_POSTS = "postsAsString";
public static final String SORT_BY_INTERVAL = "interval";
private static final long serialVersionUID = 1L;
public static final String getMembership = "getMembership";
public static final String getActiveSvieMemberships = "getActiveSvieMemberships";
public static final String getMembers = "getMembers";
public static final String getDelegatedMemberForGroup = "getDelegatedMemberForGroup";
public static final String getAllDelegated = "getAllDelegated";
public static final String findMembershipsForGroup = "findMembershipsForGroup";
public static final String findMembershipForUserAndGroup = "getMembershipForUserAndGroup";
@Id
@GeneratedValue(generator = "grp_members_seq")
@Column(name = "id")
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "grp_id", insertable = true, updatable = true)
private Group group;
@Column(name = "grp_id", insertable = false, updatable = false)
private Long groupId;
@ManyToOne(optional = false)
@JoinColumn(name = "usr_id", insertable = true, updatable = true)
private User user;
@Column(name = "usr_id", insertable = false, updatable = false)
private Long userId;
@Column(name = "membership_start", nullable = false, columnDefinition = "date")
@Temporal(TemporalType.DATE)
private Date start;
@Column(name = "membership_end", nullable = true, columnDefinition = "date")
@Temporal(TemporalType.DATE)
private Date end;
@Transient
private DateInterval interval;
@OneToMany(mappedBy = "membership", fetch = FetchType.EAGER)
private Set<Post> posts = new HashSet<>();
@Transient
private String postsAsString;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Melyik csoport tagja
*/
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
/**
* Ki a tagja a csoportnak
*/
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public DateInterval getInterval() {
if (interval == null) {
interval = new DateInterval(start, end);
}
return interval;
}
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!getClass().isAssignableFrom(obj.getClass())) {
return false;
}
final Membership other = (Membership) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.getId()))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0);
hash = 29 * hash + (this.group != null ? this.group.hashCode() : 0);
hash = 29 * hash + (this.user != null ? this.user.hashCode() : 0);
hash = 29 * hash + (this.start != null ? this.start.hashCode() : 0);
hash = 29 * hash + (this.end != null ? this.end.hashCode() : 0);
hash = 29 * hash + (this.posts != null ? this.posts.hashCode() : 0);
return hash;
}
@Override
public Membership getMembership() {
return this;
}
public String getPostsAsString() {
if (postsAsString == null) {
StringBuilder sb = new StringBuilder(posts.size() * 16 + 3);
if (end != null) {
sb.append("öregtag");
}
for (Post post : posts) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(post.getPostType().toString());
}
if (sb.length() == 0) {
sb.append("tag");
}
postsAsString = sb.toString();
}
return postsAsString;
}
} |
package org.apache.velocity.test;
import java.io.File;
import org.apache.velocity.anakia.AnakiaTask;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.util.StringUtils;
import junit.framework.TestCase;
/**
* This is a test case for Texen. Simply executes a simple
* generative task and compares the output.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @version $Id: TexenTestCase.java,v 1.3 2001/03/23 17:32:45 jvanzyl Exp $
*/
public class TexenTestCase extends BaseTestCase
{
/**
* Directory where results are generated.
*/
private static final String RESULTS_DIR = "../test/texen/results";
/**
* Directory where comparison output is stored.
*/
private static final String COMPARE_DIR = "../test/texen/compare";
/**
* Creates a new instance.
*
*/
public TexenTestCase()
{
super("TexenTestCase");
}
public static junit.framework.Test suite()
{
return new TexenTestCase();
}
/**
* Sets up the test.
*/
protected void setUp ()
{
}
/**
* Runs the test.
*/
public void runTest ()
{
try
{
assureResultsDirectoryExists(RESULTS_DIR);
if (!isMatch(RESULTS_DIR,COMPARE_DIR,"TurbineWeather","java","java") ||
!isMatch(RESULTS_DIR,COMPARE_DIR,"TurbineWeatherService","java","java") ||
!isMatch(RESULTS_DIR,COMPARE_DIR,"WeatherService","java","java") ||
!isMatch(RESULTS_DIR,COMPARE_DIR,"Test","txt","txt"))
{
fail("Output is incorrect!");
}
}
catch(Exception e)
{
/*
* do nothing.
*/
}
}
} |
package org.orbeon.oxf.xforms;
import org.dom4j.Node;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.controls.XFormsRepeatControl;
import org.orbeon.saxon.dom4j.NodeWrapper;
import org.orbeon.saxon.om.NodeInfo;
import java.util.*;
/**
* Useful functions for handling repeat indexes.
*/
public class XFormsIndexUtils {
/**
* Ajust repeat indexes so that they are put back within bounds.
*
* @param pipelineContext
* @param xformsControls
* @param currentControlsState
*/
public static void adjustIndexes(PipelineContext pipelineContext, final XFormsControls xformsControls,
final XFormsControls.ControlsState currentControlsState) {
// NOTE: You can imagine really complicated stuff related to index
// updates. Here, we assume that repeat iterations do
// *not* depend on instance values that themselves depend on the index()
// function. This scenario is not impossible, but fairly far-fetched I think, and we haven't seen it yet. So
// once an instance structure and content is determined, we assume that it won't change in a significant way
// with index updates performed below.
// However, one scenario we want to allow is a repeat "detail" on the same level as a repeat "master", where
// the repeat detail iteration depends on index('master').
// TODO: detect use of index() function
final Map updatedIndexesIds = new HashMap();
currentControlsState.visitControlsFollowRepeats(pipelineContext, xformsControls, new XFormsControls.XFormsControlVisitorListener() {
private int level = 0;
public void startVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
// Found an xforms:repeat
final XFormsRepeatControl repeatControlInfo = (XFormsRepeatControl) XFormsControl;
final String repeatId = repeatControlInfo.getOriginalId();
final List repeatNodeSet = xformsControls.getCurrentNodeset();
// Make sure the bounds of this xforms:repeat are correct
// for the rest of the visit.
final int adjustedNewIndex;
{
final int newIndex = ((Integer) currentControlsState.getRepeatIdToIndex().get(repeatId)).intValue();
// Adjust bounds if necessary
if (repeatNodeSet == null || repeatNodeSet.size() == 0)
adjustedNewIndex = 0;
else if (newIndex < 1)
adjustedNewIndex = 1;
else if (newIndex > repeatNodeSet.size())
adjustedNewIndex = repeatNodeSet.size();
else
adjustedNewIndex = newIndex;
}
// Set index
currentControlsState.updateRepeatIndex(repeatId, adjustedNewIndex);
updatedIndexesIds.put(repeatId, "");
level++;
}
}
public void endVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
level
}
}
});
// Repeats that haven't been reached are set to 0
for (Iterator i = currentControlsState.getRepeatIdToIndex().entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String repeatId = (String) currentEntry.getKey();
if (updatedIndexesIds.get(repeatId) == null) {
currentControlsState.updateRepeatIndex(repeatId, 0);
}
}
}
/**
* Adjust repeat indexes after an insertion.
*
* @param pipelineContext
* @param xformsControls
* @param currentControlsState
* @param clonedNodes
*/
public static void adjustIndexesAfterInsert(PipelineContext pipelineContext, final XFormsControls xformsControls,
final XFormsControls.ControlsState currentControlsState, final List clonedNodes) {
// NOTE: The code below assumes that there are no nested repeats bound to node-sets that intersect
currentControlsState.visitControlsFollowRepeats(pipelineContext, xformsControls, new XFormsControls.XFormsControlVisitorListener() {
private XFormsControl foundXFormsControl;
public void startVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
// Found an xforms:repeat
final XFormsRepeatControl repeatControlInfo = (XFormsRepeatControl) XFormsControl;
final String repeatId = repeatControlInfo.getOriginalId();
final List repeatNodeSet = xformsControls.getCurrentNodeset();
if (foundXFormsControl == null) {
// We are not yet inside a matching xforms:repeat
if (repeatNodeSet != null && repeatNodeSet.size() > 0) {
// Find whether one node of the repeat node-set contains one of the inserted nodes
int newRepeatIndex = -1;
{
int clonedNodesIndex = -1;
int currentRepeatIndex = 1;
for (Iterator i = repeatNodeSet.iterator(); i.hasNext(); currentRepeatIndex++) {
final NodeInfo currentNodeInfo = (NodeInfo) i.next();
if (currentNodeInfo instanceof NodeWrapper) { // underlying node can't match if it's not a NodeWrapper
final Node currentNode = (Node) ((NodeWrapper) currentNodeInfo).getUnderlyingNode();
final int currentNodeIndex = clonedNodes.indexOf(currentNode);
if (currentNodeIndex != -1) {
// This node of the repeat node-set points to an inserted node
if (currentNodeIndex > clonedNodesIndex) {
clonedNodesIndex = currentNodeIndex; // prefer nodes inserted last
newRepeatIndex = currentRepeatIndex;
}
// Stop if this node of the repeat node-set points to the last inserted node
if (clonedNodesIndex == clonedNodes.size() - 1)
break;
}
}
}
}
if (newRepeatIndex != -1) {
// This xforms:repeat affected by the change
// "The index for any repeating sequence that is bound
// to the homogeneous collection where the node was
// added is updated to point to the newly added node."
currentControlsState.updateRepeatIndex(repeatId, newRepeatIndex);
// First step: set all children indexes to 0
final List nestedRepeatIds = currentControlsState.getNestedRepeatIds(xformsControls, repeatId);
if (nestedRepeatIds != null) {
for (Iterator j = nestedRepeatIds.iterator(); j.hasNext();) {
final String nestedRepeatId = (String) j.next();
currentControlsState.updateRepeatIndex(nestedRepeatId, 0);
}
}
foundXFormsControl = XFormsControl;
}
if (foundXFormsControl == null) {
// Still not found a control. Make sure the bounds of this
// xforms:repeat are correct for the rest of the visit.
final int adjustedNewIndex;
{
final int newIndex = ((Integer) currentControlsState.getRepeatIdToIndex().get(repeatId)).intValue();
// Adjust bounds if necessary
if (newIndex < 1)
adjustedNewIndex = 1;
else if (newIndex > repeatNodeSet.size())
adjustedNewIndex = repeatNodeSet.size();
else
adjustedNewIndex = newIndex;
}
// Set index
currentControlsState.updateRepeatIndex(repeatId, adjustedNewIndex);
}
} else {
// Make sure the index is set to zero when the node-set is empty
currentControlsState.updateRepeatIndex(repeatId, 0);
}
} else {
// This is a child xforms:repeat of a matching xforms:repeat
// Second step: update non-empty repeat indexes to the appropriate value
// "The indexes for inner nested repeat collections are re-initialized to startindex."
// NOTE: We do this, but we also adjust the index:
// "The index for this repeating structure is initialized to the
// value of startindex. If the initial startindex is less than 1 it
// defaults to 1. If the index is greater than the initial node-set
// then it defaults to the size of the node-set."
if (repeatNodeSet != null && repeatNodeSet.size() > 0) {
int newIndex = repeatControlInfo.getStartIndex();
if (newIndex < 1)
newIndex = 1;
if (newIndex > repeatNodeSet.size())
newIndex = repeatNodeSet.size();
currentControlsState.updateRepeatIndex(repeatId, newIndex);
} else {
// Make sure the index is set to zero when the node-set is empty
// (although this should already have been done above by the
// enclosing xforms:repeat)
currentControlsState.updateRepeatIndex(repeatId, 0);
}
}
}
}
public void endVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
if (foundXFormsControl == XFormsControl)
foundXFormsControl = null;
}
}
});
}
/**
* Adjust indexes after a deletion.
*
* @param pipelineContext
* @param xformsControls
* @param previousRepeatIdToIndex
* @param repeatIndexUpdates
* @param nestedRepeatIndexUpdates
* @param nodeToRemove
*/
public static void adjustIndexesForDelete(PipelineContext pipelineContext, final XFormsControls xformsControls,
final Map previousRepeatIdToIndex, final Map repeatIndexUpdates,
final Map nestedRepeatIndexUpdates, final Node nodeToRemove) {
// NOTE: The code below assumes that there are no nested repeats bound to node-sets that intersect
xformsControls.getCurrentControlsState().visitControlsFollowRepeats(pipelineContext, xformsControls, new XFormsControls.XFormsControlVisitorListener() {
private XFormsControl foundXFormsControl;
private boolean reinitializeInner;
public void startVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
// Found an xforms:repeat
final XFormsRepeatControl repeatControlInfo = (XFormsRepeatControl) XFormsControl;
final String repeatId = repeatControlInfo.getOriginalId();
final List repeatNodeSet = xformsControls.getCurrentNodeset();
if (foundXFormsControl == null) {
// We are not yet inside a matching xforms:repeat
if (repeatNodeSet != null && repeatNodeSet.size() > 0) {
// Find whether one node of the repeat node-set contains the inserted node
for (Iterator i = repeatNodeSet.iterator(); i.hasNext();) {
final NodeInfo currentNode = (NodeInfo) i.next();
if ((currentNode instanceof NodeWrapper) // underlying node can't match if it's not a NodeWrapper
&& ((NodeWrapper) currentNode).getUnderlyingNode() == nodeToRemove) {
// Found xforms:repeat affected by the change
final int newIndex;
if (repeatNodeSet.size() == 1) {
// Delete the last element of the collection: the index must be set to 0
newIndex = 0;
reinitializeInner = false;
} else {
// Current index for this repeat
final int currentIndex = ((Integer) previousRepeatIdToIndex.get(repeatId)).intValue();
// Index of deleted element for this repeat
final int deletionIndexInRepeat = repeatNodeSet.indexOf(nodeToRemove) + 1;
if (currentIndex == deletionIndexInRepeat) {
if (deletionIndexInRepeat == repeatNodeSet.size()) {
// o "When the last remaining item in the collection is removed,
// the index position becomes 0."
// o "When the index was pointing to the deleted node, which was
// the last item in the collection, the index will point to the new
// last node of the collection and the index of inner repeats is
// reinitialized."
newIndex = currentIndex - 1;
reinitializeInner = true;
} else {
// o "When the index was pointing to the deleted node, which was
// not the last item in the collection, the index position is not
// changed and the index of inner repeats is re-initialized."
newIndex = currentIndex;
reinitializeInner = true;
}
} else {
// "The index should point to the same node
// after a delete as it did before the delete"
if (currentIndex < deletionIndexInRepeat) {
newIndex = currentIndex;
} else {
newIndex = currentIndex - 1;
}
reinitializeInner = false;
}
}
repeatIndexUpdates.put(repeatId, new Integer(newIndex));
// Handle children
if (reinitializeInner) {
// First step: set all children indexes to 0
final List nestedRepeatIds = xformsControls.getCurrentControlsState().getNestedRepeatIds(xformsControls, repeatId);
if (nestedRepeatIds != null) {
for (Iterator j = nestedRepeatIds.iterator(); j.hasNext();) {
final String nestedRepeatId = (String) j.next();
repeatIndexUpdates.put(nestedRepeatId, new Integer(0));
nestedRepeatIndexUpdates.put(nestedRepeatId, "");
}
}
}
foundXFormsControl = XFormsControl;
break;
}
}
}
}
}
}
public void endVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
if (foundXFormsControl == XFormsControl)
foundXFormsControl = null;
}
}
});
}
/**
* Adjust controls ids that could have gone out of bounds.
*
* What we do here is that we bring back the index within bounds. The spec does not cover this
* scenario.
*/
public static void adjustRepeatIndexes(PipelineContext pipelineContext, final XFormsControls xformsControls, final Map forceUpdate) {
// We don't rebuild before iterating because the caller has already rebuilt
final XFormsControls.ControlsState currentControlsState = xformsControls.getCurrentControlsState();
currentControlsState.visitControlsFollowRepeats(pipelineContext, xformsControls, new XFormsControls.XFormsControlVisitorListener() {
public void startVisitControl(XFormsControl XFormsControl) {
if (XFormsControl instanceof XFormsRepeatControl) {
// Found an xforms:repeat
final XFormsRepeatControl repeatControlInfo = (XFormsRepeatControl) XFormsControl;
final String repeatId = repeatControlInfo.getOriginalId();
final List repeatNodeSet = xformsControls.getCurrentNodeset();
if (repeatNodeSet != null && repeatNodeSet.size() > 0) {
// Node-set is non-empty
final int adjustedNewIndex;
{
final int newIndex;
if (forceUpdate != null && forceUpdate.get(repeatId) != null) {
// Force update of index to start index
newIndex = repeatControlInfo.getStartIndex();
// NOTE: XForms 1.0 2nd edition actually says "To re-initialize
// a repeat means to change the index to 0 if it is empty,
// otherwise 1." However, for, xforms:insert, we are supposed to
// update to startindex. Here, for now, we decide to use
// startindex for consistency.
// TODO: check latest errata
} else {
// Just use current index
newIndex = ((Integer) currentControlsState.getRepeatIdToIndex().get(repeatId)).intValue();
}
// Adjust bounds if necessary
if (newIndex < 1)
adjustedNewIndex = 1;
else if (newIndex > repeatNodeSet.size())
adjustedNewIndex = repeatNodeSet.size();
else
adjustedNewIndex = newIndex;
}
// Set index
currentControlsState.updateRepeatIndex(repeatId, adjustedNewIndex);
} else {
// Node-set is empty, make sure index is set to 0
currentControlsState.updateRepeatIndex(repeatId, 0);
}
}
}
public void endVisitControl(XFormsControl XFormsControl) {
}
});
}
} |
package com.xj.scud.route;
import com.xj.scud.commons.MurmurHash;
import io.netty.channel.Channel;
import java.util.Iterator;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class WeightRoute extends RpcRoute {
private TreeMap<Long, String> nodes = new TreeMap<>();
protected ReadWriteLock lock = new ReentrantReadWriteLock();
private Random random = new Random();
public Channel getServer() {
SortedMap<Long, String> tail = nodes.tailMap(random.nextLong());
String ni;
if (tail.isEmpty()) {
ni = nodes.get(nodes.firstKey());
} else {
ni = tail.get(tail.firstKey());
}
Channel channel = serverNodes.get(ni);//channelremove
if (channel == null) {
lock.readLock().lock();
try {
tail = nodes.tailMap(random.nextLong());
if (tail.isEmpty()) {
ni = nodes.get(nodes.firstKey());
} else {
ni = tail.get(tail.firstKey());
}
channel = serverNodes.get(ni);
} finally {
lock.readLock().unlock();
}
}
return channel;
}
@Override
public boolean addServerNode(NodeInfo node, Channel channel) {
int w = 160 * node.getWeight();
String key = node.getPath();
TreeMap<Long, String> newMap = new TreeMap<>();
lock.writeLock().lock();
try {
newMap.putAll(nodes);
for (int i = 0; i < w; i++) {
key = key + "-node-" + i;
newMap.put(MurmurHash.hash64A(key.getBytes(), key.length()), key);
}
serverNodes.put(key, channel);
nodes = newMap;
} finally {
lock.writeLock().unlock();
}
return true;
}
@Override
public Channel getServer(String key) {
Channel channel = serverNodes.get(key);//channelremove
if (channel == null) {
lock.readLock().lock();
try {
channel = serverNodes.get(key);
} finally {
lock.readLock().unlock();
}
}
return channel;
}
@Override
public boolean removeServerNode(String key) {
boolean res = false;
serverNodes.remove(key);
TreeMap<Long, String> newMap = new TreeMap<>();
lock.writeLock().lock();
try {
Iterator<Long> it = nodes.keySet().iterator();
while (it.hasNext()) {
Long key_ = it.next();
String value = nodes.get(key_);
if (!key.equals(value)) {
newMap.put(key_, value);
}
}
nodes = newMap;
} finally {
lock.writeLock().unlock();
}
return res;
}
@Override
public int size() {
return serverNodes.size();
}
} |
package org.xwiki.rendering.internal.macro.wikibridge;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.observation.ObservationManager;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.MacroBlock;
import org.xwiki.rendering.block.MacroMarkerBlock;
import org.xwiki.rendering.block.MetaDataBlock;
import org.xwiki.rendering.block.ParagraphBlock;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.internal.macro.script.NestedScriptMacroEnabled;
import org.xwiki.rendering.internal.transformation.MutableRenderingContext;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.MacroExecutionException;
import org.xwiki.rendering.macro.descriptor.MacroDescriptor;
import org.xwiki.rendering.macro.descriptor.ParameterDescriptor;
import org.xwiki.rendering.macro.parameter.MacroParameterException;
import org.xwiki.rendering.macro.wikibridge.WikiMacro;
import org.xwiki.rendering.macro.wikibridge.WikiMacroExecutionFinishedEvent;
import org.xwiki.rendering.macro.wikibridge.WikiMacroExecutionStartsEvent;
import org.xwiki.rendering.macro.wikibridge.WikiMacroParameters;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.MacroTransformationContext;
import org.xwiki.rendering.transformation.RenderingContext;
import org.xwiki.rendering.transformation.Transformation;
import org.xwiki.rendering.transformation.TransformationContext;
/**
* Default implementation of {@link WikiMacro}.
*
* @version $Id$
* @since 2.0M1
*/
public class DefaultWikiMacro implements WikiMacro, NestedScriptMacroEnabled
{
/**
* The key under which macro context will be available in the XWikiContext for scripts.
*/
private static final String MACRO_KEY = "macro";
/**
* Macro hint for {@link Transformation} component. Same as MACRO_KEY (Check style fix).
*/
private static final String MACRO_HINT = MACRO_KEY;
/**
* The key under which macro body will be available inside macro context.
*/
private static final String MACRO_CONTENT_KEY = "content";
/**
* The key under which macro parameters will be available inside macro context.
*/
private static final String MACRO_PARAMS_KEY = "params";
/**
* The key under which macro transformation context will be available inside macro context.
*/
private static final String MACRO_CONTEXT_KEY = "context";
/**
* The key under which macro can directly return the resulting {@link List} of {@link Block}.
*/
private static final String MACRO_RESULT_KEY = "result";
/**
* Event sent before wiki macro execution.
*/
private static final WikiMacroExecutionStartsEvent STARTEXECUTION_EVENT = new WikiMacroExecutionStartsEvent();
/**
* Event sent after wiki macro execution.
*/
private static final WikiMacroExecutionFinishedEvent ENDEXECUTION_EVENT = new WikiMacroExecutionFinishedEvent();
/**
* The {@link MacroDescriptor} for this macro.
*/
private MacroDescriptor descriptor;
/**
* Document which contains the definition of this macro.
*/
private DocumentReference macroDocumentReference;
/**
* User to be used to check rights for the macro.
*/
private DocumentReference macroAuthor;
/**
* Whether this macro supports inline mode or not.
*/
private boolean supportsInlineMode;
/**
* Macro content.
*/
private XDOM content;
/**
* Syntax id.
*/
private Syntax syntax;
/**
* The component manager used to lookup other components.
*/
private ComponentManager componentManager;
/**
* Constructs a new {@link DefaultWikiMacro}.
*
* @param macroDocumentReference the name of the document which contains the definition of this macro
* @param supportsInlineMode says if macro support inline mode or not
* @param descriptor the {@link MacroDescriptor} describing this macro.
* @param macroContent macro content to be evaluated.
* @param syntax syntax of the macroContent source.
* @param componentManager {@link ComponentManager} component used to look up for other components.
* @since 2.3M1
*/
public DefaultWikiMacro(DocumentReference macroDocumentReference, DocumentReference macroAuthor,
boolean supportsInlineMode, MacroDescriptor descriptor, XDOM macroContent, Syntax syntax,
ComponentManager componentManager)
{
this.macroDocumentReference = macroDocumentReference;
this.macroAuthor = macroAuthor;
this.supportsInlineMode = supportsInlineMode;
this.descriptor = descriptor;
this.content = macroContent;
this.syntax = syntax;
this.componentManager = componentManager;
}
@Override
public List<Block> execute(WikiMacroParameters parameters, String macroContent, MacroTransformationContext context)
throws MacroExecutionException
{
validate(parameters, macroContent);
// Parse the wiki macro content.
XDOM xdom = prepareWikiMacroContent(context);
// Prepare macro context.
Map<String, Object> macroBinding = new HashMap<String, Object>();
macroBinding.put(MACRO_PARAMS_KEY, parameters);
macroBinding.put(MACRO_CONTENT_KEY, macroContent);
macroBinding.put(MACRO_CONTEXT_KEY, context);
macroBinding.put(MACRO_RESULT_KEY, null);
// Extension point to add more wiki macro bindings
try {
List<WikiMacroBindingInitializer> bindingInitializers =
this.componentManager.getInstanceList(WikiMacroBindingInitializer.class);
for (WikiMacroBindingInitializer bindingInitializer : bindingInitializers) {
bindingInitializer.initialize(this.macroDocumentReference, parameters, macroContent, context,
macroBinding);
}
} catch (ComponentLookupException e) {
// TODO: we should probably log something but that should never happen
}
// Execute the macro
ObservationManager observation = null;
try {
observation = this.componentManager.getInstance(ObservationManager.class);
} catch (ComponentLookupException e) {
// TODO: maybe log something
}
// Get XWiki context
Map<String, Object> xwikiContext = null;
try {
Execution execution = this.componentManager.getInstance(Execution.class);
ExecutionContext econtext = execution.getContext();
if (econtext != null) {
xwikiContext = (Map<String, Object>) execution.getContext().getProperty("xwikicontext");
}
} catch (ComponentLookupException e) {
// TODO: maybe log something
}
try {
Transformation macroTransformation = this.componentManager.getInstance(Transformation.class, MACRO_HINT);
if (xwikiContext != null) {
// Place macro context inside xwiki context ($xcontext.macro).
xwikiContext.put(MACRO_KEY, macroBinding);
}
MacroBlock wikiMacroBlock = context.getCurrentMacroBlock();
MacroMarkerBlock wikiMacroMarker =
new MacroMarkerBlock(wikiMacroBlock.getId(), wikiMacroBlock.getParameters(),
wikiMacroBlock.getContent(), xdom.getChildren(), wikiMacroBlock.isInline());
// make sure to use provided metadatas
MetaDataBlock metaDataBlock =
new MetaDataBlock(Collections.<Block> singletonList(wikiMacroMarker), xdom.getMetaData());
// Make sure the context XDOM contains the wiki macro content
wikiMacroBlock.getParent().replaceChild(metaDataBlock, wikiMacroBlock);
try {
if (observation != null) {
observation.notify(STARTEXECUTION_EVENT, this, macroBinding);
}
// Perform internal macro transformations.
TransformationContext txContext = new TransformationContext(context.getXDOM(), this.syntax);
txContext.setId(context.getId());
RenderingContext renderingContext = componentManager.getInstance(RenderingContext.class);
((MutableRenderingContext) renderingContext).transformInContext(macroTransformation, txContext,
wikiMacroMarker);
} finally {
// Restore context XDOM to its previous state
metaDataBlock.getParent().replaceChild(wikiMacroBlock, metaDataBlock);
}
return extractResult(wikiMacroMarker.getChildren(), macroBinding, context);
} catch (Exception ex) {
throw new MacroExecutionException("Error while performing internal macro transformations", ex);
} finally {
if (xwikiContext != null) {
xwikiContext.remove(MACRO_KEY);
}
if (observation != null) {
observation.notify(ENDEXECUTION_EVENT, this);
}
}
}
/**
* Extract result of the wiki macro execution.
*
* @param blocks the wiki macro content
* @param macroContext the wiki macro context
* @param context the macro execution context
* @return the result
*/
private List<Block> extractResult(List<Block> blocks, Map<String, Object> macroContext,
MacroTransformationContext context)
{
Object resultObject = macroContext.get(MACRO_RESULT_KEY);
List<Block> result;
if (resultObject != null && resultObject instanceof List) {
result = (List<Block>) macroContext.get(MACRO_RESULT_KEY);
} else {
result = blocks;
// If in inline mode remove any top level paragraph.
if (context.isInline()) {
removeTopLevelParagraph(result);
}
}
return result;
}
/**
* Removes any top level paragraph since for example for the following use case we don't want an extra paragraph
* block: <code>= hello {{velocity}}world{{/velocity}}</code>.
*
* @param blocks the blocks to check and convert
*/
private void removeTopLevelParagraph(List<Block> blocks)
{
// Remove any top level paragraph so that the result of a macro can be used inline for example.
// We only remove the paragraph if there's only one top level element and if it's a paragraph.
if ((blocks.size() == 1) && blocks.get(0) instanceof ParagraphBlock) {
Block paragraphBlock = blocks.remove(0);
blocks.addAll(0, paragraphBlock.getChildren());
}
}
/**
* Clone and filter wiki macro content depending of the context.
*
* @param context the macro execution context
* @return the cleaned wiki macro content
*/
private XDOM prepareWikiMacroContent(MacroTransformationContext context)
{
XDOM xdom = this.content.clone();
// Macro code segment is always parsed into a separate xdom document. Now if this code segment starts with
// another macro block, it will always be interpreted as a block macro regardless of the current wiki macro's
// context (because as far as the nested macro is concerned, it starts on a new line). This will introduce
// unnecessary paragraph elements when the wiki macro is used inline, so we need to force such opening macro
// blocks to behave as inline macros if the wiki macro is used inline.
if (context.isInline()) {
List<Block> children = xdom.getChildren();
if (children.size() > 0 && children.get(0) instanceof MacroBlock) {
MacroBlock old = (MacroBlock) children.get(0);
MacroBlock replacement = new MacroBlock(old.getId(), old.getParameters(), old.getContent(), true);
xdom.replaceChild(replacement, old);
}
}
return xdom;
}
/**
* Check validity of the given macro parameters and content.
*
* @param parameters the macro parameters
* @param macroContent the macro content
* @throws MacroExecutionException given parameters of content is invalid
*/
private void validate(WikiMacroParameters parameters, String macroContent) throws MacroExecutionException
{
// First verify that all mandatory parameters are provided.
// Note that we currently verify automatically mandatory parameters in Macro Transformation but for the moment
// this is only checked for Java-based macros. Hence why we need to check here too.
Map<String, ParameterDescriptor> parameterDescriptors = getDescriptor().getParameterDescriptorMap();
for (String parameterName : parameterDescriptors.keySet()) {
ParameterDescriptor parameterDescriptor = parameterDescriptors.get(parameterName);
Object parameterValue = parameters.get(parameterName);
if (parameterDescriptor.isMandatory() && (null == parameterValue)) {
throw new MacroParameterException(String.format("Parameter [%s] is mandatory", parameterName));
}
// Set default parameter value if applicable.
Object parameterDefaultValue = parameterDescriptor.getDefaultValue();
if (parameterValue == null && parameterDefaultValue != null) {
parameters.set(parameterName, parameterDefaultValue);
}
}
// Verify the a macro content is not empty if it was declared mandatory.
if (getDescriptor().getContentDescriptor() != null && getDescriptor().getContentDescriptor().isMandatory()) {
if (macroContent == null || macroContent.length() == 0) {
throw new MacroExecutionException("Missing macro content: this macro requires content (a body)");
}
}
}
@Override
public MacroDescriptor getDescriptor()
{
return this.descriptor;
}
@Override
public int getPriority()
{
return 1000;
}
@Override
public String getId()
{
return this.descriptor.getId().getId();
}
@Override
public DocumentReference getDocumentReference()
{
return this.macroDocumentReference;
}
@Override
public DocumentReference getAuthorReference()
{
return this.macroAuthor;
}
@Override
public int compareTo(Macro< ? > macro)
{
return getPriority() - macro.getPriority();
}
@Override
public boolean supportsInlineMode()
{
return this.supportsInlineMode;
}
} |
package org.gemoc.gemoc_language_workbench.extensions.sirius.modelloader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.sirius.business.api.session.Session;
import org.eclipse.sirius.business.api.session.SessionManager;
import org.eclipse.sirius.common.tools.api.resource.ResourceSetFactory;
import org.eclipse.sirius.diagram.DDiagram;
import org.eclipse.sirius.diagram.business.internal.metamodel.spec.DSemanticDiagramSpec;
import org.eclipse.sirius.diagram.description.Layer;
import org.eclipse.sirius.diagram.tools.internal.command.ChangeLayerActivationCommand;
import org.eclipse.sirius.diagram.ui.tools.api.editor.DDiagramEditor;
import org.eclipse.sirius.diagram.ui.tools.api.graphical.edit.palette.ToolFilter;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIManager;
import org.eclipse.sirius.viewpoint.DRepresentation;
import org.eclipse.sirius.viewpoint.DView;
import org.eclipse.sirius.viewpoint.description.tool.AbstractToolDescription;
import org.eclipse.ui.IEditorPart;
import org.eclipse.xtext.resource.XtextPlatformResourceURIHandler;
import org.eclipse.xtext.util.StringInputStream;
import org.gemoc.commons.eclipse.emf.EMFResource;
import org.gemoc.execution.engine.core.CommandExecution;
import org.gemoc.execution.engine.core.DebugURIHandler;
import org.gemoc.gemoc_language_workbench.api.core.ExecutionMode;
import org.gemoc.gemoc_language_workbench.api.core.IExecutionContext;
import org.gemoc.gemoc_language_workbench.api.core.IModelLoader;
import org.gemoc.gemoc_language_workbench.extensions.sirius.debug.DebugSessionFactory;
import org.gemoc.gemoc_language_workbench.extensions.sirius.services.AbstractGemocAnimatorServices;
import fr.obeo.dsl.debug.ide.sirius.ui.services.AbstractDSLDebuggerServices;
public class DefaultModelLoader implements IModelLoader {
public final static String MODEL_ID = "org.gemoc.gemoc_modeling_workbench.ui.debugModel";
public Resource loadModel(IExecutionContext context)
throws RuntimeException {
Resource resource = null;
ResourceSet resourceSet;
resourceSet = new ResourceSetImpl();
resource = resourceSet.createResource(context.getRunConfiguration().getExecutedModelURI());
try {
resource.load(null);
} catch (IOException e) {
new RuntimeException(e);
}
return resource;
}
public Resource loadModelForAnimation(IExecutionContext context)
throws RuntimeException {
Resource resource = null;
ResourceSet resourceSet;
if (context.getExecutionMode().equals(ExecutionMode.Animation)
&& context.getRunConfiguration().getAnimatorURI() != null) {
killPreviousSiriusSession(context.getRunConfiguration()
.getAnimatorURI());
Session session;
try {
session = openNewSiriusSession(context, context.getRunConfiguration()
.getAnimatorURI());
resourceSet = session.getTransactionalEditingDomain()
.getResourceSet();
} catch (CoreException e) {
throw new RuntimeException(e);
}
resource = resourceSet.getResources().get(0);
return resource;
} else
{
//animator not available; fall back to normal run
return loadModel(context);
}
}
private void killPreviousSiriusSession(URI sessionResourceURI) {
Session session = SessionManager.INSTANCE
.getExistingSession(sessionResourceURI);
if (session != null) {
session.close(new NullProgressMonitor());
SessionManager.INSTANCE.remove(session);
}
}
private Session openNewSiriusSession(IExecutionContext context, URI sessionResourceURI)
throws CoreException
{
boolean useMelange =context.getRunConfiguration().getMelangeQuery() != null && !context.getRunConfiguration().getMelangeQuery().isEmpty();
// calculating model URI as MelangeURI
URI modelURI = useMelange ? context.getRunConfiguration().getExecutedModelAsMelangeURI() : context.getRunConfiguration().getExecutedModelURI();
// create and configure resource set
HashMap<String, String> nsURIMapping = getnsURIMapping(context);
final ResourceSet rs = createAndConfigureResourceSet(modelURI, nsURIMapping);
// load model resource and resolve all proxies
Resource r = rs.getResource(modelURI, true);
// calculating aird URI
URI airdURI = useMelange ? URI.createURI(sessionResourceURI.toString().replace("platform:/", "melange:/")): sessionResourceURI;
//URI airdURI = sessionResourceURI;
// create and load sirius session
final Session session = DebugSessionFactory.INSTANCE.createSession(rs, airdURI);
final IProgressMonitor monitor = new NullProgressMonitor();
final TransactionalEditingDomain editingDomain = session.getTransactionalEditingDomain();
session.open(monitor);
EcoreUtil.resolveAll(rs);
// activating layers
for (DView view : session.getSelectedViews()) {
for (DRepresentation representation : view
.getOwnedRepresentations()) {
final DSemanticDiagramSpec diagram = (DSemanticDiagramSpec) representation;
final List<EObject> elements = new ArrayList<EObject>();
elements.add(diagram);
final IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation,
monitor);
if (editorPart instanceof DDiagramEditor) {
((DDiagramEditor)editorPart).getPaletteManager().addToolFilter(new ToolFilter() {
@Override
public boolean filter(DDiagram diagram, AbstractToolDescription tool) {
return true;
}
});
}
RecordingCommand command = new RecordingCommand(
editingDomain, "Activating animator and debug layers") {
@Override
protected void doExecute() {
for (Layer l : diagram.getDescription()
.getAdditionalLayers()) {
boolean mustBeActive = AbstractDSLDebuggerServices.LISTENER
.isRepresentationToRefresh(MODEL_ID,
diagram.getDescription().getName(), l.getName())
|| AbstractGemocAnimatorServices.ANIMATOR
.isRepresentationToRefresh(
diagram.getDescription().getName(),
l.getName());
if (mustBeActive
&& !diagram.getActivatedLayers()
.contains(l)) {
ChangeLayerActivationCommand c = new ChangeLayerActivationCommand(
editingDomain, diagram, l, monitor);
c.execute();
}
}
}
};
CommandExecution.execute(editingDomain, command);
}
}
return session;
}
private ResourceSet createAndConfigureResourceSet(URI modelURI, HashMap<String, String> nsURIMapping)
{
final ResourceSet rs = ResourceSetFactory.createFactory().createResourceSet(modelURI);
// fix sirius to prevent non intentional model savings
rs.getURIConverter().getURIHandlers().add(0, new DebugURIHandler());
final String fileExtension = modelURI.fileExtension();
// indicates which melange query should be added to the xml uri handler for a given extension
final XMLURIHandler handler = new XMLURIHandler(modelURI.query(), fileExtension); // use to resolve cross ref URI during XMI parsing
handler.setResourceSet(rs);
rs.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, handler);
rs.setURIConverter(new MelangeURIConverter(fileExtension, nsURIMapping));
return rs;
}
// TODO must be extended to support more complex mappings, currently use only the first package in the genmodel
// TODO actually, melange should produce the nsURI mapping and register it in some way so we can retreive it
protected HashMap<String, String> getnsURIMapping(IExecutionContext context){
HashMap<String, String> nsURIMapping = new HashMap<String, String>();
// dirty hack, simply open the original file in a separate ResourceSet and ask its root element class nsURI
String melangeQuery = context.getRunConfiguration().getExecutedModelAsMelangeURI().query();
if(melangeQuery!= null && !melangeQuery.isEmpty()){
String targetNsUri = melangeQuery.substring(melangeQuery.indexOf('=')+1);
Object o = EMFResource.getFirstContent(context.getRunConfiguration().getExecutedModelURI());
if(o instanceof EObject){
// DIRTY, try to find best nsURI, need major refactoring in Melange,
EPackage rootPackage = ((EObject)o).eClass().getEPackage();
while(rootPackage.getESuperPackage() != null){
rootPackage = rootPackage.getESuperPackage();
}
nsURIMapping.put(rootPackage.getNsURI(),targetNsUri);
}
}
// a better solution would be to add the relevant data in xdsml and look for the mapping there
/*
String xdsmluri = context.getLanguageDefinitionExtension().getXDSMLFilePath();
if (!xdsmluri.startsWith("platform:/plugin"))
xdsmluri = "platform:/plugin" + xdsmluri;
Object o = EMFResource.getFirstContent(xdsmluri);
if(o != null && o instanceof LanguageDefinition){
LanguageDefinition ld = (LanguageDefinition)o;
}*/
return nsURIMapping;
}
class MelangeURIConverter extends ExtensibleURIConverterImpl
{
private String _fileExtension;
private HashMap<String, String> _nsURIMapping;
public MelangeURIConverter(String fileExtension, HashMap<String, String> nsURIMapping)
{
_fileExtension = fileExtension;
_nsURIMapping = nsURIMapping;
}
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException
{
InputStream result = null;
// the URI to use for model loading is not melange:/... but platform:/... and without the ?xx=...
URI uriToUse = uri;
boolean useSuperMethod = true;
if (uri.scheme().equals("melange"))
{
String uriAsString = uri.toString().replace("melange:/", "platform:/");
if (uri.fileExtension() != null
&& uri.fileExtension().equals(_fileExtension))
{
useSuperMethod = false;
uriAsString = uriAsString.substring(0, uriAsString.indexOf('?'));
uriToUse = URI.createURI(uriAsString);
InputStream originalInputStream = null;
try
{
originalInputStream = super.createInputStream(uriToUse, options);
String originalContent = convertStreamToString(originalInputStream);
String modifiedContent = originalContent;
for(Entry<String, String> entry : _nsURIMapping.entrySet()){
modifiedContent = modifiedContent.replace(entry.getKey(), entry.getValue());
}
result = new StringInputStream(modifiedContent);
}
finally
{
if (originalInputStream != null)
{
originalInputStream.close();
}
}
}
else
{
uriToUse = URI.createURI(uriAsString);
}
}
if (useSuperMethod)
{
result = super.createInputStream(uriToUse, options);
}
// // making sure that uri can be modified
// if (uri.fileExtension() != null
// && uri.fileExtension().equals(_fileExtension)
// && uri.scheme().equals("melange"))
// String uriAsString = uri.toString().replace("melange:/", "platform:/");
// uriAsString = uriAsString.substring(0, uriAsString.indexOf('?'));
// uriToUse = URI.createURI(uriAsString);
// InputStream originalInputStream = null;
// try
// originalInputStream = super.createInputStream(uriToUse, options);
// String originalContent = convertStreamToString(originalInputStream);
// result = new StringInputStream(modifiedContent);
// finally
// if (originalInputStream != null)
// originalInputStream.close();
// else
return result;
}
private String convertStreamToString(java.io.InputStream is)
{
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
class XMLURIHandler extends XtextPlatformResourceURIHandler
{
private String _queryParameters;
private String _fileExtension;
public XMLURIHandler(String queryParameters, String fileExtension)
{
_queryParameters = queryParameters;
if(_queryParameters==null)
_queryParameters="";
else
_queryParameters = "?"+_queryParameters;
_fileExtension = fileExtension;
}
@Override
public URI resolve(URI uri)
{
URI resolvedURI = super.resolve(uri);
if (resolvedURI.scheme().equals("melange")
&& resolvedURI.fileExtension().equals(_fileExtension)
&& !resolvedURI.toString().contains("?"))
{
String fileExtensionWithPoint = "." + _fileExtension;
int lastIndexOfFileExtension = resolvedURI.toString().lastIndexOf(fileExtensionWithPoint);
String part1 = resolvedURI.toString().substring(0, lastIndexOfFileExtension);
String part2 = fileExtensionWithPoint + _queryParameters;
String part3 = resolvedURI.toString().substring(lastIndexOfFileExtension + fileExtensionWithPoint.length());
String newURIAsString = part1 + part2 + part3;
return URI.createURI(newURIAsString);
}
return resolvedURI;
}
}
} |
package com.bitdubai.fermat_cry_plugin.layer.crypto_vault.developer.bitdubai.version_1.structure;
import com.bitdubai.fermat_api.layer.all_definition.event.PlatformEvent;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.ProtocolStatus;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.crypto_transactions.CryptoStatus;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseTransactionFailedException;
import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.DealsWithErrors;
import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.DealsWithEvents;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventManager;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventType;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.events.IncomingCryptoIdentifiedEvent;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.events.IncomingCryptoOnCryptoNetworkEvent;
import com.bitdubai.fermat_cry_plugin.layer.crypto_vault.developer.bitdubai.version_1.exceptions.CantExecuteQueryException;
import com.bitdubai.fermat_cry_plugin.layer.crypto_vault.developer.bitdubai.version_1.exceptions.UnexpectedResultReturnedFromDatabaseException;
import org.bitcoinj.core.Wallet;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class CryptoVaultDatabaseActions implements DealsWithEvents, DealsWithErrors{
/**
* CryptoVaultDatabaseActions member variables
*/
Database database;
Wallet vault;
/**
* DealsWithEvents interface member variables
*/
EventManager eventManager;
/**
* DealsWithErrors interface member variables
*/
ErrorManager errorManager;
/**
* DealsWithErrors interface implementation
* @param errorManager
*/
@Override
public void setErrorManager(ErrorManager errorManager) {
this.errorManager = errorManager;
}
@Override
public void setEventManager(EventManager eventManager) {
this.eventManager = eventManager;
}
/**
* Constructor
* @param database
*/
public CryptoVaultDatabaseActions(Database database, ErrorManager errorManager, EventManager eventManager){
this.database = database;
this.eventManager = eventManager;
this.errorManager = errorManager;
}
public void setVault(Wallet vault){
this.vault = vault;
}
public void saveIncomingTransaction(String txId, String txHash) throws CantExecuteQueryException, CantLoadTableToMemoryException {
/**
* I need to validate that this is not a transaction I already saved because it might be from a transaction
* generated by our wallet.
*/
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, txHash, DatabaseFilterType.EQUAL);
cryptoTxTable.loadToMemory();
if (cryptoTxTable.getRecords().isEmpty()){
/**
* If this is not a transaction that we previously generated, then I will identify it as a new transaction.
*/
DatabaseTransaction dbTx = this.database.newTransaction();
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
DatabaseTableRecord incomingTxRecord = cryptoTxTable.getEmptyRecord();
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString());
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, txHash);
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, ProtocolStatus.TO_BE_NOTIFIED.toString());
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME, CryptoStatus.ON_CRYPTO_NETWORK.toString());
dbTx.addRecordToInsert(cryptoTxTable, incomingTxRecord);
try {
this.database.executeTransaction(dbTx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error in saveIncomingTransaction method.", e, "Transaction Hash:" + txHash, "Error in database plugin.");
}
/**
* after I save the transaction in the database and the vault, I'll raise the incoming transaction.
*
*/
PlatformEvent event = new IncomingCryptoOnCryptoNetworkEvent(EventType.INCOMING_CRYPTO_ON_CRYPTO_NETWORK);
eventManager.raiseEvent(event);
}
}
/**
* Validates if the transaction ID passed is new or not. This helps to decide If I need to apply the transactions or not
* @param txId the ID of the transaction
* @return
*/
public boolean isNewFermatTransaction(UUID txId) throws CantExecuteQueryException {
DatabaseTable fermatTxTable;
fermatTxTable = database.getTable(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_NAME);
fermatTxTable.setStringFilter(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString(), DatabaseFilterType.EQUAL);
try {
fermatTxTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error validating transaction in DB.", cantLoadTableToMemory, "Transaction Id:" + txId, "Error in database plugin.");
}
/**
* If I couldnt find any record with this transaction id, then it is a new transactions.
*/
if (fermatTxTable.getRecords().isEmpty())
return true;
else
return false;
}
/**
* I will persist a new crypto transaction generated by our wallet.
*/
public void persistNewTransaction(String txId, String txHash) throws CantExecuteQueryException {
DatabaseTable cryptoTxTable;
DatabaseTransaction dbTx = this.database.newTransaction();
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
DatabaseTableRecord incomingTxRecord = cryptoTxTable.getEmptyRecord();
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString());
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, txHash);
/**
* since the wallet generated this transaction, we dont need to inform it.
*/
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, ProtocolStatus.NO_ACTION_REQUIRED.toString());
/**
* The transaction was just generated by us, si it will be saved in PENDING_SUBMIT just in case we are not connected to the network.
* Then the confidence level will be updated if we were able to send it to the network
*/
incomingTxRecord.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME, CryptoStatus.ON_CRYPTO_NETWORK.toString());
dbTx.addRecordToInsert(cryptoTxTable, incomingTxRecord);
try {
database.executeTransaction(dbTx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error persisting in DB.", e, "Transaction Hash:" + txHash, "Error in database plugin.");
}
}
/**
* Will retrieve all the transactions that are in status pending ProtocolStatus = TO_BE_NOTIFIED
* @return
*/
public HashMap<String, String> getPendingTransactionsHeaders() throws CantExecuteQueryException {
/**
* I need to obtain all the transactions ids with protocol status SENDING_NOTIFIED y TO_BE_NOTIFIED
*/
DatabaseTable cryptoTxTable;
HashMap<String, String> transactionsIds = new HashMap<String, String>();
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
/**
* I get the transaction IDs and Hashes for the TO_BE_NOTIFIED
*/
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, ProtocolStatus.TO_BE_NOTIFIED.toString(), DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
for (DatabaseTableRecord record : cryptoTxTable.getRecords()){
transactionsIds.put(record.getStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME), record.getStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME));
}
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, null, "Error in database plugin.");
}
return transactionsIds;
}
/**
* will update the transaction to the new state
* @param txHash
* @param newState
*/
public void updateCryptoTransactionStatus(String txId, String txHash, CryptoStatus newState) throws CantExecuteQueryException, UnexpectedResultReturnedFromDatabaseException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
DatabaseTableRecord toUpdate;
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId, DatabaseFilterType.EQUAL);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, txHash, DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
if (cryptoTxTable.getRecords().size() > 1)
throw new UnexpectedResultReturnedFromDatabaseException("Unexpected result. More than value returned.", null, "TxHash:" + txHash + " CryptoStatus:" + newState.toString(), "duplicated Transaction Hash.");
else
toUpdate = cryptoTxTable.getRecords().get(0);
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, null, "Error in database plugin.");
}
/**
* I set the Protocol status to the new value
*/
DatabaseTransaction dbTrx = this.database.newTransaction();
toUpdate.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME, newState.toString());
dbTrx.addRecordToUpdate(cryptoTxTable, toUpdate);
try {
database.executeTransaction(dbTrx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error executing query in DB.", e, null, "Error in database plugin.");
}
}
/**
* Will update the protocol status of the passed transaction.
* @param txId
* @param newStatus
*/
public void updateTransactionProtocolStatus(UUID txId, ProtocolStatus newStatus) throws CantExecuteQueryException, UnexpectedResultReturnedFromDatabaseException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString(), DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, "TxId " + txId, "Error in database plugin.");
}
DatabaseTransaction dbTrx = this.database.newTransaction();
DatabaseTableRecord toUpdate=null;
if (cryptoTxTable.getRecords().size() > 1)
throw new UnexpectedResultReturnedFromDatabaseException("Unexpected result. More than value returned.", null, "Txid:" + txId+ " Protocol Status:" + newStatus.toString(), "duplicated Transaction Id.");
else {
toUpdate = cryptoTxTable.getRecords().get(0);
}
/**
* I set the Protocol status to the new value
*/
toUpdate.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, newStatus.toString());
dbTrx.addRecordToUpdate(cryptoTxTable, toUpdate);
try {
database.executeTransaction(dbTrx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error executing query in DB.", e, "TxId " + txId, "Error in database plugin.");
}
}
/**
* returns the current protocol status of this transaction
* @param txId
* @return
*/
public ProtocolStatus getCurrentTransactionProtocolStatus(UUID txId) throws CantExecuteQueryException, UnexpectedResultReturnedFromDatabaseException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString(), DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, "TxId " + txId, "Error in database plugin.");
}
DatabaseTableRecord currentStatus = null;
/**
* I will make sure I only get one result.
*/
if (cryptoTxTable.getRecords().size() > 1)
throw new UnexpectedResultReturnedFromDatabaseException("Unexpected result. More than value returned.", null, "TxId:" + txId.toString(), "duplicated Transaction Hash.");
else
currentStatus = cryptoTxTable.getRecords().get(0);
return ProtocolStatus.valueOf(currentStatus.getStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME));
}
/**
* Gets from database the current CryptoStatus of a transaction.
* @param txId
* @return
* @throws CantExecuteQueryException
* @throws UnexpectedResultReturnedFromDatabaseException
*/
public CryptoStatus getCryptoStatus (String txId) throws CantExecuteQueryException, UnexpectedResultReturnedFromDatabaseException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId.toString(), DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, "TxId " + txId, "Error in database plugin.");
}
DatabaseTableRecord currentRecord = null;
/**
* I will make sure I only get one result.
*/
if (cryptoTxTable.getRecords().size() > 1)
throw new UnexpectedResultReturnedFromDatabaseException("Unexpected result. More than value returned.", null, "TxId:" + txId.toString(), "duplicated Transaction Hash.");
else if (cryptoTxTable.getRecords().size() == 0)
throw new UnexpectedResultReturnedFromDatabaseException("No values returned when trying to get CryptoStatus from transaction in database.", null, "TxId:" + txId.toString(), "transaction not yet persisted in database.");
else
currentRecord = cryptoTxTable.getRecords().get(0);
CryptoStatus cryptoStatus = CryptoStatus.valueOf(currentRecord.getStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME));
return cryptoStatus;
}
/**
* will return true if there are transactions in TO_BE_NOTIFIED status
* @return
*/
@Deprecated
public boolean isPendingTransactions() throws CantExecuteQueryException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME,ProtocolStatus.TO_BE_NOTIFIED.toString() ,DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
return !cryptoTxTable.getRecords().isEmpty();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, null, "Error in database plugin.");
}
}
/**
* Will search for pending transactions to be notified with the passed crypto:_Status
* @param cryptoStatus
* @return
* @throws CantExecuteQueryException
*/
public boolean isPendingTransactions(CryptoStatus cryptoStatus) throws CantExecuteQueryException {
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME,ProtocolStatus.TO_BE_NOTIFIED.toString() ,DatabaseFilterType.EQUAL);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME,cryptoStatus.toString() ,DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
return !cryptoTxTable.getRecords().isEmpty();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, null, "Error in database plugin.");
}
}
/**
* increase by one or resets to zero the counter of transactions found ready to be consumed
* @param newOcurrence
* @return the amount of iterations
* @throws CantExecuteQueryException
*/
public int updateTransactionProtocolStatus(boolean newOcurrence) throws CantExecuteQueryException {
DatabaseTable transactionProtocolStatusTable;
transactionProtocolStatusTable = database.getTable(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS);
try {
transactionProtocolStatusTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
throw new CantExecuteQueryException("Error executing query in DB.", cantLoadTableToMemory, null, "Error in database plugin.");
}
List<DatabaseTableRecord> records = transactionProtocolStatusTable.getRecords();
if (records.isEmpty()){
/**
* there are no records, I will insert the first one that will be always updated
*/
long timestamp = System.currentTimeMillis() / 1000L;
DatabaseTableRecord emptyRecord = transactionProtocolStatusTable.getEmptyRecord();
emptyRecord.setLongValue(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS_TABLE_TIMESTAMP_COLUMN_NAME, timestamp);
emptyRecord.setIntegerValue(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS_TABLE_ocurrences_COLUMN_NAME, 0);
DatabaseTransaction transaction = database.newTransaction();
transaction.addRecordToInsert(transactionProtocolStatusTable, emptyRecord);
try {
database.executeTransaction(transaction);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error trying to insert record in table Transtiion_Protocol_Status table", e, null, "error in Database plugin.");
}
/**
* returns 1
*/
return 0;
}
DatabaseTableRecord record = records.get(0);
DatabaseTransaction dbTx = database.newTransaction();
if (newOcurrence){
/**
* I need to increase the ocurrences counter by one
*/
int ocurrence = record.getIntegerValue(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS_TABLE_ocurrences_COLUMN_NAME);
ocurrence++;
record.setIntegerValue(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS_TABLE_ocurrences_COLUMN_NAME, ocurrence);
dbTx.addRecordToUpdate(transactionProtocolStatusTable, record);
try {
database.executeTransaction(dbTx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error executing query in DB.", e, null, "Error in database plugin.");
}
return ocurrence;
}else {
/**
* I need to reset the counter to 0
*/
record.setIntegerValue(CryptoVaultDatabaseConstants.TRANSITION_PROTOCOL_STATUS_TABLE_ocurrences_COLUMN_NAME, 0);
dbTx.addRecordToUpdate(transactionProtocolStatusTable, record);
try {
database.executeTransaction(dbTx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error executing query in DB.", e, null, "Error in database plugin.");
}
return 0;
}
}
/**
* Insert a new Fermat transaction in the database
* @param txId
* @throws CantExecuteQueryException
*/
public void persistnewFermatTransaction(String txId) throws CantExecuteQueryException {
DatabaseTable fermatTable;
fermatTable = database.getTable(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_NAME);
DatabaseTableRecord insert = fermatTable.getEmptyRecord();
insert.setStringValue(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, txId);
DatabaseTransaction dbTx = database.newTransaction();
dbTx.addRecordToInsert(fermatTable, insert);
try {
database.executeTransaction(dbTx);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error executing query in DB.", e, "TxId: " + txId, "Error in database plugin.");
}
}
/**
* Insert a new transaction with the confidence level or update an outgoing cryptostatus of an existing transaction.
* @param hashAsString
* @param cryptoStatus
* @throws CantExecuteQueryException
*/
public void insertNewTransactionWithNewConfidence(String hashAsString, CryptoStatus cryptoStatus) throws CantExecuteQueryException {
/**
* If a transaction exists in NO_ACTION_REQUIRED, then I will update the status.
* If not, then I will insert a new one.
*/
DatabaseTable cryptoTxTable;
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, hashAsString, DatabaseFilterType.EQUAL);
cryptoTxTable.setStringFilter(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, ProtocolStatus.NO_ACTION_REQUIRED.toString(), DatabaseFilterType.EQUAL);
try {
cryptoTxTable.loadToMemory();
} catch (CantLoadTableToMemoryException e) {
throw new CantExecuteQueryException("Error inserting new transaction because of transaction confidence changed.", e, "Transaction Hash:" + hashAsString + " CryptoStatus:" + cryptoStatus.toString(), "Error in database plugin.");
}
if (cryptoTxTable.getRecords().size() > 0) {
/**
* if I have a transaction with the same hash and status NO_ACTION_REQUIRED
* they I will update the cryptostatus.
*/
DatabaseTableRecord record = cryptoTxTable.getRecords().get(0);
record.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME, cryptoStatus.toString());
DatabaseTransaction transaction = database.newTransaction();
transaction.addRecordToUpdate(cryptoTxTable, record);
try {
database.executeTransaction(transaction);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error inserting new transaction because of transaction confidence changed.", e, "Transaction Hash:" + hashAsString + " CryptoStatus:" + cryptoStatus.toString(), "Error in database plugin.");
}
} else{
/**
* If no record exists, meaning that there is no output, then I will insert a new record and triggered the events.
*/
cryptoTxTable = database.getTable(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_NAME);
DatabaseTableRecord record = cryptoTxTable.getEmptyRecord();
/**
* I generate a new transaction Id
*/
record.setStringValue(CryptoVaultDatabaseConstants.FERMAT_TRANSACTIONS_TABLE_TRX_ID_COLUMN_NAME, UUID.randomUUID().toString());
/**
* I use the same transaction hash
*/
record.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRX_HASH_COLUMN_NAME, hashAsString);
record.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_PROTOCOL_STS_COLUMN_NAME, ProtocolStatus.TO_BE_NOTIFIED.toString());
record.setStringValue(CryptoVaultDatabaseConstants.CRYPTO_TRANSACTIONS_TABLE_TRANSACTION_STS_COLUMN_NAME, cryptoStatus.toString());
DatabaseTransaction dbTran = database.newTransaction();
dbTran.addRecordToInsert(cryptoTxTable, record);
try {
database.executeTransaction(dbTran);
} catch (DatabaseTransactionFailedException e) {
throw new CantExecuteQueryException("Error inserting new transaction because of transaction confidence changed.", e, "Transaction Hash:" + hashAsString + " CryptoStatus:" + cryptoStatus.toString(), "Error in database plugin.");
}
}
}
} |
package org.xwiki.notifications.notifiers.internal.email;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xwiki.notifications.CompositeEvent;
/**
* Sort composite events (wrapped by {@link SortedEvent}) so that it is easy to display a table of content in the email.
*
* @version $Id$
* @since 9.11RC1
*/
public class EventsSorter
{
private List<SortedEvent> sortedEvents = new ArrayList<>();
/**
* Add a new event to take into account.
*
* @param event event to add
* @param html the HTML-rendered version of the event
* @param plainText the plain text-rendered version of the event
*/
public void add(CompositeEvent event, String html, String plainText)
{
sortedEvents.add(new SortedEvent(event, html, plainText));
}
/**
* @return a map of sorted events, grouped by wiki
*/
public Map<String, List<SortedEvent>> sort()
{
// Sort the top level events, that have no parent
Collections.sort(sortedEvents, getSortedEventComparator());
// Group sorted events that concern the same document
groupEventsWithSameDocument();
// Here we are going to store only events that have no parent
List<SortedEvent> topLevelEvents = new ArrayList<>();
// Group events so that children are stored in their parent
for (SortedEvent sortedEvent : sortedEvents) {
SortedEvent nearestParent = findNearestParent(sortedEvent);
if (nearestParent != null) {
nearestParent.addChild(sortedEvent);
} else {
topLevelEvents.add(sortedEvent);
}
}
// Replace the inner list by the hierarchy
this.sortedEvents = topLevelEvents;
// Create a map of sorted events, grouped by wiki
Map<String, List<SortedEvent>> sortedEventsByWikis = new HashMap<>();
for (SortedEvent sortedEvent: sortedEvents) {
String wiki = getWiki(sortedEvent);
List<SortedEvent> list = getList(sortedEventsByWikis, wiki);
list.add(sortedEvent);
}
return sortedEventsByWikis;
}
private Comparator<SortedEvent> getSortedEventComparator()
{
// Sort by document first (if document == null, go last)
// Sort by date (more recent first) then, when document is the same
return (e1, e2) -> {
if (e1.getDocument() == null) {
return e2.getDocument() == null ? 0 : 1;
}
if (e2.getDocument() == null) {
return -1;
}
int documentSort = e1.getDocument().compareTo(e2.getDocument());
if (documentSort == 0) {
return e2.getDate().compareTo(e1.getDate());
}
return documentSort;
};
}
private String getWiki(SortedEvent sortedEvent)
{
return sortedEvent.getEvent().getDocument() != null
? sortedEvent.getEvent().getDocument().getWikiReference().getName()
: "";
}
private SortedEvent findNearestParent(SortedEvent sortedEvent)
{
if (sortedEvent.getEvent().getDocument() == null) {
return null;
}
SortedEvent nearestParent = null;
int nearestParentLevel = 0;
for (SortedEvent possibleParent : sortedEvents) {
if (possibleParent == sortedEvent) {
continue;
}
if (possibleParent.isParent(sortedEvent)
&& possibleParent.getEvent().getDocument().size() > nearestParentLevel) {
nearestParent = possibleParent;
nearestParentLevel = possibleParent.getEvent().getDocument().size();
}
}
return nearestParent;
}
private List<SortedEvent> getList(Map<String, List<SortedEvent>> sortedEventsByWikis, String wiki)
{
List<SortedEvent> list = sortedEventsByWikis.get(wiki);
if (list == null) {
list = new ArrayList<>();
sortedEventsByWikis.put(wiki, list);
}
return list;
}
private void groupEventsWithSameDocument()
{
for (int i = 0; i < sortedEvents.size(); ++i) {
SortedEvent event = sortedEvents.get(i);
if (event.getDocument() != null) {
// We start at (i + 1) because the sortedEvents list is ordered
int j = i + 1;
while (j < sortedEvents.size()) {
SortedEvent otherEvent = sortedEvents.get(j);
if (event.getDocument().equals(otherEvent.getDocument())) {
event.addEventWithTheSameDocument(otherEvent);
sortedEvents.remove(j);
} else {
++j;
}
}
}
}
}
} |
package com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_contacts.developer.bitdubai.version_1.structure;
import com.bitdubai.fermat_api.layer.all_definition.enums.Actors;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.WalletContact;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.exceptions.CantCreateWalletContactException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.exceptions.CantDeleteWalletContactException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.exceptions.CantGetAllWalletContactsException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.exceptions.CantGetWalletContactException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_contacts.exceptions.CantUpdateWalletContactException;
import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.file_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.DealsWithErrors;
import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.UnexpectedPluginExceptionSeverity;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_contacts.developer.bitdubai.version_1.exceptions.CantInitializeCryptoWalletContactsDatabaseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CryptoWalletContactsDao implements DealsWithErrors, DealsWithPluginDatabaseSystem {
/**
* Represent the Error manager.
*/
private ErrorManager errorManager;
/**
* Represent the Plugin Database.
*/
private PluginDatabaseSystem pluginDatabaseSystem;
/**
* Represent de Database where i will be working with
*/
Database database;
/**
* Constructor with parameters
*
* @param errorManager DealsWithErrors
* @param pluginDatabaseSystem DealsWithPluginDatabaseSystem
*/
public CryptoWalletContactsDao(ErrorManager errorManager, PluginDatabaseSystem pluginDatabaseSystem) {
this.errorManager = errorManager;
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
/**
* This method open or creates the database i'll be working with
*
* @param ownerId plugin id
* @param databaseName database name
* @throws CantInitializeCryptoWalletContactsDatabaseException
*/
public void initializeDatabase(UUID ownerId, String databaseName) throws CantInitializeCryptoWalletContactsDatabaseException {
try {
/*
* Open new database connection
*/
database = this.pluginDatabaseSystem.openDatabase(ownerId, databaseName);
} catch (CantOpenDatabaseException cantOpenDatabaseException) {
/*
* The database exists but cannot be open. I can not handle this situation.
*/
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, cantOpenDatabaseException);
throw new CantInitializeCryptoWalletContactsDatabaseException(cantOpenDatabaseException.getMessage());
} catch (DatabaseNotFoundException e) {
/*
* The database no exist may be the first time the plugin is running on this device,
* We need to create the new database
*/
CryptoWalletContactsDatabaseFactory walletContactsDatabaseFactory = new CryptoWalletContactsDatabaseFactory(pluginDatabaseSystem);
try {
/*
* We create the new database
*/
database = walletContactsDatabaseFactory.createDatabase(ownerId, databaseName);
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
/*
* The database cannot be created. I can not handle this situation.
*/
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, cantCreateDatabaseException);
throw new CantInitializeCryptoWalletContactsDatabaseException(cantCreateDatabaseException.getMessage());
}
}
}
/**
* Method that list the all entities on the database.
*
* @return All Wallet Contacts.
*/
public List<WalletContact> findAll(UUID walletId) throws CantGetAllWalletContactsException {
List<WalletContact> walletContactsList = new ArrayList<>();
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME, walletId, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
List<DatabaseTableRecord> records = walletContactAddressBookTable.getRecords();
for (DatabaseTableRecord record : records){
UUID contactId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME);
UUID actorId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME);
String actorName = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME);
Actors actorType = Actors.getByCode(record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME));
String receivedAddress = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME);
String receivedCurrency = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME);
CryptoAddress receivedCryptoAddress = new CryptoAddress(receivedAddress, CryptoCurrency.getByCode(receivedCurrency));
CryptoWalletContact walletContact = new CryptoWalletContact(actorId, actorName, actorType, contactId, receivedCryptoAddress, walletId);
walletContactsList.add(walletContact);
}
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantGetAllWalletContactsException(e.getMessage());
}
return walletContactsList;
}
/**
* Method that list the all entities on the database.
*
* @return All Wallet Contacts.
*/
public List<WalletContact> findAllScrolling(UUID walletId, Integer max, Integer offset) throws CantGetAllWalletContactsException {
List<WalletContact> walletContactsList = new ArrayList<>();
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME, walletId, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.setFilterTop(max.toString());
// TODO: WHEN OFFSET IS IMPLEMENTED UNCOMMENT NEXT LINE
//walletContactAddressBookTable.setFilterOffset(offset.toString());
walletContactAddressBookTable.loadToMemory();
List<DatabaseTableRecord> records = walletContactAddressBookTable.getRecords();
for (DatabaseTableRecord record : records){
UUID contactId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME);
UUID actorId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME);
String actorName = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME);
Actors actorType = Actors.getByCode(record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME));
String receivedAddress = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME);
String receivedCurrency = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME);
CryptoAddress receivedCryptoAddress = new CryptoAddress();
receivedCryptoAddress.setAddress(receivedAddress);
receivedCryptoAddress.setCryptoCurrency(CryptoCurrency.getByCode(receivedCurrency));
CryptoWalletContact walletContact = new CryptoWalletContact(actorId, actorName, actorType, contactId, receivedCryptoAddress, walletId);
walletContactsList.add(walletContact);
}
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantGetAllWalletContactsException(e.getMessage());
}
return walletContactsList;
}
/**
* Method that create a new entity in the data base.
*
* @param walletContact WalletContact to create.
*/
public void create(WalletContact walletContact) throws CantCreateWalletContactException {
if (walletContact == null){
throw new CantCreateWalletContactException("The entity is required, can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
DatabaseTableRecord entityRecord = walletContactAddressBookTable.getEmptyRecord();
entityRecord.setUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME, walletContact.getContactId());
entityRecord.setUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME, walletContact.getWalletId());
entityRecord.setUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME, walletContact.getActorId());
entityRecord.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME, walletContact.getActorName());
entityRecord.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME, walletContact.getActorType().getCode());
if (walletContact.getReceivedCryptoAddress() != null) {
entityRecord.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME, walletContact.getReceivedCryptoAddress().getAddress());
entityRecord.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME, walletContact.getReceivedCryptoAddress().getCryptoCurrency().getCode());
}
DatabaseTransaction transaction = database.newTransaction();
transaction.addRecordToInsert(walletContactAddressBookTable, entityRecord);
database.executeTransaction(transaction);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantCreateWalletContactException(e.getMessage());
}
}
/**
* Method that update a wallet contact in the database.
*
* @param walletContact WalletContact to update.
*/
public void update(WalletContact walletContact) throws CantUpdateWalletContactException {
if (walletContact == null){
throw new CantUpdateWalletContactException("The entity is required, can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME, walletContact.getContactId(), DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
DatabaseTableRecord record = walletContactAddressBookTable.getRecords().get(0);
if (walletContact.getActorName() != null)
record.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME, walletContact.getActorName());
if (walletContact.getReceivedCryptoAddress() != null) {
record.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME, walletContact.getReceivedCryptoAddress().getAddress());
record.setStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME, walletContact.getReceivedCryptoAddress().getCryptoCurrency().getCode());
}
DatabaseTransaction transaction = database.newTransaction();
transaction.addRecordToUpdate(walletContactAddressBookTable, record);
database.executeTransaction(transaction);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantUpdateWalletContactException(e.getMessage());
}
}
/**
* Method that delete a entity in the database.
*
* @param contactId UUID contactId.
* */
public void delete(UUID contactId) throws CantDeleteWalletContactException {
if (contactId == null){
throw new CantDeleteWalletContactException("The id is required can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setStringFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME, contactId.toString(), DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
//DatabaseTableRecord record = walletContactAddressBookTable.getRecords().get(0);
DatabaseTransaction transaction = database.newTransaction();
//TODO configure delete method in transaction AND UNCOMMENT THIS
//transaction.addRecordToDelete(walletContactAddressBookTable, record);
database.executeTransaction(transaction);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantDeleteWalletContactException(e.getMessage());
}
}
/**
* Method that find a WalletContact in database by actorName and walletId.
*
* @param actorName String actorName.
* @param walletId UUID wallet id
* */
public WalletContact findByNameAndWalletId(String actorName, UUID walletId) throws CantGetWalletContactException {
WalletContact walletContact;
if (actorName == null || walletId == null) {
throw new CantGetWalletContactException("The name and the actorName is required, can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setStringFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME, actorName, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME, walletId, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
DatabaseTableRecord record = walletContactAddressBookTable.getRecords().get(0);
UUID contactId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME);
UUID actorId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME);
Actors actorType = Actors.getByCode(record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME));
String receivedAddress = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME);
String receivedCurrency = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME);
CryptoAddress receivedCryptoAddress = new CryptoAddress();
receivedCryptoAddress.setAddress(receivedAddress);
receivedCryptoAddress.setCryptoCurrency(CryptoCurrency.getByCode(receivedCurrency));
walletContact = new CryptoWalletContact(actorId, actorName, actorType, contactId, receivedCryptoAddress, walletId);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantGetWalletContactException(e.getMessage());
}
return walletContact;
}
/**
* Method that find a WalletContact in database by actorName contains (string) and walletId.
*
* @param actorName String actorName.
* @param walletId UUID wallet id
* */
public WalletContact findByNameContainsAndWalletId(String actorName, UUID walletId) throws CantGetWalletContactException {
WalletContact walletContact;
if (actorName == null || walletId == null) {
throw new CantGetWalletContactException("The name and the actorName is required, can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setStringFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME, actorName, DatabaseFilterType.LIKE);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME, walletId, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
DatabaseTableRecord record = walletContactAddressBookTable.getRecords().get(0);
UUID contactId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME);
UUID actorId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME);
Actors actorType = Actors.getByCode(record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME));
String receivedAddress = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME);
String receivedCurrency = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME);
CryptoAddress receivedCryptoAddress = new CryptoAddress(receivedAddress, CryptoCurrency.getByCode(receivedCurrency));
walletContact = new CryptoWalletContact(actorId, actorName, actorType, contactId, receivedCryptoAddress, walletId);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantGetWalletContactException(e.getMessage());
}
return walletContact;
}
/**
* Method that find a WalletContact in database by contact id.
*
* @param contactId UUID contact id
* */
public WalletContact findById(UUID contactId) throws CantGetWalletContactException {
WalletContact walletContact;
if (contactId == null) {
throw new CantGetWalletContactException("The name and the contactId is required, can not be null");
}
try {
DatabaseTable walletContactAddressBookTable = database.getTable(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_NAME);
walletContactAddressBookTable.setUUIDFilter(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_CONTACT_ID_COLUMN_NAME, contactId, DatabaseFilterType.EQUAL);
walletContactAddressBookTable.loadToMemory();
DatabaseTableRecord record = walletContactAddressBookTable.getRecords().get(0);
UUID walletId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_WALLET_ID_COLUMN_NAME);
UUID actorId = record.getUUIDValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_ID_COLUMN_NAME);
String actorName = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_NAME_COLUMN_NAME);
Actors actorType = Actors.getByCode(record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_ACTOR_TYPE_COLUMN_NAME));
String receivedAddress = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_CRYPTO_ADDRESS_COLUMN_NAME);
String receivedCurrency = record.getStringValue(CryptoWalletContactsDatabaseConstants.CRYPTO_WALLET_CONTACTS_ADDRESS_BOOK_TABLE_RECEIVED_ADDRESS_CRYPTO_CURRENCY_COLUMN_NAME);
CryptoAddress receivedCryptoAddress = new CryptoAddress(receivedAddress, CryptoCurrency.getByCode(receivedCurrency));
walletContact = new CryptoWalletContact(actorId, actorName, actorType, contactId, receivedCryptoAddress, walletId);
} catch (Exception e) {
// Register the failure.
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_CONTACTS_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
throw new CantGetWalletContactException(e.getMessage());
}
return walletContact;
}
/**
* DealsWithPluginDatabaseSystem Interface implementation.
*/
@Override
public void setErrorManager(ErrorManager errorManager) {
this.errorManager = errorManager;
}
/**
* DealsWithPluginDatabaseSystem Interface implementation.
*/
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
} |
package net.acomputerdog.TerrainEdit.main;
import net.acomputerdog.BlazeLoader.api.command.ApiCommand;
import net.acomputerdog.BlazeLoader.main.Version;
import net.acomputerdog.BlazeLoader.mod.Mod;
import net.acomputerdog.BlazeLoader.util.BLLogger;
/**
* Base mod class for TerrainEdit. Registers CommandTE.
*/
public class ModTerrainEdit extends Mod {
public CommandTE command;
public BLLogger logger = new BLLogger(this, true, true);
/**
* Returns ID used to identify this mod internally, even among different versions of the same mod. Mods should override.
* --This should never be changed after the mod has been released!--
*
* @return Returns the id of the mod.
*/
@Override
public String getModId() {
return "acomputerdog.terrainedit";
}
/**
* Returns the user-friendly name of the mod. Mods should override.
* --Can be changed among versions, so this should not be used to ID mods!--
*
* @return Returns user-friendly name of the mod.
*/
@Override
public String getModName() {
return "Terrain Edit";
}
/**
* Gets the version of the mod as an integer for choosing the newer version.
*
* @return Return the version of the mod as an integer.
*/
@Override
public int getIntModVersion() {
return 0;
}
/**
* Gets the version of the mod as a String for display.
*
* @return Returns the version of the mod as an integer.
*/
@Override
public String getStringModVersion() {
return "0.0";
}
/**
* Returns true if this mod is compatible with the installed version of BlazeLoader. This should be checked using Version.class.
* -Called before mod is loaded! Do not depend on Mod.load()!-
*
* @return Returns true if the mod is compatible with the installed version of BlazeLoader.
*/
@Override
public boolean isCompatibleWithBLVersion() {
if(!Version.getMinecraftVersion().equals("1.6.4")){
System.out.println("TerrainEdit - Incorrect Minecraft version, aborting launch!");
return false;
}else if(!(Version.getGlobalVersion() == 0 && Version.getApiVersion() <= 7)){
System.out.println("TerrainEdit - Incorrect BL version, bad things may happen!");
}
return true;
}
/**
* Gets a user-friendly description of the mod.
*
* @return Return a String representing a user-friendly version of the mod.
*/
@Override
public String getModDescription() {
return "A command-line terrain editor";
}
/**
* Called when mod is started. Game is fully loaded and can be interacted with.
*/
@Override
public void start() {
ApiCommand.registerCommand(command = new CommandTE(this));
logger.logInfo("Loaded.");
}
} |
package com.cloud.capacity;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.capacity.dao.CapacityDaoImpl;
import com.cloud.exception.ConnectionException;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.storage.Storage;
import com.cloud.utils.db.SearchCriteria;
public class StorageCapacityListener implements Listener {
CapacityDao _capacityDao;
float _overProvisioningFactor = 1.0f;
public StorageCapacityListener(CapacityDao _capacityDao,
float _overProvisioningFactor) {
super();
this._capacityDao = _capacityDao;
this._overProvisioningFactor = _overProvisioningFactor;
}
@Override
public boolean processAnswers(long agentId, long seq, Answer[] answers) {
return false;
}
@Override
public boolean processCommands(long agentId, long seq, Command[] commands) {
return false;
}
@Override
public AgentControlAnswer processControlCommand(long agentId,
AgentControlCommand cmd) {
return null;
}
@Override
public void processConnect(HostVO server, StartupCommand startup, boolean forRebalance) throws ConnectionException {
if (!(startup instanceof StartupStorageCommand)) {
return;
}
SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria();
capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, server.getId());
capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ,
server.getDataCenterId());
capacitySC.addAnd("podId", SearchCriteria.Op.EQ, server.getPodId());
List<CapacityVO> capacities = _capacityDao.search(capacitySC, null);
StartupStorageCommand ssCmd = (StartupStorageCommand) startup;
if (ssCmd.getResourceType() == Storage.StorageResourceType.STORAGE_HOST) {
CapacityVO capacity = new CapacityVO(server.getId(),
server.getDataCenterId(), server.getPodId(), server.getClusterId(), 0L,
(long) (server.getTotalSize() * _overProvisioningFactor),
CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED);
_capacityDao.persist(capacity);
}
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return false;
}
@Override
public boolean isRecurring() {
return false;
}
@Override
public int getTimeout() {
return 0;
}
@Override
public boolean processTimeout(long agentId, long seq) {
return false;
}
} |
package org.spine3.base;
import com.google.common.base.Converter;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spine3.util.Exceptions.newIllegalArgumentException;
/**
* Encloses and discloses the {@code String} objects with double quotes.
*
* @author Illia Shepilov
* @author Alexander Yevsyukov
*/
class Quoter extends Converter<String, String> {
private static final char QUOTE_CHAR = '"';
private static final String QUOTE = String.valueOf(QUOTE_CHAR);
private static final String BACKSLASH_QUOTE = "\\\"";
private static final String DOUBLE_BACKSLASH = "\\\\";
private static final String ESCAPED_QUOTE = DOUBLE_BACKSLASH + QUOTE_CHAR;
private static final Pattern DOUBLE_BACKSLASH_PATTERN = Pattern.compile(DOUBLE_BACKSLASH);
private static final Pattern QUOTE_PATTERN = Pattern.compile(QUOTE);
private static final String DELIMITER_PATTERN_PREFIX = "(?<!" + DOUBLE_BACKSLASH + ')'
+ DOUBLE_BACKSLASH;
@Override
protected String doForward(String s) {
return quote(s);
}
@Override
protected String doBackward(String s) {
checkNotNull(s);
return unquote(s);
}
/**
* Prepends quote characters in the passed string with two leading backslashes,
* and then wraps the string into quotes.
*/
private static String quote(String stringToQuote) {
checkNotNull(stringToQuote);
final String escapedString = QUOTE_PATTERN.matcher(stringToQuote)
.replaceAll(ESCAPED_QUOTE);
final String result = QUOTE_CHAR + escapedString + QUOTE_CHAR;
return result;
}
/**
* Unquotes the passed string and removes double backslash prefixes for quote symbols
* found inside the passed value.
*/
private static String unquote(String value) {
checkQuoted(value);
final String unquoted = value.substring(2, value.length() - 2);
final String unescaped = DOUBLE_BACKSLASH_PATTERN.matcher(unquoted)
.replaceAll("");
return unescaped;
}
private static void checkQuoted(String str) {
if (!(str.startsWith(BACKSLASH_QUOTE)
&& str.endsWith(BACKSLASH_QUOTE))) {
throw newIllegalArgumentException("The passed string is not quoted: %s", str);
}
}
/**
* Creates the pattern to match the escaped delimiters.
*
* @param delimiter the character to match
* @return the created pattern
*/
static String createDelimiterPattern(char delimiter) {
final String quotedDelimiter = Pattern.quote(String.valueOf(delimiter));
final String result = Pattern.compile(DELIMITER_PATTERN_PREFIX + quotedDelimiter)
.pattern();
return result;
}
private enum Singleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Quoter value = new Quoter();
}
static Quoter instance() {
return Singleton.INSTANCE.value;
}
} |
package edu.mit.csail.db.ml;
import edu.mit.csail.db.ml.server.storage.FitEventDao;
import edu.mit.csail.db.ml.server.storage.MetadataDao;
import jooq.sqlite.gen.Tables;
import modeldb.FitEvent;
import modeldb.FitEventResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.util.JSON;
import com.mongodb.DBObject;
import edu.mit.csail.db.ml.server.storage.metadata.MongoMetadataDb;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestMetadata {
private TestBase.ProjExpRunTriple triple;
@Before
public void initialize() throws Exception {
triple = TestBase.reset();
}
@Test
public void testStoreGet() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1', 'key2':30}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals(parsedDbContents.get("key1"), "value1");
Assert.assertEquals(30, parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testGetModelIdsSingle() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1', 'key2':30}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Map<String, String> kvToMatch = new HashMap<>();
List<Integer> noMatch = Collections.emptyList();
List<Integer> oneMatch = Arrays.asList(resp.modelId);
Assert.assertEquals(oneMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
kvToMatch.put("key1", "value1");
Assert.assertEquals(oneMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
kvToMatch.put("key2", "wrong value");
Assert.assertEquals(noMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
}
@Test
public void testGetModelIdsMultiple() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1', 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
FitEvent fe2 = StructFactory.makeFitEvent();
String serializedMetadata2 = "{'key1':'value2', 'key2':'30'}";
fe2.setMetadata(serializedMetadata2);
FitEventResponse resp2 = FitEventDao.store(fe2, TestBase.ctx(), false);
MetadataDao.store(resp2, fe2, TestBase.getMetadataDb());
Map<String, String> kvToMatch = new HashMap<>();
List<Integer> noMatch = Collections.emptyList();
List<Integer> oneMatch = Arrays.asList(resp2.modelId);
List<Integer> allMatch = Arrays.asList(resp.modelId, resp2.modelId);
// Test when there are no kv pairs
Assert.assertEquals(allMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
// Test with 1 kv pair that matches all
kvToMatch.put("key2", "30");
Assert.assertEquals(allMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
// Test with kv pair that matches 1
kvToMatch.put("key1", "value2");
Assert.assertEquals(oneMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
// Test with 2 kv pairs where 1 doesn't match
kvToMatch.put("author", "wrong value");
Assert.assertEquals(noMatch, MetadataDao.getModelIds(kvToMatch, TestBase.getMetadataDb()));
}
@Test
public void testUpdateFieldSimpleExisting() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1', 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key1",
"new value", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals("new value", parsedDbContents.get("key1"));
Assert.assertEquals("30", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testUpdateFieldSimpleNew() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key2",
"value2", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals("value1", parsedDbContents.get("key1"));
Assert.assertEquals("value2", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testUpdateFieldNested() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1': {'nested_key_1': 'nested_value_1', 'nested_key_2': 'nested_value_2'}, 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key1.nested_key_1",
"new value", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Object key1Contents = parsedDbContents.get("key1");
Assert.assertTrue(key1Contents instanceof DBObject);
Assert.assertEquals("new value", ((DBObject) key1Contents).get("nested_key_1"));
Assert.assertEquals("nested_value_2", ((DBObject) key1Contents).get("nested_key_2"));
Assert.assertEquals("30", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testUpdateFieldVector() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1': ['value1', 'value2'], 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key1.0",
"new value",
TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Object key1Contents = parsedDbContents.get("key1");
Assert.assertTrue(key1Contents instanceof List);
Assert.assertEquals("new value", ((List) key1Contents).get(0));
Assert.assertEquals("value2", ((List) key1Contents).get(1));
Assert.assertEquals("30", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testUpdateFieldVectorAppend() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1': ['value1', 'value2'], 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key1.2",
"new value", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Object key1Contents = parsedDbContents.get("key1");
Assert.assertTrue(key1Contents instanceof List);
Assert.assertEquals("value1", ((List) key1Contents).get(0));
Assert.assertEquals("value2", ((List) key1Contents).get(1));
Assert.assertEquals("new value", ((List) key1Contents).get(2));
Assert.assertEquals("30", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testUpdateFieldScalarNestedInVector() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1': [{'nested_key_1': 'value index 0'}, {'nested_key_1': 'value index 1'}], 'key2':'30'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.updateScalarField(resp.modelId, "key1.1.nested_key_1",
"new value", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Object key1Contents = parsedDbContents.get("key1");
Assert.assertTrue(key1Contents instanceof List);
Assert.assertTrue(((List) key1Contents).get(0) instanceof DBObject);
Assert.assertEquals("value index 0", ((DBObject) ((List) key1Contents).get(0)).get("nested_key_1"));
Assert.assertTrue(((List) key1Contents).get(1) instanceof DBObject);
Assert.assertEquals("new value", ((DBObject) ((List) key1Contents).get(1)).get("nested_key_1"));
Assert.assertEquals("30", parsedDbContents.get("key2"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testCreateVectorNotExisting() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.createVector(resp.modelId, "key2",
Collections.emptyMap(), TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals("value1", parsedDbContents.get("key1"));
Assert.assertTrue(parsedDbContents.get("key2") instanceof List);
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testCreateVectorExisting() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertFalse(MetadataDao.createVector(resp.modelId, "key1",
Collections.emptyMap(), TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals("value1", parsedDbContents.get("key1"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testAddToVectorFieldNotVectorFail() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1':'value1'}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertFalse(MetadataDao.addToVectorField(resp.modelId, "key1",
"value", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Assert.assertEquals("value1", parsedDbContents.get("key1"));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
@Test
public void testAddToVectorFieldSuccess() throws Exception {
FitEvent fe = StructFactory.makeFitEvent();
String serializedMetadata = "{'key1': ['elem1']}";
fe.setMetadata(serializedMetadata);
FitEventResponse resp = FitEventDao.store(fe, TestBase.ctx(), false);
MetadataDao.store(resp, fe, TestBase.getMetadataDb());
Assert.assertTrue(MetadataDao.addToVectorField(resp.modelId, "key1",
"elem2", TestBase.getMetadataDb()));
String actualDbContents = MetadataDao.get(resp.modelId,
TestBase.getMetadataDb());
DBObject parsedDbContents = (DBObject) JSON.parse(actualDbContents);
Object key1Contents = parsedDbContents.get("key1");
Assert.assertTrue(key1Contents instanceof List);
Assert.assertEquals("elem1", ((List) key1Contents).get(0));
Assert.assertEquals("elem2", ((List) key1Contents).get(1));
Assert.assertEquals(resp.modelId,
parsedDbContents.get(MongoMetadataDb.MODELID_KEY));
}
} |
package org.jscep.server;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.jscep.request.GetCaCaps;
import org.jscep.response.Capabilities;
import org.jscep.transport.Transport;
import org.jscep.transport.Transport.Method;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@Ignore @RunWith(Parameterized.class)
public class ScepServletTest {
private static Server SERVER;
private static String PATH = "/scep/pkiclient.exe";
private static int PORT;
private final Method method;
@Parameters
public static List<Object[]> getParameters() {
final List<Object[]> params = new LinkedList<Object[]>();
params.add(new Object[] {Method.GET});
return params;
}
@BeforeClass
public static void startServer() throws Exception {
SERVER = new Server(0);
final ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(ScepServletImpl.class, PATH);
SERVER.setHandler(handler);
SERVER.start();
PORT = SERVER.getConnectors()[0].getLocalPort();
}
public ScepServletTest(Method method) {
this.method = method;
}
private URL getURL() throws MalformedURLException {
return new URL("http", "localhost", PORT, PATH);
}
@Test
public void basicTest() throws Exception {
GetCaCaps req = new GetCaCaps(null);
Transport transport = Transport.createTransport(method, getURL());
Capabilities caps = transport.sendRequest(req);
System.out.println(caps);
}
} |
package com.trendrr.strest.doc;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.DynMap;
import com.trendrr.oss.DynMapFactory;
import com.trendrr.oss.FileHelper;
import com.trendrr.oss.Reflection;
import com.trendrr.oss.Regex;
import com.trendrr.oss.StringHelper;
import com.trendrr.strest.doc.renderer.FileRenderer;
import com.trendrr.strest.doc.renderer.JSONFileRenderer;
/**
* @author Dustin Norlander
* @created Feb 18, 2011
*
*/
public class StrestDocParser {
protected Log log = LogFactory.getLog(StrestDocParser.class);
protected HashMap<String, AbstractDocTag> tags = new HashMap<String, AbstractDocTag>();
protected Set<TemplateRenderer> renderers = new HashSet<TemplateRenderer>();
protected int abstractLength = 256;
protected Set<String> annotationNames = new HashSet<String>();
public StrestDocParser() {
this.addTags("com.trendrr.strest.doc.tags", true);
this.annotationNames.add("Strest");
this.addTemplateRenderer(new JSONFileRenderer());
}
public static void main(String ...strings) {
StrestDocParser parser = new StrestDocParser();
// List<DynMap> routes = parser.parseDirectory("src");
// for(DynMap route : routes) {
// System.out.println(route.toJSONString());
// System.out.println(parser.createIndex(routes));
parser.parseAndSave("src", "strestdoc");
}
public void addAnnotationName(String ann) {
this.annotationNames.add(ann);
}
/**
* parses the given src directories and saves the resulting files in the save directory.
* @param srcDirectories
* @param saveDirectory
*/
public void parseAndSave(List<String> srcDirectories, String saveDirectory) {
List<DynMap> routes = new ArrayList<DynMap>();
for (String dir : srcDirectories) {
routes.addAll(this.parseDirectory(dir));
}
DynMap index = this.createIndex(routes);
//save the index.
for (TemplateRenderer rend : this.renderers) {
if (rend instanceof FileRenderer) {
((FileRenderer)rend).setSaveDirectory(saveDirectory);
}
rend.renderIndex(index);
}
for (DynMap route : routes) {
String r = route.get(String.class, "route");
if (r.isEmpty())
r = "/index";
for (TemplateRenderer rend : this.renderers) {
rend.renderPage(r, route);
}
}
}
/**
* parses the given src directory and saves the resulting files in the save directory.
* @param docDirectory
* @param saveDirectory
*/
public void parseAndSave(String srcDirectory, String saveDirectory) {
List<String> dirs = new ArrayList<String>();
dirs.add(srcDirectory);
this.parseAndSave(dirs, saveDirectory);
}
public DynMap createIndexes(List<DynMap> routes) {
DynMap indexes = new DynMap();
for (DynMap route : routes) {
String indexName = route.getString("index", "default");
indexes.putIfAbsent(indexName, new DynMap("name", indexName));
DynMap index = indexes.getMap(indexName);
String category = route.getString("category", "default");
DynMap mp = this.createIndexEntry(route);
if (mp == null)
continue;
index.addToListWithDot("categories." + category, mp);
}
//TODO: now need to sort the categories
for(String ind : indexes.keySet()) {
DynMap cats = indexes.getMap(ind + ".categories");
List<DynMap> catList = new ArrayList<DynMap>();
for (String c : cats.keySet()) {
DynMap ct = this.createIndexCategory(c, cats.getList(DynMap.class, "routes"));
if (ct != null) {
catList.add(ct);
}
}
//sort the categories
Collections.sort(catList, new Comparator<DynMap>() {
@Override
public int compare(DynMap o1, DynMap o2) {
return o1.getString("category").compareTo(o2.getString("category"));
}
});
//add back to the index.
indexes.getMap(ind).put("categories", catList);
}
return indexes;
}
public DynMap createIndexCategory(String category, List<DynMap> routes) {
if (routes == null || routes.isEmpty()) {
return null;
}
Collections.sort(routes, new Comparator<DynMap>(){
@Override
public int compare(DynMap o1, DynMap o2) {
String r1 = o1.getString("route", "");
String r2 = o2.getString("route", "");
return r1.compareToIgnoreCase(r2);
}
});
DynMap cat = new DynMap();
cat.put("category", category);
cat.put("routes", routes);
return cat;
}
/**
* creates the entry for the index page based on the map from the route.
*
* return null to skip this entry in the index.
* @param route
* @return
*/
public DynMap createIndexEntry(DynMap route) {
DynMap mp = new DynMap();
mp.put("route", route.get("route"));
String abs = route.get(String.class, "abstract");
if (abs == null) {
abs = route.get(String.class, "description", "");
System.out.println(abs);
abs = abs.substring(0, Math.min(this.abstractLength, abs.length()));
}
mp.put("abstract", abs);
if (route.containsKey("method")) {
mp.put("method", route.get("method"));
}
return mp;
}
/**
* recursively parses this directory and all others below it.
*
* Each member of the returned list contains a single route. List is sorted by route.
*
* @param dir
* @throws Exception
*/
public List<DynMap> parseDirectory(String dir) {
try {
List<String> filenames = FileHelper.listDirectory(dir, true);
List<DynMap> routes = new ArrayList<DynMap>();
for (String filename : filenames) {
if (!filename.endsWith(".java")) {
continue;
}
String java = FileHelper.loadString(filename);
routes.addAll(this.parse(java));
}
Collections.sort(routes, new Comparator<DynMap>() {
@Override
public int compare(DynMap o1, DynMap o2) {
String r1 = o1.get(String.class, "route") + "_" + o1.get(String.class, "method", "");
String r2 = o1.get(String.class, "route") + "_" + o2.get(String.class, "method", "");
return r1.compareTo(r2);
}
});
return routes;
} catch (Exception x) {
log.error("Caught", x);
}
return null;
}
/**
* adds a new template renderer
* @param renderer
*/
public void addTemplateRenderer(TemplateRenderer renderer) {
this.renderers.add(renderer);
}
/**
* sets the list of template renderers
* @param renderers
*/
public void setTemplateRenderers(Collection<TemplateRenderer> renderers) {
this.renderers.clear();
this.renderers.addAll(renderers);
}
public void addTag(AbstractDocTag tag) {
tags.put(tag.tagName(), tag);
}
public void addTags(String packageName, boolean recure) {
try {
List<AbstractDocTag> tags = Reflection.defaultInstances(AbstractDocTag.class, packageName, recure);
for (AbstractDocTag t : tags) {
this.addTag(t);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* returns a list of maps,
*
* Each map represents a single route.
*
* returns empty list if the java contains no useful documentation
* @param java
* @return
*/
public List<DynMap> parse(String java) {
DynMap mp = this.parseAnnotation(java);
List<DynMap> docs = this.getStrestDoc(java);
if (mp.isEmpty() && docs.isEmpty()) {
return docs;
}
if (docs.isEmpty()) {
docs.add(mp);
}
List<DynMap> vals = new ArrayList<DynMap>();
for(DynMap v : docs) {
DynMap m = new DynMap().extend(mp,v);
List<String> routes = m.getList(String.class, "route");
if (routes != null) {
for(String route : routes) {
DynMap v1 = new DynMap();
v1.putAll(m);
v1.put("route", route);
v1 = this.cleanUpRoute(v1);
vals.add(v1);
}
}
}
return vals;
}
/**
* does final processing on a route map (the data associated with a single route)
*
*
*
* @param route
* @return
*/
protected DynMap cleanUpRoute(DynMap route) {
List<DynMap> params = route.getList(DynMap.class, "param");
if (params == null)
return route;
//Make unify the requiredParams annotation with the markup.
List<String> requiredParams = route.getList(String.class, "requiredParams");
if (requiredParams != null) {
HashMap<String, DynMap> pmsMap = new HashMap<String,DynMap>();
for (DynMap p : params) {
pmsMap.put(p.getString("param"), p);
}
for (String rp : requiredParams) {
if (pmsMap.containsKey(rp)) {
pmsMap.get(rp).put("required", true);
} else {
DynMap p = new DynMap();
p.put("param", rp);
p.put("required", true);
p.put("description", "");
params.add(p);
}
}
}
Collections.sort(params, new Comparator<DynMap>(){
@Override
public int compare(DynMap o1, DynMap o2) {
if (o1.getBoolean("required", false) != o2.getBoolean("required", false)) {
if (o1.getBoolean("required", false)) {
return -1;
} else {
return 1;
}
}
return o1.getString("param").compareTo(o1.getString("param"));
}
});
System.out.println(params);
route.put("params", params);
route.removeAll("requiredParams", "param");
return route;
}
/**
* parses the Strest annotation into a map.
* @param java
* @return
*/
public DynMap parseAnnotation(String java) {
/*
* This is all ugly as hell, and pretty slow, but it works :)
*/
DynMap mp = new DynMap();
for (String annotationName : this.annotationNames) {
String ann = Regex.matchFirst(java, "\\@" + annotationName + "\\s*\\([^\\)]+\\)", false);
if (ann == null) {
continue;
}
ann = ann.replaceFirst("\\@" + annotationName + "\\s*\\(", "");
ann = ann.replaceAll("\\)$", "");
String[] tokens = ann.split("\\s*\\=\\s*");
String key = null;
String value = null;
for (String t : tokens) {
if (key == null) {
key = t;
continue;
}
//else parse the value.
String nextKey = Regex.matchFirst(t, "[\\n\\r]+\\s*[^\\s]+\\s*$", false);
value = t.replaceFirst("[\\n\\r]+\\s*[^\\s]+\\s*$", "").trim();
boolean isList = value.startsWith("{");
value = StringHelper.trim(value, ",");
value = StringHelper.trim(value, "{");
value = StringHelper.trim(value, "}");
value = StringHelper.trim(value.trim(), "\"");
if (isList) {
List<String> values = new ArrayList<String>();
for (String v : value.split(",")) {
values.add(StringHelper.trim(v.trim(), "\""));
}
mp.put(key.trim(), values);
} else {
mp.put(key.trim(), value);
}
if (nextKey != null) {
key = nextKey;
}
}
}
System.out.println(mp.toJSONString());
return mp;
}
public List<DynMap> getStrestDoc(String java) {
// String doc = Regex.matchFirst(java, "\\/\\*\\/\\/(?s).*?\\*\\/", false);
List<DynMap> results = new ArrayList<DynMap>();
for (String doc : Regex.matchAll(java, "\\/\\*\\/\\/(?s).*?\\*\\/", false)) {
//now clean it up.
doc = doc.replaceFirst("^\\/\\*\\/\\/", "");
doc = doc.replaceAll("(?m)^\\s*\\*", "");
doc = doc.replaceAll("\\/$", "");
doc = doc.trim();
DynMap mp = new DynMap();
//now split into key values
for (String tmp : doc.split("[\\r\\n]\\s*\\@")) {
tmp = StringHelper.trim(tmp, "@");
int ind = tmp.indexOf(' ');
if (ind < 0)
continue;
String key = tmp.substring(0, ind).trim();
String value = tmp.substring(ind).trim();
if (value.isEmpty()) {
log.warn("TAG: " + key + " IS EMPTY!");
continue;
}
Object v = this.processTag(key, value);
if (v == null) {
log.warn("TAG: " + key + " IS EMPTY!");
continue;
}
if (mp.containsKey(key)) {
List values = mp.get(List.class, key);
values.add(v);
mp.put(key, values);
} else {
mp.put(key, v);
}
}
if (mp.get("method") == null) {
mp.put("method", this.parseMethod(java));
} else {
mp.put("method", mp.getList(String.class, "method", ","));
}
results.add(mp);
}
return results;
}
/**
* attempts to figure out if the route is GET, POST, DELETE, ect.
* @param java
* @return
*/
protected List<String> parseMethod(String java) {
List<String> methods = new ArrayList<String>();
if (java.contains("handleGET")) {
methods.add("GET");
}
if (java.contains("handlePOST")) {
methods.add("POST");
}
if (java.contains("handleDELETE")) {
methods.add("DELETE");
}
if (java.contains("handlePUT")) {
methods.add("PUT");
}
return methods;
}
/**
* processes the text associated with a tag.
*
* by default just returns the value.
*
* @param tag
* @param value
* @return
*/
public Object processTag(String tag, String value) {
AbstractDocTag t = this.tags.get(tag);
if (t == null)
return value;
return t.process(this, value);
}
} |
package Calculations.Calculations;
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
public class AppTest {
@Test
public void test(){
assertEquals(true, true);
}
@Test
public void test_wrong(){
assertEquals(true, false);
}
} |
package co.phoenixlab.common.lang;
import java.util.*;
import java.util.function.*;
public class SafeNav<T> {
/**
* The current value being processed, possibly null
*/
private T val;
/**
* The last call number of {@link #next(Function)}
*/
private int lastNonNullDepth;
/**
* Private constructor
*/
private SafeNav(T val, int lastNonNullDepth) {
this.val = val;
this.lastNonNullDepth = lastNonNullDepth;
}
/**
* Starts a SafeNavigation chain with the given object.
*
* @param t The object, possibly null, to start the chain with
* @param <T> The type of t
* @return A SafeNav<T> object to operate with.
* @see SafeNav
*/
public static <T> SafeNav<T> of(T t) {
return new SafeNav<>(t, 0);
}
/**
* Starts a SafeNavigation chain with the given Optional.
*
* @param optional An Optional<T> object, empty or occupied, to start the chain with
* @param <T> The type of t
* @return A SafeNav<T> object to operate with.
*/
public static <T> SafeNav<T> ofOptional(Optional<T> optional) {
return new SafeNav<>(optional.orElse(null), 0);
}
/**
* Applies the given {@code function} if the contained value is not null, or does nothing if it is null.
* <p>
* This is the generalized method, which will construct a new SafeNav<R> for completion of {@code function} (as in,
* if the contained value is null, no new instance will be constructed and this method will return the current
* SafeNav).
*
* @param function The function to apply to the contained value if present.
* @param <R> The return type of {@code function}
* @return A SafeNav<R> object containing the result of the function, or an empty SafeNav<R> object if the contained
* value was null.
*/
@SuppressWarnings("unchecked")
public <R> SafeNav<R> next(Function<T, R> function) {
if (val == null) {
// We return ourselves if val is null because there's no distinction of nulls
// Consider it an optimization
return (SafeNav<R>) this;
}
++lastNonNullDepth;
return new SafeNav<>(function.apply(val), lastNonNullDepth);
}
/**
* Gets the final result of the chain, or null if the contained value was initially null or any calls to
* {@code next()} produced a null result.
*
* @return The final result of applying the functions from previous {@code next()} calls, or null if at any point
* the contained value was null.
*/
public T get() {
return val;
}
/**
* Takes the final result of the chain, and if it is not null, applies the provided {@code function} to it and
* returns the resulting value. If it is null, this method simply returns null without applying {@code function}
*
* @param function The function to apply if the final result is not null
* @param <R> The return type of the provided function
* @return The result of calling the {@code function} with the final result, or null if the final result was null
*/
public <R> R get(Function<T, R> function) {
return next(function).get();
}
public <E extends Throwable> T orElseThrow(IntFunction<E> exceptionFactory) throws E {
if (val == null) {
throw exceptionFactory.apply(lastNonNullDepth);
}
return val;
}
/**
* Convenience method for throwing a NullPointerException with a default message for
* {@link #orElseThrow(IntFunction)}
*
* @return The contained value
* @throws NullPointerException If the contained value is not present
*/
public T orElseThrowNPE() throws NullPointerException {
return orElseThrow((int i) -> new NullPointerException("Val null since next()
}
/**
* Convenience method for throwing a NoSuchElementException with a default message for
* {@link #orElseThrow(IntFunction)}
*
* @return The contained value
* @throws NoSuchElementException If the contained value is not present
*/
public T orElseThrowNSEE() throws NoSuchElementException {
return orElseThrow((int i) -> new NoSuchElementException("Val null since next()
}
/**
* @return The last call number of {@code next()} where the contained value was present (so far)
*/
public int getLastNonNullDepth() {
return lastNonNullDepth;
}
/**
* Passes the current last call number of {@code next()} where the contained value was present (so far) to the
* given consumer. This method allows for continued chaining, unlike {@link #getLastNonNullDepth()}.
*
* @param consumer The consumer of the current last call number
* @return The current SafeNav<T>
*/
public SafeNav<T> lastNonNullDepth(IntConsumer consumer) {
consumer.accept(lastNonNullDepth);
return this;
}
/**
* Passes the contained value to the given consumer if it is present, otherwise does nothing.
*
* @param consumer The consumer that will accept the contained value if present
*/
public void ifPresent(Consumer<T> consumer) {
if (val != null) {
consumer.accept(val);
}
}
/**
* Returns the contained value, if present, or the given default value.
*
* @param defaultVal The value (can be null) to return if the contained value is not present
* @return The contained value, if present, or the default value
*/
public T orElse(T defaultVal) {
if (val == null) {
return defaultVal;
}
return val;
}
/**
* If the contained value is present, returns the result of applying {@code function} to it. If not
* present, returns the given default value.
*
* @param function The function to apply to the contained value if present
* @param defaultVal The value to return if the contained value is not present
* @param <R> The return type of {@code function} and the type of the default value
* @return The result of {@code function}, if the contained value is present, or the default value
*/
public <R> R orElse(Function<T, R> function, R defaultVal) {
return next(function).orElse(defaultVal);
}
/**
* Converts this SafeNav to an Optional
*
* @return An Optional of the contained value, if present, or an empty Optional, if not
*/
public Optional<T> toOptional() {
return Optional.ofNullable(val);
}
/**
* Integer specialization of {@link #toOptional()}
*/
public OptionalInt toOptionalInt(ToIntFunction<T> function) {
if (val == null) {
return OptionalInt.empty();
}
return OptionalInt.of(function.applyAsInt(val));
}
/**
* Long specialization of {@link #toOptional()}
*/
public OptionalLong toOptionalLong(ToLongFunction<T> function) {
if (val == null) {
return OptionalLong.empty();
}
return OptionalLong.of(function.applyAsLong(val));
}
/**
* Double specialization of {@link #toOptional()}
*/
public OptionalDouble toOptionalDouble(ToDoubleFunction<T> function) {
if (val == null) {
return OptionalDouble.empty();
}
return OptionalDouble.of(function.applyAsDouble(val));
}
} |
package com.annimon.ownlang.parser;
import com.annimon.ownlang.exceptions.ParseException;
import com.annimon.ownlang.lib.NumberValue;
import com.annimon.ownlang.lib.StringValue;
import com.annimon.ownlang.lib.UserDefinedFunction;
import com.annimon.ownlang.parser.ast.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author aNNiMON
*/
public final class Parser {
public static Statement parse(List<Token> tokens) {
final Parser parser = new Parser(tokens);
final Statement program = parser.parse();
if (parser.getParseErrors().hasErrors()) {
throw new ParseException();
}
return program;
}
private static final Token EOF = new Token(TokenType.EOF, "", -1, -1);
private static final EnumMap<TokenType, BinaryExpression.Operator> ASSIGN_OPERATORS;
static {
ASSIGN_OPERATORS = new EnumMap(TokenType.class);
ASSIGN_OPERATORS.put(TokenType.EQ, null);
ASSIGN_OPERATORS.put(TokenType.PLUSEQ, BinaryExpression.Operator.ADD);
ASSIGN_OPERATORS.put(TokenType.MINUSEQ, BinaryExpression.Operator.SUBTRACT);
ASSIGN_OPERATORS.put(TokenType.STAREQ, BinaryExpression.Operator.MULTIPLY);
ASSIGN_OPERATORS.put(TokenType.SLASHEQ, BinaryExpression.Operator.DIVIDE);
ASSIGN_OPERATORS.put(TokenType.PERCENTEQ, BinaryExpression.Operator.REMAINDER);
ASSIGN_OPERATORS.put(TokenType.AMPEQ, BinaryExpression.Operator.AND);
ASSIGN_OPERATORS.put(TokenType.CARETEQ, BinaryExpression.Operator.XOR);
ASSIGN_OPERATORS.put(TokenType.BAREQ, BinaryExpression.Operator.OR);
ASSIGN_OPERATORS.put(TokenType.COLONCOLONEQ, BinaryExpression.Operator.PUSH);
ASSIGN_OPERATORS.put(TokenType.LTLTEQ, BinaryExpression.Operator.LSHIFT);
ASSIGN_OPERATORS.put(TokenType.GTGTEQ, BinaryExpression.Operator.RSHIFT);
ASSIGN_OPERATORS.put(TokenType.GTGTGTEQ, BinaryExpression.Operator.URSHIFT);
ASSIGN_OPERATORS.put(TokenType.ATEQ, BinaryExpression.Operator.AT);
}
private final List<Token> tokens;
private final int size;
private final ParseErrors parseErrors;
private Statement parsedStatement;
private int pos;
public Parser(List<Token> tokens) {
this.tokens = tokens;
size = tokens.size();
parseErrors = new ParseErrors();
}
public Statement getParsedStatement() {
return parsedStatement;
}
public ParseErrors getParseErrors() {
return parseErrors;
}
public Statement parse() {
parseErrors.clear();
final BlockStatement result = new BlockStatement();
while (!match(TokenType.EOF)) {
try {
result.add(statement());
} catch (Exception ex) {
parseErrors.add(ex, getErrorLine());
recover();
}
}
parsedStatement = result;
return result;
}
private int getErrorLine() {
if (size == 0) return 0;
if (pos >= size) return tokens.get(size - 1).getRow();
return tokens.get(pos).getRow();
}
private void recover() {
int preRecoverPosition = pos;
for (int i = preRecoverPosition; i <= size; i++) {
pos = i;
try {
statement();
// successfully parsed,
pos = i; // restore position
return;
} catch (Exception ex) {
// fail
}
}
}
private Statement block() {
final BlockStatement block = new BlockStatement();
consume(TokenType.LBRACE);
while (!match(TokenType.RBRACE)) {
block.add(statement());
}
return block;
}
private Statement statementOrBlock() {
if (lookMatch(0, TokenType.LBRACE)) return block();
return statement();
}
private Statement statement() {
if (match(TokenType.PRINT)) {
return new PrintStatement(expression());
}
if (match(TokenType.PRINTLN)) {
return new PrintlnStatement(expression());
}
if (match(TokenType.IF)) {
return ifElse();
}
if (match(TokenType.WHILE)) {
return whileStatement();
}
if (match(TokenType.DO)) {
return doWhileStatement();
}
if (match(TokenType.BREAK)) {
return new BreakStatement();
}
if (match(TokenType.CONTINUE)) {
return new ContinueStatement();
}
if (match(TokenType.RETURN)) {
return new ReturnStatement(expression());
}
if (match(TokenType.USE)) {
return new UseStatement(expression());
}
if (match(TokenType.INCLUDE)) {
return new IncludeStatement(expression());
}
if (match(TokenType.FOR)) {
return forStatement();
}
if (match(TokenType.DEF)) {
return functionDefine();
}
if (match(TokenType.MATCH)) {
return new ExprStatement(match());
}
if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.LPAREN)) {
return new ExprStatement(functionChain(qualifiedName()));
}
return assignmentStatement();
}
private Statement assignmentStatement() {
if (match(TokenType.EXTRACT)) {
return destructuringAssignment();
}
final Expression expression = expression();
if (expression instanceof Statement) {
return (Statement) expression;
}
throw new ParseException("Unknown statement: " + get(0));
}
private DestructuringAssignmentStatement destructuringAssignment() {
// extract(var1, var2, ...) = ...
consume(TokenType.LPAREN);
final List<String> variables = new ArrayList<>();
while (!match(TokenType.RPAREN)) {
if (lookMatch(0, TokenType.WORD)) {
variables.add(consume(TokenType.WORD).getText());
} else {
variables.add(null);
}
consume(TokenType.COMMA);
}
consume(TokenType.EQ);
return new DestructuringAssignmentStatement(variables, expression());
}
private Statement ifElse() {
final Expression condition = expression();
final Statement ifStatement = statementOrBlock();
final Statement elseStatement;
if (match(TokenType.ELSE)) {
elseStatement = statementOrBlock();
} else {
elseStatement = null;
}
return new IfStatement(condition, ifStatement, elseStatement);
}
private Statement whileStatement() {
final Expression condition = expression();
final Statement statement = statementOrBlock();
return new WhileStatement(condition, statement);
}
private Statement doWhileStatement() {
final Statement statement = statementOrBlock();
consume(TokenType.WHILE);
final Expression condition = expression();
return new DoWhileStatement(condition, statement);
}
private Statement forStatement() {
int foreachIndex = lookMatch(0, TokenType.LPAREN) ? 1 : 0;
if (lookMatch(foreachIndex, TokenType.WORD) && lookMatch(foreachIndex + 1, TokenType.COLON)) {
// for v : arr || for (v : arr)
return foreachArrayStatement();
}
if (lookMatch(foreachIndex, TokenType.WORD) && lookMatch(foreachIndex + 1, TokenType.COMMA)
&& lookMatch(foreachIndex + 2, TokenType.WORD) && lookMatch(foreachIndex + 3, TokenType.COLON)) {
// for key, value : arr || for (key, value : arr)
return foreachMapStatement();
}
// for (init, condition, increment) body
boolean optParentheses = match(TokenType.LPAREN);
final Statement initialization = assignmentStatement();
consume(TokenType.COMMA);
final Expression termination = expression();
consume(TokenType.COMMA);
final Statement increment = assignmentStatement();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForStatement(initialization, termination, increment, statement);
}
private ForeachArrayStatement foreachArrayStatement() {
boolean optParentheses = match(TokenType.LPAREN);
final String variable = consume(TokenType.WORD).getText();
consume(TokenType.COLON);
final Expression container = expression();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForeachArrayStatement(variable, container, statement);
}
private ForeachMapStatement foreachMapStatement() {
boolean optParentheses = match(TokenType.LPAREN);
final String key = consume(TokenType.WORD).getText();
consume(TokenType.COMMA);
final String value = consume(TokenType.WORD).getText();
consume(TokenType.COLON);
final Expression container = expression();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForeachMapStatement(key, value, container, statement);
}
private FunctionDefineStatement functionDefine() {
// def name(arg1, arg2 = value) { ... } || def name(args) = expr
final String name = consume(TokenType.WORD).getText();
final Arguments arguments = arguments();
final Statement body = statementBody();
return new FunctionDefineStatement(name, arguments, body);
}
private Arguments arguments() {
// (arg1, arg2, arg3 = expr1, arg4 = expr2)
final Arguments arguments = new Arguments();
boolean startsOptionalArgs = false;
consume(TokenType.LPAREN);
while (!match(TokenType.RPAREN)) {
final String name = consume(TokenType.WORD).getText();
if (match(TokenType.EQ)) {
startsOptionalArgs = true;
arguments.addOptional(name, variable());
} else if (!startsOptionalArgs) {
arguments.addRequired(name);
} else {
throw new ParseException("Required argument cannot be after optional");
}
match(TokenType.COMMA);
}
return arguments;
}
private Statement statementBody() {
if (match(TokenType.EQ)) {
return new ReturnStatement(expression());
}
return statementOrBlock();
}
private Expression functionChain(Expression qualifiedNameExpr) {
// f1().f2().f3() || f1().key
final Expression expr = function(qualifiedNameExpr);
if (lookMatch(0, TokenType.DOT)) {
final List<Expression> indices = variableSuffix();
if (indices == null | indices.isEmpty()) return expr;
if (lookMatch(0, TokenType.LPAREN)) {
// next function call
return functionChain(new ContainerAccessExpression(expr, indices));
}
// container access
return new ContainerAccessExpression(expr, indices);
}
return expr;
}
private FunctionalExpression function(Expression qualifiedNameExpr) {
// function(arg1, arg2, ...)
consume(TokenType.LPAREN);
final FunctionalExpression function = new FunctionalExpression(qualifiedNameExpr);
while (!match(TokenType.RPAREN)) {
function.addArgument(expression());
match(TokenType.COMMA);
}
return function;
}
private Expression array() {
// [value1, value2, ...]
consume(TokenType.LBRACKET);
final List<Expression> elements = new ArrayList<>();
while (!match(TokenType.RBRACKET)) {
elements.add(expression());
match(TokenType.COMMA);
}
return new ArrayExpression(elements);
}
private Expression map() {
// {key1 : value1, key2 : value2, ...}
consume(TokenType.LBRACE);
final Map<Expression, Expression> elements = new HashMap<>();
while (!match(TokenType.RBRACE)) {
final Expression key = primary();
consume(TokenType.COLON);
final Expression value = expression();
elements.put(key, value);
match(TokenType.COMMA);
}
return new MapExpression(elements);
}
private MatchExpression match() {
// match expression {
// case pattern1: result1
// case pattern2 if extr: result2
final Expression expression = expression();
consume(TokenType.LBRACE);
final List<MatchExpression.Pattern> patterns = new ArrayList<>();
do {
consume(TokenType.CASE);
MatchExpression.Pattern pattern = null;
final Token current = get(0);
if (match(TokenType.NUMBER)) {
// case 0.5:
pattern = new MatchExpression.ConstantPattern(
NumberValue.of(createNumber(current.getText(), 10))
);
} else if (match(TokenType.HEX_NUMBER)) {
// case
pattern = new MatchExpression.ConstantPattern(
NumberValue.of(createNumber(current.getText(), 16))
);
} else if (match(TokenType.TEXT)) {
// case "text":
pattern = new MatchExpression.ConstantPattern(
new StringValue(current.getText())
);
} else if (match(TokenType.WORD)) {
// case value:
pattern = new MatchExpression.VariablePattern(current.getText());
} else if (match(TokenType.LBRACKET)) {
// case [x :: xs]:
final MatchExpression.ListPattern listPattern = new MatchExpression.ListPattern();
while (!match(TokenType.RBRACKET)) {
listPattern.add(consume(TokenType.WORD).getText());
match(TokenType.COLONCOLON);
}
pattern = listPattern;
} else if (match(TokenType.LPAREN)) {
// case (1, 2):
final MatchExpression.TuplePattern tuplePattern = new MatchExpression.TuplePattern();
while (!match(TokenType.RPAREN)) {
if ("_".equals(get(0).getText())) {
tuplePattern.addAny();
consume(TokenType.WORD);
} else {
tuplePattern.add(expression());
}
match(TokenType.COMMA);
}
pattern = tuplePattern;
}
if (pattern == null) {
throw new ParseException("Wrong pattern in match expression: " + current);
}
if (match(TokenType.IF)) {
// case e if e > 0:
pattern.optCondition = expression();
}
consume(TokenType.COLON);
if (lookMatch(0, TokenType.LBRACE)) {
pattern.result = block();
} else {
pattern.result = new ReturnStatement(expression());
}
patterns.add(pattern);
} while (!match(TokenType.RBRACE));
return new MatchExpression(expression, patterns);
}
private Expression expression() {
return assignment();
}
private Expression assignment() {
final Expression assignment = assignmentStrict();
if (assignment != null) {
return assignment;
}
return ternary();
}
private Expression assignmentStrict() {
final int position = pos;
final Expression targetExpr = qualifiedName();
if ((targetExpr == null) || !(targetExpr instanceof Accessible)) {
pos = position;
return null;
}
final TokenType currentType = get(0).getType();
if (!ASSIGN_OPERATORS.containsKey(currentType)) {
pos = position;
return null;
}
match(currentType);
final BinaryExpression.Operator op = ASSIGN_OPERATORS.get(currentType);
final Expression expression = expression();
return new AssignmentExpression(op, (Accessible) targetExpr, expression);
}
private Expression ternary() {
Expression result = logicalOr();
if (match(TokenType.QUESTION)) {
final Expression trueExpr = expression();
consume(TokenType.COLON);
final Expression falseExpr = expression();
return new TernaryExpression(result, trueExpr, falseExpr);
}
if (match(TokenType.QUESTIONCOLON)) {
return new BinaryExpression(BinaryExpression.Operator.ELVIS, result, expression());
}
return result;
}
private Expression logicalOr() {
Expression result = logicalAnd();
while (true) {
if (match(TokenType.BARBAR)) {
result = new ConditionalExpression(ConditionalExpression.Operator.OR, result, logicalAnd());
continue;
}
break;
}
return result;
}
private Expression logicalAnd() {
Expression result = bitwiseOr();
while (true) {
if (match(TokenType.AMPAMP)) {
result = new ConditionalExpression(ConditionalExpression.Operator.AND, result, bitwiseOr());
continue;
}
break;
}
return result;
}
private Expression bitwiseOr() {
Expression expression = bitwiseXor();
while (true) {
if (match(TokenType.BAR)) {
expression = new BinaryExpression(BinaryExpression.Operator.OR, expression, bitwiseXor());
continue;
}
break;
}
return expression;
}
private Expression bitwiseXor() {
Expression expression = bitwiseAnd();
while (true) {
if (match(TokenType.CARET)) {
expression = new BinaryExpression(BinaryExpression.Operator.XOR, expression, bitwiseAnd());
continue;
}
break;
}
return expression;
}
private Expression bitwiseAnd() {
Expression expression = equality();
while (true) {
if (match(TokenType.AMP)) {
expression = new BinaryExpression(BinaryExpression.Operator.AND, expression, equality());
continue;
}
break;
}
return expression;
}
private Expression equality() {
Expression result = conditional();
if (match(TokenType.EQEQ)) {
return new ConditionalExpression(ConditionalExpression.Operator.EQUALS, result, conditional());
}
if (match(TokenType.EXCLEQ)) {
return new ConditionalExpression(ConditionalExpression.Operator.NOT_EQUALS, result, conditional());
}
return result;
}
private Expression conditional() {
Expression result = shift();
while (true) {
if (match(TokenType.LT)) {
result = new ConditionalExpression(ConditionalExpression.Operator.LT, result, shift());
continue;
}
if (match(TokenType.LTEQ)) {
result = new ConditionalExpression(ConditionalExpression.Operator.LTEQ, result, shift());
continue;
}
if (match(TokenType.GT)) {
result = new ConditionalExpression(ConditionalExpression.Operator.GT, result, shift());
continue;
}
if (match(TokenType.GTEQ)) {
result = new ConditionalExpression(ConditionalExpression.Operator.GTEQ, result, shift());
continue;
}
break;
}
return result;
}
private Expression shift() {
Expression expression = additive();
while (true) {
if (match(TokenType.LTLT)) {
expression = new BinaryExpression(BinaryExpression.Operator.LSHIFT, expression, additive());
continue;
}
if (match(TokenType.GTGT)) {
expression = new BinaryExpression(BinaryExpression.Operator.RSHIFT, expression, additive());
continue;
}
if (match(TokenType.GTGTGT)) {
expression = new BinaryExpression(BinaryExpression.Operator.URSHIFT, expression, additive());
continue;
}
if (match(TokenType.DOTDOT)) {
expression = new BinaryExpression(BinaryExpression.Operator.RANGE, expression, additive());
continue;
}
break;
}
return expression;
}
private Expression additive() {
Expression result = multiplicative();
while (true) {
if (match(TokenType.PLUS)) {
result = new BinaryExpression(BinaryExpression.Operator.ADD, result, multiplicative());
continue;
}
if (match(TokenType.MINUS)) {
result = new BinaryExpression(BinaryExpression.Operator.SUBTRACT, result, multiplicative());
continue;
}
if (match(TokenType.COLONCOLON)) {
result = new BinaryExpression(BinaryExpression.Operator.PUSH, result, multiplicative());
continue;
}
if (match(TokenType.AT)) {
result = new BinaryExpression(BinaryExpression.Operator.AT, result, multiplicative());
continue;
}
break;
}
return result;
}
private Expression multiplicative() {
Expression result = unary();
while (true) {
if (match(TokenType.STAR)) {
result = new BinaryExpression(BinaryExpression.Operator.MULTIPLY, result, unary());
continue;
}
if (match(TokenType.SLASH)) {
result = new BinaryExpression(BinaryExpression.Operator.DIVIDE, result, unary());
continue;
}
if (match(TokenType.PERCENT)) {
result = new BinaryExpression(BinaryExpression.Operator.REMAINDER, result, unary());
continue;
}
if (match(TokenType.STARSTAR)) {
result = new BinaryExpression(BinaryExpression.Operator.POWER, result, unary());
continue;
}
break;
}
return result;
}
private Expression unary() {
if (match(TokenType.PLUSPLUS)) {
return new UnaryExpression(UnaryExpression.Operator.INCREMENT_PREFIX, primary());
}
if (match(TokenType.MINUSMINUS)) {
return new UnaryExpression(UnaryExpression.Operator.DECREMENT_PREFIX, primary());
}
if (match(TokenType.MINUS)) {
return new UnaryExpression(UnaryExpression.Operator.NEGATE, primary());
}
if (match(TokenType.EXCL)) {
return new UnaryExpression(UnaryExpression.Operator.NOT, primary());
}
if (match(TokenType.TILDE)) {
return new UnaryExpression(UnaryExpression.Operator.COMPLEMENT, primary());
}
if (match(TokenType.PLUS)) {
return primary();
}
return primary();
}
private Expression primary() {
if (match(TokenType.LPAREN)) {
Expression result = expression();
match(TokenType.RPAREN);
return result;
}
if (match(TokenType.COLONCOLON)) {
final String functionName = consume(TokenType.WORD).getText();
return new FunctionReferenceExpression(functionName);
}
if (match(TokenType.MATCH)) {
return match();
}
if (match(TokenType.DEF)) {
final Arguments arguments = arguments();
final Statement statement = statementBody();
return new ValueExpression(new UserDefinedFunction(arguments, statement));
}
return variable();
}
private Expression variable() {
// function(...
if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.LPAREN)) {
return functionChain(new ValueExpression(consume(TokenType.WORD).getText()));
}
final Expression qualifiedNameExpr = qualifiedName();
if (qualifiedNameExpr != null) {
// variable(args) || arr["key"](args) || obj.key(args)
if (lookMatch(0, TokenType.LPAREN)) {
return functionChain(qualifiedNameExpr);
}
// postfix increment/decrement
if (match(TokenType.PLUSPLUS)) {
return new UnaryExpression(UnaryExpression.Operator.INCREMENT_POSTFIX, qualifiedNameExpr);
}
if (match(TokenType.MINUSMINUS)) {
return new UnaryExpression(UnaryExpression.Operator.DECREMENT_POSTFIX, qualifiedNameExpr);
}
return qualifiedNameExpr;
}
if (lookMatch(0, TokenType.LBRACKET)) {
return array();
}
if (lookMatch(0, TokenType.LBRACE)) {
return map();
}
return value();
}
private Expression qualifiedName() {
// var || var.key[index].key2
final Token current = get(0);
if (!match(TokenType.WORD)) return null;
final List<Expression> indices = variableSuffix();
if ((indices == null) || indices.isEmpty()) {
return new VariableExpression(current.getText());
}
return new ContainerAccessExpression(current.getText(), indices);
}
private List<Expression> variableSuffix() {
// .key1.arr1[expr1][expr2].key2
if (!lookMatch(0, TokenType.DOT) && !lookMatch(0, TokenType.LBRACKET)) {
return null;
}
final List<Expression> indices = new ArrayList<>();
while (lookMatch(0, TokenType.DOT) || lookMatch(0, TokenType.LBRACKET)) {
if (match(TokenType.DOT)) {
final String fieldName = consume(TokenType.WORD).getText();
final Expression key = new ValueExpression(fieldName);
indices.add(key);
}
if (match(TokenType.LBRACKET)) {
indices.add(expression());
consume(TokenType.RBRACKET);
}
}
return indices;
}
private Expression value() {
final Token current = get(0);
if (match(TokenType.NUMBER)) {
return new ValueExpression(createNumber(current.getText(), 10));
}
if (match(TokenType.HEX_NUMBER)) {
return new ValueExpression(createNumber(current.getText(), 16));
}
if (match(TokenType.TEXT)) {
return new ValueExpression(current.getText());
}
throw new ParseException("Unknown expression: " + current);
}
private Number createNumber(String text, int radix) {
// Double
if (text.contains(".")) {
return Double.parseDouble(text);
}
// Integer
try {
return Integer.parseInt(text, radix);
} catch (NumberFormatException nfe) {
return Long.parseLong(text, radix);
}
}
private Token consume(TokenType type) {
final Token current = get(0);
if (type != current.getType()) throw new ParseException("Token " + current + " doesn't match " + type);
pos++;
return current;
}
private boolean match(TokenType type) {
final Token current = get(0);
if (type != current.getType()) return false;
pos++;
return true;
}
private boolean lookMatch(int pos, TokenType type) {
return get(pos).getType() == type;
}
private Token get(int relativePosition) {
final int position = pos + relativePosition;
if (position >= size) return EOF;
return tokens.get(position);
}
} |
package com.artemis.utils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Collection type a bit like ArrayList but does not preserve the order of its
* entities, speedwise it is very good, especially suited for games.
*
* @param <E>
* object type this bag holds
*
* @author Arni Arent
*/
public class Bag<E> implements ImmutableBag<E> {
/** The backing array. */
E[] data;
/** The amount of elements contained in bag. */
protected int size = 0;
private BagIterator it;
/**
* Constructs an empty Bag with an initial capacity of 64.
*/
public Bag() {
this(64);
}
/**
* Constructs an empty Bag with the specified initial capacity.
*
* @param capacity
* the initial capacity of Bag
*/
@SuppressWarnings("unchecked")
public Bag(int capacity) {
data = (E[])new Object[capacity];
}
/**
* Removes the element at the specified position in this Bag.
* <p>
* It does this by overwriting it was last element then removing last
* element
* </p>
*
* @param index
* the index of element to be removed
*
* @return element that was removed from the Bag
*
* @throws ArrayIndexOutOfBoundsException
*/
public E remove(int index) throws ArrayIndexOutOfBoundsException {
E e = data[index]; // make copy of element to remove so it can be returned
data[index] = data[--size]; // overwrite item to remove with last element
data[size] = null; // null last element, so gc can do its work
return e;
}
/**
* Sorts the bag using the {@code comparator}.
*
* @param comparator
*/
public void sort(Comparator<E> comparator) {
Sort.instance().sort(this, comparator);
}
/**
* Remove and return the last object in the bag.
*
* @return the last object in the bag, null if empty
*/
public E removeLast() {
if(size > 0) {
E e = data[--size];
data[size] = null;
return e;
}
return null;
}
/**
* Removes the first occurrence of the specified element from this Bag, if
* it is present.
* <p>
* If the Bag does not contain the element, it is unchanged. It does this
* by overwriting it was last element then removing last element
* </p>
*
* @param e
* element to be removed from this list, if present
*
* @return {@code true} if this list contained the specified element
*/
public boolean remove(E e) {
for (int i = 0; i < size; i++) {
E e2 = data[i];
if (e == e2) {
data[i] = data[--size]; // overwrite item to remove with last element
data[size] = null; // null last element, so gc can do its work
return true;
}
}
return false;
}
/**
* Check if bag contains this element.
*
* @param e
* element to check
*
* @return {@code true} if the bag contains this element
*/
@Override
public boolean contains(E e) {
for(int i = 0; size > i; i++) {
if(e == data[i]) {
return true;
}
}
return false;
}
/**
* Removes from this Bag all of its elements that are contained in the
* specified Bag.
*
* @param bag
* Bag containing elements to be removed from this Bag
*
* @return {@code true} if this Bag changed as a result of the call
*/
public boolean removeAll(ImmutableBag<E> bag) {
boolean modified = false;
for (int i = 0, s = bag.size(); s > i; i++) {
E e1 = bag.get(i);
for (int j = 0; j < size; j++) {
E e2 = data[j];
if (e1 == e2) {
remove(j);
j
modified = true;
break;
}
}
}
return modified;
}
/**
* Returns the element at the specified position in Bag.
*
* @param index
* index of the element to return
*
* @return the element at the specified position in bag
*
* @throws ArrayIndexOutOfBoundsException
*/
@Override
public E get(int index) throws ArrayIndexOutOfBoundsException {
return data[index];
}
/**
* Returns the element at the specified position in Bag. This method
* ensures that the bag grows if the requested index is outside the bounds
* of the current backing array.
*
* @param index
* index of the element to return
*
* @return the element at the specified position in bag
*
*/
public E safeGet(int index) {
ensureCapacity(index);
return data[index];
}
/**
* Returns the number of elements in this bag.
*
* @return the number of elements in this bag
*/
@Override
public int size() {
return size;
}
/**
* Returns the number of elements the bag can hold without growing.
*
* @return the number of elements the bag can hold without growing
*/
public int getCapacity() {
return data.length;
}
/**
* Checks if the internal storage supports this index.
*
* @param index
* index to check
*
* @return {@code true} if the index is within bounds
*/
public boolean isIndexWithinBounds(int index) {
return index < getCapacity();
}
/**
* Returns true if this bag contains no elements.
*
* @return {@code true} if this bag contains no elements
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Adds the specified element to the end of this bag.
* <p>
* If required, it also increases the capacity of the bag.
* </p>
*
* @param e
* element to be added to this list
*/
public void add(E e) {
// is size greater than capacity increase capacity
if (size == data.length) {
grow();
}
data[size++] = e;
}
/**
* Set element at specified index in the bag.
*
* @param index
* position of element
* @param e
* the element
*/
public void set(int index, E e) {
if(index >= data.length) {
grow(index * (7 / 4) + 1);
}
size = Math.max(size, index + 1);
data[index] = e;
}
/**
* Increase the capacity of the bag.
* <p>
* Capacity will increase by (3/2)*capacity + 1.
* </p>
*/
private void grow() {
int newCapacity = data.length * (7 / 4) + 1;
grow(newCapacity);
}
/**
* Increase the capacity of the bag.
*
* @param newCapacity
* new capacity to grow to
*
* @throws ArrayIndexOutOfBoundsException if new capacity is smaller than old
*/
@SuppressWarnings("unchecked")
private void grow(int newCapacity) throws ArrayIndexOutOfBoundsException {
E[] oldData = data;
data = (E[])new Object[newCapacity];
System.arraycopy(oldData, 0, data, 0, oldData.length);
}
/**
* Check if an item, if added at the given item will fit into the bag.
* <p>
* If not, the bag capacity will be increased to hold an item at the index.
* </p>
*
* @param index
* index to check
*/
public void ensureCapacity(int index) {
if(index >= data.length) {
grow(index * (7 / 4) + 1);
}
}
/**
* Removes all of the elements from this bag.
* <p>
* The bag will be empty after this call returns.
* </p>
*/
public void clear() {
Arrays.fill(data, 0, size, null);
size = 0;
}
/**
* Removes all of the elements from this by re-allocating the backing
* array.
* <p>
* The bag will be empty after this call returns.
* </p>
*/
@SuppressWarnings("unchecked")
public void fastClear() {
// new null array so gc can clean up old one
data = (E[])new Object[data.length];
size = 0;
}
/**
* Add all items into this bag.
*
* @param items
* bag with items to add
*/
public void addAll(ImmutableBag<E> items) {
for(int i = 0, s = items.size(); s > i; i++) {
add(items.get(i));
}
}
/**
* Returns this bag's underlying array.
* <p>
* Use with care.
* </p>
*
* @return the underlying array
*
* @see Bag#size()
*/
public Object[] getData() {
return data;
}
@Override
public Iterator<E> iterator() {
if (it == null) it = new BagIterator();
it.validCursorPos = false;
it.cursor = 0;
return it;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Bag(");
for (int i = 0; size > i; i++) {
if (i > 0) sb.append(", ");
sb.append(data[i]);
}
sb.append(')');
return sb.toString();
}
/**
* An Iterator for Bag.
*
* @see java.util.Iterator
*/
private final class BagIterator implements Iterator<E> {
/** Current position. */
private int cursor;
/** True if the current position is within bounds. */
private boolean validCursorPos;
@Override
public boolean hasNext() {
return (cursor < size);
}
@Override
public E next() throws NoSuchElementException {
if (cursor == size) {
throw new NoSuchElementException("Iterated past last element");
}
E e = data[cursor++];
validCursorPos = true;
return e;
}
@Override
public void remove() throws IllegalStateException {
if (!validCursorPos) {
throw new IllegalStateException();
}
validCursorPos = false;
Bag.this.remove(--cursor);
}
}
} |
package com.belling.base.util;
import org.apache.log4j.Logger;
import com.google.common.base.Strings;
/**
*
* <br/>
* XX 2014730 <br/>
* <p>
* Logger
* <p>
*
* @version 1.0,2014730 <br/>
*
*/
public class LoggerUtils {
/**
* Debug
*/
public static boolean isDebug = Logger.getLogger(LoggerUtils.class).isDebugEnabled();
/**
* Debug
* @param clazz .Class
* @param message
*/
public static void debug(Class<? extends Object> clazz ,String message){
if(!isDebug)return ;
Logger logger = Logger.getLogger(clazz);
logger.debug(message);
}
/**
* Debug
* @param clazz .Class
* @param fmtString key
* @param value value
*/
public static void fmtDebug(Class<? extends Object> clazz,String fmtString,Object...value){
if(!isDebug)return ;
if(Strings.isNullOrEmpty(fmtString)){
return ;
}
if(null != value && value.length != 0){
fmtString = String.format(fmtString, value);
}
debug(clazz, fmtString);
}
/**
* Error
* @param clazz .Class
* @param message
* @param e
*/
public static void error(Class<? extends Object> clazz ,String message,Exception e){
Logger logger = Logger.getLogger(clazz);
if(null == e){
logger.error(message);
return ;
}
logger.error(message, e);
}
/**
* Error
* @param clazz .Class
* @param message
*/
public static void error(Class<? extends Object> clazz ,String message){
error(clazz, message, null);
}
/**
*
* @param clazz .Class
* @param fmtString key
* @param e
* @param value value
*/
public static void fmtError(Class<? extends Object> clazz,Exception e,String fmtString,Object...value){
if(Strings.isNullOrEmpty(fmtString)){
return ;
}
if(null != value && value.length != 0){
fmtString = String.format(fmtString, value);
}
error(clazz, fmtString, e);
}
/**
*
* @param clazz .Class
* @param fmtString key
* @param value value
*/
public static void fmtError(Class<? extends Object> clazz,
String fmtString, Object...value) {
if(Strings.isNullOrEmpty(fmtString)){
return ;
}
if(null != value && value.length != 0){
fmtString = String.format(fmtString, value);
}
error(clazz, fmtString);
}
} |
package com.ctc.wstx.msv;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.*;
import org.xml.sax.InputSource;
import org.codehaus.stax2.validation.*;
import com.sun.msv.grammar.xmlschema.XMLSchemaGrammar;
import com.sun.msv.reader.GrammarReaderController;
import com.sun.msv.reader.xmlschema.XMLSchemaReader;
public class W3CSchemaFactory
extends BaseSchemaFactory
{
/**
* For now, there's no need for fine-grained error/problem reporting
* infrastructure, so let's just use a dummy controller.
*/
protected final GrammarReaderController mDummyController =
new com.sun.msv.reader.util.IgnoreController();
public W3CSchemaFactory()
{
super(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
}
/*
////////////////////////////////////////////////////////////
// Non-public methods
////////////////////////////////////////////////////////////
*/
@Override
protected XMLValidationSchema loadSchema(InputSource src, Object sysRef)
throws XMLStreamException
{
/* 26-Oct-2007, TSa: Are sax parser factories safe to share?
* If not, should just create new instances for each
* parsed schema.
*/
SAXParserFactory saxFactory = getSaxFactory();
MyGrammarController ctrl = new MyGrammarController();
XMLSchemaGrammar grammar = XMLSchemaReader.parse(src, saxFactory, ctrl);
if (grammar == null) {
String msg = "Failed to load W3C Schema from '"+sysRef+"'";
String emsg = ctrl.mErrorMsg;
if (emsg != null) {
msg = msg + ": "+emsg;
}
throw new XMLStreamException(msg);
}
return new W3CSchema(grammar);
}
} |
package com.dua3.utility.logging;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.time.Instant;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import com.dua3.utility.lang.RingBuffer;
public class LogPanel extends JPanel implements LogListener {
private static final long serialVersionUID = 1L;
private final JTable table;
private final LogDispatcher dispatcher;
private static class Column {
String name;
Function<LogRecord, Object> extractor;
Column(String name, Function<LogRecord,Object> extractor) {
this.name = name;
this.extractor = extractor;
}
String name() {
return name;
}
Object get(LogRecord r) {
return extractor.apply(r);
}
}
private static final Column[] COLUMNS = {
new Column("Time", r -> Instant.ofEpochMilli(r.getMillis())),
new Column("Level", r -> r.getLevel()),
new Column("Message", r -> r.getMessage())
};
private static final class LogTableModel extends AbstractTableModel {
LogTableModel(){
initStyles();
}
private static final long serialVersionUID = 1L;
private RingBuffer<LogRecord> records = new RingBuffer<>(1000);
private final TreeMap<Integer, MessageStyle> styles = new TreeMap<>();
@Override
public int getRowCount() {
return records.size();
}
@Override
public int getColumnCount() {
return COLUMNS.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return COLUMNS[columnIndex].get(getRecordForRow(rowIndex));
}
private LogRecord getRecordForRow(int rowIndex) {
return records.get(rowIndex);
}
public void publish(LogRecord r) {
SwingUtilities.invokeLater(() -> addRecord(r));
}
private void addRecord(LogRecord r) {
records.add(r);
fireTableDataChanged();
}
private MessageStyle getStyle(Level level) {
Entry<Integer, MessageStyle> entry = styles.ceilingEntry(level.intValue());
return entry == null ? styles.lastEntry().getValue() : entry.getValue();
}
private MessageStyle createStyle(Level level, Color color) {
MessageStyle ms = new MessageStyle(color);
styles.put(level.intValue(), ms);
return ms;
}
private void initStyles() {
createStyle(Level.SEVERE, Color.RED);
createStyle(Level.WARNING, Color.RED);
createStyle(Level.INFO, Color.BLUE);
createStyle(Level.CONFIG, Color.BLACK);
createStyle(Level.FINE, Color.BLACK);
createStyle(Level.FINER, Color.BLACK);
createStyle(Level.FINEST, Color.BLACK);
}
}
static class LogRecordTableCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
LogTableModel model = (LogTableModel) table.getModel();
LogRecord r = model.getRecordForRow(row);
MessageStyle style = model.getStyle(r.getLevel());
comp.setForeground(style.color);
return comp;
}
}
static class MessageStyle {
public MessageStyle(Color color) {
this.color = color;
}
Color color;
}
private LogTableModel dataModel;
public LogPanel() {
super();
setLayout(new BorderLayout());
table = new JTable();
add(table);
dataModel = new LogTableModel();
table.setModel(dataModel);
table.getColumnModel().getColumn(1).setCellRenderer(new LogRecordTableCellRenderer());
dispatcher = new LogDispatcher(this);
}
@Override
public void publish(LogRecord record) {
dataModel.publish(record);
}
@Override
public void flush() {
// nop
}
@Override
public void close() {
// nop
}
public Handler getHandler() {
return dispatcher;
}
} |
package com.edmundophie.cassandra;
import com.datastax.driver.core.*;
import com.datastax.driver.core.utils.UUIDs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Twitter {
private Cluster cluster;
private Session session;
private final static String DEFAULT_HOST = "127.0.0.1";
private final static String DEFAULT_REPLICATION_STRATEGY = "SimpleStrategy";
private final static String DEFAULT_REPLICATION_FACTOR = "1";
private final static String TWITTER_KEYSPACE = "twitter";
private final static String TABLE_USERS = "users";
private final static String TABLE_FOLLOWERS = "followers";
private final static String TABLE_USERLINE = "userline";
private final static String TABLE_TIMELINE = "timeline";
private final static String TABLE_TWEETS = "tweets";
private final static String TABLE_FRIENDS = "friends";
public static void main(String[] args) throws IOException {
String host = DEFAULT_HOST;
String replicationStrategy = DEFAULT_REPLICATION_STRATEGY;
String replicationFactor = DEFAULT_REPLICATION_FACTOR;
if(args.length>0)
host = args[0];
if(args.length>1)
replicationStrategy = args[1];
if(args.length>2)
replicationFactor = args[2];
Twitter twitter = new Twitter();
twitter.connect(host);
twitter.createSchema(TWITTER_KEYSPACE, replicationStrategy, replicationFactor);
System.out.println("\n*** DIRECTIVES ***");
System.out.println("
System.out.println("* REGISTER <username> <password>");
System.out.println("* FOLLOW <follower_username> <followed_username>");
System.out.println("* ADDTWEET <username> <tweet>");
System.out.println("* VIEWTWEET <username>");
System.out.println("* TIMELINE <username>");
System.out.println("* EXIT");
System.out.println("
System.out.println("* Type your command...");
String command = null;
String unsplittedParams = null;
do {
String input = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
if(input.isEmpty()){
printInvalidCommand();
}
else {
String[] parameters = new String[0];
int i = input.indexOf(" ");
if (i > -1) {
command = input.substring(0, i);
unsplittedParams = input.substring(i + 1);
parameters = unsplittedParams.split(" ");
} else
command = input;
if (command.equalsIgnoreCase("REGISTER") && parameters.length == 2) {
if(twitter.isUserExist(parameters[0]))
System.out.println("* Username already exist!");
else {
twitter.registerUser(parameters[0], parameters[1]);
System.out.println("* " + parameters[0] + " succesfully registered");
}
} else if (command.equalsIgnoreCase("FOLLOW") && parameters.length == 2) {
if(!twitter.isUserExist(parameters[0]) || !twitter.isUserExist(parameters[1]))
System.out.println("* Failed to execute command!\n* User may have not been registered");
else {
twitter.followUser(parameters[0], parameters[1]);
System.out.println("* " + parameters[0] + " is now following " + parameters[1]);
}
} else if (command.equalsIgnoreCase("ADDTWEET") && parameters.length>=2) {
if(!twitter.isUserExist(parameters[0]))
System.out.println("* Failed to execute command!\n* User may have not been registered");
else {
twitter.insertTweet(parameters[0], unsplittedParams.substring(parameters[0].length()));
System.out.println("* " + parameters[0] + " tweet has been added");
}
} else if (command.equalsIgnoreCase("VIEWTWEET") && parameters.length==1) {
ResultSet results = twitter.getUserline(parameters[0]);
printTweet(results);
} else if (command.equalsIgnoreCase("TIMELINE") && parameters.length==1) {
ResultSet results = twitter.getTimeline(parameters[0]);
printTweet(results);
} else if (command.equalsIgnoreCase("EXIT")) {
System.out.println("Exiting...");
} else
printInvalidCommand();
}
} while(!command.equalsIgnoreCase("EXIT"));
twitter.close();
}
public static void printInvalidCommand() {
System.err.println("* Invalid Command");
}
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.println("Connected to cluster: " + metadata.getClusterName());
for(Host host:metadata.getAllHosts()) {
System.out.printf("Datacenter: %s, Host: %s, Rack: %s\n", host.getDatacenter(), host.getDatacenter(), host.getRack());
}
session = cluster.connect();
}
public void close() {
session.close();
cluster.close();
}
public Session getSession() {
return this.session;
}
public void createSchema(String keyspace, String replicationStrategy, String replicationFactor) {
System.out.println("\nCreating schema...");
// Create keyspace
String query = "CREATE KEYSPACE IF NOT EXISTS " + keyspace +
" WITH replication = {'class':'" + replicationStrategy + "', 'replication_factor':"+replicationFactor+"};";
session.execute(query);
session.execute("USE "+TWITTER_KEYSPACE + ";");
// Create table 'users'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_USERS +" (" +
"username text PRIMARY KEY, " +
"password text" +
")";
session.execute(query);
// Create table 'friends'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_FRIENDS +" (" +
" username text, " +
" friend text, " +
" since timestamp, " +
" PRIMARY KEY (username, friend) " +
")";
session.execute(query);
// Create table 'followers'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_FOLLOWERS+" (" +
" username text, " +
" follower text, " +
" since timestamp, " +
" PRIMARY KEY (username, follower) " +
")";
session.execute(query);
// Create table 'tweets'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_TWEETS +" (" +
" tweet_id uuid PRIMARY KEY, " +
" username text, " +
" body text " +
")";
session.execute(query);
// Create table 'userline'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_USERLINE +" (" +
" username text, " +
" time timeuuid, " +
" tweet_id uuid, " +
" PRIMARY KEY (username, time)" +
") WITH CLUSTERING ORDER BY (time DESC)";
session.execute(query);
// Create table 'timeline'
query = "CREATE TABLE IF NOT EXISTS "+ TABLE_TIMELINE +" (" +
" username text, " +
" time timeuuid, " +
" tweet_id uuid, " +
" PRIMARY KEY (username, time)" +
") WITH CLUSTERING ORDER BY (time DESC)";
session.execute(query);
}
public void registerUser(String username, String password) {
String query = "INSERT INTO " + TABLE_USERS + " (username, password) " +
"VALUES ('" + username + "', '" + password + "');";
session.execute(query);
}
public void followUser(String followerUsername, String followedUsername) {
Long unixTime = System.currentTimeMillis();
String query = "INSERT INTO " + TABLE_FOLLOWERS + " (username, follower, since) " +
"VALUES ('" + followedUsername + "', '" + followerUsername+ "', " + unixTime + ");";
session.execute(query);
query = "INSERT INTO " + TABLE_FRIENDS + " (username, friend, since) " +
"VALUES ('" + followerUsername + "', '" + followedUsername+ "', " + unixTime + ");";
session.execute(query);
}
public void insertTweet(String username, String tweet) {
String tweetId = UUIDs.random().toString();
String timeId = UUIDs.timeBased().toString();
String query = "INSERT INTO " + TABLE_TWEETS + " (tweet_id, username, body) " +
"VALUES (" + tweetId + ", '" + username +"', '"+ tweet +"');";
session.execute(query);
query = "INSERT INTO "+ TABLE_USERLINE +" (username, time, tweet_id) " +
"VALUES ('" + username + "', " + timeId +", "+ tweetId +");";
session.execute(query);
query = "INSERT INTO "+ TABLE_TIMELINE +" (username, time, tweet_id) " +
"VALUES ('" + username + "', " + timeId +", "+ tweetId +");";
session.execute(query);
ResultSet results = session.execute("SELECT follower FROM " + TABLE_FOLLOWERS +
" WHERE username = '" + username + "';");
List<Row> rows = results.all();
if(rows.size()>0) {
query = "INSERT INTO " + TABLE_TIMELINE + " (username, time, tweet_id) VALUES ";
for(int i=0;i<rows.size();++i) {
query += "('" + rows.get(i).getString(0) + "', "+ timeId +", " + tweetId + ")";
if(i!=rows.size()-1)
query += ",";
}
query += ";";
session.execute(query);
}
}
public ResultSet getUserline(String username) {
ResultSet results = session.execute("SELECT tweet_id FROM " + TABLE_USERLINE +
" WHERE username = '" + username + "';");
List<Row> rows = results.all();
String tweetIds = "";
for(int i=0;i<rows.size();++i) {
tweetIds += rows.get(i).getUUID("tweet_id");
if(i!=rows.size()-1)
tweetIds += ",";
}
String query = "SELECT username, body FROM " + TABLE_TWEETS +
" WHERE tweet_id IN ("+ tweetIds +");";
results = session.execute(query);
return results;
}
public ResultSet getTimeline(String username) {
ResultSet results = session.execute("SELECT tweet_id FROM " + TABLE_TIMELINE +
" WHERE username = '" + username + "';");
List<Row> rows = results.all();
String tweetIds = "";
for(int i=0;i<rows.size();++i) {
tweetIds += rows.get(i).getUUID("tweet_id");
if(i!=rows.size()-1)
tweetIds += ",";
}
String query = "SELECT * FROM " + TABLE_TWEETS +
" WHERE tweet_id IN ("+ tweetIds +");";
results = session.execute(query);
return results;
}
public static void printTweet(ResultSet results) {
List<Row> resultslist = results.all();
if(resultslist.isEmpty()) {
System.out.println("* No tweet yet");
}
int size = resultslist.size();
for (int i=0; i<size; i++){
Row row = ((Row) resultslist.get(i));
System.out.println("@" + row.getString("username") + ": " +row.getString("body"));
}
}
public boolean isUserExist(String username) {
ResultSet results = session.execute("SELECT * FROM " + TABLE_USERS +
" WHERE username = '" + username + "';");
List<Row> rows = results.all();
return rows.size()>0;
}
} |
package com.flightstats.http;
import com.github.rholder.retry.RetryException;
import com.github.rholder.retry.Retryer;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.io.CharStreams;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import static com.flightstats.http.HttpException.Details;
import static java.util.stream.Collectors.toList;
@AllArgsConstructor
public class HttpTemplate {
public static final String APPLICATION_JSON = "application/json";
public static final Logger logger = LoggerFactory.getLogger(HttpTemplate.class);
private final HttpClient client;
private final Gson gson;
private final Retryer<Response> retryer;
private final String contentType;
private final String acceptType;
@Inject
public HttpTemplate(HttpClient client, Gson gson, Retryer<Response> retryer) {
this.client = client;
this.gson = gson;
this.retryer = retryer;
this.contentType = APPLICATION_JSON;
this.acceptType = APPLICATION_JSON;
}
public <T> T get(String hostUrl, String path, Function<String, T> responseCreator, NameValuePair... params) {
URI uri;
try {
uri = new URIBuilder(hostUrl).setPath(path).setParameters(params).build();
} catch (URISyntaxException e) {
throw Throwables.propagate(e);
}
return get(uri, responseCreator);
}
public <T> T get(String uri, Function<String, T> responseCreator) {
return get(URI.create(uri), responseCreator);
}
public <T> T get(URI uri, Function<String, T> responseCreator) {
AtomicReference<T> result = new AtomicReference<>();
get(uri, (Response response) -> {
if (isFailedStatusCode(response.getCode())) {
throw new HttpException(new Details(response.getCode(), "Post failed to: " + uri + ". response: " + response));
}
result.set(responseCreator.apply(response.getBody()));
});
return result.get();
}
public int get(String uri, Consumer<Response> responseConsumer) {
return get(URI.create(uri), responseConsumer).getCode();
}
public Response get(URI uri) {
return get(uri, (Response c) -> {
});
}
public Response get(URI uri, Consumer<Response> responseConsumer) {
HttpGet request = new HttpGet(uri);
return handleRequest(request, responseConsumer);
}
public Response head(URI uri) {
return head(uri, true);
}
public Response head(String uri) {
return head(uri, true);
}
public Response head(String uri, boolean followRedirects) {
return head(URI.create(uri), followRedirects);
}
public Response head(URI uri, boolean followRedirects) {
HttpHead httpHead = new HttpHead(uri);
if (!followRedirects) {
httpHead.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
}
return handleRequest(httpHead, x -> {
});
}
public <T> T get(URI uri, Type type) {
return get(uri, (String body) -> gson.fromJson(body, type));
}
public String getSimple(String uri) {
return get(uri, (Function<String, String>) s -> s);
}
private Response handleRequest(HttpRequestBase request, Consumer<Response> responseConsumer) {
try {
HttpResponse httpResponse = client.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String body = "";
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream content = entity.getContent();
body = CharStreams.toString(new InputStreamReader(content));
}
Response response = new Response(statusCode, body, mapHeaders(httpResponse));
responseConsumer.accept(response);
return response;
} catch (IOException e) {
throw Throwables.propagate(e);
} finally {
request.reset();
}
}
private Multimap<String, String> mapHeaders(HttpResponse response) {
Header[] headers = response.getAllHeaders();
ListMultimap<String, Header> headersByName = Multimaps.index(Arrays.asList(headers), Header::getName);
return Multimaps.transformValues(headersByName, Header::getValue);
}
public int postWithNoResponseCodeValidation(String fullUri, Object bodyToPost, Consumer<Response> responseConsumer) {
try {
String bodyEntity = convertBodyToString(bodyToPost, contentType);
Response response = retryer.call(() -> executePost(fullUri, responseConsumer, contentType, new StringEntity(bodyEntity, Charsets.UTF_8)));
return response.getCode();
} catch (ExecutionException | RetryException e) {
throw Throwables.propagate(e);
}
}
private Response executePost(String fullUri, String contentType, HttpEntity entity) throws Exception {
return executePost(fullUri, x -> {}, contentType, entity);
}
private Response executePost(String fullUri, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) throws Exception {
HttpPost httpPost = new HttpPost(fullUri);
return execute(httpPost, responseConsumer, contentType, entity);
}
private Response executePut(String fullUri, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) throws Exception {
HttpPut httpPut = new HttpPut(fullUri);
return execute(httpPut, responseConsumer, contentType, entity);
}
private Response execute(HttpEntityEnclosingRequestBase httpRequest, String contentType, HttpEntity entity) throws IOException {
return execute(httpRequest, x -> {}, contentType, entity);
}
private Response execute(HttpEntityEnclosingRequestBase httpRequest, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) throws IOException {
try {
httpRequest.setHeader("Content-Type", contentType);
httpRequest.setHeader("Accept", acceptType);
httpRequest.setEntity(entity);
HttpResponse httpResponse = client.execute(httpRequest);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String body = CharStreams.toString(new InputStreamReader(httpResponse.getEntity().getContent()));
if (isRetryableStatusCode(statusCode)) {
logger.error("Internal server error, status code " + statusCode);
throw new HttpException(new Details(statusCode, "Post failed to: " + httpRequest.getURI() + ". Status = " + statusCode + ", message = " + body));
}
Response response = new Response(statusCode, body, mapHeaders(httpResponse));
responseConsumer.accept(response);
return response;
} finally {
httpRequest.reset();
}
}
private boolean isFailedStatusCode(int responseStatusCode) {
return (HttpStatus.SC_OK > responseStatusCode) || (responseStatusCode > HttpStatus.SC_NO_CONTENT);
}
private boolean isRetryableStatusCode(int responseStatusCode) {
return 502 <= responseStatusCode && responseStatusCode <= 504;
}
private String convertBodyToString(Object bodyToPost, String contentType) {
switch (contentType) {
case APPLICATION_JSON:
return gson.toJson(bodyToPost);
default:
return String.valueOf(bodyToPost);
}
}
public Response post(URI uri, byte[] bytes, String contentType) {
try {
return executePost(uri.toString(), contentType, new ByteArrayEntity(bytes));
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* Fire & Forget...don't care about the response at all.
*/
public void post(String fullUri, Object bodyToPost) {
postWithResponse(fullUri, bodyToPost, httpResponse -> {
});
}
/**
* Post, and return the response body as a String.
*/
public String postSimple(String fullUri, Object bodyToPost) {
return post(fullUri, bodyToPost, s -> s);
}
public <T> T post(String fullUri, Object bodyToPost, Function<String, T> responseConverter) {
AtomicReference<T> result = new AtomicReference<>();
postWithResponse(fullUri, bodyToPost, (Response response) -> result.set(responseConverter.apply(response.getBody())));
return result.get();
}
public Response put(URI uri, byte[] bytes, String contentType) {
try {
HttpPut httpPut = new HttpPut(uri.toString());
return execute(httpPut, contentType, new ByteArrayEntity(bytes));
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* todo: this needs a better name, but different than "post", so it doesn't collide with the other one. I hate type erasure!
*/
public Response postWithResponse(String fullUri, Object bodyToPost, Consumer<Response> responseConsumer) {
try {
String bodyEntity = convertBodyToString(bodyToPost, contentType);
Response response = retryer.call(() -> executePost(fullUri, responseConsumer, contentType, new StringEntity(bodyEntity, Charsets.UTF_8)));
if (isFailedStatusCode(response.getCode())) {
throw new HttpException(new Details(response.getCode(), "Post failed to: " + fullUri + ". response: " + response));
}
return response;
} catch (ExecutionException | RetryException e) {
throw Throwables.propagate(e);
}
}
public int postSimpleHtmlForm(String fullUri, Map<String, String> formValues) throws Exception {
List<NameValuePair> nameValuePairs = formValues.entrySet().stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList());
HttpPost httpPost = new HttpPost(fullUri);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (isFailedStatusCode(statusCode)) {
throw new HttpException(new Details(statusCode, "Post failed to: " + fullUri));
}
return statusCode;
} finally {
httpPost.reset();
}
}
} |
package com.google.appengine.appcfg;
import java.util.ArrayList;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Debug the specified VM Runtime instance.
*
* @author Ludovic Champenois <ludo@google.com>
* @goal debug
* @execute phase="package"
*/
public class Debug extends AbstractAppCfgMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("");
getLog().info("Google App Engine Java SDK - Debug the specified VM Runtime instance.");
getLog().info("");
getLog().info("Retrieving Google App Engine Java SDK from Maven");
resolveAndSetSdkRoot();
String appDir = project.getBuild().getDirectory() + "/" + project.getBuild().getFinalName();
executeAppCfgCommand("debug", appDir);
}
} |
package com.greghaskins.spectrum;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public final class Spectrum extends Runner {
/**
* A generic code block with a {@link #run()} method to perform any action. Usually defined by a
* lambda function.
*/
@FunctionalInterface
public interface Block extends com.greghaskins.spectrum.Block {
/**
* Execute the code block, raising any {@code Throwable} that may occur.
*
* @throws Throwable any uncaught Error or Exception
*/
@Override
void run() throws Throwable;
}
/**
* Declare a test suite that describes the expected behavior of the system in a given context.
*
* @param context Description of the context for this suite
* @param block {@link Block} with one or more calls to {@link #it(String, Block) it} that define
* each expected behavior
*
*/
public static void describe(final String context, final Block block) {
final Suite suite = getCurrentSuiteBeingDeclared().addSuite(context);
beginDefintion(suite, block);
}
/**
* Focus on this specific suite, while ignoring others.
*
* @param context Description of the context for this suite
* @param block {@link Block} with one or more calls to {@link #it(String, Block) it} that define
* each expected behavior
*
* @see #describe(String, Block)
*
*/
public static void fdescribe(final String context, final Block block) {
final Suite suite = getCurrentSuiteBeingDeclared().addSuite(context);
suite.focus();
beginDefintion(suite, block);
}
/**
* Ignore the specific suite.
*
* @param context Description of the context for this suite
* @param block {@link Block} with one or more calls to {@link #it(String, Block) it} that define
* each expected behavior
*
* @see #describe(String, Block)
*
*/
public static void xdescribe(final String context, final Block block) {
final Suite suite = getCurrentSuiteBeingDeclared().addSuite(context);
suite.ignore();
beginDefintion(suite, block);
}
/**
* Declare a spec, or test, for an expected behavior of the system in this suite context.
*
* @param behavior Description of the expected behavior
* @param block {@link Block} that verifies the system behaves as expected and throws a
* {@link java.lang.Throwable Throwable} if that expectation is not met.
*/
public static void it(final String behavior, final Block block) {
getCurrentSuiteBeingDeclared().addSpec(behavior, block);
}
/**
* Declare a pending spec (without a block) that will be ignored.
*
* @param behavior Description of the expected behavior
*
* @see #xit(String, Block)
*/
public static void it(final String behavior) {
getCurrentSuiteBeingDeclared().addSpec(behavior, null).ignore();
}
/**
* Focus on this specific spec, while ignoring others.
*
* @param behavior Description of the expected behavior
* @param block {@link Block} that verifies the system behaves as expected and throws a
* {@link java.lang.Throwable Throwable} if that expectation is not met.
*
* @see #it(String, Block)
*/
public static void fit(final String behavior, final Block block) {
getCurrentSuiteBeingDeclared().addSpec(behavior, block).focus();
}
/**
* Mark a spec as ignored so that it will be skipped.
*
* @param behavior Description of the expected behavior
* @param block {@link Block} that will not run, since this spec is ignored.
*
* @see #it(String, Block)
*/
public static void xit(final String behavior, final Block block) {
it(behavior);
}
/**
* Declare a {@link Block} to be run before each spec in the suite.
*
* <p>
* Use this to perform setup actions that are common across tests in the context. If multiple
* {@code beforeEach} blocks are declared, they will run in declaration order.
* </p>
*
* @param block {@link Block} to run once before each spec
*/
public static void beforeEach(final Block block) {
getCurrentSuiteBeingDeclared().beforeEach(block);
}
/**
* Declare a {@link Block} to be run after each spec in the current suite.
*
* <p>
* Use this to perform teardown or cleanup actions that are common across specs in this suite. If
* multiple {@code afterEach} blocks are declared, they will run in declaration order.
* </p>
*
* @param block {@link Block} to run once after each spec
*/
public static void afterEach(final Block block) {
getCurrentSuiteBeingDeclared().afterEach(block);
}
/**
* Declare a {@link Block} to be run once before all the specs in the current suite begin.
*
* <p>
* Use {@code beforeAll} and {@link #afterAll(Block) afterAll} blocks with caution: since they
* only run once, shared state <strong>will</strong> leak across specs.
* </p>
*
* @param block {@link Block} to run once before all specs in this suite
*/
public static void beforeAll(final Block block) {
getCurrentSuiteBeingDeclared().beforeAll(block);
}
/**
* Declare a {@link Block} to be run once after all the specs in the current suite have run.
*
* <p>
* Use {@link #beforeAll(Block) beforeAll} and {@code afterAll} blocks with caution: since they
* only run once, shared state <strong>will</strong> leak across tests.
* </p>
*
* @param block {@link Block} to run once after all specs in this suite
*/
public static void afterAll(final Block block) {
getCurrentSuiteBeingDeclared().afterAll(block);
}
/**
* Define a memoized helper function. The value will be cached across multiple calls in the same
* spec, but not across specs.
*
* <p>
* Note that {@code let} is lazy-evaluated: the {@code supplier} is not called until the first
* time it is used.
* </p>
*
* @param <T> The type of value
*
* @param supplier {@link ThrowingSupplier} function that either generates the value, or throws a
* `Throwable`
* @return memoized supplier
*/
public static <T> Supplier<T> let(final ThrowingSupplier<T> supplier) {
final ConcurrentHashMap<Supplier<T>, T> cache = new ConcurrentHashMap<>(1);
afterEach(() -> cache.clear());
return () -> {
if (getCurrentSuiteBeingDeclared() == null) {
return cache.computeIfAbsent(supplier, s -> s.get());
}
throw new IllegalStateException("Cannot use the value from let() in a suite declaration. "
+ "It may only be used in the context of a running spec.");
};
}
/**
* Supplier of results similar to {@link Supplier}, but may optionally throw checked exceptions.
* Using {@link ThrowingSupplier} is more convenient for lambda functions since it requires less
* exception handling.
*
* @see Supplier
*
* @param <T> The type of result that will be supplied
*/
@FunctionalInterface
public interface ThrowingSupplier<T> extends Supplier<T> {
/**
* Get a result.
*
* @return a result
* @throws Throwable any uncaught Error or Exception
*/
T getOrThrow() throws Throwable;
@Override
default T get() {
try {
return getOrThrow();
} catch (final RuntimeException | Error unchecked) {
throw unchecked;
} catch (final Throwable checked) {
throw new RuntimeException(checked);
}
}
}
private static final Deque<Suite> suiteStack = new ArrayDeque<>();
private final Suite rootSuite;
/**
* Main constructor called via reflection by the JUnit runtime.
*
* @param testClass The class file that defines the current suite
*
* @see org.junit.runner.Runner
*/
public Spectrum(final Class<?> testClass) {
this(Description.createSuiteDescription(testClass), new ConstructorBlock(testClass));
}
Spectrum(final Description description, final com.greghaskins.spectrum.Block definitionBlock) {
this.rootSuite = Suite.rootSuite(description);
beginDefintion(this.rootSuite, definitionBlock);
}
@Override
public Description getDescription() {
return this.rootSuite.getDescription();
}
@Override
public void run(final RunNotifier notifier) {
this.rootSuite.run(notifier);
}
private static synchronized void beginDefintion(final Suite suite,
final com.greghaskins.spectrum.Block definitionBlock) {
suiteStack.push(suite);
try {
definitionBlock.run();
} catch (final Throwable error) {
suite.removeAllChildren();
it("encountered an error", () -> {
throw error;
});
}
suiteStack.pop();
}
private static synchronized Suite getCurrentSuiteBeingDeclared() {
return suiteStack.peek();
}
} |
package com.hh.adapters;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.hh.clientdatatable.ClientDataTable;
import com.hh.clientdatatable.TCell;
import com.hh.droid.R;
import com.hh.execption.WrongTypeException;
import com.hh.listeners.*;
import com.hh.ui.widget.UiPicassoImageView;
public class CDTRecycleAdapter extends RecyclerView.Adapter<RecycleViewHolder> {
protected Context mContext;
protected Resources mRes;
protected ClientDataTable mClientDataTable;
private boolean _mIsEnableOnClickWidget;
private int _mLayoutRes;
private int mBase64OptionSize=2;
private boolean mIsNotUsePicassoCache=false;
public void setPicassoCachePolicy(boolean isDisableCache){
mIsNotUsePicassoCache=isDisableCache;
}
public void setBase64OptionSize(int optionSize){
mBase64OptionSize=optionSize;
}
public CDTRecycleAdapter(Context pContext, int pLayoutRes, ClientDataTable pCDT){
mContext=pContext;
mRes=pContext.getResources();
mClientDataTable = pCDT;
_mLayoutRes = pLayoutRes;
setHasStableIds(true);
}
@Override
protected void finalize() throws Throwable {
mContext = null;
super.finalize();
}
@Override
public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(_mLayoutRes, parent,false);
onCreateRow(v);
return new RecycleViewHolder(mContext,v,mClientDataTable,_mIsEnableOnClickWidget);
}
public int getLayoutRes(){
return _mLayoutRes;
}
public void setEnableOnClickWidget(boolean pIsEnabled) {
_mIsEnableOnClickWidget = pIsEnabled;
}
@Override
public void onBindViewHolder(RecycleViewHolder holder, int position) {
if(mClientDataTable.isEmpty())
return;
mClientDataTable.moveToPosition(position);
if ((position >= getItemCount() - 1))
onLoadMore();
int lListHolderSize = holder.mSparseArrayHolderViews.size();
for (int i = 0; i < lListHolderSize; i++) {
int lColumnIndex = holder.mSparseArrayHolderViews.keyAt(i);
View lWidget = holder.mSparseArrayHolderViews.get(lColumnIndex);
if (lWidget != null) {
final TCell data = mClientDataTable.getCell(position, lColumnIndex);
if (lWidget instanceof Checkable) {
((Checkable) lWidget).setChecked(data.asBoolean());
} else if (lWidget instanceof TextView) {
((TextView) lWidget).setText(data.asString());
}else if (lWidget instanceof UiPicassoImageView) {
if(data.getValueType() == TCell.ValueType.BASE64){
try {
throw new WrongTypeException(mContext, R.string.exception_canotUserBase64);
} catch (WrongTypeException e) {
e.printStackTrace();
}
}else {
UiPicassoImageView picassoImageView = (UiPicassoImageView) lWidget;
picassoImageView.setData(data.asString(),mIsNotUsePicassoCache);
}
} else if (lWidget instanceof ImageView) {
ImageView im= (ImageView) lWidget;
if (data.getValueType() == TCell.ValueType.INTEGER && !data.asString().isEmpty()) {
im.setImageResource(data.asInteger());
} else if (data.getValueType() == TCell.ValueType.BASE64) {
byte[] decodedString = Base64.decode(data.asString(), Base64.NO_WRAP);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = mBase64OptionSize;
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
im.setImageBitmap(decodedByte);
} else {
if (!data.asString().equals(""))
setViewImage((ImageView) lWidget, data.asString());
else
im.setImageDrawable(null);
}
} else if (lWidget instanceof Spinner) {
Spinner spinner=((Spinner) lWidget);
if(spinner.getAdapter() instanceof ArrayAdapter){
ArrayAdapter arrayAdapter= (ArrayAdapter) spinner.getAdapter();
spinner.setSelection(arrayAdapter.getPosition(data.asString()));
}else
Log.e(this.getClass().getName(), "Cannot set Spinner default value, because Spinner Adapter is not ArrayAdapter Type, you need to customize it in onIterateWidget method");
}
onIteratedRow(holder.mRowView,lWidget, lWidget.getTag().toString());
}
}
int lListHolderSizeNotInCDT = holder.mSparseArrayHolderViewsNotInCDT.size();
for (int i = 0; i < lListHolderSizeNotInCDT; i++) {
int lColumnIndex = holder.mSparseArrayHolderViewsNotInCDT.keyAt(i);
View lWidget = holder.mSparseArrayHolderViewsNotInCDT.get(lColumnIndex);
if (lWidget != null) {
onIteratedRow(holder.mRowView, lWidget, lWidget.getTag().toString());
}
}
// ClickListener
holder.setClickListener(new OnRecycleClickListener() {
@Override
public void onClick(View v, int position) {
onClickRow(v,position);
}
@Override
public void onLongClick(View v, int position) {
onLongClickRow(v, position);
}
});
holder.setOnRecycleWidgetClickListener(new OnRecycleWidgetClickListener() {
@Override
public void onClick(View parentView, View clickedView, String tag, int position) {
onClickWidget(parentView, clickedView, tag, position);
}
});
holder.setOnRecycleCheckedRadioButtonGroupChangeListener(new OnRecycleCheckedRadioButtonGroupChangeListener() {
@Override
public void onCheckedChanged(View parentView, RadioGroup radioButtonGroup, String widgetTag, int radioButtonID, int position) {
onCheckRadioButtonGroupWidget(parentView, radioButtonGroup, widgetTag, radioButtonID, position);
}
});
holder.setOnRecycleCheckedChangeListener(new OnRecycleCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean isWidgetInCDT,CompoundButton buttonView, boolean isChecked, int position) {
onOnCheckedChangeWidget(buttonView,buttonView.getTag().toString(),isChecked,position);
if (!isWidgetInCDT || position >= mClientDataTable.getRowsCount())
return;
String columnName = buttonView.getTag().toString();
mClientDataTable.moveToPosition(position);
mClientDataTable.cellByName(columnName).setValue(isChecked);
}
});
holder.setOnRecycleTextWatcher(new OnRecycleTextWatcher() {
@Override
public void afterTextChanged(boolean isWidgetInCDT,EditText v, String newText, int position) {
if (!isWidgetInCDT || position >= mClientDataTable.getRowsCount() || !(v.isFocusable() || v.isFocusableInTouchMode()))
return;
mClientDataTable.moveToPosition(position);
String columnName = v.getTag().toString();
mClientDataTable.cellByName(columnName).setValue(newText);
}
});
}
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
@Override
public int getItemCount() {
return mClientDataTable.getRowsCount();
}
@Override
public long getItemId(int position) {
return position;
}
public void clear() {
mClientDataTable.clear();
notifyDataRecycleChanged();
}
public void notifyDataRecycleChanged(){
mClientDataTable.requery();
notifyDataSetChanged();
}
/**
* override this method when we need to access to CDT content
* for each row when iterate all the data
*
* @param widget : Button , TextView etc...
* @param position : position of row
*/
protected void onIteratedRow(View row, View widget,String widgetTag){};
protected void onLoadMore(){};
protected void onCreateRow(View row){} ;
/**
* override this method to capture the click on selected row
*
* @param row
* @param position : position of selected row
*/
protected void onClickRow(View row, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
;
/**
* override this method to capture the click on selected widget (Button, ImageView ...) inside a row
*
* @param tagWidget : the tag of the selected widget
* @param position : the position of row of selected widget
*/
protected void onClickWidget(View parentView,View clickedView,String tagWidget, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
protected void onCheckRadioButtonGroupWidget(View parentView,RadioGroup radioGroup,String widgetTag,int radioButtonID, int position){
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
protected void onOnCheckedChangeWidget(CompoundButton compoundButton,String tag,boolean b, int position){
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
/**
* override this method to capture the Long click on selected Row,
* and we can create context Menu inside this method
*
* @param row : selected row
* @param position : position of selected row
*/
protected void onLongClickRow(View row, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
public boolean isEmpty(){
return getItemCount()==0;
}
public String getString(int resID){
return mRes.getString(resID);
}
} |
package grakn.core.pattern.variable;
import grakn.core.common.exception.GraknException;
import grakn.core.pattern.Conjunction;
import grakn.core.traversal.common.Identifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static grakn.common.collection.Collections.set;
import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE;
public class VariableCloner {
private final Map<Identifier.Variable, Variable> variables;
public VariableCloner() {
variables = new HashMap<>();
}
public static VariableCloner cloneFromConjunction(Conjunction conjunction) {
VariableCloner cloner = new VariableCloner();
conjunction.variables().forEach(cloner::clone);
return cloner;
}
public Variable clone(Variable variable) {
if (variable.isThing()) return clone(variable.asThing());
else if (variable.isType()) return clone(variable.asType());
else throw GraknException.of(ILLEGAL_STATE);
}
public ThingVariable clone(ThingVariable variable) {
assert variable.identifier().isVariable();
ThingVariable newClone = variables.computeIfAbsent(variable.identifier().asVariable(), ThingVariable::new).asThing();
newClone.constrainClone(variable, this);
return newClone;
}
public TypeVariable clone(TypeVariable variable) {
assert variable.identifier().isVariable();
TypeVariable newClone = variables.computeIfAbsent(variable.identifier().asVariable(), TypeVariable::new).asType();
newClone.constrainClone(variable, this);
return newClone;
}
public Set<Variable> variables() {
return set(variables.values());
}
} |
package com.messners.gitlab.api;
/**
* This class specifies methods to interact with a GitLab server utilizing the standard GitLab API.
*
* @author Greg Messner <greg@messners.com>
*/
public class GitLabApi {
GitLabApiClient apiClient;
private CommitsApi commitsApi;
private GroupApi groupApi;
private MergeRequestApi mergeRequestApi;
private ProjectApi projectApi;
private RepositoryApi repositoryApi;
private UserApi userApi;
/**
* Contructs a GitLabApi instance set up to interact with the GitLab server
* specified by hostUrl.
*
* @param hostUrl
* @param privateToken
*/
public GitLabApi (String hostUrl, String privateToken) {
apiClient = new GitLabApiClient(hostUrl, privateToken);
commitsApi = new CommitsApi(this);
groupApi = new GroupApi(this);
mergeRequestApi = new MergeRequestApi(this);
projectApi = new ProjectApi(this);
repositoryApi = new RepositoryApi(this);
userApi = new UserApi(this);
}
/**
* Return the GitLabApiClient associated with this instance. This is used by all the sub API classes
* to communicate with the GitLab API.
*
* @return the GitLabApiClient associated with this instance
*/
GitLabApiClient getApiClient () {
return (apiClient);
}
/**
* Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used
* to perform all commit related API calls.
*
* @return the CommitsApi instance owned by this GitLabApi instance
*/
public CommitsApi getCommitsApi () {
return (commitsApi);
}
/**
* Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used
* to perform all merge request related API calls.
*
* @return the MergeRequestApi instance owned by this GitLabApi instance
*/
public MergeRequestApi getMergeRequestApi () {
return (mergeRequestApi);
}
/**
* Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used
* to perform all group related API calls.
*
* @return the GroupApi instance owned by this GitLabApi instance
*/
public GroupApi getGroupApi () {
return (groupApi);
}
/**
* Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used
* to perform all project related API calls.
*
* @return the ProjectApi instance owned by this GitLabApi instance
*/
public ProjectApi getProjectApi () {
return (projectApi);
}
/**
* Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used
* to perform all user related API calls.
*
* @return the RepositoryApi instance owned by this GitLabApi instance
*/
public RepositoryApi getRepositoryApi () {
return (repositoryApi);
}
/**
* Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used
* to perform all user related API calls.
*
* @return the ProjectApi instance owned by this GitLabApi instance
*/
public UserApi getUserApi () {
return (userApi);
}
} |
package com.orctom.mojo.was;
import com.orctom.mojo.was.model.WebSphereModel;
import com.orctom.mojo.was.model.WebSphereServiceException;
import com.orctom.mojo.was.service.impl.WebSphereServiceScriptImpl;
import com.orctom.mojo.was.utils.AntTaskUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.ExceptionUtils;
import org.codehaus.plexus.util.StringUtils;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Mojo(name = "deploy", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDirectInvocation = true, threadSafe = true)
public class WASDeployMojo extends AbstractWASMojo {
@Parameter
protected String parallel;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info(Constants.PLUGIN_ID + " - deploy");
Set<WebSphereModel> models = getWebSphereModels();
if (null == models || models.isEmpty()) {
getLog().info("[SKIPPED DEPLOYMENT] empty target server configured, please check your configuration");
return;
}
boolean parallelDeploy = StringUtils.isEmpty(parallel) ? models.size() > 1 : Boolean.valueOf(parallel);
if (parallelDeploy) {
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int poolSize = models.size() > numOfProcessors ? numOfProcessors : models.size();
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
for (final WebSphereModel model : models) {
executor.execute(new Runnable() {
@Override
public void run() {
execute(model);
}
});
}
executor.shutdown();
try {
executor.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (WebSphereModel model : models) {
execute(model);
}
}
}
private void execute(WebSphereModel model) {
getLog().info("============================================================");
getLog().info("[DEPLOY] " + model.getHost() + " " + model.getApplicationName());
getLog().info("============================================================");
try {
getLog().info("==================== pre-steps =======================");
executeAntTasks(model, super.preSteps);
getLog().info("====================== deploy ========================");
new WebSphereServiceScriptImpl(model, project.getBuild().getDirectory()).deploy();
getLog().info("==================== post-steps ======================");
executeAntTasks(model, super.postSteps);
} catch (RuntimeException e) {
if (failOnError) {
throw e;
} else {
getLog().error("
getLog().error(ExceptionUtils.getFullStackTrace(e));
}
} catch (Throwable t) {
if (failOnError) {
throw new WebSphereServiceException(t);
} else {
getLog().error("
getLog().error(ExceptionUtils.getFullStackTrace(t));
}
}
}
private void executeAntTasks(WebSphereModel model, PlexusConfiguration[] targets) throws IOException, MojoExecutionException {
if (null == targets || 0 == targets.length) {
getLog().info("Skipped, not configured.");
return;
}
for (PlexusConfiguration target : targets) {
AntTaskUtils.execute(model, target, project, projectHelper, pluginArtifacts, getLog());
}
}
} |
package com.rarchives.ripme.ui;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.rarchives.ripme.ripper.AbstractRipper;
import com.rarchives.ripme.utils.RipUtils;
import com.rarchives.ripme.utils.Utils;
import javax.swing.UnsupportedLookAndFeelException;
/**
* Everything UI-related starts and ends here.
*/
public final class MainWindow implements Runnable, RipStatusHandler {
private static final Logger logger = Logger.getLogger(MainWindow.class);
private boolean isRipping = false; // Flag to indicate if we're ripping something
private static JFrame mainFrame;
private static JTextField ripTextfield;
private static JButton ripButton,
stopButton;
private static JLabel statusLabel;
private static JButton openButton;
private static JProgressBar statusProgress;
// Put an empty JPanel on the bottom of the window to keep components
// anchored to the top when there is no open lower panel
private static JPanel emptyPanel;
// Log
private static JButton optionLog;
private static JPanel logPanel;
private static JTextPane logText;
// History
private static JButton optionHistory;
private static final History HISTORY = new History();
private static JPanel historyPanel;
private static JTable historyTable;
private static AbstractTableModel historyTableModel;
private static JButton historyButtonRemove,
historyButtonClear,
historyButtonRerip;
// Queue
public static JButton optionQueue;
private static JPanel queuePanel;
private static DefaultListModel queueListModel;
// Configuration
private static JButton optionConfiguration;
private static JPanel configurationPanel;
private static JButton configUpdateButton;
private static JLabel configUpdateLabel;
private static JTextField configTimeoutText;
private static JTextField configThreadsText;
private static JCheckBox configOverwriteCheckbox;
private static JLabel configSaveDirLabel;
private static JButton configSaveDirButton;
private static JTextField configRetriesText;
private static JCheckBox configAutoupdateCheckbox;
private static JComboBox configLogLevelCombobox;
private static JCheckBox configURLHistoryCheckbox;
private static JCheckBox configPlaySound;
private static JCheckBox configSaveOrderCheckbox;
private static JCheckBox configShowPopup;
private static JCheckBox configSaveLogs;
private static JCheckBox configSaveURLsOnly;
private static JCheckBox configSaveAlbumTitles;
private static JCheckBox configClipboardAutorip;
private static JCheckBox configSaveDescriptions;
private static JCheckBox configPreferMp4;
private static JCheckBox configWindowPosition;
private static TrayIcon trayIcon;
private static MenuItem trayMenuMain;
private static CheckboxMenuItem trayMenuAutorip;
private static Image mainIcon;
private static AbstractRipper ripper;
private static void addCheckboxListener(JCheckBox checkBox, String configString) {
checkBox.addActionListener(arg0 -> {
Utils.setConfigBoolean(configString, checkBox.isSelected());
Utils.configureLogger();
});
}
private static JCheckBox addNewCheckbox(String text, String configString, Boolean configBool) {
JCheckBox checkbox = new JCheckBox(text, Utils.getConfigBoolean(configString, configBool));
checkbox.setHorizontalAlignment(JCheckBox.RIGHT);
checkbox.setHorizontalTextPosition(JCheckBox.LEFT);
return checkbox;
}
public MainWindow() {
mainFrame = new JFrame("RipMe v" + UpdateUtils.getThisJarVersion());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new GridBagLayout());
createUI(mainFrame.getContentPane());
pack();
loadHistory();
setupHandlers();
Thread shutdownThread = new Thread(this::shutdownCleanup);
Runtime.getRuntime().addShutdownHook(shutdownThread);
if (Utils.getConfigBoolean("auto.update", true)) {
upgradeProgram();
}
boolean autoripEnabled = Utils.getConfigBoolean("clipboard.autorip", false);
ClipboardUtils.setClipboardAutoRip(autoripEnabled);
trayMenuAutorip.setState(autoripEnabled);
}
private void upgradeProgram() {
if (!configurationPanel.isVisible()) {
optionConfiguration.doClick();
}
Runnable r = () -> UpdateUtils.updateProgram(configUpdateLabel);
new Thread(r).start();
}
public void run() {
pack();
restoreWindowPosition(mainFrame);
mainFrame.setVisible(true);
}
private void shutdownCleanup() {
Utils.setConfigBoolean("file.overwrite", configOverwriteCheckbox.isSelected());
Utils.setConfigInteger("threads.size", Integer.parseInt(configThreadsText.getText()));
Utils.setConfigInteger("download.retries", Integer.parseInt(configRetriesText.getText()));
Utils.setConfigInteger("download.timeout", Integer.parseInt(configTimeoutText.getText()));
Utils.setConfigBoolean("clipboard.autorip", ClipboardUtils.getClipboardAutoRip());
Utils.setConfigBoolean("auto.update", configAutoupdateCheckbox.isSelected());
Utils.setConfigString("log.level", configLogLevelCombobox.getSelectedItem().toString());
Utils.setConfigBoolean("play.sound", configPlaySound.isSelected());
Utils.setConfigBoolean("download.save_order", configSaveOrderCheckbox.isSelected());
Utils.setConfigBoolean("download.show_popup", configShowPopup.isSelected());
Utils.setConfigBoolean("log.save", configSaveLogs.isSelected());
Utils.setConfigBoolean("urls_only.save", configSaveURLsOnly.isSelected());
Utils.setConfigBoolean("album_titles.save", configSaveAlbumTitles.isSelected());
Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected());
Utils.setConfigBoolean("descriptions.save", configSaveDescriptions.isSelected());
Utils.setConfigBoolean("prefer.mp4", configPreferMp4.isSelected());
Utils.setConfigBoolean("remember.url_history", configURLHistoryCheckbox.isSelected());
saveWindowPosition(mainFrame);
saveHistory();
Utils.saveConfig();
}
private void status(String text) {
statusWithColor(text, Color.BLACK);
}
private void error(String text) {
statusWithColor(text, Color.RED);
}
private void statusWithColor(String text, Color color) {
statusLabel.setForeground(color);
statusLabel.setText(text);
pack();
}
private void pack() {
SwingUtilities.invokeLater(() -> {
Dimension preferredSize = mainFrame.getPreferredSize();
mainFrame.setMinimumSize(preferredSize);
if (isCollapsed()) {
mainFrame.setSize(preferredSize);
}
});
}
private boolean isCollapsed() {
return (!logPanel.isVisible() &&
!historyPanel.isVisible() &&
!queuePanel.isVisible() &&
!configurationPanel.isVisible()
);
}
private void createUI(Container pane) {
//If creating the tray icon fails, ignore it.
try {
setupTrayIcon();
} catch (Exception e) { }
EmptyBorder emptyBorder = new EmptyBorder(5, 5, 5, 5);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1; gbc.ipadx = 2; gbc.gridx = 0;
gbc.weighty = 0; gbc.ipady = 2; gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
logger.error("[!] Exception setting system theme:", e);
}
ripTextfield = new JTextField("", 20);
ripTextfield.addMouseListener(new ContextMenuMouseListener());
ImageIcon ripIcon = new ImageIcon(mainIcon);
ripButton = new JButton("<html><font size=\"5\"><b>Rip</b></font></html>", ripIcon);
stopButton = new JButton("<html><font size=\"5\"><b>Stop</b></font></html>");
stopButton.setEnabled(false);
try {
Image stopIcon = ImageIO.read(getClass().getClassLoader().getResource("stop.png"));
stopButton.setIcon(new ImageIcon(stopIcon));
} catch (Exception ignored) { }
JPanel ripPanel = new JPanel(new GridBagLayout());
ripPanel.setBorder(emptyBorder);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
gbc.gridx = 0; ripPanel.add(new JLabel("URL:", JLabel.RIGHT), gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 1; ripPanel.add(ripTextfield, gbc);
gbc.weighty = 0;
gbc.weightx = 0;
gbc.gridx = 2; ripPanel.add(ripButton, gbc);
gbc.gridx = 3; ripPanel.add(stopButton, gbc);
gbc.weightx = 1;
statusLabel = new JLabel("Inactive");
statusLabel.setHorizontalAlignment(JLabel.CENTER);
openButton = new JButton();
openButton.setVisible(false);
JPanel statusPanel = new JPanel(new GridBagLayout());
statusPanel.setBorder(emptyBorder);
gbc.gridx = 0; statusPanel.add(statusLabel, gbc);
gbc.gridy = 1; statusPanel.add(openButton, gbc);
gbc.gridy = 0;
JPanel progressPanel = new JPanel(new GridBagLayout());
progressPanel.setBorder(emptyBorder);
statusProgress = new JProgressBar(0, 100);
progressPanel.add(statusProgress, gbc);
JPanel optionsPanel = new JPanel(new GridBagLayout());
optionsPanel.setBorder(emptyBorder);
optionLog = new JButton("Log");
optionHistory = new JButton("History");
optionQueue = new JButton("Queue");
optionConfiguration = new JButton("Configuration");
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
try {
Image icon;
icon = ImageIO.read(getClass().getClassLoader().getResource("comment.png"));
optionLog.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("time.png"));
optionHistory.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("list.png"));
optionQueue.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("gear.png"));
optionConfiguration.setIcon(new ImageIcon(icon));
} catch (Exception e) { }
gbc.gridx = 0; optionsPanel.add(optionLog, gbc);
gbc.gridx = 1; optionsPanel.add(optionHistory, gbc);
gbc.gridx = 2; optionsPanel.add(optionQueue, gbc);
gbc.gridx = 3; optionsPanel.add(optionConfiguration, gbc);
logPanel = new JPanel(new GridBagLayout());
logPanel.setBorder(emptyBorder);
logText = new JTextPane();
logText.setEditable(false);
JScrollPane logTextScroll = new JScrollPane(logText);
logTextScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logPanel.setVisible(false);
logPanel.setPreferredSize(new Dimension(300, 250));
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
logPanel.add(logTextScroll, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
historyPanel = new JPanel(new GridBagLayout());
historyPanel.setBorder(emptyBorder);
historyPanel.setVisible(false);
historyPanel.setPreferredSize(new Dimension(300, 250));
historyTableModel = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
return HISTORY.getColumnName(col);
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public Object getValueAt(int row, int col) {
return HISTORY.getValueAt(row, col);
}
@Override
public int getRowCount() {
return HISTORY.toList().size();
}
@Override
public int getColumnCount() {
return HISTORY.getColumnCount();
}
@Override
public boolean isCellEditable(int row, int col) {
return (col == 0 || col == 4);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col == 4) {
HISTORY.get(row).selected = (Boolean) value;
historyTableModel.fireTableDataChanged();
}
}
};
historyTable = new JTable(historyTableModel);
historyTable.addMouseListener(new HistoryMenuMouseListener());
historyTable.setAutoCreateRowSorter(true);
for (int i = 0; i < historyTable.getColumnModel().getColumnCount(); i++) {
int width = 130; // Default
switch (i) {
case 0: // URL
width = 270;
break;
case 3:
width = 40;
break;
case 4:
width = 15;
break;
}
historyTable.getColumnModel().getColumn(i).setPreferredWidth(width);
}
JScrollPane historyTableScrollPane = new JScrollPane(historyTable);
historyButtonRemove = new JButton("Remove");
historyButtonClear = new JButton("Clear");
historyButtonRerip = new JButton("Re-rip Checked");
gbc.gridx = 0;
// History List Panel
JPanel historyTablePanel = new JPanel(new GridBagLayout());
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
historyTablePanel.add(historyTableScrollPane, gbc);
gbc.ipady = 180;
gbc.gridy = 0;
historyPanel.add(historyTablePanel, gbc);
gbc.ipady = 0;
JPanel historyButtonPanel = new JPanel(new GridBagLayout());
historyButtonPanel.setPreferredSize(new Dimension(300, 10));
historyButtonPanel.setBorder(emptyBorder);
gbc.gridx = 0; historyButtonPanel.add(historyButtonRemove, gbc);
gbc.gridx = 1; historyButtonPanel.add(historyButtonClear, gbc);
gbc.gridx = 2; historyButtonPanel.add(historyButtonRerip, gbc);
gbc.gridy = 1; gbc.gridx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
historyPanel.add(historyButtonPanel, gbc);
queuePanel = new JPanel(new GridBagLayout());
queuePanel.setBorder(emptyBorder);
queuePanel.setVisible(false);
queuePanel.setPreferredSize(new Dimension(300, 250));
queueListModel = new DefaultListModel();
JList queueList = new JList(queueListModel);
queueList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
queueList.addMouseListener(new QueueMenuMouseListener());
JScrollPane queueListScroll = new JScrollPane(queueList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
for (String item : Utils.getConfigList("queue")) {
queueListModel.addElement(item);
}
if (queueListModel.size() > 0) {
optionQueue.setText("Queue (" + queueListModel.size() + ")");
} else {
optionQueue.setText("Queue");
}
gbc.gridx = 0;
JPanel queueListPanel = new JPanel(new GridBagLayout());
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
queueListPanel.add(queueListScroll, gbc);
queuePanel.add(queueListPanel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
gbc.ipady = 0;
configurationPanel = new JPanel(new GridBagLayout());
configurationPanel.setBorder(emptyBorder);
configurationPanel.setVisible(false);
// TODO Configuration components
configUpdateButton = new JButton("Check for updates");
configUpdateLabel = new JLabel("Current version: " + UpdateUtils.getThisJarVersion(), JLabel.RIGHT);
JLabel configThreadsLabel = new JLabel("Maximum download threads:", JLabel.RIGHT);
JLabel configTimeoutLabel = new JLabel("Timeout (in milliseconds):", JLabel.RIGHT);
JLabel configRetriesLabel = new JLabel("Retry download count:", JLabel.RIGHT);
configThreadsText = new JTextField(Integer.toString(Utils.getConfigInteger("threads.size", 3)));
configTimeoutText = new JTextField(Integer.toString(Utils.getConfigInteger("download.timeout", 60000)));
configRetriesText = new JTextField(Integer.toString(Utils.getConfigInteger("download.retries", 3)));
configOverwriteCheckbox = addNewCheckbox("Overwrite existing files?", "file.overwrite", false);
configAutoupdateCheckbox = addNewCheckbox("Auto-update?", "auto.update", true);
configPlaySound = addNewCheckbox("Sound when rip completes", "play.sound", false);
configShowPopup = addNewCheckbox("Notification when rip starts", "download.show_popup", false);
configSaveOrderCheckbox = addNewCheckbox("Preserve order", "download.save_order", true);
configSaveLogs = addNewCheckbox("Save logs", "log.save", false);
configSaveURLsOnly = addNewCheckbox("Save URLs only", "urls_only.save", false);
configSaveAlbumTitles = addNewCheckbox("Save album titles", "album_titles.save", true);
configClipboardAutorip = addNewCheckbox("Autorip from Clipboard", "clipboard.autorip", false);
configSaveDescriptions = addNewCheckbox("Save descriptions", "descriptions.save", true);
configPreferMp4 = addNewCheckbox("Prefer MP4 over GIF","prefer.mp4", false);
configWindowPosition = addNewCheckbox("Restore window position", "window.position", true);
configURLHistoryCheckbox = addNewCheckbox("Remember URL history", "remember.url_history", true);
configLogLevelCombobox = new JComboBox(new String[] {"Log level: Error", "Log level: Warn", "Log level: Info", "Log level: Debug"});
configLogLevelCombobox.setSelectedItem(Utils.getConfigString("log.level", "Log level: Debug"));
setLogLevel(configLogLevelCombobox.getSelectedItem().toString());
configSaveDirLabel = new JLabel();
try {
String workingDir = (Utils.shortenPath(Utils.getWorkingDirectory()));
configSaveDirLabel.setText(workingDir);
configSaveDirLabel.setForeground(Color.BLUE);
configSaveDirLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception e) { }
configSaveDirLabel.setToolTipText(configSaveDirLabel.getText());
configSaveDirLabel.setHorizontalAlignment(JLabel.RIGHT);
configSaveDirButton = new JButton("Select Save Directory...");
gbc.gridy = 0; gbc.gridx = 0; configurationPanel.add(configUpdateLabel, gbc);
gbc.gridx = 1; configurationPanel.add(configUpdateButton, gbc);
gbc.gridy = 1; gbc.gridx = 0; configurationPanel.add(configAutoupdateCheckbox, gbc);
gbc.gridx = 1; configurationPanel.add(configLogLevelCombobox, gbc);
gbc.gridy = 2; gbc.gridx = 0; configurationPanel.add(configThreadsLabel, gbc);
gbc.gridx = 1; configurationPanel.add(configThreadsText, gbc);
gbc.gridy = 3; gbc.gridx = 0; configurationPanel.add(configTimeoutLabel, gbc);
gbc.gridx = 1; configurationPanel.add(configTimeoutText, gbc);
gbc.gridy = 4; gbc.gridx = 0; configurationPanel.add(configRetriesLabel, gbc);
gbc.gridx = 1; configurationPanel.add(configRetriesText, gbc);
gbc.gridy = 5; gbc.gridx = 0; configurationPanel.add(configOverwriteCheckbox, gbc);
gbc.gridx = 1; configurationPanel.add(configSaveOrderCheckbox, gbc);
gbc.gridy = 6; gbc.gridx = 0; configurationPanel.add(configPlaySound, gbc);
gbc.gridx = 1; configurationPanel.add(configSaveLogs, gbc);
gbc.gridy = 7; gbc.gridx = 0; configurationPanel.add(configShowPopup, gbc);
gbc.gridx = 1; configurationPanel.add(configSaveURLsOnly, gbc);
gbc.gridy = 8; gbc.gridx = 0; configurationPanel.add(configClipboardAutorip, gbc);
gbc.gridx = 1; configurationPanel.add(configSaveAlbumTitles, gbc);
gbc.gridy = 9; gbc.gridx = 0; configurationPanel.add(configSaveDescriptions, gbc);
gbc.gridx = 1; configurationPanel.add(configPreferMp4, gbc);
gbc.gridy = 10; gbc.gridx = 0; configurationPanel.add(configWindowPosition, gbc);
gbc.gridx = 1; configurationPanel.add(configURLHistoryCheckbox, gbc);
gbc.gridy = 11; gbc.gridx = 0; configurationPanel.add(configSaveDirLabel, gbc);
gbc.gridx = 1; configurationPanel.add(configSaveDirButton, gbc);
emptyPanel = new JPanel();
emptyPanel.setPreferredSize(new Dimension(0, 0));
emptyPanel.setSize(0, 0);
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.gridy = 0; pane.add(ripPanel, gbc);
gbc.gridy = 1; pane.add(statusPanel, gbc);
gbc.gridy = 2; pane.add(progressPanel, gbc);
gbc.gridy = 3; pane.add(optionsPanel, gbc);
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 4; pane.add(logPanel, gbc);
gbc.gridy = 5; pane.add(historyPanel, gbc);
gbc.gridy = 5; pane.add(queuePanel, gbc);
gbc.gridy = 5; pane.add(configurationPanel, gbc);
gbc.gridy = 5; pane.add(emptyPanel, gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
}
private void setupHandlers() {
ripButton.addActionListener(new RipButtonHandler());
ripTextfield.addActionListener(new RipButtonHandler());
ripTextfield.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
try {
String urlText = ripTextfield.getText().trim();
if (urlText.equals("")) {
return;
}
if (!urlText.startsWith("http")) {
urlText = "http://" + urlText;
}
URL url = new URL(urlText);
AbstractRipper ripper = AbstractRipper.getRipper(url);
statusWithColor(ripper.getHost() + " album detected", Color.GREEN);
} catch (Exception e) {
statusWithColor("Can't rip this URL: " + e.getMessage(), Color.RED);
}
}
});
stopButton.addActionListener(event -> {
if (ripper != null) {
ripper.stop();
isRipping = false;
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
pack();
statusProgress.setValue(0);
status("Ripping interrupted");
appendLog("Ripper interrupted", Color.RED);
}
});
optionLog.addActionListener(event -> {
logPanel.setVisible(!logPanel.isVisible());
emptyPanel.setVisible(!logPanel.isVisible());
historyPanel.setVisible(false);
queuePanel.setVisible(false);
configurationPanel.setVisible(false);
if (logPanel.isVisible()) {
optionLog.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionHistory.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(!historyPanel.isVisible());
emptyPanel.setVisible(!historyPanel.isVisible());
queuePanel.setVisible(false);
configurationPanel.setVisible(false);
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (historyPanel.isVisible()) {
optionHistory.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionQueue.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(false);
queuePanel.setVisible(!queuePanel.isVisible());
emptyPanel.setVisible(!queuePanel.isVisible());
configurationPanel.setVisible(false);
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (queuePanel.isVisible()) {
optionQueue.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionConfiguration.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(false);
queuePanel.setVisible(false);
configurationPanel.setVisible(!configurationPanel.isVisible());
emptyPanel.setVisible(!configurationPanel.isVisible());
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (configurationPanel.isVisible()) {
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
pack();
});
historyButtonRemove.addActionListener(event -> {
int[] indices = historyTable.getSelectedRows();
for (int i = indices.length - 1; i >= 0; i
int modelIndex = historyTable.convertRowIndexToModel(indices[i]);
HISTORY.remove(modelIndex);
}
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) { }
saveHistory();
});
historyButtonClear.addActionListener(event -> {
Utils.clearURLHistory();
HISTORY.clear();
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) { }
saveHistory();
});
// Re-rip all history
historyButtonClear.addActionListener(event -> {
if (Utils.getConfigBoolean("history.warn_before_delete", true)) {
JPanel checkChoise = new JPanel();
checkChoise.setLayout(new FlowLayout());
JButton yesButton = new JButton("YES");
JButton noButton = new JButton("NO");
yesButton.setPreferredSize(new Dimension(70, 30));
noButton.setPreferredSize(new Dimension(70, 30));
checkChoise.add(yesButton);
checkChoise.add(noButton);
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Are you sure?");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(checkChoise);
frame.setSize(405, 70);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
noButton.addActionListener(e -> {
frame.setVisible(false);
});
yesButton.addActionListener(ed -> {
frame.setVisible(false);
Utils.clearURLHistory();
HISTORY.clear();
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) {
}
saveHistory();
});
}
else {
Utils.clearURLHistory();
HISTORY.clear();
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) {
}
saveHistory();
}
});
int added = 0;
for (HistoryEntry entry : HISTORY.toList()) {
if (entry.selected) {
added++;
queueListModel.addElement(entry.url);
}
}
if (added == 0) {
JOptionPane.showMessageDialog(null,
"No history entries have been 'Checked'\n" +
"Check an entry by clicking the checkbox to the right of the URL or Right-click a URL to check/uncheck all items",
"RipMe Error",
JOptionPane.ERROR_MESSAGE);
}
});
configUpdateButton.addActionListener(arg0 -> {
Thread t = new Thread(() -> UpdateUtils.updateProgram(configUpdateLabel));
t.start();
});
configLogLevelCombobox.addActionListener(arg0 -> {
String level = ((JComboBox) arg0.getSource()).getSelectedItem().toString();
setLogLevel(level);
});
configSaveDirLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
File file = new File(Utils.getWorkingDirectory().toString());
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
} catch (Exception e1) { }
}
});
configSaveDirButton.addActionListener(arg0 -> {
UIManager.put("FileChooser.useSystemExtensionHiding", false);
JFileChooser jfc = new JFileChooser(Utils.getWorkingDirectory());
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = jfc.showDialog(null, "select directory");
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File chosenFile = jfc.getSelectedFile();
String chosenPath = null;
try {
chosenPath = chosenFile.getCanonicalPath();
} catch (Exception e) {
logger.error("Error while getting selected path: ", e);
return;
}
configSaveDirLabel.setText(Utils.shortenPath(chosenPath));
Utils.setConfigString("rips.directory", chosenPath);
});
addCheckboxListener(configSaveOrderCheckbox, "download.save_order");
addCheckboxListener(configOverwriteCheckbox, "file.overwrite");
addCheckboxListener(configSaveLogs, "log.save");
addCheckboxListener(configSaveURLsOnly, "urls_only.save");
addCheckboxListener(configURLHistoryCheckbox, "remember.url_history");
addCheckboxListener(configSaveAlbumTitles, "album_titles.save");
addCheckboxListener(configSaveDescriptions, "descriptions.save");
addCheckboxListener(configPreferMp4, "prefer.mp4");
addCheckboxListener(configWindowPosition, "window.position");
configClipboardAutorip.addActionListener(arg0 -> {
Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected());
ClipboardUtils.setClipboardAutoRip(configClipboardAutorip.isSelected());
trayMenuAutorip.setState(configClipboardAutorip.isSelected());
Utils.configureLogger();
});
queueListModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent arg0) {
if (queueListModel.size() > 0) {
optionQueue.setText("Queue (" + queueListModel.size() + ")");
} else {
optionQueue.setText("Queue");
}
if (!isRipping) {
ripNextAlbum();
}
}
@Override
public void contentsChanged(ListDataEvent arg0) { }
@Override
public void intervalRemoved(ListDataEvent arg0) { }
});
}
private void setLogLevel(String level) {
Level newLevel = Level.ERROR;
level = level.substring(level.lastIndexOf(' ') + 1);
switch (level) {
case "Debug":
newLevel = Level.DEBUG;
break;
case "Info":
newLevel = Level.INFO;
break;
case "Warn":
newLevel = Level.WARN;
break;
case "Error":
newLevel = Level.ERROR;
break;
}
Logger.getRootLogger().setLevel(newLevel);
logger.setLevel(newLevel);
ConsoleAppender ca = (ConsoleAppender)Logger.getRootLogger().getAppender("stdout");
if (ca != null) {
ca.setThreshold(newLevel);
}
FileAppender fa = (FileAppender)Logger.getRootLogger().getAppender("FILE");
if (fa != null) {
fa.setThreshold(newLevel);
}
}
private void setupTrayIcon() {
mainFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) { trayMenuMain.setLabel("Hide"); }
@Override
public void windowDeactivated(WindowEvent e) { trayMenuMain.setLabel("Show"); }
@Override
public void windowDeiconified(WindowEvent e) { trayMenuMain.setLabel("Hide"); }
@Override
public void windowIconified(WindowEvent e) { trayMenuMain.setLabel("Show"); }
});
PopupMenu trayMenu = new PopupMenu();
trayMenuMain = new MenuItem("Hide");
trayMenuMain.addActionListener(arg0 -> toggleTrayClick());
MenuItem trayMenuAbout = new MenuItem("About " + mainFrame.getTitle());
trayMenuAbout.addActionListener(arg0 -> {
StringBuilder about = new StringBuilder();
about.append("<html><h1>")
.append(mainFrame.getTitle())
.append("</h1>");
about.append("Download albums from various websites:");
try {
List<String> rippers = Utils.getListOfAlbumRippers();
about.append("<ul>");
for (String ripper : rippers) {
about.append("<li>");
ripper = ripper.substring(ripper.lastIndexOf('.') + 1);
if (ripper.contains("Ripper")) {
ripper = ripper.substring(0, ripper.indexOf("Ripper"));
}
about.append(ripper);
about.append("</li>");
}
about.append("</ul>");
} catch (Exception e) { }
about.append("<br>And download videos from video sites:");
try {
List<String> rippers = Utils.getListOfVideoRippers();
about.append("<ul>");
for (String ripper : rippers) {
about.append("<li>");
ripper = ripper.substring(ripper.lastIndexOf('.') + 1);
if (ripper.contains("Ripper")) {
ripper = ripper.substring(0, ripper.indexOf("Ripper"));
}
about.append(ripper);
about.append("</li>");
}
about.append("</ul>");
} catch (Exception e) { }
about.append("Do you want to visit the project homepage on Github?");
about.append("</html>");
int response = JOptionPane.showConfirmDialog(null,
about.toString(),
mainFrame.getTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
new ImageIcon(mainIcon));
if (response == JOptionPane.YES_OPTION) {
try {
Desktop.getDesktop().browse(URI.create("http://github.com/4pr0n/ripme"));
} catch (IOException e) {
logger.error("Exception while opening project home page", e);
}
}
});
MenuItem trayMenuExit = new MenuItem("Exit");
trayMenuExit.addActionListener(arg0 -> System.exit(0));
trayMenuAutorip = new CheckboxMenuItem("Clipboard Autorip");
trayMenuAutorip.addItemListener(arg0 -> {
ClipboardUtils.setClipboardAutoRip(trayMenuAutorip.getState());
configClipboardAutorip.setSelected(trayMenuAutorip.getState());
});
trayMenu.add(trayMenuMain);
trayMenu.add(trayMenuAbout);
trayMenu.addSeparator();
trayMenu.add(trayMenuAutorip);
trayMenu.addSeparator();
trayMenu.add(trayMenuExit);
try {
mainIcon = ImageIO.read(getClass().getClassLoader().getResource("icon.png"));
trayIcon = new TrayIcon(mainIcon);
trayIcon.setToolTip(mainFrame.getTitle());
trayIcon.setImageAutoSize(true);
trayIcon.setPopupMenu(trayMenu);
SystemTray.getSystemTray().add(trayIcon);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
toggleTrayClick();
if (mainFrame.getExtendedState() != JFrame.NORMAL) {
mainFrame.setExtendedState(JFrame.NORMAL);
}
mainFrame.setAlwaysOnTop(true);
mainFrame.setAlwaysOnTop(false);
}
});
} catch (IOException | AWTException e) {
//TODO implement proper stack trace handling this is really just intented as a placeholder until you implement proper error handling
e.printStackTrace();
}
}
private void toggleTrayClick() {
if (mainFrame.getExtendedState() == JFrame.ICONIFIED
|| !mainFrame.isActive()
|| !mainFrame.isVisible()) {
mainFrame.setVisible(true);
mainFrame.setAlwaysOnTop(true);
mainFrame.setAlwaysOnTop(false);
trayMenuMain.setLabel("Hide");
} else {
mainFrame.setVisible(false);
trayMenuMain.setLabel("Show");
}
}
private void appendLog(final String text, final Color color) {
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, color);
StyledDocument sd = logText.getStyledDocument();
try {
synchronized (this) {
sd.insertString(sd.getLength(), text + "\n", sas);
}
} catch (BadLocationException e) { }
logText.setCaretPosition(sd.getLength());
}
private void loadHistory() {
File historyFile = new File(Utils.getConfigDir() + File.separator + "history.json");
HISTORY.clear();
if (historyFile.exists()) {
try {
logger.info("Loading history from " + historyFile.getCanonicalPath());
HISTORY.fromFile(historyFile.getCanonicalPath());
} catch (IOException e) {
logger.error("Failed to load history from file " + historyFile, e);
JOptionPane.showMessageDialog(null,
"RipMe failed to load the history file at " + historyFile.getAbsolutePath() + "\n\n" +
"Error: " + e.getMessage() + "\n\n" +
"Closing RipMe will automatically overwrite the contents of this file,\n" +
"so you may want to back the file up before closing RipMe!",
"RipMe - history load failure",
JOptionPane.ERROR_MESSAGE);
}
} else {
logger.info("Loading history from configuration");
HISTORY.fromList(Utils.getConfigList("download.history"));
if (HISTORY.toList().size() == 0) {
// Loaded from config, still no entries.
// Guess rip history based on rip folder
String[] dirs = Utils.getWorkingDirectory().list((dir, file) -> new File(dir.getAbsolutePath() + File.separator + file).isDirectory());
for (String dir : dirs) {
String url = RipUtils.urlFromDirectoryName(dir);
if (url != null) {
// We found one, add it to history
HistoryEntry entry = new HistoryEntry();
entry.url = url;
HISTORY.add(entry);
}
}
}
}
}
private void saveHistory() {
Path historyFile = Paths.get(Utils.getConfigDir() + File.separator + "history.json");
try {
if (!Files.exists(historyFile)) {
Files.createDirectories(historyFile.getParent());
Files.createFile(historyFile);
}
HISTORY.toFile(historyFile.toString());
Utils.setConfigList("download.history", Collections.emptyList());
} catch (IOException e) {
logger.error("Failed to save history to file " + historyFile, e);
}
}
@SuppressWarnings("unchecked")
private void ripNextAlbum() {
isRipping = true;
// Save current state of queue to configuration.
Utils.setConfigList("queue", (Enumeration<Object>) queueListModel.elements());
if (queueListModel.isEmpty()) {
// End of queue
isRipping = false;
return;
}
String nextAlbum = (String) queueListModel.remove(0);
if (queueListModel.isEmpty()) {
optionQueue.setText("Queue");
} else {
optionQueue.setText("Queue (" + queueListModel.size() + ")");
}
Thread t = ripAlbum(nextAlbum);
if (t == null) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
logger.error("Interrupted while waiting to rip next album", ie);
}
ripNextAlbum();
} else {
t.start();
}
}
private Thread ripAlbum(String urlString) {
//shutdownCleanup();
if (!logPanel.isVisible()) {
optionLog.doClick();
}
urlString = urlString.trim();
if (urlString.toLowerCase().startsWith("gonewild:")) {
urlString = "http://gonewild.com/user/" + urlString.substring(urlString.indexOf(':') + 1);
}
if (!urlString.startsWith("http")) {
urlString = "http://" + urlString;
}
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
logger.error("[!] Could not generate URL for '" + urlString + "'", e);
error("Given URL is not valid, expecting http://website.com/page/...");
return null;
}
stopButton.setEnabled(true);
statusProgress.setValue(100);
openButton.setVisible(false);
statusLabel.setVisible(true);
pack();
boolean failed = false;
try {
ripper = AbstractRipper.getRipper(url);
ripper.setup();
} catch (Exception e) {
failed = true;
logger.error("Could not find ripper for URL " + url, e);
error(e.getMessage());
}
if (!failed) {
try {
mainFrame.setTitle("Ripping - RipMe v" + UpdateUtils.getThisJarVersion());
status("Starting rip...");
ripper.setObserver(this);
Thread t = new Thread(ripper);
if (configShowPopup.isSelected() &&
(!mainFrame.isVisible() || !mainFrame.isActive())) {
mainFrame.toFront();
mainFrame.setAlwaysOnTop(true);
trayIcon.displayMessage(mainFrame.getTitle(), "Started ripping " + ripper.getURL().toExternalForm(), MessageType.INFO);
mainFrame.setAlwaysOnTop(false);
}
return t;
} catch (Exception e) {
logger.error("[!] Error while ripping: " + e.getMessage(), e);
error("Unable to rip this URL: " + e.getMessage());
}
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
pack();
return null;
}
class RipButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (!queueListModel.contains(ripTextfield.getText()) && !ripTextfield.getText().equals("")) {
queueListModel.add(queueListModel.size(), ripTextfield.getText());
ripTextfield.setText("");
} else {
if (!isRipping) {
ripNextAlbum();
}
}
}
}
private class StatusEvent implements Runnable {
private final AbstractRipper ripper;
private final RipStatusMessage msg;
StatusEvent(AbstractRipper ripper, RipStatusMessage msg) {
this.ripper = ripper;
this.msg = msg;
}
public void run() {
handleEvent(this);
}
}
private synchronized void handleEvent(StatusEvent evt) {
if (ripper.isStopped()) {
return;
}
RipStatusMessage msg = evt.msg;
int completedPercent = evt.ripper.getCompletionPercentage();
statusProgress.setValue(completedPercent);
statusProgress.setVisible(true);
status( evt.ripper.getStatusText() );
switch(msg.getStatus()) {
case LOADING_RESOURCE:
case DOWNLOAD_STARTED:
if (logger.isEnabledFor(Level.INFO)) {
appendLog("Downloading " + msg.getObject(), Color.BLACK);
}
break;
case DOWNLOAD_COMPLETE:
if (logger.isEnabledFor(Level.INFO)) {
appendLog("Downloaded " + msg.getObject(), Color.GREEN);
}
break;
case DOWNLOAD_ERRORED:
if (logger.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
break;
case DOWNLOAD_WARN:
if (logger.isEnabledFor(Level.WARN)) {
appendLog((String) msg.getObject(), Color.ORANGE);
}
break;
case RIP_ERRORED:
if (logger.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(false);
pack();
statusWithColor("Error: " + msg.getObject(), Color.RED);
break;
case RIP_COMPLETE:
RipStatusComplete rsc = (RipStatusComplete) msg.getObject();
String url = ripper.getURL().toExternalForm();
if (HISTORY.containsURL(url)) {
// TODO update "modifiedDate" of entry in HISTORY
HistoryEntry entry = HISTORY.getEntryByURL(url);
entry.count = rsc.count;
entry.modifiedDate = new Date();
} else {
HistoryEntry entry = new HistoryEntry();
entry.url = url;
entry.dir = rsc.getDir();
entry.count = rsc.count;
try {
entry.title = ripper.getAlbumTitle(ripper.getURL());
} catch (MalformedURLException e) { }
HISTORY.add(entry);
historyTableModel.fireTableDataChanged();
}
if (configPlaySound.isSelected()) {
Utils.playSound("camera.wav");
}
saveHistory();
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(true);
File f = rsc.dir;
String prettyFile = Utils.shortenPath(f);
openButton.setText("Open " + prettyFile);
mainFrame.setTitle("RipMe v" + UpdateUtils.getThisJarVersion());
try {
Image folderIcon = ImageIO.read(getClass().getClassLoader().getResource("folder.png"));
openButton.setIcon(new ImageIcon(folderIcon));
} catch (Exception e) { }
appendLog("Rip complete, saved to " + f.getAbsolutePath(), Color.GREEN);
openButton.setActionCommand(f.toString());
openButton.addActionListener(event -> {
try {
Desktop.getDesktop().open(new File(event.getActionCommand()));
} catch (Exception e) {
logger.error(e);
}
});
pack();
ripNextAlbum();
break;
case COMPLETED_BYTES:
// Update completed bytes
break;
case TOTAL_BYTES:
// Update total bytes
break;
}
}
public void update(AbstractRipper ripper, RipStatusMessage message) {
StatusEvent event = new StatusEvent(ripper, message);
SwingUtilities.invokeLater(event);
}
public static void ripAlbumStatic(String url) {
ripTextfield.setText(url.trim());
ripButton.doClick();
}
public static void enableWindowPositioning() {
Utils.setConfigBoolean("window.position", true);
}
public static void disableWindowPositioning() {
Utils.setConfigBoolean("window.position", false);
}
private static boolean hasWindowPositionBug() {
String osName = System.getProperty("os.name");
// Java on Windows has a bug where if we try to manually set the position of the Window,
// javaw.exe will not close itself down when the application is closed.
// Therefore, even if isWindowPositioningEnabled, if we are on Windows, we ignore it.
return osName == null || osName.startsWith("Windows");
}
private static boolean isWindowPositioningEnabled() {
boolean isEnabled = Utils.getConfigBoolean("window.position", true);
return isEnabled && !hasWindowPositionBug();
}
private static void saveWindowPosition(Frame frame) {
if (!isWindowPositioningEnabled()) {
return;
}
Point point;
try {
point = frame.getLocationOnScreen();
} catch (Exception e) {
e.printStackTrace();
try {
point = frame.getLocation();
} catch (Exception e2) {
e2.printStackTrace();
return;
}
}
int x = (int)point.getX();
int y = (int)point.getY();
int w = frame.getWidth();
int h = frame.getHeight();
Utils.setConfigInteger("window.x", x);
Utils.setConfigInteger("window.y", y);
Utils.setConfigInteger("window.w", w);
Utils.setConfigInteger("window.h", h);
logger.debug("Saved window position (x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ")");
}
private static void restoreWindowPosition(Frame frame) {
if (!isWindowPositioningEnabled()) {
mainFrame.setLocationRelativeTo(null); // default to middle of screen
return;
}
try {
int x = Utils.getConfigInteger("window.x", -1);
int y = Utils.getConfigInteger("window.y", -1);
int w = Utils.getConfigInteger("window.w", -1);
int h = Utils.getConfigInteger("window.h", -1);
if (x < 0 || y < 0 || w <= 0 || h <= 0) {
logger.debug("UNUSUAL: One or more of: x, y, w, or h was still less than 0 after reading config");
mainFrame.setLocationRelativeTo(null); // default to middle of screen
return;
}
frame.setBounds(x, y, w, h);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package com.rarchives.ripme.ui;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;
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.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.rarchives.ripme.ripper.AbstractRipper;
import com.rarchives.ripme.utils.RipUtils;
import com.rarchives.ripme.utils.Utils;
import javax.swing.UnsupportedLookAndFeelException;
/**
* Everything UI-related starts and ends here.
*/
public final class MainWindow implements Runnable, RipStatusHandler {
private static final Logger LOGGER = Logger.getLogger(MainWindow.class);
private boolean isRipping = false; // Flag to indicate if we're ripping something
private static JFrame mainFrame;
private static JTextField ripTextfield;
private static JButton ripButton,
stopButton;
private static JLabel statusLabel;
private static JButton openButton;
private static JProgressBar statusProgress;
// Put an empty JPanel on the bottom of the window to keep components
// anchored to the top when there is no open lower panel
private static JPanel emptyPanel;
// Log
private static JButton optionLog;
private static JPanel logPanel;
private static JTextPane logText;
// History
private static JButton optionHistory;
private static final History HISTORY = new History();
private static JPanel historyPanel;
private static JTable historyTable;
private static AbstractTableModel historyTableModel;
private static JButton historyButtonRemove,
historyButtonClear,
historyButtonRerip;
// Queue
public static JButton optionQueue;
private static JPanel queuePanel;
private static DefaultListModel queueListModel;
// Configuration
private static JButton optionConfiguration;
private static JPanel configurationPanel;
private static JButton configUpdateButton;
private static JLabel configUpdateLabel;
private static JTextField configTimeoutText;
private static JTextField configThreadsText;
private static JCheckBox configOverwriteCheckbox;
private static JLabel configSaveDirLabel;
private static JButton configSaveDirButton;
private static JTextField configRetriesText;
private static JCheckBox configAutoupdateCheckbox;
private static JComboBox<String> configLogLevelCombobox;
private static JCheckBox configURLHistoryCheckbox;
private static JCheckBox configPlaySound;
private static JCheckBox configSaveOrderCheckbox;
private static JCheckBox configShowPopup;
private static JCheckBox configSaveLogs;
private static JCheckBox configSaveURLsOnly;
private static JCheckBox configSaveAlbumTitles;
private static JCheckBox configClipboardAutorip;
private static JCheckBox configSaveDescriptions;
private static JCheckBox configPreferMp4;
private static JCheckBox configWindowPosition;
private static JComboBox<String> configSelectLangComboBox;
private static JLabel configThreadsLabel;
private static JLabel configTimeoutLabel;
private static JLabel configRetriesLabel;
// This doesn't really belong here but I have no idea where else to put it
private static JButton configUrlFileChooserButton;
private static TrayIcon trayIcon;
private static MenuItem trayMenuMain;
private static CheckboxMenuItem trayMenuAutorip;
private static Image mainIcon;
private static AbstractRipper ripper;
public static ResourceBundle rb = Utils.getResourceBundle(null);
// All the langs ripme has been translated into
private static String[] supportedLanges = new String[] {"en_US", "de_DE", "es_ES", "fr_CH", "kr_KR", "pt_BR", "pt_PT",
"fi_FI", "in_ID", "nl_NL", "porrisavvo_FI", "ru_RU"};
private void updateQueueLabel() {
if (queueListModel.size() > 0) {
optionQueue.setText(rb.getString("Queue") + " (" + queueListModel.size() + ")");
} else {
optionQueue.setText(rb.getString("Queue"));
}
}
private static int getAverageFontWidth(JComponent component) {
int sum = 0;
int[] widths = component.getFontMetrics(component.getFont()).getWidths();
for(int i : widths) {
sum += i;
}
return sum / widths.length;
}
private static void insertWrappedString(JComponent parent, StyledDocument document, String string, SimpleAttributeSet s)
throws BadLocationException {
StringBuilder resultString = new StringBuilder();
int maxCharsToFit = parent.getWidth() / getAverageFontWidth(parent);
int i = 0;
while(i < string.length()/maxCharsToFit) {
if(i > 0) resultString.append(string.substring(i*maxCharsToFit-2, i*maxCharsToFit));
resultString.append(string.substring(i*maxCharsToFit, (i+1)*maxCharsToFit-2));
resultString.append("\n");
i++;
}
resultString.append(string.substring(string.length()-(string.length()%maxCharsToFit)));
resultString.append("\n");
document.insertString(document.getLength(), resultString.toString(), s);
}
private static void addCheckboxListener(JCheckBox checkBox, String configString) {
checkBox.addActionListener(arg0 -> {
Utils.setConfigBoolean(configString, checkBox.isSelected());
Utils.configureLogger();
});
}
private static JCheckBox addNewCheckbox(String text, String configString, Boolean configBool) {
JCheckBox checkbox = new JCheckBox(text, Utils.getConfigBoolean(configString, configBool));
checkbox.setHorizontalAlignment(JCheckBox.RIGHT);
checkbox.setHorizontalTextPosition(JCheckBox.LEFT);
return checkbox;
}
public static void addUrlToQueue(String url) {
queueListModel.addElement(url);
}
public MainWindow() {
mainFrame = new JFrame("RipMe v" + UpdateUtils.getThisJarVersion());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new GridBagLayout());
createUI(mainFrame.getContentPane());
pack();
loadHistory();
setupHandlers();
Thread shutdownThread = new Thread(this::shutdownCleanup);
Runtime.getRuntime().addShutdownHook(shutdownThread);
if (Utils.getConfigBoolean("auto.update", true)) {
upgradeProgram();
}
boolean autoripEnabled = Utils.getConfigBoolean("clipboard.autorip", false);
ClipboardUtils.setClipboardAutoRip(autoripEnabled);
trayMenuAutorip.setState(autoripEnabled);
}
private void upgradeProgram() {
if (!configurationPanel.isVisible()) {
optionConfiguration.doClick();
}
Runnable r = () -> UpdateUtils.updateProgramGUI(configUpdateLabel);
new Thread(r).start();
}
public void run() {
pack();
restoreWindowPosition(mainFrame);
mainFrame.setVisible(true);
}
private void shutdownCleanup() {
Utils.setConfigBoolean("file.overwrite", configOverwriteCheckbox.isSelected());
Utils.setConfigInteger("threads.size", Integer.parseInt(configThreadsText.getText()));
Utils.setConfigInteger("download.retries", Integer.parseInt(configRetriesText.getText()));
Utils.setConfigInteger("download.timeout", Integer.parseInt(configTimeoutText.getText()));
Utils.setConfigBoolean("clipboard.autorip", ClipboardUtils.getClipboardAutoRip());
Utils.setConfigBoolean("auto.update", configAutoupdateCheckbox.isSelected());
Utils.setConfigString("log.level", configLogLevelCombobox.getSelectedItem().toString());
Utils.setConfigBoolean("play.sound", configPlaySound.isSelected());
Utils.setConfigBoolean("download.save_order", configSaveOrderCheckbox.isSelected());
Utils.setConfigBoolean("download.show_popup", configShowPopup.isSelected());
Utils.setConfigBoolean("log.save", configSaveLogs.isSelected());
Utils.setConfigBoolean("urls_only.save", configSaveURLsOnly.isSelected());
Utils.setConfigBoolean("album_titles.save", configSaveAlbumTitles.isSelected());
Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected());
Utils.setConfigBoolean("descriptions.save", configSaveDescriptions.isSelected());
Utils.setConfigBoolean("prefer.mp4", configPreferMp4.isSelected());
Utils.setConfigBoolean("remember.url_history", configURLHistoryCheckbox.isSelected());
saveWindowPosition(mainFrame);
saveHistory();
Utils.saveConfig();
}
private void status(String text) {
statusWithColor(text, Color.BLACK);
}
private void error(String text) {
statusWithColor(text, Color.RED);
}
private void statusWithColor(String text, Color color) {
statusLabel.setForeground(color);
statusLabel.setToolTipText(text);
int averageWidth = getAverageFontWidth(statusLabel);
int numCharsToFit = statusLabel.getWidth() / averageWidth;
if(text.length() > (mainFrame.getWidth() / averageWidth)) {
statusLabel.setText(text.substring(0, numCharsToFit-6) + "...");
} else {
statusLabel.setText(text);
}
pack();
}
private void pack() {
SwingUtilities.invokeLater(() -> {
Dimension preferredSize = mainFrame.getPreferredSize();
mainFrame.setMinimumSize(preferredSize);
if (isCollapsed()) {
mainFrame.setSize(preferredSize);
}
});
}
private boolean isCollapsed() {
return (!logPanel.isVisible() &&
!historyPanel.isVisible() &&
!queuePanel.isVisible() &&
!configurationPanel.isVisible()
);
}
private void createUI(Container pane) {
//If creating the tray icon fails, ignore it.
try {
setupTrayIcon();
} catch (Exception e) { }
EmptyBorder emptyBorder = new EmptyBorder(5, 5, 5, 5);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1; gbc.ipadx = 2; gbc.gridx = 0;
gbc.weighty = 0; gbc.ipady = 2; gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
LOGGER.error("[!] Exception setting system theme:", e);
}
ripTextfield = new JTextField("", 20);
ripTextfield.addMouseListener(new ContextMenuMouseListener());
ImageIcon ripIcon = new ImageIcon(mainIcon);
ripButton = new JButton("<html><font size=\"5\"><b>Rip</b></font></html>", ripIcon);
stopButton = new JButton("<html><font size=\"5\"><b>Stop</b></font></html>");
stopButton.setEnabled(false);
try {
Image stopIcon = ImageIO.read(getClass().getClassLoader().getResource("stop.png"));
stopButton.setIcon(new ImageIcon(stopIcon));
} catch (Exception ignored) { }
JPanel ripPanel = new JPanel(new GridBagLayout());
ripPanel.setBorder(emptyBorder);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
gbc.gridx = 0; ripPanel.add(new JLabel("URL:", JLabel.RIGHT), gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 1; ripPanel.add(ripTextfield, gbc);
gbc.weighty = 0;
gbc.weightx = 0;
gbc.gridx = 2; ripPanel.add(ripButton, gbc);
gbc.gridx = 3; ripPanel.add(stopButton, gbc);
gbc.weightx = 1;
statusLabel = new JLabel(rb.getString("inactive"));
statusLabel.setToolTipText(rb.getString("inactive"));
statusLabel.setHorizontalAlignment(JLabel.CENTER);
openButton = new JButton();
openButton.setVisible(false);
JPanel statusPanel = new JPanel(new GridBagLayout());
statusPanel.setBorder(emptyBorder);
gbc.gridx = 0; statusPanel.add(statusLabel, gbc);
gbc.gridy = 1; statusPanel.add(openButton, gbc);
gbc.gridy = 0;
JPanel progressPanel = new JPanel(new GridBagLayout());
progressPanel.setBorder(emptyBorder);
statusProgress = new JProgressBar(0, 100);
progressPanel.add(statusProgress, gbc);
JPanel optionsPanel = new JPanel(new GridBagLayout());
optionsPanel.setBorder(emptyBorder);
optionLog = new JButton(rb.getString("Log"));
optionHistory = new JButton(rb.getString("History"));
optionQueue = new JButton(rb.getString("Queue"));
optionConfiguration = new JButton(rb.getString("Configuration"));
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
try {
Image icon;
icon = ImageIO.read(getClass().getClassLoader().getResource("comment.png"));
optionLog.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("time.png"));
optionHistory.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("list.png"));
optionQueue.setIcon(new ImageIcon(icon));
icon = ImageIO.read(getClass().getClassLoader().getResource("gear.png"));
optionConfiguration.setIcon(new ImageIcon(icon));
} catch (Exception e) { }
gbc.gridx = 0; optionsPanel.add(optionLog, gbc);
gbc.gridx = 1; optionsPanel.add(optionHistory, gbc);
gbc.gridx = 2; optionsPanel.add(optionQueue, gbc);
gbc.gridx = 3; optionsPanel.add(optionConfiguration, gbc);
logPanel = new JPanel(new GridBagLayout());
logPanel.setBorder(emptyBorder);
logText = new JTextPane();
logText.setEditable(false);
JScrollPane logTextScroll = new JScrollPane(logText);
logTextScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logPanel.setVisible(false);
logPanel.setPreferredSize(new Dimension(300, 250));
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
logPanel.add(logTextScroll, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
historyPanel = new JPanel(new GridBagLayout());
historyPanel.setBorder(emptyBorder);
historyPanel.setVisible(false);
historyPanel.setPreferredSize(new Dimension(300, 250));
historyTableModel = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
return HISTORY.getColumnName(col);
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public Object getValueAt(int row, int col) {
return HISTORY.getValueAt(row, col);
}
@Override
public int getRowCount() {
return HISTORY.toList().size();
}
@Override
public int getColumnCount() {
return HISTORY.getColumnCount();
}
@Override
public boolean isCellEditable(int row, int col) {
return (col == 0 || col == 4);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col == 4) {
HISTORY.get(row).selected = (Boolean) value;
historyTableModel.fireTableDataChanged();
}
}
};
historyTable = new JTable(historyTableModel);
historyTable.addMouseListener(new HistoryMenuMouseListener());
historyTable.setAutoCreateRowSorter(true);
for (int i = 0; i < historyTable.getColumnModel().getColumnCount(); i++) {
int width = 130; // Default
switch (i) {
case 0: // URL
width = 270;
break;
case 3:
width = 40;
break;
case 4:
width = 15;
break;
}
historyTable.getColumnModel().getColumn(i).setPreferredWidth(width);
}
JScrollPane historyTableScrollPane = new JScrollPane(historyTable);
historyButtonRemove = new JButton(rb.getString("remove"));
historyButtonClear = new JButton(rb.getString("clear"));
historyButtonRerip = new JButton(rb.getString("re-rip.checked"));
gbc.gridx = 0;
// History List Panel
JPanel historyTablePanel = new JPanel(new GridBagLayout());
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
historyTablePanel.add(historyTableScrollPane, gbc);
gbc.ipady = 180;
gbc.gridy = 0;
historyPanel.add(historyTablePanel, gbc);
gbc.ipady = 0;
JPanel historyButtonPanel = new JPanel(new GridBagLayout());
historyButtonPanel.setPreferredSize(new Dimension(300, 10));
historyButtonPanel.setBorder(emptyBorder);
gbc.gridx = 0; historyButtonPanel.add(historyButtonRemove, gbc);
gbc.gridx = 1; historyButtonPanel.add(historyButtonClear, gbc);
gbc.gridx = 2; historyButtonPanel.add(historyButtonRerip, gbc);
gbc.gridy = 1; gbc.gridx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
historyPanel.add(historyButtonPanel, gbc);
queuePanel = new JPanel(new GridBagLayout());
queuePanel.setBorder(emptyBorder);
queuePanel.setVisible(false);
queuePanel.setPreferredSize(new Dimension(300, 250));
queueListModel = new DefaultListModel();
JList queueList = new JList(queueListModel);
queueList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
queueList.addMouseListener(new QueueMenuMouseListener());
JScrollPane queueListScroll = new JScrollPane(queueList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
for (String item : Utils.getConfigList("queue")) {
queueListModel.addElement(item);
}
updateQueueLabel();
gbc.gridx = 0;
JPanel queueListPanel = new JPanel(new GridBagLayout());
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
queueListPanel.add(queueListScroll, gbc);
queuePanel.add(queueListPanel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
gbc.ipady = 0;
configurationPanel = new JPanel(new GridBagLayout());
configurationPanel.setBorder(emptyBorder);
configurationPanel.setVisible(false);
// TODO Configuration components
configUpdateButton = new JButton(rb.getString("check.for.updates"));
configUpdateLabel = new JLabel( rb.getString("current.version") + ": " + UpdateUtils.getThisJarVersion(), JLabel.RIGHT);
configThreadsLabel = new JLabel(rb.getString("max.download.threads") + ":", JLabel.RIGHT);
configTimeoutLabel = new JLabel(rb.getString("timeout.mill"), JLabel.RIGHT);
configRetriesLabel = new JLabel(rb.getString("retry.download.count"), JLabel.RIGHT);
configThreadsText = new JTextField(Integer.toString(Utils.getConfigInteger("threads.size", 3)));
configTimeoutText = new JTextField(Integer.toString(Utils.getConfigInteger("download.timeout", 60000)));
configRetriesText = new JTextField(Integer.toString(Utils.getConfigInteger("download.retries", 3)));
configOverwriteCheckbox = addNewCheckbox(rb.getString("overwrite.existing.files"), "file.overwrite", false);
configAutoupdateCheckbox = addNewCheckbox(rb.getString("auto.update"), "auto.update", true);
configPlaySound = addNewCheckbox(rb.getString("sound.when.rip.completes"), "play.sound", false);
configShowPopup = addNewCheckbox(rb.getString("notification.when.rip.starts"), "download.show_popup", false);
configSaveOrderCheckbox = addNewCheckbox(rb.getString("preserve.order"), "download.save_order", true);
configSaveLogs = addNewCheckbox(rb.getString("save.logs"), "log.save", false);
configSaveURLsOnly = addNewCheckbox(rb.getString("save.urls.only"), "urls_only.save", false);
configSaveAlbumTitles = addNewCheckbox(rb.getString("save.album.titles"), "album_titles.save", true);
configClipboardAutorip = addNewCheckbox(rb.getString("autorip.from.clipboard"), "clipboard.autorip", false);
configSaveDescriptions = addNewCheckbox(rb.getString("save.descriptions"), "descriptions.save", true);
configPreferMp4 = addNewCheckbox(rb.getString("prefer.mp4.over.gif"),"prefer.mp4", false);
configWindowPosition = addNewCheckbox(rb.getString("restore.window.position"), "window.position", true);
configURLHistoryCheckbox = addNewCheckbox(rb.getString("remember.url.history"), "remember.url_history", true);
configUrlFileChooserButton = new JButton(rb.getString("download.url.list"));
configLogLevelCombobox = new JComboBox<>(new String[] {"Log level: Error", "Log level: Warn", "Log level: Info", "Log level: Debug"});
configSelectLangComboBox = new JComboBox<>(supportedLanges);
configLogLevelCombobox.setSelectedItem(Utils.getConfigString("log.level", "Log level: Debug"));
setLogLevel(configLogLevelCombobox.getSelectedItem().toString());
configSaveDirLabel = new JLabel();
try {
String workingDir = (Utils.shortenPath(Utils.getWorkingDirectory()));
configSaveDirLabel.setText(workingDir);
configSaveDirLabel.setForeground(Color.BLUE);
configSaveDirLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception e) { }
configSaveDirLabel.setToolTipText(configSaveDirLabel.getText());
configSaveDirLabel.setHorizontalAlignment(JLabel.RIGHT);
configSaveDirButton = new JButton(rb.getString("select.save.dir") + "...");
addItemToConfigGridBagConstraints(gbc, 0, configUpdateLabel, configUpdateButton);
addItemToConfigGridBagConstraints(gbc, 1, configAutoupdateCheckbox, configLogLevelCombobox);
addItemToConfigGridBagConstraints(gbc, 2, configThreadsLabel, configThreadsText);
addItemToConfigGridBagConstraints(gbc, 3, configTimeoutLabel, configTimeoutText);
addItemToConfigGridBagConstraints(gbc, 4, configRetriesLabel, configRetriesText);
addItemToConfigGridBagConstraints(gbc, 5, configOverwriteCheckbox, configSaveOrderCheckbox);
addItemToConfigGridBagConstraints(gbc, 6, configPlaySound, configSaveLogs);
addItemToConfigGridBagConstraints(gbc, 7, configShowPopup, configSaveURLsOnly);
addItemToConfigGridBagConstraints(gbc, 8, configClipboardAutorip, configSaveAlbumTitles);
addItemToConfigGridBagConstraints(gbc, 9, configSaveDescriptions, configPreferMp4);
addItemToConfigGridBagConstraints(gbc, 10, configWindowPosition, configURLHistoryCheckbox);
addItemToConfigGridBagConstraints(gbc, 11, configSelectLangComboBox, configUrlFileChooserButton);
addItemToConfigGridBagConstraints(gbc, 12, configSaveDirLabel, configSaveDirButton);
emptyPanel = new JPanel();
emptyPanel.setPreferredSize(new Dimension(0, 0));
emptyPanel.setSize(0, 0);
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.gridy = 0; pane.add(ripPanel, gbc);
gbc.gridy = 1; pane.add(statusPanel, gbc);
gbc.gridy = 2; pane.add(progressPanel, gbc);
gbc.gridy = 3; pane.add(optionsPanel, gbc);
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 4; pane.add(logPanel, gbc);
gbc.gridy = 5; pane.add(historyPanel, gbc);
gbc.gridy = 5; pane.add(queuePanel, gbc);
gbc.gridy = 5; pane.add(configurationPanel, gbc);
gbc.gridy = 5; pane.add(emptyPanel, gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JLabel thing1ToAdd, JButton thing2ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
gbc.gridx = 1; configurationPanel.add(thing2ToAdd, gbc);
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JLabel thing1ToAdd, JTextField thing2ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
gbc.gridx = 1; configurationPanel.add(thing2ToAdd, gbc);
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JCheckBox thing1ToAdd, JCheckBox thing2ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
gbc.gridx = 1; configurationPanel.add(thing2ToAdd, gbc);
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JCheckBox thing1ToAdd, JComboBox thing2ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
gbc.gridx = 1; configurationPanel.add(thing2ToAdd, gbc);
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JComboBox thing1ToAdd, JButton thing2ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
gbc.gridx = 1; configurationPanel.add(thing2ToAdd, gbc);
}
private void addItemToConfigGridBagConstraints(GridBagConstraints gbc, int gbcYValue, JComboBox thing1ToAdd ) {
gbc.gridy = gbcYValue; gbc.gridx = 0; configurationPanel.add(thing1ToAdd, gbc);
}
private void changeLocale() {
statusLabel.setText(rb.getString("inactive"));
configUpdateButton.setText(rb.getString("check.for.updates"));
configUpdateLabel.setText(rb.getString("current.version") + ": " + UpdateUtils.getThisJarVersion());
configThreadsLabel.setText(rb.getString("max.download.threads"));
configTimeoutLabel.setText(rb.getString("timeout.mill"));
configRetriesLabel.setText(rb.getString("retry.download.count"));
configOverwriteCheckbox.setText(rb.getString("overwrite.existing.files"));
configAutoupdateCheckbox.setText(rb.getString("auto.update"));
configPlaySound.setText(rb.getString("sound.when.rip.completes"));
configShowPopup.setText(rb.getString("notification.when.rip.starts"));
configSaveOrderCheckbox.setText(rb.getString("preserve.order"));
configSaveLogs.setText(rb.getString("save.logs"));
configSaveURLsOnly.setText(rb.getString("save.urls.only"));
configSaveAlbumTitles.setText(rb.getString("save.album.titles"));
configClipboardAutorip.setText(rb.getString("autorip.from.clipboard"));
configSaveDescriptions.setText(rb.getString("save.descriptions"));
configUrlFileChooserButton.setText(rb.getString("download.url.list"));
configSaveDirButton.setText(rb.getString("select.save.dir") + "...");
configPreferMp4.setText(rb.getString("prefer.mp4.over.gif"));
configWindowPosition.setText(rb.getString("restore.window.position"));
configURLHistoryCheckbox.setText(rb.getString("remember.url.history"));
optionLog.setText(rb.getString("Log"));
optionHistory.setText(rb.getString("History"));
optionQueue.setText(rb.getString("Queue"));
optionConfiguration.setText(rb.getString("Configuration"));
}
private void setupHandlers() {
ripButton.addActionListener(new RipButtonHandler());
ripTextfield.addActionListener(new RipButtonHandler());
ripTextfield.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
try {
String urlText = ripTextfield.getText().trim();
if (urlText.equals("")) {
return;
}
if (!urlText.startsWith("http")) {
urlText = "http://" + urlText;
}
URL url = new URL(urlText);
AbstractRipper ripper = AbstractRipper.getRipper(url);
statusWithColor(ripper.getHost() + " album detected", Color.GREEN);
} catch (Exception e) {
statusWithColor("Can't rip this URL: " + e.getMessage(), Color.RED);
}
}
});
stopButton.addActionListener(event -> {
if (ripper != null) {
ripper.stop();
isRipping = false;
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
pack();
statusProgress.setValue(0);
status("Ripping interrupted");
appendLog("Ripper interrupted", Color.RED);
}
});
optionLog.addActionListener(event -> {
logPanel.setVisible(!logPanel.isVisible());
emptyPanel.setVisible(!logPanel.isVisible());
historyPanel.setVisible(false);
queuePanel.setVisible(false);
configurationPanel.setVisible(false);
if (logPanel.isVisible()) {
optionLog.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionHistory.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(!historyPanel.isVisible());
emptyPanel.setVisible(!historyPanel.isVisible());
queuePanel.setVisible(false);
configurationPanel.setVisible(false);
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (historyPanel.isVisible()) {
optionHistory.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionQueue.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(false);
queuePanel.setVisible(!queuePanel.isVisible());
emptyPanel.setVisible(!queuePanel.isVisible());
configurationPanel.setVisible(false);
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (queuePanel.isVisible()) {
optionQueue.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
pack();
});
optionConfiguration.addActionListener(event -> {
logPanel.setVisible(false);
historyPanel.setVisible(false);
queuePanel.setVisible(false);
configurationPanel.setVisible(!configurationPanel.isVisible());
emptyPanel.setVisible(!configurationPanel.isVisible());
optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
if (configurationPanel.isVisible()) {
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.BOLD));
} else {
optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN));
}
pack();
});
historyButtonRemove.addActionListener(event -> {
int[] indices = historyTable.getSelectedRows();
for (int i = indices.length - 1; i >= 0; i
int modelIndex = historyTable.convertRowIndexToModel(indices[i]);
HISTORY.remove(modelIndex);
}
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) { }
saveHistory();
});
historyButtonClear.addActionListener(event -> {
if (Utils.getConfigBoolean("history.warn_before_delete", true)) {
JPanel checkChoise = new JPanel();
checkChoise.setLayout(new FlowLayout());
JButton yesButton = new JButton("YES");
JButton noButton = new JButton("NO");
yesButton.setPreferredSize(new Dimension(70, 30));
noButton.setPreferredSize(new Dimension(70, 30));
checkChoise.add(yesButton);
checkChoise.add(noButton);
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Are you sure?");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(checkChoise);
frame.setSize(405, 70);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
noButton.addActionListener(e -> {
frame.setVisible(false);
});
yesButton.addActionListener(ed -> {
frame.setVisible(false);
Utils.clearURLHistory();
HISTORY.clear();
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) {
}
saveHistory();
});
}
else {
Utils.clearURLHistory();
HISTORY.clear();
try {
historyTableModel.fireTableDataChanged();
} catch (Exception e) {
}
saveHistory();
}
});
// Re-rip all history
historyButtonRerip.addActionListener(event -> {
if (HISTORY.isEmpty()) {
JOptionPane.showMessageDialog(null,
"There are no history entries to re-rip. Rip some albums first",
"RipMe Error",
JOptionPane.ERROR_MESSAGE);
return;
}
int added = 0;
for (HistoryEntry entry : HISTORY.toList()) {
if (entry.selected) {
added++;
queueListModel.addElement(entry.url);
}
}
if (added == 0) {
JOptionPane.showMessageDialog(null,
"No history entries have been 'Checked'\n" +
"Check an entry by clicking the checkbox to the right of the URL or Right-click a URL to check/uncheck all items",
"RipMe Error",
JOptionPane.ERROR_MESSAGE);
}
});
configUpdateButton.addActionListener(arg0 -> {
Thread t = new Thread(() -> UpdateUtils.updateProgramGUI(configUpdateLabel));
t.start();
});
configLogLevelCombobox.addActionListener(arg0 -> {
String level = ((JComboBox) arg0.getSource()).getSelectedItem().toString();
setLogLevel(level);
});
configSelectLangComboBox.addActionListener(arg0 -> {
String level = ((JComboBox) arg0.getSource()).getSelectedItem().toString();
rb = Utils.getResourceBundle(level);
changeLocale();
});
configSaveDirLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
File file = new File(Utils.getWorkingDirectory().toString());
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
} catch (Exception e1) { }
}
});
configSaveDirButton.addActionListener(arg0 -> {
UIManager.put("FileChooser.useSystemExtensionHiding", false);
JFileChooser jfc = new JFileChooser(Utils.getWorkingDirectory());
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = jfc.showDialog(null, "select directory");
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File chosenFile = jfc.getSelectedFile();
String chosenPath = null;
try {
chosenPath = chosenFile.getCanonicalPath();
} catch (Exception e) {
LOGGER.error("Error while getting selected path: ", e);
return;
}
configSaveDirLabel.setText(Utils.shortenPath(chosenPath));
Utils.setConfigString("rips.directory", chosenPath);
});
configUrlFileChooserButton.addActionListener(arg0 -> {
UIManager.put("FileChooser.useSystemExtensionHiding", false);
JFileChooser jfc = new JFileChooser(Utils.getWorkingDirectory());
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = jfc.showDialog(null, "Open");
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File chosenFile = jfc.getSelectedFile();
String chosenPath = null;
try {
chosenPath = chosenFile.getCanonicalPath();
} catch (Exception e) {
LOGGER.error("Error while getting selected path: ", e);
return;
}
try {
BufferedReader br = new BufferedReader(new FileReader(chosenPath));
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (line.startsWith("http")) {
MainWindow.addUrlToQueue(line);
} else {
LOGGER.error("Skipping url " + line + " because it looks malformed (doesn't start with http)");
}
}
} catch(IOException e) {
LOGGER.error("Error reading file " + e.getMessage());
}
});
addCheckboxListener(configSaveOrderCheckbox, "download.save_order");
addCheckboxListener(configOverwriteCheckbox, "file.overwrite");
addCheckboxListener(configSaveLogs, "log.save");
addCheckboxListener(configSaveURLsOnly, "urls_only.save");
addCheckboxListener(configURLHistoryCheckbox, "remember.url_history");
addCheckboxListener(configSaveAlbumTitles, "album_titles.save");
addCheckboxListener(configSaveDescriptions, "descriptions.save");
addCheckboxListener(configPreferMp4, "prefer.mp4");
addCheckboxListener(configWindowPosition, "window.position");
configClipboardAutorip.addActionListener(arg0 -> {
Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected());
ClipboardUtils.setClipboardAutoRip(configClipboardAutorip.isSelected());
trayMenuAutorip.setState(configClipboardAutorip.isSelected());
Utils.configureLogger();
});
queueListModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent arg0) {
updateQueueLabel();
if (!isRipping) {
ripNextAlbum();
}
}
@Override
public void contentsChanged(ListDataEvent arg0) { }
@Override
public void intervalRemoved(ListDataEvent arg0) { }
});
}
private void setLogLevel(String level) {
Level newLevel = Level.ERROR;
level = level.substring(level.lastIndexOf(' ') + 1);
switch (level) {
case "Debug":
newLevel = Level.DEBUG;
break;
case "Info":
newLevel = Level.INFO;
break;
case "Warn":
newLevel = Level.WARN;
break;
case "Error":
newLevel = Level.ERROR;
break;
}
Logger.getRootLogger().setLevel(newLevel);
LOGGER.setLevel(newLevel);
ConsoleAppender ca = (ConsoleAppender)Logger.getRootLogger().getAppender("stdout");
if (ca != null) {
ca.setThreshold(newLevel);
}
FileAppender fa = (FileAppender)Logger.getRootLogger().getAppender("FILE");
if (fa != null) {
fa.setThreshold(newLevel);
}
}
private void setupTrayIcon() {
mainFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) { trayMenuMain.setLabel("Hide"); }
@Override
public void windowDeactivated(WindowEvent e) { trayMenuMain.setLabel("Show"); }
@Override
public void windowDeiconified(WindowEvent e) { trayMenuMain.setLabel("Hide"); }
@Override
public void windowIconified(WindowEvent e) { trayMenuMain.setLabel("Show"); }
});
PopupMenu trayMenu = new PopupMenu();
trayMenuMain = new MenuItem("Hide");
trayMenuMain.addActionListener(arg0 -> toggleTrayClick());
MenuItem trayMenuAbout = new MenuItem("About " + mainFrame.getTitle());
trayMenuAbout.addActionListener(arg0 -> {
StringBuilder about = new StringBuilder();
about.append("<html><h1>")
.append(mainFrame.getTitle())
.append("</h1>");
about.append("Download albums from various websites:");
try {
List<String> rippers = Utils.getListOfAlbumRippers();
about.append("<ul>");
for (String ripper : rippers) {
about.append("<li>");
ripper = ripper.substring(ripper.lastIndexOf('.') + 1);
if (ripper.contains("Ripper")) {
ripper = ripper.substring(0, ripper.indexOf("Ripper"));
}
about.append(ripper);
about.append("</li>");
}
about.append("</ul>");
} catch (Exception e) { }
about.append("<br>And download videos from video sites:");
try {
List<String> rippers = Utils.getListOfVideoRippers();
about.append("<ul>");
for (String ripper : rippers) {
about.append("<li>");
ripper = ripper.substring(ripper.lastIndexOf('.') + 1);
if (ripper.contains("Ripper")) {
ripper = ripper.substring(0, ripper.indexOf("Ripper"));
}
about.append(ripper);
about.append("</li>");
}
about.append("</ul>");
} catch (Exception e) { }
about.append("Do you want to visit the project homepage on Github?");
about.append("</html>");
int response = JOptionPane.showConfirmDialog(null,
about.toString(),
mainFrame.getTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
new ImageIcon(mainIcon));
if (response == JOptionPane.YES_OPTION) {
try {
Desktop.getDesktop().browse(URI.create("http://github.com/ripmeapp/ripme"));
} catch (IOException e) {
LOGGER.error("Exception while opening project home page", e);
}
}
});
MenuItem trayMenuExit = new MenuItem("Exit");
trayMenuExit.addActionListener(arg0 -> System.exit(0));
trayMenuAutorip = new CheckboxMenuItem("Clipboard Autorip");
trayMenuAutorip.addItemListener(arg0 -> {
ClipboardUtils.setClipboardAutoRip(trayMenuAutorip.getState());
configClipboardAutorip.setSelected(trayMenuAutorip.getState());
});
trayMenu.add(trayMenuMain);
trayMenu.add(trayMenuAbout);
trayMenu.addSeparator();
trayMenu.add(trayMenuAutorip);
trayMenu.addSeparator();
trayMenu.add(trayMenuExit);
try {
mainIcon = ImageIO.read(getClass().getClassLoader().getResource("icon.png"));
trayIcon = new TrayIcon(mainIcon);
trayIcon.setToolTip(mainFrame.getTitle());
trayIcon.setImageAutoSize(true);
trayIcon.setPopupMenu(trayMenu);
SystemTray.getSystemTray().add(trayIcon);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
toggleTrayClick();
if (mainFrame.getExtendedState() != JFrame.NORMAL) {
mainFrame.setExtendedState(JFrame.NORMAL);
}
mainFrame.setAlwaysOnTop(true);
mainFrame.setAlwaysOnTop(false);
}
});
} catch (IOException | AWTException e) {
//TODO implement proper stack trace handling this is really just intented as a placeholder until you implement proper error handling
e.printStackTrace();
}
}
private void toggleTrayClick() {
if (mainFrame.getExtendedState() == JFrame.ICONIFIED
|| !mainFrame.isActive()
|| !mainFrame.isVisible()) {
mainFrame.setVisible(true);
mainFrame.setAlwaysOnTop(true);
mainFrame.setAlwaysOnTop(false);
trayMenuMain.setLabel("Hide");
} else {
mainFrame.setVisible(false);
trayMenuMain.setLabel("Show");
}
}
private void appendLog(final String text, final Color color) {
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, color);
StyledDocument sd = logText.getStyledDocument();
try {
synchronized (this) {
insertWrappedString(logText, sd, text, sas);
}
} catch (BadLocationException e) { }
logText.setCaretPosition(sd.getLength());
}
private void loadHistory() {
File historyFile = new File(Utils.getConfigDir() + File.separator + "history.json");
HISTORY.clear();
if (historyFile.exists()) {
try {
LOGGER.info(rb.getString("loading.history.from") + " " + historyFile.getCanonicalPath());
HISTORY.fromFile(historyFile.getCanonicalPath());
} catch (IOException e) {
LOGGER.error("Failed to load history from file " + historyFile, e);
JOptionPane.showMessageDialog(null,
"RipMe failed to load the history file at " + historyFile.getAbsolutePath() + "\n\n" +
"Error: " + e.getMessage() + "\n\n" +
"Closing RipMe will automatically overwrite the contents of this file,\n" +
"so you may want to back the file up before closing RipMe!",
"RipMe - history load failure",
JOptionPane.ERROR_MESSAGE);
}
} else {
LOGGER.info(rb.getString("loading.history.from.configuration"));
HISTORY.fromList(Utils.getConfigList("download.history"));
if (HISTORY.toList().isEmpty()) {
// Loaded from config, still no entries.
// Guess rip history based on rip folder
String[] dirs = Utils.getWorkingDirectory().list((dir, file) -> new File(dir.getAbsolutePath() + File.separator + file).isDirectory());
for (String dir : dirs) {
String url = RipUtils.urlFromDirectoryName(dir);
if (url != null) {
// We found one, add it to history
HistoryEntry entry = new HistoryEntry();
entry.url = url;
HISTORY.add(entry);
}
}
}
}
}
private void saveHistory() {
Path historyFile = Paths.get(Utils.getConfigDir() + File.separator + "history.json");
try {
if (!Files.exists(historyFile)) {
Files.createDirectories(historyFile.getParent());
Files.createFile(historyFile);
}
HISTORY.toFile(historyFile.toString());
Utils.setConfigList("download.history", Collections.emptyList());
} catch (IOException e) {
LOGGER.error("Failed to save history to file " + historyFile, e);
}
}
@SuppressWarnings("unchecked")
private void ripNextAlbum() {
isRipping = true;
// Save current state of queue to configuration.
Utils.setConfigList("queue", (Enumeration<Object>) queueListModel.elements());
if (queueListModel.isEmpty()) {
// End of queue
isRipping = false;
return;
}
String nextAlbum = (String) queueListModel.remove(0);
updateQueueLabel();
Thread t = ripAlbum(nextAlbum);
if (t == null) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
LOGGER.error(rb.getString("interrupted.while.waiting.to.rip.next.album"), ie);
}
ripNextAlbum();
} else {
t.start();
}
}
private Thread ripAlbum(String urlString) {
//shutdownCleanup();
if (!logPanel.isVisible()) {
optionLog.doClick();
}
urlString = urlString.trim();
if (urlString.toLowerCase().startsWith("gonewild:")) {
urlString = "http://gonewild.com/user/" + urlString.substring(urlString.indexOf(':') + 1);
}
if (!urlString.startsWith("http")) {
urlString = "http://" + urlString;
}
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
LOGGER.error("[!] Could not generate URL for '" + urlString + "'", e);
error("Given URL is not valid, expecting http://website.com/page/...");
return null;
}
stopButton.setEnabled(true);
statusProgress.setValue(100);
openButton.setVisible(false);
statusLabel.setVisible(true);
pack();
boolean failed = false;
try {
ripper = AbstractRipper.getRipper(url);
ripper.setup();
} catch (Exception e) {
failed = true;
LOGGER.error("Could not find ripper for URL " + url, e);
error(e.getMessage());
}
if (!failed) {
try {
mainFrame.setTitle("Ripping - RipMe v" + UpdateUtils.getThisJarVersion());
status("Starting rip...");
ripper.setObserver(this);
Thread t = new Thread(ripper);
if (configShowPopup.isSelected() &&
(!mainFrame.isVisible() || !mainFrame.isActive())) {
mainFrame.toFront();
mainFrame.setAlwaysOnTop(true);
trayIcon.displayMessage(mainFrame.getTitle(), "Started ripping " + ripper.getURL().toExternalForm(), MessageType.INFO);
mainFrame.setAlwaysOnTop(false);
}
return t;
} catch (Exception e) {
LOGGER.error("[!] Error while ripping: " + e.getMessage(), e);
error("Unable to rip this URL: " + e.getMessage());
}
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
pack();
return null;
}
private boolean canRip(String urlString) {
try {
String urlText = urlString.trim();
if (urlText.equals("")) {
return false;
}
if (!urlText.startsWith("http")) {
urlText = "http://" + urlText;
}
URL url = new URL(urlText);
// Ripper is needed here to throw.not throw an Exception
AbstractRipper ripper = AbstractRipper.getRipper(url);
return true;
} catch (Exception e) {
return false;
}
}
class RipButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String url = ripTextfield.getText();
if (!queueListModel.contains(url) && !url.equals("")) {
// Check if we're ripping a range of urls
if (url.contains("{")) {
// Make sure the user hasn't forgotten the closing }
if (url.contains("}")) {
String rangeToParse = url.substring(url.indexOf("{") + 1, url.indexOf("}"));
int rangeStart = Integer.parseInt(rangeToParse.split("-")[0]);
int rangeEnd = Integer.parseInt(rangeToParse.split("-")[1]);
for (int i = rangeStart; i < rangeEnd +1; i++) {
if (canRip(url.replaceAll("\\{\\S*\\}", Integer.toString(i)))) {
queueListModel.add(queueListModel.size(), url.replaceAll("\\{\\S*\\}", Integer.toString(i)));
ripTextfield.setText("");
} else {
LOGGER.error("Can't find ripper for " + url.replaceAll("\\{\\S*\\}", Integer.toString(i)));
}
}
}
} else {
queueListModel.add(queueListModel.size(), ripTextfield.getText());
ripTextfield.setText("");
}
} else {
if (!isRipping) {
ripNextAlbum();
}
}
}
}
private class StatusEvent implements Runnable {
private final AbstractRipper ripper;
private final RipStatusMessage msg;
StatusEvent(AbstractRipper ripper, RipStatusMessage msg) {
this.ripper = ripper;
this.msg = msg;
}
public void run() {
handleEvent(this);
}
}
private synchronized void handleEvent(StatusEvent evt) {
if (ripper.isStopped()) {
return;
}
RipStatusMessage msg = evt.msg;
int completedPercent = evt.ripper.getCompletionPercentage();
statusProgress.setValue(completedPercent);
statusProgress.setVisible(true);
status( evt.ripper.getStatusText() );
switch(msg.getStatus()) {
case LOADING_RESOURCE:
case DOWNLOAD_STARTED:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("Downloading " + msg.getObject(), Color.BLACK);
}
break;
case DOWNLOAD_COMPLETE:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("Downloaded " + msg.getObject(), Color.GREEN);
}
break;
case DOWNLOAD_COMPLETE_HISTORY:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("" + msg.getObject(), Color.GREEN);
}
break;
case DOWNLOAD_ERRORED:
if (LOGGER.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
break;
case DOWNLOAD_WARN:
if (LOGGER.isEnabledFor(Level.WARN)) {
appendLog((String) msg.getObject(), Color.ORANGE);
}
break;
case RIP_ERRORED:
if (LOGGER.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(false);
pack();
statusWithColor("Error: " + msg.getObject(), Color.RED);
break;
case RIP_COMPLETE:
RipStatusComplete rsc = (RipStatusComplete) msg.getObject();
String url = ripper.getURL().toExternalForm();
if (HISTORY.containsURL(url)) {
// TODO update "modifiedDate" of entry in HISTORY
HistoryEntry entry = HISTORY.getEntryByURL(url);
entry.count = rsc.count;
entry.modifiedDate = new Date();
} else {
HistoryEntry entry = new HistoryEntry();
entry.url = url;
entry.dir = rsc.getDir();
entry.count = rsc.count;
try {
entry.title = ripper.getAlbumTitle(ripper.getURL());
} catch (MalformedURLException e) { }
HISTORY.add(entry);
historyTableModel.fireTableDataChanged();
}
if (configPlaySound.isSelected()) {
Utils.playSound("camera.wav");
}
saveHistory();
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(true);
File f = rsc.dir;
String prettyFile = Utils.shortenPath(f);
openButton.setText("Open " + prettyFile);
mainFrame.setTitle("RipMe v" + UpdateUtils.getThisJarVersion());
try {
Image folderIcon = ImageIO.read(getClass().getClassLoader().getResource("folder.png"));
openButton.setIcon(new ImageIcon(folderIcon));
} catch (Exception e) { }
appendLog("Rip complete, saved to " + f.getAbsolutePath(), Color.GREEN);
openButton.setActionCommand(f.toString());
openButton.addActionListener(event -> {
try {
Desktop.getDesktop().open(new File(event.getActionCommand()));
} catch (Exception e) {
LOGGER.error(e);
}
});
pack();
ripNextAlbum();
break;
case COMPLETED_BYTES:
// Update completed bytes
break;
case TOTAL_BYTES:
// Update total bytes
break;
}
}
public void update(AbstractRipper ripper, RipStatusMessage message) {
StatusEvent event = new StatusEvent(ripper, message);
SwingUtilities.invokeLater(event);
}
public static void ripAlbumStatic(String url) {
ripTextfield.setText(url.trim());
ripButton.doClick();
}
public static void enableWindowPositioning() {
Utils.setConfigBoolean("window.position", true);
}
public static void disableWindowPositioning() {
Utils.setConfigBoolean("window.position", false);
}
private static boolean hasWindowPositionBug() {
String osName = System.getProperty("os.name");
// Java on Windows has a bug where if we try to manually set the position of the Window,
// javaw.exe will not close itself down when the application is closed.
// Therefore, even if isWindowPositioningEnabled, if we are on Windows, we ignore it.
return osName == null || osName.startsWith("Windows");
}
private static boolean isWindowPositioningEnabled() {
boolean isEnabled = Utils.getConfigBoolean("window.position", true);
return isEnabled && !hasWindowPositionBug();
}
private static void saveWindowPosition(Frame frame) {
if (!isWindowPositioningEnabled()) {
return;
}
Point point;
try {
point = frame.getLocationOnScreen();
} catch (Exception e) {
e.printStackTrace();
try {
point = frame.getLocation();
} catch (Exception e2) {
e2.printStackTrace();
return;
}
}
int x = (int)point.getX();
int y = (int)point.getY();
int w = frame.getWidth();
int h = frame.getHeight();
Utils.setConfigInteger("window.x", x);
Utils.setConfigInteger("window.y", y);
Utils.setConfigInteger("window.w", w);
Utils.setConfigInteger("window.h", h);
LOGGER.debug("Saved window position (x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ")");
}
private static void restoreWindowPosition(Frame frame) {
if (!isWindowPositioningEnabled()) {
mainFrame.setLocationRelativeTo(null); // default to middle of screen
return;
}
try {
int x = Utils.getConfigInteger("window.x", -1);
int y = Utils.getConfigInteger("window.y", -1);
int w = Utils.getConfigInteger("window.w", -1);
int h = Utils.getConfigInteger("window.h", -1);
if (x < 0 || y < 0 || w <= 0 || h <= 0) {
LOGGER.debug("UNUSUAL: One or more of: x, y, w, or h was still less than 0 after reading config");
mainFrame.setLocationRelativeTo(null); // default to middle of screen
return;
}
frame.setBounds(x, y, w, h);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package com.sdl.selenium.extjs6.grid;
import com.sdl.selenium.extjs6.form.ComboBox;
import com.sdl.selenium.extjs6.form.DateField;
import com.sdl.selenium.extjs6.form.TextArea;
import com.sdl.selenium.extjs6.form.TextField;
import com.sdl.selenium.utils.config.WebLocatorConfig;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.table.Table;
import com.sdl.selenium.web.utils.RetryUtils;
import com.sdl.selenium.web.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
@Slf4j
public class Grid extends Table implements Scrollable {
private String version;
public Grid() {
setClassName("Grid");
setBaseCls("x-grid");
setTag("*");
WebLocator header = new WebLocator().setClasses("x-title-text");
setTemplateTitle(header);
}
public Grid(WebLocator container) {
this();
setContainer(container);
}
/**
* <pre>{@code
* Grid grid = new Grid().setHeaders("Company", "Price", "Change");
* }</pre>
*
* @param headers grid's headers in any order
* @param <T> element which extended the Grid
* @return this Grid
*/
public <T extends Table> T setHeaders(final String... headers) {
return setHeaders(false, headers);
}
/**
* <pre>{@code
* Grid grid = new Grid().setHeaders(true, "Company", "Price", "Change");
* }</pre>
*
* @param strictPosition true if grid's headers is order
* @param headers grid's headers in order, if grid has no header put empty string
* @param <T> element which extended the Table
* @return this Grid
*/
public <T extends Table> T setHeaders(boolean strictPosition, final String... headers) {
List<WebLocator> list = new ArrayList<>();
for (int i = 0; i < headers.length; i++) {
WebLocator headerEL = new WebLocator(this).setClasses("x-column-header").
setText(headers[i], SearchType.DEEP_CHILD_NODE_OR_SELF, SearchType.EQUALS);
if (strictPosition) {
headerEL.setTag("*[" + (i + 1) + "]");
}
list.add(headerEL);
}
setChildNodes(list.toArray(new WebLocator[0]));
return (T) this;
}
@Override
public Row getRow(int rowIndex) {
return new Row(this, rowIndex).setInfoMessage("-Row");
}
public Group getGroup(String groupName) {
return new Group(this, groupName).setInfoMessage("-Group");
}
public Group getGroup(int rowIndex) {
return new Group(this, rowIndex).setInfoMessage("-Group");
}
@Override
public Row getRow(String searchElement) {
return new Row(this, searchElement, SearchType.EQUALS).setInfoMessage("-Row");
}
@Override
public Row getRow(String searchElement, SearchType... searchTypes) {
return new Row(this, searchElement, searchTypes).setInfoMessage("-Row");
}
public Row getRow(Cell... byCells) {
return new Row(this, byCells).setInfoMessage("-Row");
}
public Row getRow(int indexRow, Cell... byCells) {
return new Row(this, indexRow, byCells).setInfoMessage("-Row");
}
@Override
public Cell getCell(int rowIndex, int columnIndex) {
Row row = getRow(rowIndex);
return new Cell(row, columnIndex).setInfoMessage("cell - Table");
}
@Override
public Cell getCell(String searchElement, SearchType... searchTypes) {
Row row = new Row(this);
return new Cell(row).setText(searchElement, searchTypes);
}
public Cell getCell(int rowIndex, int columnIndex, String text) {
Row row = getRow(rowIndex);
return new Cell(row, columnIndex, text, SearchType.EQUALS);
}
public Cell getCell(String searchElement, String columnText, SearchType... searchTypes) {
Row row = getRow(searchElement, SearchType.CONTAINS);
return new Cell(row).setText(columnText, searchTypes);
}
@Override
public Cell getCell(String searchElement, int columnIndex, SearchType... searchTypes) {
return new Cell(new Row(this, searchElement, searchTypes), columnIndex);
}
public Cell getCell(int columnIndex, Cell... byCells) {
return new Cell(getRow(byCells), columnIndex);
}
public Cell getCell(int columnIndex, String text, Cell... byCells) {
return new Cell(getRow(byCells), columnIndex, text, SearchType.EQUALS);
}
protected String getVersion() {
return version == null ? WebLocatorConfig.getExtJsVersion() : version;
}
public <T extends Grid> T setVersion(String version) {
this.version = version;
return (T) this;
}
public boolean waitToActivate(int seconds) {
String info = toString();
int count = 0;
boolean hasMask;
while ((hasMask = hasMask()) && (count < seconds)) {
count++;
log.info("waitToActivate:" + (seconds - count) + " seconds; " + info);
Utils.sleep(900);
}
return !hasMask;
}
private boolean hasMask() {
WebLocator mask = new WebLocator(this).setClasses("x-mask").setElPathSuffix("style", "not(contains(@style, 'display: none'))").setAttribute("aria-hidden", "false").setInfoMessage("Mask");
return mask.waitToRender(500L, false);
}
@Override
public boolean waitToPopulate(int seconds) {
Row row = getRow(1).setVisibility(true).setRoot("//..//").setInfoMessage("first Row");
WebLocator body = new WebLocator(this).setClasses("x-grid-header-ct"); // TODO see if must add for all rows
row.setContainer(body);
return row.waitToRender(seconds * 1000L);
}
public List<String> getHeaders() {
WebLocator header = new WebLocator(this).setClasses("x-grid-header-ct");
String headerText = RetryUtils.retrySafe(4, header::getText);
return new ArrayList<>(Arrays.asList(headerText.trim().split("\n")));
}
private List<List<String>> getLists(int rows, boolean rowExpand, List<Integer> columnsList) {
Row rowsEl = new Row(this);
int size = rowsEl.size();
List<List<String>> listOfList = new ArrayList<>();
boolean canRead = true;
String id = "";
int timeout = 0;
do {
for (int i = 1; i <= rows; ++i) {
if (canRead) {
List<String> list = new ArrayList<>();
for (int j : columnsList) {
Row row = new Row(this).setTag("tr").setResultIdx(i);
if (rowExpand) {
row.setExcludeClasses("x-grid-rowbody-tr");
}
Cell cell = new Cell(row, j);
String text = cell.getText(true).trim();
list.add(text);
}
listOfList.add(list);
} else {
if (size == i + 1) {
break;
}
Row row = new Row(this, i);
String currentId = row.getAttributeId();
if (!"".equals(id) && id.equals(currentId)) {
canRead = true;
}
}
}
if (isScrollBottom()) {
break;
}
Row row = new Row(this, size);
id = row.getAttributeId();
scrollPageDownInTree();
canRead = false;
timeout++;
} while (timeout < 30);
return listOfList;
}
@Override
public List<List<String>> getCellsText(int... excludedColumns) {
return getCellsText(false, false, excludedColumns);
}
public List<List<String>> getCellsText(boolean rowExpand, int... excludedColumns) {
return getCellsText(false, rowExpand, excludedColumns);
}
public List<List<String>> getCellsText(boolean parallel, boolean rowExpand, int... excludedColumns) {
Row rowsEl = new Row(this).setTag("tr");
Row rowEl = new Row(this, 1);
if (rowExpand) {
rowsEl.setExcludeClasses("x-grid-rowbody-tr");
rowEl = new Row(this).setTag("tr").setExcludeClasses("x-grid-rowbody-tr").setResultIdx(1);
}
Cell columnsEl = new Cell(rowEl);
int rows = rowsEl.size();
int columns = columnsEl.size();
final List<Integer> columnsList = getColumns(columns, excludedColumns);
if (rows <= 0) {
return null;
} else {
return parallel ? getListsParallel(rows, rowExpand, columnsList) : getLists(rows, rowExpand, columnsList);
}
}
private List<List<String>> getListsParallel(int rows, boolean rowExpand, List<Integer> columnsList) {
List<List<String>> listOfList = new ArrayList<>();
boolean canRead = true;
String id = "";
int timeout = 0;
ExecutorService executorService = Executors.newFixedThreadPool(10);
do {
List<Future<List<String>>> futures = new ArrayList<>();
for (int i = 1; i <= rows; ++i) {
if (canRead) {
final int fi = i;
futures.add(executorService.submit(() -> {
List<String> list = new ArrayList<>();
for (int j : columnsList) {
Grid parent = (Grid) clone();
Row row = new Row(parent).setTag("tr").setResultIdx(fi);
if (rowExpand) {
row.setExcludeClasses("x-grid-rowbody-tr");
}
Cell cell = new Cell(row.clone(), j);
String text = "";
try {
text = cell.getText(true).trim();
} catch (NullPointerException e) {
Utils.sleep(1);
}
list.add(text);
}
return list;
}));
} else {
Row row = new Row(this, i);
String currentId = row.getAttributeId();
if (!"".equals(id) && id.equals(currentId)) {
canRead = true;
}
}
}
for (Future<List<String>> future : futures) {
try {
listOfList.add(future.get());
} catch (InterruptedException | ExecutionException e) {
log.debug("{}", e);
}
}
if (isScrollBottom()) {
break;
}
Row row = new Row(this, rows);
id = row.getAttributeId();
scrollPageDownInTree();
canRead = false;
timeout++;
} while (timeout < 30);
executorService.shutdown();
return listOfList;
}
private String getTextNode(Cell cell) {
String text = cell.getText(true).trim();
// WebLocator childs = new WebLocator(cell).setClasses("user-avatar");
// if (childs.waitToRender(150L, false)) {
// List<WebElement> children = childs.findElements();
// for (WebElement child : children) {
// text = text.replaceFirst(child.getText(), "").trim();
return text;
}
public List<List<String>> getCellsText(String group, int... excludedColumns) {
Group groupEl = getGroup(group);
groupEl.expand();
List<Row> groupElRows = groupEl.getRows();
Cell columnsEl = new Cell(groupElRows.get(1));
int rows = groupElRows.size();
int columns = columnsEl.size();
List<Integer> columnsList = getColumns(columns, excludedColumns);
if (rows <= 0) {
return null;
} else {
List<List<String>> listOfList = new ArrayList<>();
boolean canRead = true;
String id = "";
int timeout = 0;
do {
for (int i = 0; i < rows; ++i) {
if (canRead) {
List<String> list = new ArrayList<>();
for (int j : columnsList) {
String text = getTextNode(groupElRows.get(i).getCell(j));
list.add(text);
}
listOfList.add(list);
} else {
String currentId = new Row(this, i + 1).getAttributeId();
if (!"".equals(id) && id.equals(currentId)) {
canRead = true;
}
}
}
if (isScrollBottom() || listOfList.size() >= rows) {
break;
}
id = new Row(this, rows).getAttributeId();
scrollPageDownInTree();
canRead = false;
timeout++;
} while (listOfList.size() < rows && timeout < 30);
return listOfList;
}
}
public <V> List<V> getCellsText(Class<V> type, int... excludedColumns) {
Class<?> newclazz = null;
int s = 0;
Class[] parameterTypes = null;
try {
newclazz = Class.forName(type.getTypeName());
s = newclazz.getDeclaredFields().length;
Constructor[] constructors = newclazz.getConstructors();
for (Constructor c : constructors) {
if (s == c.getParameterCount()) {
parameterTypes = c.getParameterTypes();
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Class<?> finalNewclazz = newclazz;
int finalS = s;
Class[] finalParameterTypes = parameterTypes;
return getCellsText(excludedColumns).stream().map(t -> {
List<Object> arr = new ArrayList<>();
try {
for (int i = 0; i < finalS; i++) {
arr.add(t.get(i));
}
Constructor<V> constructor = (Constructor<V>) finalNewclazz.getConstructor(finalParameterTypes);
return constructor.newInstance(arr.toArray(new Object[0]));
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
}
@Override
public int getCount() {
if (ready(true)) {
return new Row(this).size();
} else {
return -1;
}
}
public List<String> getGroupsName() {
Group group = new Group(this);
int size = group.size();
List<String> list = new ArrayList<>();
for (int i = 1; i <= size; i++) {
group.setResultIdx(i);
list.add(group.getNameGroup());
}
return list;
}
public String getNextGroupName(String groupName) {
Group group = new Group(this);
int size = group.size();
for (int i = 1; i < size; i++) {
group.setResultIdx(i);
String g = group.getNameGroup().toLowerCase();
if (g.contains(groupName.toLowerCase())) {
group.setResultIdx(i + 1);
return group.getNameGroup();
}
}
return null;
}
public void selectAll() {
WebLocator checkBox = new WebLocator(this).setBaseCls("x-column-header-checkbox");
checkBox.click();
}
public <T extends TextField> T getEditor() {
TextField editor;
WebLocator container = new WebLocator("x-editor", this);
WebLocator editableEl1 = new WebLocator(container).setTag("input");
String type = editableEl1.getAttribute("data-componentid");
log.debug("active editor type: {}", type);
if (type.contains("combo")) {
editor = new ComboBox();
} else if (type.contains("textarea")) {
editor = new TextArea();
} else if (type.contains("datefield")) {
editor = new DateField();
} else {
editor = new TextField();
}
editor.setContainer(this).setClasses("x-form-focus").setRenderMillis(1000).setInfoMessage("active editor");
return (T) editor;
}
} |
package com.sodash.jlinkedin;
import java.lang.reflect.Constructor;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import winterwell.json.JSONArray;
import winterwell.json.JSONObject;
import winterwell.utils.TodoException;
import winterwell.utils.Utils;
import winterwell.utils.containers.ArrayMap;
import winterwell.utils.time.Time;
import com.sodash.jlinkedin.fields.CompanyField;
import com.sodash.jlinkedin.fields.GroupMembershipField;
import com.sodash.jlinkedin.fields.NetworkUpdateType;
import com.sodash.jlinkedin.fields.PostField;
import com.sodash.jlinkedin.fields.PostSortOrder;
import com.sodash.jlinkedin.fields.UpdateType;
import com.sodash.jlinkedin.model.LIComment;
import com.sodash.jlinkedin.model.LICompany;
import com.sodash.jlinkedin.model.LIEvent;
import com.sodash.jlinkedin.model.LIGroup;
import com.sodash.jlinkedin.model.LIGroupMembership;
import com.sodash.jlinkedin.model.LIJobPosting;
import com.sodash.jlinkedin.model.LIModelBase;
import com.sodash.jlinkedin.model.LIPostBase;
import com.sodash.jlinkedin.model.LIUpdate;
import com.sodash.jlinkedin.model.ListResults;
public class JLinkedInGet extends JLinkedInAPIFacet<JLinkedInGet> {
// private Time since;
// private Time until;
private int start;
private int count;
@Override
protected Map addStdParams(Map vars) {
Map map = super.addStdParams(vars);
// if (since!=null) vars.put();
// if (until!=null) vars.put();
if (start!=0) vars.put("start", start);
if (count!=0) vars.put("count", count);
return map;
}
public JLinkedInGet(JLinkedIn jLinkedIn) {
this.jli = jLinkedIn;
}
public boolean getSharingEnabled(String companyId) {
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/is-company-share-enabled";
String json = getPage(jsonUrl, new ArrayMap());
return "true".equalsIgnoreCase(json);
}
public boolean getCanAdminCompany(String companyId) {
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/relation-to-viewer/is-company-share-enabled";
String json = getPage(jsonUrl, new ArrayMap());
return "true".equalsIgnoreCase(json);
}
public List<LICompany> getUserCompanies() {
String json = getPage("https://api.linkedin.com/v1/companies", new ArrayMap("is-company-admin", true));
ListResults<LICompany> list = toResults(json, LICompany.class);
return list;
}
public LICompany getCompanyById(String companyId) {
String jsonUrl = "https://api.linkedin.com/v1/companies/" + companyId + ":(id,name,logo-url,square-logo-url,locations,num-followers)";
String json = getPage(jsonUrl, new ArrayMap());
return new LICompany(new JSONObject(json));
}
/**
*
* @param companyId
* @param eventType Can be null
* @return
*/
public ListResults<LIPostBase> getCompanyUpdates(String companyId, UpdateType eventType) {
assert companyId!=null;
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/updates";
Map params = new ArrayMap();
if(eventType != null) {
params.put("event-type", eventType);
}
String json = getPage(jsonUrl, params);
return toResults(json);
}
public LIUpdate getCompanyUpdate(String companyId, String updateKey) {
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/updates/key="+updateKey;
String json = getPage(jsonUrl, new ArrayMap());
return new LIUpdate(new JSONObject(json));
}
public ListResults<LIComment> getCompanyUpdateComments(String companyId, String updateKey) {
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/updates/key="+updateKey+"/update-comments";
String json = getPage(jsonUrl, new ArrayMap());
assert json != null : jsonUrl;
return toResults(json, LIComment.class);
}
public ListResults<LIEvent> getCompanyUpdateLikes(String companyId, String updateKey) {
String jsonUrl = "https://api.linkedin.com/v1/companies/"+companyId+"/updates/key="+updateKey+"/likes";
String json = getPage(jsonUrl, new ArrayMap());
return toResults(json, LIEvent.class);
}
public LIGroup getGroupById(String gid) {
String html = getPage("https:
return new LIGroup(gid, html);
}
public static <LI extends LIModelBase> ListResults<LI> toResults(String json, Class<LI> class1) {
assert json != null;
if (json==null || "null".equals(json)) {
return new ListResults();
}
return toResults(new JSONObject(json), class1);
}
public static <LI extends LIModelBase> ListResults<LI> toResults(JSONObject jobj, Class<LI> class1) {
try {
int total = jobj.optInt("_total");
JSONArray vs = jobj.optJSONArray("values");
if (vs==null) {
assert total==0;
return new ListResults();
}
ListResults list = new ListResults();
list.setTotal(total);
Constructor<LI> cons = class1.getConstructor(JSONObject.class);
for(JSONObject v : vs) {
LI obj = cons.newInstance(v);
list.add(obj);
}
return list;
} catch(Exception ex) {
throw Utils.runtime(ex);
}
}
/**
* Turns a string-form JSON list, known to be a mix of status-updates and job-postings, into a list of LIUpdates and LIJobPostings.
* @param json
* @return
*/
public static ListResults<LIPostBase> toResults(String json) {
assert json != null;
if (json==null || "null".equals(json)) {
return new ListResults();
}
return toResultsAuto(new JSONObject(json));
}
/**
* Turns a JSON list, known to be a mix of status-updates and job-postings, into a list of LIUpdates and LIJobPostings.
* @param json
* @return
*/
public static ListResults<LIPostBase> toResultsAuto(JSONObject jobj) {
try {
int total = jobj.optInt("_total");
JSONArray vs = jobj.optJSONArray("values");
if (vs == null) {
assert total == 0;
return new ListResults<LIPostBase>();
}
ListResults<LIPostBase> list = new ListResults<LIPostBase>();
list.setTotal(total);
Constructor<LIUpdate> updateCons = LIUpdate.class.getConstructor(JSONObject.class);
Constructor<LIJobPosting> jobCons = LIJobPosting.class.getConstructor(JSONObject.class);
for(JSONObject v : vs) {
JSONObject content = v.optJSONObject("updateContent");
if (content == null) continue;
if (content.has("companyStatusUpdate")) list.add(updateCons.newInstance(v));
else if (content.has("companyJobUpdate")) list.add(jobCons.newInstance(v));
}
return list;
} catch(Exception ex) {
throw Utils.runtime(ex);
}
}
public ListResults<LIComment> getPostComments(String id) {
throw new TodoException();
}
public List<LIPostBase> getPostsByGroup(String groupId, PostSortOrder recency, String type) {
throw new TodoException();
}
public List<LIGroupMembership> getGroupMemberships(String dewart)
{
throw new TodoException();
}
public List getUserUpdates(Set<NetworkUpdateType> ut) {
throw new TodoException();
}
public List getUserUpdates(String id, Set<NetworkUpdateType> ut) {
throw new TodoException();
}
/**
* @deprecated I don't think LinkedIn support this anymore :(
* @param since
* @return
*/
public JLinkedInGet setSince(Time since) {
// this.since = since;
return this;
}
/**
* @deprecated I don't think LinkedIn support this anymore :(
* @param until
* @return
*/
public JLinkedInGet setUntil(Time until) {
// this.until = until;
return this;
}
public LICompany getCompanyByUniversalName(String co) {
throw new TodoException();
}
/**
*
* @param start Usually 0 (unless you want the 2nd page of results)
* @return
*/
public JLinkedInGet setResultRange(int start, int count) {
this.start = start;
this.count = count;
return this;
}
public ListResults<LIComment> getNetworkUpdateComments(
String networkUpdateKey) {
throw new TodoException(networkUpdateKey);
}
} |
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.io;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ReflectPermission;
import java.util.Date;
import java.util.Map;
import com.google.common.collect.Maps;
import static com.threerings.NaryaLog.log;
/**
* Used to read and write a single field of a {@link Streamable} instance.
*/
public abstract class FieldMarshaller
{
public FieldMarshaller ()
{
this(null);
}
public FieldMarshaller (String type)
{
_type = type;
}
/**
* Reads the contents of the supplied field from the supplied stream and sets it in the
* supplied object.
*/
public abstract void readField (Field field, Object target, ObjectInputStream in)
throws Exception;
/**
* Writes the contents of the supplied field in the supplied object to the supplied stream.
*/
public abstract void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception;
@Override
public String toString ()
{
if (_type != null) {
return "FieldMarshaller " + _type;
}
return super.toString();
}
protected final String _type;
/**
* Returns a field marshaller appropriate for the supplied field or null if no marshaller
* exists for the type contained by the field in question.
*/
public static FieldMarshaller getFieldMarshaller (Field field)
{
if (_marshallers == null) {
createMarshallers();
}
// if necessary (we're running in a sandbox), look for custom field accessors
if (useFieldAccessors()) {
Method reader = null, writer = null;
try {
reader = field.getDeclaringClass().getMethod(
getReaderMethodName(field.getName()), READER_ARGS);
} catch (NoSuchMethodException nsme) {
// no problem
}
try {
writer = field.getDeclaringClass().getMethod(
getWriterMethodName(field.getName()), WRITER_ARGS);
} catch (NoSuchMethodException nsme) {
// no problem
}
if (reader != null && writer != null) {
return new MethodFieldMarshaller(reader, writer);
}
if ((reader == null && writer != null) || (writer == null && reader != null)) {
log.warning("Class contains one but not both custom field reader and writer",
"class", field.getDeclaringClass().getName(), "field", field.getName(),
"reader", reader, "writer", writer);
// fall through to using reflection on the fields...
}
}
Class<?> ftype = field.getType();
// use the intern marshaller for pooled strings
if (ftype == String.class && field.isAnnotationPresent(Intern.class)) {
return _internMarshaller;
}
// if we have an exact match, use that
FieldMarshaller fm = _marshallers.get(ftype);
if (fm == null) {
Class<?> collClass = Streamer.getCollectionClass(ftype);
if (collClass != null && !collClass.equals(ftype)) {
log.warning("Specific field types are discouraged " +
"for Iterables/Collections and Maps. The implementation type may not be " +
"recreated on the other side.",
"class", field.getDeclaringClass(), "field", field.getName(),
"type", ftype, "shouldBe", collClass);
fm = _marshallers.get(collClass);
}
// otherwise if the class is a pure interface or streamable,
// use the streamable marshaller
if (fm == null && (ftype.isInterface() || Streamer.isStreamable(ftype))) {
fm = _marshallers.get(Streamable.class);
}
}
return fm;
}
/**
* Returns the name of the custom reader method which will be used if it exists to stream a
* field with the supplied name.
*/
public static final String getReaderMethodName (String field)
{
return "readField_" + field;
}
/**
* Returns the name of the custom writer method which will be used if it exists to stream a
* field with the supplied name.
*/
public static final String getWriterMethodName (String field)
{
return "writeField_" + field;
}
/**
* Returns true if we should use the generated field marshaller methods that allow us to work
* around our inability to read and write protected and private fields of a {@link Streamable}.
*/
protected static boolean useFieldAccessors ()
{
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new ReflectPermission("suppressAccessChecks"));
}
return false;
} catch (SecurityException se) {
return true;
}
}
/**
* Used to marshall and unmarshall classes for which we have a basic {@link Streamer}.
*/
protected static class StreamerMarshaller extends FieldMarshaller
{
public StreamerMarshaller (Streamer streamer)
{
_streamer = streamer;
}
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception
{
if (in.readBoolean()) {
Object value = _streamer.createObject(in);
_streamer.readObject(value, in, true);
field.set(target, value);
} else {
field.set(target, null);
}
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception
{
Object value = field.get(source);
if (value == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
_streamer.writeObject(value, out, true);
}
}
@Override
public String toString ()
{
return "StreamerMarshaller:" + _streamer.toString();
}
/** The streamer we use to read and write our field. */
protected Streamer _streamer;
}
/**
* Uses custom accessor methods to read and write a field.
*/
protected static class MethodFieldMarshaller extends FieldMarshaller
{
public MethodFieldMarshaller (Method reader, Method writer)
{
_reader = reader;
_writer = writer;
}
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception
{
_reader.invoke(target, in);
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception
{
_writer.invoke(source, out);
}
protected Method _reader, _writer;
}
/**
* Creates instances of all known field marshaller types and populates the {@link
* #_marshallers} table with them. This is called the first time a marshaller is requested.
*/
protected static void createMarshallers ()
{
// create our table
_marshallers = Maps.newHashMap();
// create a generic marshaller for streamable instances
FieldMarshaller gmarsh = new FieldMarshaller("Generic") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, in.readObject());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeObject(field.get(source));
}
};
_marshallers.put(Streamable.class, gmarsh);
// use the same generic marshaller for fields declared as Object with the expectation that
// they will contain only primitive types or Streamables; the runtime will fail
// informatively if we attempt to store non-Streamable objects in that field
_marshallers.put(Object.class, gmarsh);
// create marshallers for the primitive types
_marshallers.put(Boolean.TYPE, new FieldMarshaller("boolean") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setBoolean(target, in.readBoolean());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeBoolean(field.getBoolean(source));
}
});
_marshallers.put(Byte.TYPE, new FieldMarshaller("byte") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setByte(target, in.readByte());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeByte(field.getByte(source));
}
});
_marshallers.put(Character.TYPE, new FieldMarshaller("char") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setChar(target, in.readChar());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeChar(field.getChar(source));
}
});
_marshallers.put(Short.TYPE, new FieldMarshaller("short") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setShort(target, in.readShort());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeShort(field.getShort(source));
}
});
_marshallers.put(Integer.TYPE, new FieldMarshaller("int") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setInt(target, in.readInt());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeInt(field.getInt(source));
}
});
_marshallers.put(Long.TYPE, new FieldMarshaller("long") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setLong(target, in.readLong());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeLong(field.getLong(source));
}
});
_marshallers.put(Float.TYPE, new FieldMarshaller("float") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setFloat(target, in.readFloat());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeFloat(field.getFloat(source));
}
});
_marshallers.put(Double.TYPE, new FieldMarshaller("double") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setDouble(target, in.readDouble());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeDouble(field.getDouble(source));
}
});
_marshallers.put(Date.class, new FieldMarshaller("Date") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, new Date(in.readLong()));
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeLong(((Date)field.get(source)).getTime());
}
});
// create field marshallers for all of the basic types
for (Map.Entry<Class<?>,Streamer> entry : BasicStreamers.BSTREAMERS.entrySet()) {
_marshallers.put(entry.getKey(), new StreamerMarshaller(entry.getValue()));
}
// create the field marshaller for pooled strings
_internMarshaller = new FieldMarshaller("intern") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, in.readIntern());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeIntern((String)field.get(source));
}
};
}
/** Contains a mapping from field type to field marshaller instance for that type. */
protected static Map<Class<?>, FieldMarshaller> _marshallers;
/** The field marshaller for pooled strings. */
protected static FieldMarshaller _internMarshaller;
/** Defines the signature to a custom field reader method. */
protected static final Class<?>[] READER_ARGS = { ObjectInputStream.class };
/** Defines the signature to a custom field writer method. */
protected static final Class<?>[] WRITER_ARGS = { ObjectOutputStream.class };
} |
package com.westudio.java.etcd;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import org.apache.http.*;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.FutureRequestExecutionService;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.HttpRequestFutureTask;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EtcdClient {
private static final CloseableHttpClient httpClient = buildClient();
private static final Gson gson = new GsonBuilder().create();
private static final String URI_PREFIX = "v2/keys";
private static final String DEFAULT_CHARSET = "UTF-8";
private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
private final URI baseURI;
// Future executor service
private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
private static final FutureRequestExecutionService futureExecutorService = new FutureRequestExecutionService(
httpClient, executorService);
private static CloseableHttpClient buildClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
.setSocketTimeout(DEFAULT_CONNECT_TIMEOUT)
.build();
CloseableHttpClient httpClient;
httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setRedirectStrategy(new RedirectHandler())
.setServiceUnavailableRetryStrategy(new RetryHandler())
.build();
return httpClient;
}
public EtcdClient(URI uri) {
String url = uri.toString();
if (!url.endsWith("/")) {
url += "/";
uri = URI.create(url);
}
this.baseURI = uri;
}
/**
* Get the value of the key
* @param key the key
* @return the corresponding response
*/
public EtcdResponse get(String key) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, null);
HttpGet httpGet;
httpGet = new HttpGet(uri);
return execute(httpGet);
}
/**
* Changing the value of a key without ttl
* @param key the key
* @param value the value
* @return response maybe a simple key node or a directory node
*/
public EtcdResponse set(String key, String value) throws EtcdClientException {
return set(key, value, null);
}
/**
* Changing the value of a key with ttl setting
* @param key the key
* @param value the value
* @param ttl the time-to-leave
* @return response maybe a simple key node or a directory node
*/
public EtcdResponse set(String key, String value, Integer ttl) throws EtcdClientException {
List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
data.add(new BasicNameValuePair("value", value));
if (ttl != null) {
data.add(new BasicNameValuePair("ttl", String.valueOf(ttl)));
}
return put(key, data, null);
}
/**
* Deleting a key
* @param key the key
* @return response
*/
public EtcdResponse delete(String key) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, null);
HttpDelete httpDelete = new HttpDelete(uri);
return execute(httpDelete);
}
/**
* Create a directory explicitly and you can't set the value
* @param key the key
* @param ttl the ttl setting
* @param prevExist exist before
* @return response
* @throws EtcdClientException
*/
public EtcdResponse createDir(String key, Integer ttl, Boolean prevExist) throws EtcdClientException {
List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
data.add(new BasicNameValuePair("dir", String.valueOf(true)));
if (ttl != null) {
data.add(new BasicNameValuePair("ttl", String.valueOf(ttl)));
}
if (prevExist != null) {
data.add(new BasicNameValuePair("prevExist", String.valueOf(prevExist)));
}
return put(key, data, null);
}
/**
* Listing a directory
* @param key the key
* @param recursive listing directory recursive or not
* @return response
* @throws EtcdClientException
*/
public List<EtcdNode> listDir(String key, Boolean recursive) throws EtcdClientException {
Map<String, String> params = new HashMap<String, String>();
params.put("recursive", String.valueOf(recursive));
URI uri = buildUriWithKeyAndParams(key, params);
HttpGet httpGet = new HttpGet(uri);
EtcdResponse response = execute(httpGet);
if (response == null || response.node == null) {
return null;
}
return response.node.nodes;
}
/**
* Deleting a directory
* @param key the key
* @param recursive set recursive {@code true} if the directory holds keys
* @return response
*/
public EtcdResponse deleteDir(String key, Boolean recursive) throws EtcdClientException {
Map<String, String> params = new HashMap<String, String>();
if (recursive) {
params.put("recursive", String.valueOf(true));
} else {
params.put("dir", String.valueOf(true));
}
URI uri = buildUriWithKeyAndParams(key, params);
HttpDelete httpDelete = new HttpDelete(uri);
return execute(httpDelete);
}
/**
* Getting etcd version
* @return the version
* @throws IOException
*/
public String getVersion() throws IOException {
URI uri = baseURI.resolve("version");
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new EtcdClientException("Error while geting version", httpResponse.getStatusLine().getStatusCode());
} else {
return EntityUtils.toString(httpResponse.getEntity(), DEFAULT_CHARSET);
}
} catch (IOException e) {
throw new EtcdClientException("Error while getting version", e);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
}
/**
* List children under a key
* @param key the key
* @return response
* @throws EtcdClientException
*/
public EtcdResponse listChildren(String key) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key + "/", null);
HttpGet httpGet = new HttpGet(uri);
return execute(httpGet);
}
/**
* Atomic compare and swap
* @param key the key
* @param value the new value
* @param params comparable conditions
* @return response
* @throws EtcdClientException
*/
public EtcdResponse cas(String key, String value, Map<String, String> params) throws EtcdClientException {
List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
data.add(new BasicNameValuePair("value", value));
return put(key, data, params);
}
/**
* Atomic compare and delete
* @param key the key
* @param params comparable conditions
* @return response
* @throws EtcdClientException
*/
public EtcdResponse cad(String key, Map<String, String> params) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, params);
HttpDelete delete = new HttpDelete(uri);
return execute(delete);
}
/**
* Atomically create in-order keys
* @param key the key for the container directory
* @param value the value
* @return response
* @throws EtcdClientException
*/
public EtcdResponse inOrderKeys(String key, String value) throws EtcdClientException {
List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
data.add(new BasicNameValuePair("value", value));
return post(key, data, null);
}
/**
* Enumerate the in-order keys as a sorted list
* @param key the directory key
* @return a sorted list of in-order keys
* @throws EtcdClientException
*/
public List<EtcdNode> listInOrderKeys(String key) throws EtcdClientException {
Map<String, String> params = new HashMap<String, String>();
params.put("recursive", String.valueOf(true));
params.put("sorted", String.valueOf(true));
URI uri = buildUriWithKeyAndParams(key, params);
HttpGet httpGet = new HttpGet(uri);
EtcdResponse response = execute(httpGet);
if (response == null || response.node == null) {
return null;
}
return response.node.nodes;
}
/**
* Watch for a change on a key
* @param key the key
* @return a future task
*/
public HttpRequestFutureTask<EtcdResponse> watch(String key) {
Map<String, String> params = new HashMap<String, String>();
params.put("wait", String.valueOf(true));
URI uri = buildUriWithKeyAndParams(key, params);
HttpGet httpGet = new HttpGet(uri);
return futureExecutorService.execute(httpGet, HttpClientContext.create(), new JsonResponseHandler());
}
/**
* General put method
* @param key the key
* @param data put data
* @param params url params
* @return response
* @throws EtcdClientException
*/
private EtcdResponse put(String key, List<BasicNameValuePair> data, Map<String, String> params) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, params);
HttpPut httpPut = new HttpPut(uri);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data, Charset.forName(DEFAULT_CHARSET));
httpPut.setEntity(formEntity);
return execute(httpPut);
}
/**
* General post method
* @param key the key
* @param data post data
* @param params url params
* @return response
* @throws EtcdClientException
*/
private EtcdResponse post(String key, List<BasicNameValuePair> data, Map<String, String> params) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, params);
HttpPost httpPost = new HttpPost(uri);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data, Charset.forName(DEFAULT_CHARSET));
httpPost.setEntity(formEntity);
return execute(httpPost);
}
/**
* Execute the specific HttpUriRequest
* @param request request instance
* @return EtcdResponse
* @throws EtcdClientException
*/
private EtcdResponse execute(HttpUriRequest request) throws EtcdClientException {
try {
return httpClient.execute(request, new JsonResponseHandler());
} catch (IOException e) {
throw unwrap(e);
}
}
/**
* Generate URI with key and params
* @param key key of etcd
* @param params the query params
* @return A valid URI instance
*/
private URI buildUriWithKeyAndParams(String key, Map<String, String> params) {
StringBuilder sb = new StringBuilder();
sb.append(URI_PREFIX);
if (key.startsWith("/")) {
key = key.substring(1);
}
for (String token : key.split("/")) {
sb.append("/").append(urlEscape(token));
}
if (params != null) {
sb.append("?");
for (String str : params.keySet()) {
sb.append(urlEscape(str)).append("=").append(urlEscape(params.get(str)));
sb.append("&");
}
}
String url = sb.toString();
if (url.endsWith("&")) {
url = url.substring(0, url.length() - 1);
}
return baseURI.resolve(url);
}
private String urlEscape(String url) {
try {
return URLEncoder.encode(url, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException();
}
}
public static String format(Object obj) {
try {
return gson.toJson(obj);
} catch (Exception e) {
return "Error formatting response" + e.getMessage();
}
}
private EtcdClientException unwrap(IOException e) {
if (e instanceof EtcdClientException) {
return (EtcdClientException) e;
} else {
Throwable t = e.getCause();
if (t instanceof EtcdClientException) {
return (EtcdClientException) t;
} else {
return new EtcdClientException("Error execute request", e);
}
}
}
private static EtcdResponse parseResponse(String json) throws EtcdClientException {
EtcdResponse response;
try {
response = gson.fromJson(json, EtcdResponse.class);
// Throw exception when the response has error
if (response.isError()) {
throw new EtcdClientException("Error response", response);
}
} catch (JsonParseException e) {
throw new EtcdClientException("Error parsing response", e);
}
return response;
}
static class RedirectHandler implements RedirectStrategy {
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
int statusCode = httpResponse.getStatusLine().getStatusCode();
return (statusCode >= 300 && statusCode < 400);
}
@Override
public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
String redirectUrl = httpResponse.getFirstHeader("location").getValue();
HttpRequestWrapper requestWrapper = (HttpRequestWrapper) httpRequest;
HttpUriRequest uriRequest;
HttpRequest origin = requestWrapper.getOriginal();
if (origin instanceof HttpPut) {
uriRequest = new HttpPut(redirectUrl);
((HttpPut) uriRequest).setEntity(((HttpPut) origin).getEntity());
} else if (origin instanceof HttpPost) {
uriRequest = new HttpPost(redirectUrl);
((HttpPost) uriRequest).setEntity(((HttpPost) origin).getEntity());
} else if (origin instanceof HttpDelete) {
uriRequest = new HttpDelete(redirectUrl);
} else {
uriRequest = new HttpGet(redirectUrl);
}
return uriRequest;
}
}
static class RetryHandler implements ServiceUnavailableRetryStrategy {
@Override
public boolean retryRequest(HttpResponse httpResponse, int i, HttpContext httpContext) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Retry 10 times
return statusCode == 500 && i <= 10;
}
@Override
public long getRetryInterval() {
return 0;
}
}
static class JsonResponseHandler implements ResponseHandler<EtcdResponse> {
@Override
public EtcdResponse handleResponse(HttpResponse httpResponse) throws IOException {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 500) {
// Do if we still get 500 after 10 times retry
throw new EtcdClientException("Error after 10 times", 500);
}
HttpEntity entity = httpResponse.getEntity();
String json = null;
if (entity != null) {
try {
json = EntityUtils.toString(entity, DEFAULT_CHARSET);
} catch (IOException e) {
throw new EtcdClientException("Error reading response", e);
}
}
return parseResponse(json);
}
}
} |
package com.wmba.collections;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Represents an immutable parcelable map.
* This is basically a decorator around Hashmap.
*
* @param <K> a type of keys.
* @param <V> a type of values.
*/
public class ImmutableMap<K, V> implements Map<K, V>, Parcelable {
private static final ImmutableMap<Object, Object> EMPTY = new ImmutableMap<>(new LinkedHashMap<>());
private static final ClassLoader CLASS_LOADER = ImmutableMap.class.getClassLoader();
private final Map<K, V> map;
/**
* Constructs a SolidMap from a given map.
*
* @param map a source map.
*/
public ImmutableMap(Map<K, V> map) {
this.map = Collections.unmodifiableMap(new LinkedHashMap<>(map));
}
/**
* Constructs a SolidMap from a given iterable stream of entries.
*
* @param iterable a source iterable.
*/
public ImmutableMap(Iterable<? extends Entry<K, V>> iterable) {
LinkedHashMap<K, V> m = new LinkedHashMap<>();
for (Entry<K, V> entry : iterable)
m.put(entry.getKey(), entry.getValue());
this.map = Collections.unmodifiableMap(m);
}
/**
* Returns an empty {@link ImmutableMap}.
*
* @param <K> a type of keys.
* @param <V> a type of values.
* @return an empty {@link ImmutableMap}.
*/
public static <K, V> ImmutableMap<K, V> empty() {
//noinspection unchecked
return (ImmutableMap<K, V>)EMPTY;
}
@Deprecated
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override public boolean containsValue(Object value) {
return map.containsKey(value);
}
@Override public Set<Entry<K, V>> entrySet() {
return map.entrySet();
}
@Override public V get(Object key) {
return map.get(key);
}
@Override public boolean isEmpty() {
return map.isEmpty();
}
@Override public Set<K> keySet() {
return map.keySet();
}
@Deprecated
@Override public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override public void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override public int size() {
return map.size();
}
@Override public Collection<V> values() {
return map.values();
}
@Override public int describeContents() {
return 0;
}
public ImmutableMap(Parcel in) {
LinkedHashMap<K, V> temp = new LinkedHashMap<>();
in.readMap(temp, CLASS_LOADER);
//noinspection unchecked
map = Collections.unmodifiableMap(temp);
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeMap(map);
}
public static final Creator<ImmutableMap> CREATOR = new Creator<ImmutableMap>() {
@Override public ImmutableMap createFromParcel(Parcel in) {
return new ImmutableMap(in);
}
@Override public ImmutableMap[] newArray(int size) {
return new ImmutableMap[size];
}
};
@Override public boolean equals(Object object) {
if (this == object)
return true;
if (object instanceof Map) {
Map<?, ?> other = (Map<?, ?>)object;
if (size() != other.size())
return false;
for (Entry<K, V> entry : entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
Object value2 = other.get(key);
if (value == null) {
if (value2 != null || !other.containsKey(key))
return false;
}
else if (!value.equals(value2))
return false;
}
return true;
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
@Override public String toString() {
return "ImmutableMap{" +
"map=" + map +
'}';
}
} |
package de.tblsoft.solr.pipeline;
import de.tblsoft.solr.pipeline.bean.Document;
import de.tblsoft.solr.pipeline.bean.Filter;
import java.io.Serializable;
import java.util.Map;
public interface FilterIF extends Serializable {
public void init();
public void document(Document document);
public void end();
public void setFilterConfig(Filter filter);
public void setNextFilter(FilterIF filter);
public void setBaseDir(String baseDir);
public String getId();
public void setVariables(Map<String,String> variables);
void setPipelineExecuter(PipelineExecuter pipelineExecuter);
} |
package dk.aau.cs.qweb.airbase.types;
public class Quad {
private String subject;
private String predicate;
private String object;
private String graphLabel;
public Quad(String subject, String predicate, String object, String graphLabel) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.graphLabel = graphLabel;
}
public Quad(String subject, String predicate, String object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.graphLabel = null;
}
public void setGraphLabel(String graphLabel2) {
graphLabel = graphLabel2;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPredicate() {
return predicate;
}
public void setPredicate(String predicate) {
this.predicate = predicate;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getGraphLabel() {
return graphLabel;
}
@Override
public String toString() {
return subject +" "+predicate + " " + object + " " + graphLabel;
}
} |
package editor.gui.display;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import editor.database.card.Card;
import editor.database.card.CardLayout;
import editor.database.symbol.FunctionalSymbol;
import editor.gui.generic.ComponentUtils;
import editor.gui.settings.SettingsDialog;
/**
* This class represents a panel that shows the images associated with a card if they
* can be found, or a card-shaped rectangle with its oracle text and a warning if
* they cannot.
*
* @author Alec Roelke
*/
@SuppressWarnings("serial")
public class CardImagePanel extends JPanel
{
/**
* Aspect ratio of a Magic: The Gathering card.
*/
public static final double ASPECT_RATIO = 63.0/88.0;
/**
* This class represents a request by a CardImagePanel to download the image(s)
* of a Card.
*/
private static class DownloadRequest
{
/**
* CardImagePanel that needs to download a card.
*/
public final CardImagePanel source;
/**
* Card that needs to be downloaded.
*/
public final Card card;
/**
* Create a new DownloadRequest.
*
* @param panel CardImagePanel making the request
* @param c Card whose images need to be downloaded
*/
public DownloadRequest(CardImagePanel panel, Card c)
{
source = panel;
card = c;
}
}
/**
* This class represents a worker that downloads a card image for its parent CardImagePanel
* from Gatherer.
*/
private static class ImageDownloadWorker extends SwingWorker<Void, DownloadRequest>
{
/**
* Queue of cards whose images still need to be downloaded.
*/
private BlockingQueue<DownloadRequest> toDownload;
/**
* Create a new ImageDownloadWorker.
*/
public ImageDownloadWorker()
{
super();
toDownload = new LinkedBlockingQueue<>();
}
/**
* Create a request to download the image(s) of a card to display on the given
* CardImagePanel.
*/
public void downloadCard(CardImagePanel source, Card card)
{
try
{
toDownload.put(new DownloadRequest(source, card));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
@Override
protected Void doInBackground() throws Exception
{
while (true)
{
DownloadRequest req = toDownload.take();
for (long multiverseid : req.card.multiverseid())
{
File img = Paths.get(SettingsDialog.settings().inventory.scans, multiverseid + ".jpg").toFile();
if (!img.exists())
{
URL site = new URL(String.join("/", "https://gatherer.wizards.com", "Handlers", "Image.ashx?multiverseid=" + multiverseid + "&type=card"));
img.getParentFile().mkdirs();
try (BufferedInputStream in = new BufferedInputStream(site.openStream()))
{
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(img)))
{
byte[] data = new byte[1024];
int x;
while ((x = in.read(data)) > 0)
out.write(data, 0, x);
}
}
catch (Exception e)
{
System.err.println("Error downloading " + multiverseid + ".jpg: " + e.getMessage());
}
}
}
publish(req);
}
}
@Override
protected void process(List<DownloadRequest> chunks)
{
for (DownloadRequest req: chunks)
if (req.source.card == req.card)
req.source.loadImages();
}
}
/**
* Global ImageDownloadWorker to manage downloading cards images.
*/
private static ImageDownloadWorker downloader = new ImageDownloadWorker();
static
{
downloader.execute();
}
/**
* This class represents a listener that listens for clicks on a CardImagePanel.
*/
private class FaceListener extends MouseAdapter
{
/**
* When the mouse is clicked, flip to the next face.
*/
public void mousePressed(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e) && card != null)
{
face = switch (card.layout()) {
case SPLIT, AFTERMATH, ADVENTURE -> 0;
default -> (face + 1) % card.faces();
};
getParent().revalidate();
repaint();
}
}
}
/**
* Card this CardImagePanel should display.
*/
private Card card;
/**
* List of images to draw for the card.
*/
private List<BufferedImage> faceImages;
/**
* Image of the card this CardImagePanel should display.
*/
private BufferedImage image;
/**
* Face of the card to display.
*/
private int face;
/**
* Create a new CardImagePanel displaying nothing.
*/
public CardImagePanel()
{
super(null);
card = null;
image = null;
faceImages = new ArrayList<>();
face = 0;
addMouseListener(new FaceListener());
}
/**
* Create a new CardImagePanel displaying the specified card.
*
* @param c card to display
*/
public CardImagePanel(Card c)
{
this();
setCard(c);
}
/**
* {@inheritDoc}
* The preferred size is the largest rectangle that fits the image this CardImagePanel is trying
* to draw that fits within the parent container.
*/
@Override
public Dimension getPreferredSize()
{
if (getParent() == null)
return super.getPreferredSize();
else if (image == null)
return super.getPreferredSize();
else
{
double aspect = (double)image.getWidth()/(double)image.getHeight();
return new Dimension((int)(getParent().getHeight()*aspect), getParent().getHeight());
}
}
/**
* Once the images have been downloaded, try to load them. If they don't exist,
* create a rectangle with Oracle text instead.
*/
private synchronized void loadImages()
{
if (card != null)
{
faceImages.clear();
for (long i : card.multiverseid())
{
BufferedImage img = null;
try
{
if (i > 0)
{
File imageFile = Paths.get(SettingsDialog.settings().inventory.scans, i + ".jpg").toFile();
if (imageFile.exists())
img = ImageIO.read(imageFile);
}
}
catch (IOException e)
{}
finally
{
faceImages.add(img);
}
}
if (getParent() != null)
{
SwingUtilities.invokeLater(() -> {
getParent().revalidate();
repaint();
});
}
}
}
/**
* {@inheritDoc}
* The panel will basically just be the image generated in {@link CardImagePanel#setCard(Card)}
* scaled to fit the container.
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
double aspectRatio = (double)image.getWidth()/(double)image.getHeight();
int width = (int)(getHeight()*aspectRatio);
int height = getHeight();
if (width > getWidth())
{
width = getWidth();
height = (int)(width/aspectRatio);
}
g2.drawImage(image, (getWidth() - width)/2, (getHeight() - height)/2, width, height, null);
if (card.faces() > 1 && !List.of(CardLayout.SPLIT, CardLayout.AFTERMATH, CardLayout.ADVENTURE).contains(card.layout()))
{
final int SIZE = 15;
final int BORDER = 3;
FunctionalSymbol.SYMBOLS.get(face % 2 == 0 ? "T" : "Q").getIcon(SIZE).paintIcon(this, g2, getWidth() - SIZE - BORDER, getHeight() - SIZE - BORDER);
}
}
}
/**
* Set the bounding box of this CardImagePanel. This will cause it to refresh its image
* to fit inside the new bounding box.
*/
@Override
public void setBounds(int x, int y, int width, int height)
{
super.setBounds(x, y, width, height);
if (card == null || height == 0 || width == 0)
image = null;
else
{
int h = 0, w = 0;
if (faceImages.size() <= face || faceImages.get(face) == null)
{
h = height;
w = (int)(h*ASPECT_RATIO);
}
else
{
h = faceImages.get(face).getHeight();
w = faceImages.get(face).getWidth();
}
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.createGraphics();
if (faceImages.size() <= face || faceImages.get(face) == null)
{
int faceWidth = (int)(h*ASPECT_RATIO);
JTextPane missingCardPane = new JTextPane();
StyledDocument document = (StyledDocument)missingCardPane.getDocument();
Style textStyle = document.addStyle("text", null);
StyleConstants.setFontFamily(textStyle, UIManager.getFont("Label.font").getFamily());
StyleConstants.setFontSize(textStyle, ComponentUtils.TEXT_SIZE);
Style reminderStyle = document.addStyle("reminder", textStyle);
StyleConstants.setItalic(reminderStyle, true);
card.formatDocument(document, false, face);
missingCardPane.setSize(new Dimension(faceWidth - 4, h - 4));
BufferedImage img = new BufferedImage(faceWidth, h, BufferedImage.TYPE_INT_ARGB);
missingCardPane.paint(img.getGraphics());
g.drawImage(img, 2, 2, null);
g.setColor(Color.BLACK);
g.drawRect(0, 0, faceWidth - 1, h - 1);
}
else
{
if (card.layout() == CardLayout.FLIP && face%2 == 1)
g.drawImage(faceImages.get(face), faceImages.get(0).getWidth(), faceImages.get(0).getHeight(), -faceImages.get(0).getWidth(), -faceImages.get(0).getHeight(), null);
else
g.drawImage(faceImages.get(face), 0, 0, null);
}
}
}
/**
* Set the card to display. If its image is missing, try to download it.
*
* @param c card to display
*/
public void setCard(Card c)
{
card = Objects.requireNonNull(c);
face = 0;
faceImages.clear();
revalidate();
repaint();
downloader.downloadCard(this, card);
}
} |
package gov.adlnet.xapi.client;
import gov.adlnet.xapi.model.Actor;
import gov.adlnet.xapi.model.IStatementObject;
import gov.adlnet.xapi.model.adapters.ActorAdapter;
import gov.adlnet.xapi.model.adapters.StatementObjectAdapter;
import gov.adlnet.xapi.util.Base64;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.servlet.http.HttpServletResponse;
public class BaseClient {
protected URL _host;
protected Gson gson;
protected String username;
protected String password;
protected String authString;
public BaseClient(String uri, String username, String password)
throws MalformedURLException {
init(new URL(uri), username, password);
}
public BaseClient(URL uri, String username, String password)
throws MalformedURLException {
init(uri, username, password);
}
public BaseClient(String uri, String encodedUsernamePassword)
throws MalformedURLException {
init(new URL(uri), encodedUsernamePassword);
}
public BaseClient(URL uri, String encodedUsernamePassword)
throws MalformedURLException {
init(uri, encodedUsernamePassword);
}
protected Gson getDecoder() {
if (gson == null) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Actor.class, new ActorAdapter());
builder.registerTypeAdapter(IStatementObject.class,
new StatementObjectAdapter());
gson = builder.create();
}
return gson;
}
protected void init(URL uri, String user, String password)
throws MalformedURLException{
String holder = uri.toString();
if(holder.endsWith("/")){
URL newUri = new URL(holder.substring(0, holder.length()-1));
this._host = newUri;
}
else{
this._host = uri;
}
this.username = user;
this.password = password;
this.authString = "Basic " + Base64.encodeToString((this.username + ":" + this.password).getBytes(), Base64.NO_WRAP);
}
protected void init(URL uri, String encodedUsernamePassword)
throws MalformedURLException{
String holder = uri.toString();
if(holder.endsWith("/")){
URL newUri = new URL(holder.substring(0, holder.length()-1));
this._host = newUri;
}
else{
this._host = uri;
}
this.authString = "Basic " + encodedUsernamePassword;
}
protected String readFromConnection(HttpURLConnection conn)
throws java.io.IOException {
InputStream in;
if(conn.getResponseCode() >= 400){
String server = conn.getURL().toString();
int statusCode = conn.getResponseCode();
in = new BufferedInputStream(conn.getErrorStream());
StringBuilder sb = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
try {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
finally {
throw new IOException(String.format("Server (%s) Responded with %d: %s",
server, statusCode, sb.toString()));
}
}
else {
in = new BufferedInputStream(conn.getInputStream());
StringBuilder sb = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
try {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} finally {
br.close();
reader.close();
}
}
}
protected HttpURLConnection initializeConnection(URL url)
throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.addRequestProperty("X-Experience-API-Version", "1.0.0");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", this.authString);
return conn;
}
protected HttpURLConnection initializePOSTConnection(URL url)
throws IOException {
HttpURLConnection conn = initializeConnection(url);
conn.setDoOutput(true);
return conn;
}
protected String issuePost(String path, String data)
throws java.io.IOException {
URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+path);
HttpURLConnection conn = initializePOSTConnection(url);
conn.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());
try {
writer.write(data);
} catch (IOException ex) {
InputStream s = conn.getErrorStream();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while((line = br.readLine()) != null){
System.out.print(line);
}
System.out.println();
} finally {
s.close();
}
throw ex;
} finally {
writer.close();
}
try {
return readFromConnection(conn);
} finally {
conn.disconnect();
}
}
protected String issuePut(String path, String data)
throws java.io.IOException {
URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+path);
HttpURLConnection conn = initializePOSTConnection(url);
conn.setRequestMethod("PUT");
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());
try {
writer.write(data);
} catch (IOException ex) {
InputStream s = conn.getErrorStream();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while((line = br.readLine()) != null){
System.out.print(line);
}
System.out.println();
} finally {
s.close();
}
throw ex;
} finally {
writer.close();
}
try {
return readFromConnection(conn);
} finally {
conn.disconnect();
}
}
protected String issueDelete(String path)
throws java.io.IOException {
URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+path);
HttpURLConnection conn = initializeConnection(url);
conn.setRequestMethod("DELETE");
try{
return readFromConnection(conn);
}
catch (IOException ex){
InputStream s = conn.getErrorStream();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while((line = br.readLine()) != null){
System.out.print(line);
}
System.out.println();
} finally {
s.close();
}
throw ex;
}
finally{
conn.disconnect();
}
}
protected String issueGet(String path) throws java.io.IOException {
String fixedPath = checkPath(path);
URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+fixedPath);
HttpURLConnection conn = initializeConnection(url);
try {
return readFromConnection(conn);
} catch (IOException ex) {
InputStream s = conn.getErrorStream();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while((line = br.readLine()) != null){
System.out.print(line);
}
System.out.println();
} finally {
s.close();
}
throw ex;
}finally {
conn.disconnect();
}
}
protected HttpServletResponse issueGetWithAttachments(String path) throws java.io.IOException {
URL url = new URL(this._host.getProtocol(), this._host.getHost(),this._host.getPort() ,path);
HttpURLConnection conn = initializeConnection(url);
try {
return (HttpServletResponse)conn.getInputStream();
} catch (IOException ex) {
InputStream s = conn.getErrorStream();
InputStreamReader isr = new InputStreamReader(s);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while((line = br.readLine()) != null){
System.out.print(line);
}
System.out.println();
} finally {
s.close();
}
throw ex;
}finally {
conn.disconnect();
}
}
// When retrieving 'more' statements, LRS will return full path..the client will have part in the URI already so cut that off
protected String checkPath(String path){
if (path.toLowerCase().contains("statements") && path.toLowerCase().contains("more")){
int pathLength = this._host.getPath().length();
return path.substring(pathLength, path.length());
}
return path;
}
} |
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*
* (Deliberately contains bugs.)
*/
public class TorpedoStore {
// rate of failing to fire torpedos [0.0, 1.0]
private double FAILURE_RATE = 0.0; //NOSONAR
private int torpedoCount = 0;
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
// update failure rate if it was specified in an environment variable
String failureEnv = System.getenv("IVT_RATE");
if (failureEnv != null){
try {
FAILURE_RATE = Double.parseDouble(failureEnv);
} catch (NumberFormatException nfe) {
FAILURE_RATE = 0.0;
}
}
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
// simulate random overheating of the launcher bay which prevents firing
Random generator = new Random();
double r = generator.nextDouble();
if (r >= FAILURE_RATE) {
// successful firing
this.torpedoCount =- numberOfTorpedos;
success = true;
} else {
// simulated failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
} |
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedos of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.1) {
// successful firing
this.torpedos -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
} |
package hudson.remoting;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.List;
import java.util.ArrayList;
/**
* Loads class files from the other peer through {@link Channel}.
*
* @author Kohsuke Kawaguchi
*/
final class RemoteClassLoader extends ClassLoader {
private final IClassLoader proxy;
/**
* Remote peer that the {@link #proxy} is connected to.
*/
private final Channel channel;
private final Map<String,File> resourceMap = new HashMap<String,File>();
private final Map<String,Vector<File>> resourcesMap = new HashMap<String,Vector<File>>();
public static ClassLoader create(ClassLoader parent, IClassLoader proxy) {
if(proxy instanceof ClassLoaderProxy) {
// when the remote sends 'RemoteIClassLoader' as the proxy, on this side we get it
// as ClassLoaderProxy. This means, the so-called remote classloader here is
// actually our classloader that we exported to the other side.
return ((ClassLoaderProxy)proxy).cl;
}
return new RemoteClassLoader(parent, proxy);
}
private RemoteClassLoader(ClassLoader parent, IClassLoader proxy) {
super(parent);
this.proxy = proxy;
this.channel = RemoteInvocationHandler.unwrap(proxy);
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
long startTime = System.nanoTime();
byte[] bytes = proxy.fetch(name);
channel.classLoadingTime.addAndGet(System.nanoTime()-startTime);
channel.classLoadingCount.incrementAndGet();
return defineClass(name, bytes, 0, bytes.length);
}
protected URL findResource(String name) {
try {
if(resourceMap.containsKey(name)) {
File f = resourceMap.get(name);
if(f==null) return null; // no such resource
if(f.exists())
// be defensive against external factors that might have deleted this file, since we use /tmp
return f.toURL();
}
long startTime = System.nanoTime();
byte[] image = proxy.getResource(name);
channel.resourceLoadingTime.addAndGet(System.nanoTime()-startTime);
channel.resourceLoadingCount.incrementAndGet();
if(image==null) {
resourceMap.put(name,null);
return null;
}
File res = makeResource(name, image);
resourceMap.put(name,res);
return res.toURL();
} catch (IOException e) {
throw new Error("Unable to load resource "+name,e);
}
}
private static Vector<URL> toURLs(Vector<File> files) throws MalformedURLException {
Vector<URL> r = new Vector<URL>(files.size());
for (File f : files) {
if(!f.exists()) return null; // abort
r.add(f.toURL());
}
return r;
}
protected Enumeration<URL> findResources(String name) throws IOException {
Vector<File> files = resourcesMap.get(name);
if(files!=null) {
Vector<URL> urls = toURLs(files);
if(urls!=null)
return urls.elements();
}
long startTime = System.nanoTime();
byte[][] images = proxy.getResources(name);
channel.resourceLoadingTime.addAndGet(System.nanoTime()-startTime);
channel.resourceLoadingCount.incrementAndGet();
files = new Vector<File>();
for( byte[] image: images )
files.add(makeResource(name,image));
resourcesMap.put(name,files);
return toURLs(files).elements();
}
private File makeResource(String name, byte[] image) throws IOException {
int idx = name.lastIndexOf('/');
File f = File.createTempFile("hudson-remoting","."+name.substring(idx+1));
FileOutputStream fos = new FileOutputStream(f);
fos.write(image);
fos.close();
f.deleteOnExit();
return f;
}
/**
* Remoting interface.
*/
/*package*/ static interface IClassLoader {
byte[] fetch(String className) throws ClassNotFoundException;
byte[] getResource(String name) throws IOException;
byte[][] getResources(String name) throws IOException;
}
public static IClassLoader export(ClassLoader cl, Channel local) {
if (cl instanceof RemoteClassLoader) {
// check if this is a remote classloader from the channel
final RemoteClassLoader rcl = (RemoteClassLoader) cl;
int oid = RemoteInvocationHandler.unwrap(rcl.proxy, local);
if(oid!=-1) {
return new RemoteIClassLoader(oid,rcl.proxy);
}
}
return local.export(IClassLoader.class, new ClassLoaderProxy(cl), false);
}
/**
* Exports and just returns the object ID, instead of obtaining the proxy.
*/
static int exportId(ClassLoader cl, Channel local) {
return local.export(new ClassLoaderProxy(cl));
}
/*package*/ static final class ClassLoaderProxy implements IClassLoader {
private final ClassLoader cl;
public ClassLoaderProxy(ClassLoader cl) {
this.cl = cl;
}
public byte[] fetch(String className) throws ClassNotFoundException {
InputStream in = cl.getResourceAsStream(className.replace('.', '/') + ".class");
if(in==null)
throw new ClassNotFoundException(className);
try {
return readFully(in);
} catch (IOException e) {
throw new ClassNotFoundException();
}
}
public byte[] getResource(String name) throws IOException {
InputStream in = cl.getResourceAsStream(name);
if(in==null) return null;
return readFully(in);
}
public byte[][] getResources(String name) throws IOException {
List<byte[]> images = new ArrayList<byte[]>();
Enumeration<URL> e = cl.getResources(name);
while(e.hasMoreElements()) {
images.add(readFully(e.nextElement().openStream()));
}
return images.toArray(new byte[images.size()][]);
}
private byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0)
baos.write(buf,0,len);
in.close();
return baos.toByteArray();
}
public boolean equals(Object that) {
if (this == that) return true;
if (that == null || getClass() != that.getClass()) return false;
return cl.equals(((ClassLoaderProxy) that).cl);
}
public int hashCode() {
return cl.hashCode();
}
}
/**
* {@link IClassLoader} to be shipped back to the channel where it came from.
*
* <p>
* When the object stays on the side where it's created, delegate to the proxy field
* to work (which will be the remote instance.) Once transferred to the other side,
* resolve back to the instance on the server.
*/
private static class RemoteIClassLoader implements IClassLoader, Serializable {
private transient final IClassLoader proxy;
private final int oid;
private RemoteIClassLoader(int oid, IClassLoader proxy) {
this.proxy = proxy;
this.oid = oid;
}
public byte[] fetch(String className) throws ClassNotFoundException {
return proxy.fetch(className);
}
public byte[] getResource(String name) throws IOException {
return proxy.getResource(name);
}
public byte[][] getResources(String name) throws IOException {
return proxy.getResources(name);
}
private Object readResolve() {
return Channel.current().getExportedObject(oid);
}
private static final long serialVersionUID = 1L;
}
} |
package info.faceland.strife;
import com.comphenix.xp.lookup.LevelingRate;
import com.tealcube.minecraft.bukkit.TextUtils;
import com.tealcube.minecraft.bukkit.facecore.logging.PluginLogger;
import com.tealcube.minecraft.bukkit.facecore.plugin.FacePlugin;
import com.tealcube.minecraft.bukkit.shade.objecthunter.exp4j.Expression;
import com.tealcube.minecraft.bukkit.shade.objecthunter.exp4j.ExpressionBuilder;
import info.faceland.strife.api.StrifeExperienceManager;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.commands.AttributesCommand;
import info.faceland.strife.commands.LevelUpCommand;
import info.faceland.strife.commands.SpawnerCommand;
import info.faceland.strife.commands.StrifeCommand;
import info.faceland.strife.commands.UniqueEntityCommand;
import info.faceland.strife.data.Spawner;
import info.faceland.strife.data.UniqueEntity;
import info.faceland.strife.data.ability.Ability;
import info.faceland.strife.data.ability.EntityAbilitySet;
import info.faceland.strife.data.ability.EntityAbilitySet.AbilityType;
import info.faceland.strife.listeners.AttributeUpdateListener;
import info.faceland.strife.listeners.BullionListener;
import info.faceland.strife.listeners.DataListener;
import info.faceland.strife.listeners.EntityMagicListener;
import info.faceland.strife.listeners.ExperienceListener;
import info.faceland.strife.listeners.FallListener;
import info.faceland.strife.listeners.HeadDropListener;
import info.faceland.strife.listeners.HealthListener;
import info.faceland.strife.listeners.LoreAbilityListener;
import info.faceland.strife.listeners.MinionListener;
import info.faceland.strife.listeners.SkillLevelUpListener;
import info.faceland.strife.listeners.SneakAttackListener;
import info.faceland.strife.listeners.SpawnListener;
import info.faceland.strife.listeners.TargetingListener;
import info.faceland.strife.listeners.UniqueSplashListener;
import info.faceland.strife.listeners.combat.BowListener;
import info.faceland.strife.listeners.combat.CombatListener;
import info.faceland.strife.listeners.combat.DOTListener;
import info.faceland.strife.listeners.combat.DogeListener;
import info.faceland.strife.listeners.combat.SwingListener;
import info.faceland.strife.managers.AbilityManager;
import info.faceland.strife.managers.AttackSpeedManager;
import info.faceland.strife.managers.AttributeUpdateManager;
import info.faceland.strife.managers.AttributedEntityManager;
import info.faceland.strife.managers.BarrierManager;
import info.faceland.strife.managers.BleedManager;
import info.faceland.strife.managers.BlockManager;
import info.faceland.strife.managers.BossBarManager;
import info.faceland.strife.managers.ChampionManager;
import info.faceland.strife.managers.DarknessManager;
import info.faceland.strife.managers.EffectManager;
import info.faceland.strife.managers.EntityEquipmentManager;
import info.faceland.strife.managers.ExperienceManager;
import info.faceland.strife.managers.GlobalBoostManager;
import info.faceland.strife.managers.LoreAbilityManager;
import info.faceland.strife.managers.MinionManager;
import info.faceland.strife.managers.MonsterManager;
import info.faceland.strife.managers.RageManager;
import info.faceland.strife.managers.SkillExperienceManager;
import info.faceland.strife.managers.SneakManager;
import info.faceland.strife.managers.SpawnerManager;
import info.faceland.strife.managers.StrifeStatManager;
import info.faceland.strife.managers.UniqueEntityManager;
import info.faceland.strife.menus.levelup.ConfirmationMenu;
import info.faceland.strife.menus.levelup.LevelupMenu;
import info.faceland.strife.menus.stats.StatsMenu;
import info.faceland.strife.storage.DataStorage;
import info.faceland.strife.storage.FlatfileStorage;
import info.faceland.strife.tasks.BarrierTask;
import info.faceland.strife.tasks.BleedTask;
import info.faceland.strife.tasks.BossBarsTask;
import info.faceland.strife.tasks.DarknessReductionTask;
import info.faceland.strife.tasks.GlobalMultiplierTask;
import info.faceland.strife.tasks.HealthRegenTask;
import info.faceland.strife.tasks.MinionDecayTask;
import info.faceland.strife.tasks.MonsterLimitTask;
import info.faceland.strife.tasks.PruneBossBarsTask;
import info.faceland.strife.tasks.RageTask;
import info.faceland.strife.tasks.SaveTask;
import info.faceland.strife.tasks.SneakTask;
import info.faceland.strife.tasks.SpawnerLeashTask;
import info.faceland.strife.tasks.SpawnerSpawnTask;
import info.faceland.strife.tasks.TimedAbilityTask;
import info.faceland.strife.tasks.TrackedPruneTask;
import info.faceland.strife.tasks.UniqueParticleTask;
import info.faceland.strife.tasks.UniquePruneTask;
import info.faceland.strife.util.LogUtil;
import info.faceland.strife.util.LogUtil.LogLevel;
import io.pixeloutlaw.minecraft.spigot.config.MasterConfiguration;
import io.pixeloutlaw.minecraft.spigot.config.SmartYamlConfiguration;
import io.pixeloutlaw.minecraft.spigot.config.VersionedConfiguration;
import io.pixeloutlaw.minecraft.spigot.config.VersionedSmartYamlConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import ninja.amp.ampmenus.MenuListener;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.scheduler.BukkitTask;
import se.ranzdo.bukkit.methodcommand.CommandHandler;
public class StrifePlugin extends FacePlugin {
private static StrifePlugin instance;
private PluginLogger debugPrinter;
private LogLevel logLevel;
private CommandHandler commandHandler;
private MasterConfiguration settings;
private VersionedSmartYamlConfiguration configYAML;
private VersionedSmartYamlConfiguration langYAML;
private VersionedSmartYamlConfiguration statsYAML;
private VersionedSmartYamlConfiguration baseStatsYAML;
private VersionedSmartYamlConfiguration uniqueEnemiesYAML;
private VersionedSmartYamlConfiguration equipmentYAML;
private VersionedSmartYamlConfiguration conditionYAML;
private VersionedSmartYamlConfiguration effectYAML;
private VersionedSmartYamlConfiguration abilityYAML;
private VersionedSmartYamlConfiguration loreAbilityYAML;
private VersionedSmartYamlConfiguration globalBoostsYAML;
private SmartYamlConfiguration spawnerYAML;
private AttributedEntityManager attributedEntityManager;
private AttributeUpdateManager attributeUpdateManager;
private StrifeStatManager statManager;
private ChampionManager championManager;
private StrifeExperienceManager experienceManager;
private SkillExperienceManager skillExperienceManager;
private AttackSpeedManager attackSpeedManager;
private BlockManager blockManager;
private BarrierManager barrierManager;
private BleedManager bleedManager;
private DarknessManager darknessManager;
private RageManager rageManager;
private MonsterManager monsterManager;
private UniqueEntityManager uniqueEntityManager;
private SneakManager sneakManager;
private BossBarManager bossBarManager;
private MinionManager minionManager;
private EntityEquipmentManager equipmentManager;
private EffectManager effectManager;
private AbilityManager abilityManager;
private LoreAbilityManager loreAbilityManager;
private SpawnerManager spawnerManager;
private GlobalBoostManager globalBoostManager;
private DataStorage storage;
private List<BukkitTask> taskList = new ArrayList<>();
private SaveTask saveTask;
private TrackedPruneTask trackedPruneTask;
private HealthRegenTask regenTask;
private BleedTask bleedTask;
private SneakTask sneakTask;
private BarrierTask barrierTask;
private BossBarsTask bossBarsTask;
private MinionDecayTask minionDecayTask;
private GlobalMultiplierTask globalMultiplierTask;
private PruneBossBarsTask pruneBossBarsTask;
private DarknessReductionTask darkTask;
private MonsterLimitTask monsterLimitTask;
private RageTask rageTask;
private UniquePruneTask uniquePruneTask;
private UniqueParticleTask uniqueParticleTask;
private TimedAbilityTask timedAbilityTask;
private SpawnerSpawnTask spawnerSpawnTask;
private SpawnerLeashTask spawnerLeashTask;
private LevelingRate levelingRate;
private LevelingRate craftingRate;
private LevelingRate enchantRate;
private LevelingRate fishRate;
private LevelingRate miningRate;
private LevelingRate sneakRate;
private LevelupMenu levelupMenu;
private ConfirmationMenu confirmMenu;
private StatsMenu statsMenu;
private int maxSkillLevel;
private static void setInstance(StrifePlugin plugin) {
instance = plugin;
}
public static StrifePlugin getInstance() {
return instance;
}
@Override
public void enable() {
setInstance(this);
debugPrinter = new PluginLogger(this);
configYAML = defaultSettingsLoad("config.yml");
langYAML = defaultSettingsLoad("language.yml");
statsYAML = defaultSettingsLoad("stats.yml");
baseStatsYAML = defaultSettingsLoad("base-entity-stats.yml");
uniqueEnemiesYAML = defaultSettingsLoad("unique-enemies.yml");
equipmentYAML = defaultSettingsLoad("equipment.yml");
conditionYAML = defaultSettingsLoad("conditions.yml");
effectYAML = defaultSettingsLoad("effects.yml");
abilityYAML = defaultSettingsLoad("abilities.yml");
loreAbilityYAML = defaultSettingsLoad("lore-abilities.yml");
globalBoostsYAML = defaultSettingsLoad("global-boosts.yml");
spawnerYAML = new SmartYamlConfiguration(new File(getDataFolder(), "spawners.yml"));
if (configYAML.update()) {
getLogger().info("Updating config.yml");
}
if (langYAML.update()) {
getLogger().info("Updating language.yml");
}
if (statsYAML.update()) {
getLogger().info("Updating stats.yml");
}
if (baseStatsYAML.update()) {
getLogger().info("Updating base-entity-stats.yml");
}
if (uniqueEnemiesYAML.update()) {
getLogger().info("Updating unique-enemies.yml");
}
if (equipmentYAML.update()) {
getLogger().info("Updating equipment.yml");
}
if (effectYAML.update()) {
getLogger().info("Updating effects.yml");
}
if (abilityYAML.update()) {
getLogger().info("Updating abilities.yml");
}
settings = MasterConfiguration.loadFromFiles(configYAML, langYAML);
storage = new FlatfileStorage(this);
championManager = new ChampionManager(this);
uniqueEntityManager = new UniqueEntityManager(this);
bossBarManager = new BossBarManager(this);
minionManager = new MinionManager();
sneakManager = new SneakManager();
experienceManager = new ExperienceManager(this);
skillExperienceManager = new SkillExperienceManager(this);
attributedEntityManager = new AttributedEntityManager(this);
abilityManager = new AbilityManager(this);
commandHandler = new CommandHandler(this);
statManager = new StrifeStatManager();
blockManager = new BlockManager();
bleedManager = new BleedManager();
darknessManager = new DarknessManager();
attackSpeedManager = new AttackSpeedManager();
equipmentManager = new EntityEquipmentManager();
globalBoostManager = new GlobalBoostManager();
barrierManager = new BarrierManager();
attributeUpdateManager = new AttributeUpdateManager(attributedEntityManager);
rageManager = new RageManager(attributeUpdateManager);
monsterManager = new MonsterManager(championManager);
effectManager = new EffectManager(statManager, attributedEntityManager);
spawnerManager = new SpawnerManager(uniqueEntityManager);
loreAbilityManager = new LoreAbilityManager(abilityManager, effectManager);
MenuListener.getInstance().register(this);
try {
logLevel = LogLevel.valueOf(settings.getString("config.log-level", "ERROR"));
} catch (Exception e) {
logLevel = LogLevel.ERROR;
LogUtil.printError("You don't have an acceptable log level you dangus");
}
buildEquipment();
buildLevelpointStats();
buildBaseStats();
loadBoosts();
loadScheduledBoosts();
buildConditions();
buildEffects();
buildAbilities();
buildLoreAbilities();
buildUniqueEnemies();
loadSpawners();
saveTask = new SaveTask(this);
trackedPruneTask = new TrackedPruneTask(this);
regenTask = new HealthRegenTask(this);
bleedTask = new BleedTask(bleedManager, barrierManager,
settings.getDouble("config.mechanics.base-bleed-damage", 1D),
settings.getDouble("config.mechanics.percent-bleed-damage", 0.1D));
sneakTask = new SneakTask(sneakManager);
barrierTask = new BarrierTask(this);
bossBarsTask = new BossBarsTask(bossBarManager);
minionDecayTask = new MinionDecayTask(minionManager);
globalMultiplierTask = new GlobalMultiplierTask(globalBoostManager);
pruneBossBarsTask = new PruneBossBarsTask(bossBarManager);
darkTask = new DarknessReductionTask(darknessManager);
rageTask = new RageTask(rageManager, attributedEntityManager);
monsterLimitTask = new MonsterLimitTask(settings);
uniquePruneTask = new UniquePruneTask(this);
uniqueParticleTask = new UniqueParticleTask(uniqueEntityManager);
spawnerLeashTask = new SpawnerLeashTask(spawnerManager);
spawnerSpawnTask = new SpawnerSpawnTask(spawnerManager);
timedAbilityTask = new TimedAbilityTask(abilityManager, uniqueEntityManager,
attributedEntityManager);
commandHandler.registerCommands(new AttributesCommand(this));
commandHandler.registerCommands(new LevelUpCommand(this));
commandHandler.registerCommands(new StrifeCommand(this));
commandHandler.registerCommands(new UniqueEntityCommand(this));
commandHandler.registerCommands(new SpawnerCommand(this));
levelingRate = new LevelingRate();
maxSkillLevel = settings.getInt("config.leveling.max-skill-level", 60);
Expression normalExpr = new ExpressionBuilder(settings.getString("config.leveling.formula",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < 200; i++) {
levelingRate.put(i, i, (int) Math.round(normalExpr.setVariable("LEVEL", i).evaluate()));
}
craftingRate = new LevelingRate();
Expression craftExpr = new ExpressionBuilder(settings.getString("config.leveling.crafting",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < maxSkillLevel; i++) {
craftingRate.put(i, i, (int) Math.round(craftExpr.setVariable("LEVEL", i).evaluate()));
}
enchantRate = new LevelingRate();
Expression enchantExpr = new ExpressionBuilder(settings.getString("config.leveling.enchanting",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < maxSkillLevel; i++) {
enchantRate.put(i, i, (int) Math.round(enchantExpr.setVariable("LEVEL", i).evaluate()));
}
fishRate = new LevelingRate();
Expression fishExpr = new ExpressionBuilder(settings.getString("config.leveling.fishing",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < maxSkillLevel; i++) {
fishRate.put(i, i, (int) Math.round(fishExpr.setVariable("LEVEL", i).evaluate()));
}
miningRate = new LevelingRate();
Expression mineExpr = new ExpressionBuilder(settings.getString("config.leveling.mining",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < maxSkillLevel; i++) {
miningRate.put(i, i, (int) Math.round(mineExpr.setVariable("LEVEL", i).evaluate()));
}
sneakRate = new LevelingRate();
Expression sneakExpr = new ExpressionBuilder(settings.getString("config.leveling.sneak",
"(5+(2*LEVEL)+(LEVEL^1.2))*LEVEL")).variable("LEVEL").build();
for (int i = 0; i < maxSkillLevel; i++) {
sneakRate.put(i, i, (int) Math.round(sneakExpr.setVariable("LEVEL", i).evaluate()));
}
taskList.add(trackedPruneTask.runTaskTimer(this,
20L * 61, // Start save after 1 minute, 1 second cuz yolo
20L * 60 // Run every 1 minute after that
));
taskList.add(saveTask.runTaskTimer(this,
20L * 680, // Start save after 11 minutes, 20 seconds cuz yolo
20L * 600 // Run every 10 minutes after that
));
taskList.add(regenTask.runTaskTimer(this,
20L * 9, // Start timer after 9s
20L * 2 // Run it every 2s after
));
taskList.add(bleedTask.runTaskTimer(this,
20L * 10, // Start timer after 10s
settings.getLong("config.mechanics.ticks-per-bleed", 10L)
));
taskList.add(sneakTask.runTaskTimer(this,
20L * 10, // Start timer after 10s
10L // Run every 1/2 second
));
taskList.add(barrierTask.runTaskTimer(this,
2201L, // Start timer after 11s
4L // Run it every 1/5th of a second after
));
taskList.add(bossBarsTask.runTaskTimer(this,
240L, // Start timer after 12s
2L // Run it every 1/10th of a second after
));
taskList.add(minionDecayTask.runTaskTimer(this,
220L, // Start timer after 11s
11L
));
taskList.add(globalMultiplierTask.runTaskTimer(this,
20L * 15, // Start timer after 15s
20L * 60 // Run it every minute after
));
taskList.add(pruneBossBarsTask.runTaskTimer(this,
20L * 13, // Start timer after 13s
20L * 60 * 7 // Run it every 7 minutes
));
taskList.add(darkTask.runTaskTimer(this,
20L * 14, // Start timer after 14s
10L // Run it every 0.5s after
));
taskList.add(monsterLimitTask.runTaskTimer(this,
20L * 15, // Start timer after 15s
20L * 60 // Run it every minute after
));
taskList.add(rageTask.runTaskTimer(this,
20L * 10, // Start timer after 10s
5L // Run it every 0.25s after
));
taskList.add(uniquePruneTask.runTaskTimer(this,
30 * 20L,
30 * 20L
));
taskList.add(uniqueParticleTask.runTaskTimer(this,
20 * 20L,
2L
));
taskList.add(spawnerSpawnTask.runTaskTimer(this,
20 * 20L, // Start timer after 20s
6 * 20L // Run it every 6 seconds
));
taskList.add(timedAbilityTask.runTaskTimer(this,
20 * 20L, // Start timer after 20s
2 * 20L // Run it every 2 seconds
));
taskList.add(spawnerLeashTask.runTaskTimer(this,
20 * 20L, // Start timer after 20s
5 * 20L // Run it every 5s
));
globalBoostManager.startScheduledEvents();
//Bukkit.getPluginManager().registerEvents(new EndermanListener(), this);
Bukkit.getPluginManager().registerEvents(new ExperienceListener(this), this);
Bukkit.getPluginManager().registerEvents(new HealthListener(), this);
Bukkit.getPluginManager().registerEvents(new CombatListener(this), this);
Bukkit.getPluginManager().registerEvents(
new UniqueSplashListener(attributedEntityManager, blockManager, effectManager), this);
Bukkit.getPluginManager().registerEvents(new DOTListener(this), this);
Bukkit.getPluginManager().registerEvents(new SwingListener(this), this);
Bukkit.getPluginManager().registerEvents(new BowListener(this), this);
Bukkit.getPluginManager().registerEvents(new HeadDropListener(attributedEntityManager), this);
Bukkit.getPluginManager().registerEvents(new DataListener(this), this);
Bukkit.getPluginManager().registerEvents(new SkillLevelUpListener(settings), this);
Bukkit.getPluginManager().registerEvents(new AttributeUpdateListener(this), this);
Bukkit.getPluginManager().registerEvents(new EntityMagicListener(), this);
Bukkit.getPluginManager().registerEvents(new SpawnListener(this), this);
Bukkit.getPluginManager()
.registerEvents(new MinionListener(attributedEntityManager, minionManager), this);
Bukkit.getPluginManager().registerEvents(new TargetingListener(this), this);
Bukkit.getPluginManager().registerEvents(new FallListener(), this);
Bukkit.getPluginManager().registerEvents(new SneakAttackListener(this), this);
Bukkit.getPluginManager().registerEvents(new DogeListener(attributedEntityManager), this);
Bukkit.getPluginManager().registerEvents(
new LoreAbilityListener(attributedEntityManager, championManager, loreAbilityManager),
this);
if (Bukkit.getPluginManager().getPlugin("Bullion") != null) {
Bukkit.getPluginManager().registerEvents(new BullionListener(this), this);
}
levelupMenu = new LevelupMenu(this, getStatManager().getStats());
confirmMenu = new ConfirmationMenu(this);
statsMenu = new StatsMenu(this);
for (Player player : Bukkit.getOnlinePlayers()) {
getChampionManager().updateAll(championManager.getChampion(player));
attributeUpdateManager.updateAttributes(player);
}
LogUtil.printInfo("+===================================+");
LogUtil.printInfo("Successfully enabled Strife-v" + getDescription().getVersion());
LogUtil.printInfo("+===================================+");
}
@Override
public void disable() {
saveSpawners();
storage.saveAll();
uniqueEntityManager.killAllSpawnedUniques();
attributedEntityManager.despawnAllTempEntities();
bossBarManager.removeAllBars();
HandlerList.unregisterAll(this);
for (BukkitTask task : taskList) {
task.cancel();
}
LogUtil.printInfo("+===================================+");
LogUtil.printInfo("Successfully disabled Strife-v" + getDescription().getVersion());
LogUtil.printInfo("+===================================+");
}
private VersionedSmartYamlConfiguration defaultSettingsLoad(String name) {
return new VersionedSmartYamlConfiguration(new File(getDataFolder(), name),
getResource(name), VersionedConfiguration.VersionUpdateType.BACKUP_AND_UPDATE);
}
private void buildAbilities() {
for (String key : abilityYAML.getKeys(false)) {
if (!abilityYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = abilityYAML.getConfigurationSection(key);
abilityManager.loadAbility(key, cs);
}
}
private void buildEffects() {
for (String key : effectYAML.getKeys(false)) {
if (!effectYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = effectYAML.getConfigurationSection(key);
effectManager.loadEffect(key, cs);
}
}
private void buildConditions() {
for (String key : conditionYAML.getKeys(false)) {
if (!conditionYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = conditionYAML.getConfigurationSection(key);
effectManager.loadCondition(key, cs);
}
}
private void buildLoreAbilities() {
for (String key : loreAbilityYAML.getKeys(false)) {
if (!loreAbilityYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = loreAbilityYAML.getConfigurationSection(key);
loreAbilityManager.loadLoreAbility(key, cs);
}
}
private void buildEquipment() {
for (String itemStackKey : equipmentYAML.getKeys(false)) {
if (!equipmentYAML.isConfigurationSection(itemStackKey)) {
continue;
}
ConfigurationSection cs = equipmentYAML.getConfigurationSection(itemStackKey);
equipmentManager.loadEquipmentItem(itemStackKey, cs);
}
}
private void buildLevelpointStats() {
for (String key : statsYAML.getKeys(false)) {
if (!statsYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = statsYAML.getConfigurationSection(key);
statManager.loadStat(key, cs);
}
}
private void buildBaseStats() {
monsterManager.loadBaseStats("default", baseStatsYAML.getConfigurationSection("default"));
for (String entityKey : baseStatsYAML.getKeys(false)) {
if (!baseStatsYAML.isConfigurationSection(entityKey)) {
continue;
}
ConfigurationSection cs = baseStatsYAML.getConfigurationSection(entityKey);
monsterManager.loadBaseStats(entityKey, cs);
}
}
private void loadScheduledBoosts() {
ConfigurationSection cs = globalBoostsYAML.getConfigurationSection("scheduled-boosts");
globalBoostManager.loadScheduledBoosts(cs);
}
private void loadBoosts() {
ConfigurationSection cs = globalBoostsYAML.getConfigurationSection("boost-templates");
globalBoostManager.loadStatBoosts(cs);
}
private void buildUniqueEnemies() {
for (String entityNameKey : uniqueEnemiesYAML.getKeys(false)) {
if (!uniqueEnemiesYAML.isConfigurationSection(entityNameKey)) {
continue;
}
ConfigurationSection cs = uniqueEnemiesYAML.getConfigurationSection(entityNameKey);
UniqueEntity uniqueEntity = new UniqueEntity();
String type = cs.getString("type");
try {
uniqueEntity.setType(EntityType.valueOf(type));
} catch (Exception e) {
getLogger().severe("Failed to parse entity " + entityNameKey + ". Invalid type: " + type);
continue;
}
uniqueEntity.setId(entityNameKey);
uniqueEntity.setName(TextUtils.color(cs.getString("name", "&fSET &cA &9NAME")));
uniqueEntity.setExperience(cs.getInt("experience", 0));
uniqueEntity.setKnockbackImmune(cs.getBoolean("knockback-immune", false));
uniqueEntity.setFollowRange(cs.getInt("follow-range", -1));
uniqueEntity.setBaby(cs.getBoolean("baby", false));
String disguise = cs.getString("disguise", null);
if (StringUtils.isNotBlank(disguise)) {
uniqueEntityManager
.cacheDisguise(uniqueEntity, disguise, cs.getString("disguise-player", null));
}
ConfigurationSection attrCS = cs.getConfigurationSection("attributes");
Map<StrifeAttribute, Double> attributeMap = new HashMap<>();
for (String k : attrCS.getKeys(false)) {
StrifeAttribute attr = StrifeAttribute.valueOf(k);
attributeMap.put(attr, attrCS.getDouble(k));
}
uniqueEntity.setAttributeMap(attributeMap);
ConfigurationSection equipmentCS = cs.getConfigurationSection("equipment");
if (equipmentCS != null) {
uniqueEntity
.setMainHandItem(equipmentManager.getItem(equipmentCS.getString("main-hand", "")));
uniqueEntity
.setOffHandItem(equipmentManager.getItem(equipmentCS.getString("off-hand", "")));
uniqueEntity.setHelmetItem(equipmentManager.getItem(equipmentCS.getString("helmet", "")));
uniqueEntity
.setChestItem(equipmentManager.getItem(equipmentCS.getString("chestplate", "")));
uniqueEntity.setLegsItem(equipmentManager.getItem(equipmentCS.getString("leggings", "")));
uniqueEntity.setBootsItem(equipmentManager.getItem(equipmentCS.getString("boots", "")));
}
ConfigurationSection particleCS = cs.getConfigurationSection("particles");
if (particleCS != null) {
try {
uniqueEntity.setParticle(Particle.valueOf(particleCS.getString("effect")));
} catch (Exception e) {
getLogger().severe("Particle for " + entityNameKey + " is invalid. Setting to FLAME");
uniqueEntity.setParticle(Particle.FLAME);
}
uniqueEntity.setParticleCount(particleCS.getInt("count", 1));
uniqueEntity.setParticleRadius((float) particleCS.getDouble("radius", 0));
} else {
uniqueEntity.setParticle(null);
}
ConfigurationSection abilityCS = cs.getConfigurationSection("abilities");
uniqueEntity.setAbilitySet(null);
if (abilityCS != null) {
EntityAbilitySet abilitySet = new EntityAbilitySet();
for (int i = 1; i <= 5; i++) {
List<String> phaseBegin = abilityCS.getStringList("phase" + i + ".phase-begin");
List<String> phaseOnHit = abilityCS.getStringList("phase" + i + ".on-hit");
List<String> phaseWhenHit = abilityCS.getStringList("phase" + i + ".when-hit");
List<String> phaseTimer = abilityCS.getStringList("phase" + i + ".timer");
if (!phaseBegin.isEmpty()) {
List<Ability> abilities = setupPhase(phaseBegin, i);
if (!abilities.isEmpty()) {
abilitySet.addAbilityPhase(i, AbilityType.PHASE_SHIFT, abilities);
}
}
if (!phaseOnHit.isEmpty()) {
List<Ability> abilities = setupPhase(phaseOnHit, i);
if (!abilities.isEmpty()) {
abilitySet.addAbilityPhase(i, AbilityType.ON_HIT, abilities);
}
}
if (!phaseWhenHit.isEmpty()) {
List<Ability> abilities = setupPhase(phaseWhenHit, i);
if (!abilities.isEmpty()) {
abilitySet.addAbilityPhase(i, AbilityType.WHEN_HIT, abilities);
}
}
if (!phaseTimer.isEmpty()) {
List<Ability> abilities = setupPhase(phaseTimer, i);
if (!abilities.isEmpty()) {
abilitySet.addAbilityPhase(i, AbilityType.TIMER, abilities);
}
}
}
uniqueEntity.setAbilitySet(abilitySet);
}
uniqueEntityManager.addUniqueEntity(entityNameKey, uniqueEntity);
}
}
private List<Ability> setupPhase(List<String> strings, int phase) {
List<Ability> abilities = new ArrayList<>();
for (String s : strings) {
Ability ability = abilityManager.getAbility(s);
if (ability == null) {
getLogger().warning("Failed to add phase" + phase + " ability " + s + " - Not found");
continue;
}
abilities.add(ability);
}
return abilities;
}
public void loadSpawners() {
Map<String, Spawner> spawners = new HashMap<>();
for (String spawnerId : spawnerYAML.getKeys(false)) {
if (!spawnerYAML.isConfigurationSection(spawnerId)) {
continue;
}
ConfigurationSection cs = spawnerYAML.getConfigurationSection(spawnerId);
String uniqueId = cs.getString("unique");
if (!uniqueEntityManager.isLoadedUnique(uniqueId)) {
LogUtil.printWarning("Skipping spawner " + spawnerId + " with invalid unique " + uniqueId);
continue;
}
UniqueEntity uniqueEntity = uniqueEntityManager.getLoadedUniquesMap().get(uniqueId);
int respawnSeconds = cs.getInt("respawn-seconds", 30);
double leashRange = cs.getDouble("leash-dist", 10);
double xPos = cs.getDouble("location.x");
double yPos = cs.getDouble("location.y");
double zPos = cs.getDouble("location.z");
World world = Bukkit.getWorld(cs.getString("location.world"));
Location location = new Location(world, xPos, yPos, zPos);
spawners.put(spawnerId, new Spawner(uniqueEntity, location, respawnSeconds, leashRange));
spawnerManager.setSpawnerMap(spawners);
}
}
private void saveSpawners() {
for (String spawnerId : spawnerYAML.getKeys(false)) {
Spawner spawner = spawnerManager.getSpawnerMap().get(spawnerId);
if (spawner == null) {
spawnerYAML.getConfigurationSection(spawnerId).getParent().set(spawnerId, null);
LogUtil.printDebug("Spawner " + spawnerId + " has been removed.");
}
}
for (String spawnerId : spawnerManager.getSpawnerMap().keySet()) {
Spawner spawner = spawnerManager.getSpawnerMap().get(spawnerId);
spawnerYAML.set(spawnerId + ".unique", spawner.getUniqueEntity().getId());
spawnerYAML.set(spawnerId + ".respawn-seconds", spawner.getRespawnSeconds());
spawnerYAML.set(spawnerId + ".leash-dist", spawner.getLeashRange());
spawnerYAML.set(spawnerId + ".location.world", spawner.getLocation().getWorld().getName());
spawnerYAML.set(spawnerId + ".location.x", spawner.getLocation().getX());
spawnerYAML.set(spawnerId + ".location.y", spawner.getLocation().getY());
spawnerYAML.set(spawnerId + ".location.z", spawner.getLocation().getZ());
LogUtil.printDebug("Saved spawner " + spawnerId + ".");
}
spawnerYAML.save();
}
public AttributeUpdateManager getAttributeUpdateManager() {
return attributeUpdateManager;
}
public AttackSpeedManager getAttackSpeedManager() {
return attackSpeedManager;
}
public StrifeStatManager getStatManager() {
return statManager;
}
public BlockManager getBlockManager() {
return blockManager;
}
public BarrierManager getBarrierManager() {
return barrierManager;
}
public BleedManager getBleedManager() {
return bleedManager;
}
public DarknessManager getDarknessManager() {
return darknessManager;
}
public RageManager getRageManager() {
return rageManager;
}
public MonsterManager getMonsterManager() {
return monsterManager;
}
public UniqueEntityManager getUniqueEntityManager() {
return uniqueEntityManager;
}
public BossBarManager getBossBarManager() {
return bossBarManager;
}
public MinionManager getMinionManager() {
return minionManager;
}
public EffectManager getEffectManager() {
return effectManager;
}
public AbilityManager getAbilityManager() {
return abilityManager;
}
public SpawnerManager getSpawnerManager() {
return spawnerManager;
}
public GlobalBoostManager getGlobalBoostManager() {
return globalBoostManager;
}
public SkillExperienceManager getSkillExperienceManager() {
return skillExperienceManager;
}
public StrifeExperienceManager getExperienceManager() {
return experienceManager;
}
public LoreAbilityManager getLoreAbilityManager() {
return loreAbilityManager;
}
public void debug(Level level, String... messages) {
if (debugPrinter != null) {
debugPrinter.log(level, Arrays.asList(messages));
}
}
public DataStorage getStorage() {
return storage;
}
public ChampionManager getChampionManager() {
return championManager;
}
public SneakManager getSneakManager() {
return sneakManager;
}
public AttributedEntityManager getAttributedEntityManager() {
return attributedEntityManager;
}
public MasterConfiguration getSettings() {
return settings;
}
public LevelupMenu getLevelupMenu() {
return levelupMenu;
}
public ConfirmationMenu getConfirmationMenu() {
return confirmMenu;
}
public StatsMenu getStatsMenu() {
return statsMenu;
}
public LevelingRate getLevelingRate() {
return levelingRate;
}
public int getMaxSkillLevel() {
return maxSkillLevel;
}
public LevelingRate getCraftingRate() {
return craftingRate;
}
public LevelingRate getEnchantRate() {
return enchantRate;
}
public LevelingRate getFishRate() {
return fishRate;
}
public LevelingRate getMiningRate() {
return miningRate;
}
public LevelingRate getSneakRate() {
return sneakRate;
}
public LogLevel getLogLevel() {
return logLevel;
}
} |
package io.fnx.backend.tools.ofy;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Ref;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Useful function to call when you are dealing with Objectify.
* Can be statically imported (shhh. don't tell Tomuchacha)
* @author Jiri Zuna (jiri@zunovi.cz)
*/
public class OfyUtils {
/**
* Null safe getter of the underlying id in given key
* @param k key to get id for
* @return id bound to the given key
*/
public static Long keyToId(Key<?> k) {
if (k != null) {
return k.getId();
} else {
return null;
}
}
/**
* Null safe getter of the underlying id in given ref
* @param ref ref to get id for
* @return id bound to the given ref
*/
public static Long refToId(Ref<?> ref) {
if (ref != null) {
return keyToId(ref.getKey());
} else {
return null;
}
}
/**
* Null safe converter from refs to keys
* @param ref ref to convert
* @param <T> entity type
* @return key from given ref. Null if ref is null.
*/
public static <T> Key<T> refToKey(Ref<T> ref) {
if (ref != null) {
return ref.getKey();
} else {
return null;
}
}
/**
* Convert all refs to respective keys
* @param refs to convert
* @param <T> refs type
* @return all non null refs as keys
*/
public static <T> List<Key<T>> refsToKeys(Collection<Ref<T>> refs) {
if (refs == null) return new ArrayList<>();
final List<Key<T>> results = new ArrayList<>(refs.size());
for (Ref<T> ref : refs) {
if (ref != null) results.add(ref.getKey());
}
return results;
}
/**
* Null safe factory for keys from ids
* @param entity the entity to create key for
* @param id entity id
* @param <T> entity Type
* @return entity key
*/
public static <T> Key<T> idToKey(Class<T> entity, Long id) {
if (id == null) {
return null;
} else {
return Key.create(entity, id);
}
}
/**
* Null safe factory for keys from ids
* @param entity the entity to create key for
* @param name entity id (name)
* @param <T> entity Type
* @return entity key
*/
public static <T> Key<T> nameToKey(Class<T> entity, String name) {
if (name == null) {
return null;
} else {
return Key.create(entity, name);
}
}
/**
* Null safe factory for refs from ids
* @param entity the entity to create ref for
* @param id entity id
* @param <T> entity type
* @return entity ref
*/
public static <T> Ref<T> idToRef(Class<T> entity, Long id) {
if (id == null) {
return null;
} else {
return Ref.create(idToKey(entity, id));
}
}
/**
* Null safe factory for refs from keys
* @param key key to convert to ref
* @param <T> key type
* @return entity ref
*/
public static <T> Ref<T> keyToRef(Key<T> key) {
if (key == null) {
return null;
} else {
return Ref.create(key);
}
}
/**
* Null safe load of given Ref
* @param ref the ref to load
* @param <T> entity type
* @return loaded entity
*/
public static <T> T loadRef(Ref<T> ref) {
if (ref == null) {
return null;
} else {
return ref.get();
}
}
/**
* Null safe load of given Key
* @param key the entity key to load
* @param <T> entity type
* @return loaded entity
*/
public static <T> T loadKey(Key<T> key) {
return loadRef(keyToRef(key));
}
/**
* Loads all not null refs from given collection
* @param ref refs to load
* @param <T> entity type
* @return list of hydrated entities instead of refs
*/
public static <T> List<T> loadRefs(Collection<Ref<T>> ref) {
if (ref == null) {
return Lists.newArrayList();
}
final ImmutableList<T> hydrated = FluentIterable.from(ref).transform(new Function<Ref<T>, T>() {
@Override
public T apply(final Ref<T> ref) {
return loadRef(ref);
}
}).toList();
return Lists.newArrayList(hydrated);
}
/**
* Transforms given ids to keys of given entity
* @param entityClass the class of the entity
* @param ids entity ids
* @param <T> entity type
* @return All not null ids converted to keys. Never null and no nulls inside the collection.
*/
public static <T> List<Key<T>> idsToKeys(final Class<T> entityClass, Collection<Long> ids) {
if (ids == null) return Lists.newArrayList();
return FluentIterable.from(ids).filter(Predicates.notNull()).transform(new Function<Long, Key<T>>() {
@Override
public Key<T> apply(Long id) {
return idToKey(entityClass, id);
}
}).toList();
}
public static <T> Function<? super Ref<T>, Key<T>> refToKeyTransformer() {
return new Function<Ref<T>, Key<T>>() {
@Override
public Key<T> apply(Ref<T> ref) {
return refToKey(ref);
}
};
}
public static void assertTransaction(Objectify ofy) {
if (ofy.getTransaction() == null) throw new IllegalStateException("No transaction");
if (!ofy.getTransaction().isActive()) throw new IllegalStateException("Transaction is not active!");
}
/**
* Returns list consisting of string formatted dates between given 2 dates.
* The index will always include the starting and ending date. The dates are formatted as <code>yyyyMMdd</code>.
* Returns empty index, if one of the dates is null or ending date is before starting date.
* @param start starting date to count index from
* @param end ending date to count index to
* @return date index for all days between given 2 dates
*/
public static List<String> indexPeriodDays(final DateTime start, final DateTime end) {
if (start == null || end == null || start.isAfter(end)) return Lists.newArrayList();
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
final ArrayList<String> result = Lists.newArrayList();
final DateTime truncatedStart = start.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
final DateTime truncatedEnd = end.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
DateTime current = truncatedStart;
while (current.isBefore(truncatedEnd)) {
result.add(current.toString(formatter));
current = current.plusDays(1);
}
result.add(truncatedEnd.toString(formatter));
return result;
}
} |
package io.github.data4all.view;
import io.github.data4all.logger.Log;
import io.github.data4all.model.drawing.DrawingMotion;
import io.github.data4all.model.drawing.MotionInterpreter;
import io.github.data4all.model.drawing.WayMotionInterpreter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* @author tbrose
*
*/
public class TouchView extends View {
private List<DrawingMotion> motions = new ArrayList<DrawingMotion>();
private DrawingMotion currentMotion;
private MotionInterpreter<Void> interpreter;
public TouchView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TouchView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TouchView(Context context) {
super(context);
}
public void setInterpreter(MotionInterpreter<Void> interpreter) {
this.interpreter = interpreter;
}
public MotionInterpreter<Void> getInterpreter() {
return interpreter;
}
/**
* Remove all recorded DrawingMotions from this TouchView
*/
public void clearMotions() {
motions.clear();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
interpreter = new WayMotionInterpreter();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawARGB(0, 0, 0, 0);
interpreter.draw(canvas, motions);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
currentMotion = new DrawingMotion();
motions.add(currentMotion);
handleMotion(event, "end");
break;
case MotionEvent.ACTION_UP:
handleMotion(event, "start");
break;
case MotionEvent.ACTION_MOVE:
handleMotion(event, "move");
break;
}
return true;
}
/**
* Handles the given motion:<br/>
* Add the point to the current motion<br/>
* Logs the motion<br/>
* Causes the view to redraw itself afterwards
*
* @param event
* The touch event
* @param action
* the named action which is in progress
*/
private void handleMotion(MotionEvent event, String action) {
currentMotion.addPoint(event.getX(), event.getY());
Log.d(this.getClass().getSimpleName(),
"Motion " + action + ": " + currentMotion.getPathSize()
+ ", point: " + currentMotion.isPoint());
postInvalidate();
}
} |
package kuleuven.group2.data;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* A class that has access to all tests (Test) and tested methods (TestedMethod)
* for access by updaters and users.
*
* @author Vital D'haveloose
*/
public class TestDatabase {
protected Set<Test> tests = Collections.synchronizedSet(new HashSet<Test>());
protected Set<TestedMethod> methods = Collections.synchronizedSet(new HashSet<TestedMethod>());
// LAST FAILURE FIRST, FREQUENT FAILURE FIRST
// TODO: methodes implementeren voor TestResultUpdater
// DISTINCT FAILURE FIRST
public void addMethodTestLink(Test currentRunningTest, TestedMethod enteredMethod) {
enteredMethod.addTest(currentRunningTest);
methods.add(enteredMethod);
}
public void printMethodLinks() {
Set<Test> tests;
for(TestedMethod method : methods) {
System.out.println(method);
tests = new HashSet<Test>(method.getTests());
for(Test test : tests) {
System.out.println(test);
}
}
}
// CHANGED CODE FIRST
// TODO: methodes implementeren voor LastChangeUpdater
// ACCESS
public Method getMethod(String className, String methodSignature) {
// TODO: implementeren
return null;
}
} |
package logbook.internal.gui;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.WindowEvent;
import logbook.bean.BattleLog;
import logbook.bean.BattleResult;
import logbook.bean.BattleTypes;
import logbook.bean.BattleTypes.AirBaseAttack;
import logbook.bean.BattleTypes.CombinedType;
import logbook.bean.BattleTypes.IAirBaseAttack;
import logbook.bean.BattleTypes.IAirbattle;
import logbook.bean.BattleTypes.IFormation;
import logbook.bean.BattleTypes.IKouku;
import logbook.bean.BattleTypes.ILdAirbattle;
import logbook.bean.BattleTypes.ILdShooting;
import logbook.bean.BattleTypes.IMidnightBattle;
import logbook.bean.BattleTypes.INSupport;
import logbook.bean.BattleTypes.INightToDayBattle;
import logbook.bean.BattleTypes.ISortieHougeki;
import logbook.bean.BattleTypes.ISupport;
import logbook.bean.BattleTypes.Kouku;
import logbook.bean.BattleTypes.Stage1;
import logbook.bean.BattleTypes.Stage2;
import logbook.bean.BattleTypes.SupportAiratack;
import logbook.bean.BattleTypes.SupportInfo;
import logbook.bean.CombinedBattleEachBattle;
import logbook.bean.MapStartNext;
import logbook.bean.Ship;
import logbook.bean.SlotItem;
import logbook.bean.SlotitemMst;
import logbook.bean.SlotitemMstCollection;
import logbook.internal.Items;
import logbook.internal.PhaseState;
import logbook.internal.Rank;
import logbook.internal.Ships;
import lombok.Getter;
public class BattleDetail extends WindowController {
private BattleLog log;
private MapStartNext last;
private CombinedType combinedType;
private Map<Integer, List<Ship>> deckMap;
private Map<Integer, SlotItem> itemMap;
private Set<Integer> escape;
private IFormation battle;
private IMidnightBattle midnight;
private BattleResult result;
@FXML
private VBox detail;
@FXML
private VBox phase;
@FXML
private Label mapcell;
@FXML
private Label intercept;
@FXML
private Label fFormation;
@FXML
private Label eFormation;
@FXML
private Label seiku;
@FXML
private Label dispSeiku;
@FXML
private ImageView fTouchPlaneImage;
@FXML
private Label fTouchPlane;
@FXML
private ImageView eTouchPlaneImage;
@FXML
private Label eTouchPlane;
@FXML
private Label tykuCI;
@FXML
private Label judge;
@FXML
private Label baseExp;
@FXML
private Label shipExp;
@FXML
private Label exp;
private Timeline timeline = new Timeline();
private int hashCode;
/**
*
*
* @param supplier
*/
void setInterval(Supplier<BattleLog> supplier) {
this.timeline.setCycleCount(Animation.INDEFINITE);
this.timeline.getKeyFrames().add(new KeyFrame(javafx.util.Duration.millis(1000),
e -> this.setData(supplier.get())));
this.timeline.play();
}
/**
*
*
* @param log
*/
void setData(BattleLog log) {
if (log != null && log.getBattle() != null) {
this.log = log;
}
if (this.log != null) {
MapStartNext last = this.log.getNext().get(this.log.getNext().size() - 1);
CombinedType combinedType = this.log.getCombinedType();
Map<Integer, List<Ship>> deckMap = this.log.getDeckMap();
Map<Integer, SlotItem> itemMap = this.log.getItemMap();
IFormation battle = this.log.getBattle();
IMidnightBattle midnight = this.log.getMidnight();
Set<Integer> escape = this.log.getEscape();
BattleResult result = this.log.getResult();
this.setData(last, combinedType, deckMap, escape, itemMap, battle, midnight, result);
}
}
/**
*
* @param last /
* @param combinedType
* @param deckMap
* @param escape ID
* @param itemMap
* @param battle
* @param midnight
* @param result
*/
void setData(MapStartNext last, CombinedType combinedType, Map<Integer, List<Ship>> deckMap, Set<Integer> escape,
Map<Integer, SlotItem> itemMap, IFormation battle, IMidnightBattle midnight, BattleResult result) {
int hashCode = Objects.hash(last, battle, midnight, result);
if (this.hashCode == hashCode) {
return;
}
this.hashCode = hashCode;
this.last = last;
this.combinedType = combinedType;
this.deckMap = deckMap;
this.itemMap = itemMap;
this.escape = escape;
this.battle = battle;
this.midnight = midnight;
this.result = result;
this.update();
}
/**
*
*
* @param event ActionEvent
*/
@FXML
void storeImageAction(ActionEvent event) {
Control source = null;
if (event.getSource() instanceof Control) {
source = (Control) event.getSource();
}
if (source != null) {
source.setVisible(false);
}
Tools.Conrtols.storeSnapshot(this.detail, "", this.getWindow());
if (source != null) {
source.setVisible(true);
}
}
private void update() {
this.setInfo();
this.setPhase();
}
private void setInfo() {
PhaseState ps = new PhaseState(this.combinedType, this.battle, this.deckMap, this.itemMap, this.escape);
boolean boss = this.last.getNo().equals(this.last.getBosscellNo()) || this.last.getEventId() == 5;
this.mapcell.setText(this.last.getMapareaId()
+ "-" + this.last.getMapinfoNo()
+ "-" + this.last.getNo()
+ (boss ? "()" : ""));
this.intercept.setText(BattleTypes.Intercept.toIntercept(this.battle.getFormation().get(2)).toString());
this.fFormation.setText(BattleTypes.Formation.toFormation(this.battle.getFormation().get(0)).toString());
this.eFormation.setText(BattleTypes.Formation.toFormation(this.battle.getFormation().get(1)).toString());
if (this.battle instanceof CombinedBattleEachBattle) {
int friend = ps.getAfterFriend().stream()
.filter(Objects::nonNull)
.mapToInt(Ships::airSuperiority)
.sum();
int friendCombined = ps.getAfterFriendCombined().stream()
.filter(Objects::nonNull)
.mapToInt(Ships::airSuperiority)
.sum();
this.seiku.setText((friend + friendCombined) + "(" + friend + "+" + friendCombined + ")");
} else {
this.seiku.setText(Integer.toString(ps.getAfterFriend().stream()
.filter(Objects::nonNull)
.mapToInt(Ships::airSuperiority)
.sum()));
}
this.dispSeiku.setText("");
this.dispSeiku.getStyleClass().removeIf(n -> n.startsWith("dispseiku"));
this.fTouchPlaneImage.setImage(null);
this.fTouchPlaneImage.setFitWidth(0);
this.fTouchPlaneImage.setFitHeight(0);
this.fTouchPlane.setText("");
this.eTouchPlaneImage.setImage(null);
this.eTouchPlaneImage.setFitWidth(0);
this.eTouchPlaneImage.setFitHeight(0);
this.eTouchPlane.setText("");
this.tykuCI.setText("");
if (this.battle instanceof IKouku) {
Kouku kouku = ((IKouku) this.battle).getKouku();
if (kouku != null) {
Stage1 stage1 = kouku.getStage1();
Stage2 stage2 = kouku.getStage2();
if (stage1 != null) {
Map<Integer, SlotitemMst> slotitemMst = SlotitemMstCollection.get()
.getSlotitemMap();
this.dispSeiku.setText(BattleTypes.DispSeiku.toDispSeiku(stage1.getDispSeiku()).toString());
this.dispSeiku.getStyleClass().add("dispseiku" + stage1.getDispSeiku());
SlotitemMst fTouchPlaneItem = slotitemMst.get(stage1.getTouchPlane().get(0));
if (fTouchPlaneItem != null) {
Image image = Items.itemImage(fTouchPlaneItem);
if (image != null) {
this.fTouchPlaneImage.setImage(image);
this.fTouchPlaneImage.setFitWidth(24);
this.fTouchPlaneImage.setFitHeight(24);
}
this.fTouchPlane.setText(fTouchPlaneItem.getName()
+ "(+" + (int) (Ships.touchPlaneAttackCompensation(fTouchPlaneItem) * 100) + "%)");
} else {
this.fTouchPlaneImage.setFitWidth(0);
this.fTouchPlaneImage.setFitHeight(0);
this.fTouchPlane.setText("");
}
SlotitemMst eTouchPlaneItem = slotitemMst.get(stage1.getTouchPlane().get(1));
if (eTouchPlaneItem != null) {
Image image = Items.itemImage(eTouchPlaneItem);
if (image != null) {
this.eTouchPlaneImage.setImage(image);
this.eTouchPlaneImage.setFitWidth(24);
this.eTouchPlaneImage.setFitHeight(24);
}
this.eTouchPlane.setText(eTouchPlaneItem.getName()
+ "(+" + (int) (Ships.touchPlaneAttackCompensation(eTouchPlaneItem) * 100) + "%)");
} else {
this.eTouchPlaneImage.setFitWidth(0);
this.eTouchPlaneImage.setFitHeight(0);
this.eTouchPlane.setText("");
}
}
if (stage2 != null) {
if (stage2.getAirFire() != null && stage2.getAirFire().getIdx() != null) {
int idx = stage2.getAirFire().getIdx();
Ship ship;
if (idx < 6) {
ship = ps.getAfterFriend().get(idx);
} else {
ship = ps.getAfterFriendCombined().get(idx - 6);
}
this.tykuCI.setText(Ships.toName(ship)
+ " (" + stage2.getAirFire().getKind() + ")");
}
}
}
}
}
private void setPhase() {
PhaseState ps = new PhaseState(this.combinedType, this.battle, this.deckMap, this.itemMap, this.escape);
Judge judge = new Judge();
judge.setBefore(ps);
List<Node> phases = this.phase.getChildren();
phases.clear();
BattleDetailPhase phaseBeforePane = new BattleDetailPhase(ps);
phaseBeforePane.setText("");
phases.add(phaseBeforePane);
if (!(this.battle instanceof INightToDayBattle)) {
this.airBaseInjectionAttack(ps, phases);
this.injectionKouku(ps, phases);
this.airBaseAttack(ps, phases);
this.kouku(ps, phases);
this.support(ps, phases);
this.sortieHougeki(ps, phases);
this.airbattle(ps, phases);
this.nSupport(ps, phases);
this.friendlyHougeki(ps, phases);
this.midnightBattle(ps, phases);
this.midnight(ps, phases);
} else {
this.nSupport(ps, phases);
this.friendlyHougeki(ps, phases);
this.midnightBattle(ps, phases);
this.airBaseInjectionAttack(ps, phases);
this.injectionKouku(ps, phases);
this.airBaseAttack(ps, phases);
this.kouku(ps, phases);
this.support(ps, phases);
this.sortieHougeki(ps, phases);
}
judge.setAfter(ps, this.battle);
this.judge.setText(String.valueOf(judge.getRank())
+ "(:" + (int) judge.getFriendDamageRatio()
+ "/:" + (int) judge.getEnemyDamageRatio() + ")");
if (this.result != null) {
this.baseExp.setText(String.valueOf(this.result.getGetBaseExp()));
this.shipExp.setText(String.valueOf(this.result.getGetShipExp().stream().mapToInt(Integer::intValue).sum()
+ Optional.ofNullable(this.result.getGetShipExpCombined())
.map(v -> v.stream().mapToInt(Integer::intValue).sum()).orElse(0)));
this.exp.setText(this.result.getGetExp()
+ "(" + BigDecimal.valueOf(this.result.getGetExp())
.divide(BigDecimal.valueOf(1428.571), 3, RoundingMode.FLOOR)
.toPlainString()
+ ")");
} else {
this.baseExp.setText("?");
this.shipExp.setText("?");
this.exp.setText("?");
}
((BattleDetailPhase) phases.get(phases.size() - 1)).setExpanded(true);
}
/**
* ()
* @param ps
* @param phases
*/
private void airBaseInjectionAttack(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IAirBaseAttack) {
if (((IAirBaseAttack) this.battle).getAirBaseInjection() != null) {
ps.applyAirBaseInject((IAirBaseAttack) this.battle);
List<Node> stage = new ArrayList<>();
AirBaseAttack airBaseAttack = ((IAirBaseAttack) this.battle).getAirBaseInjection();
if (airBaseAttack.getStage1() != null) {
Stage1 stage1 = airBaseAttack.getStage1();
stage.add(new BattleDetailPhaseStage1(stage1, ""));
}
if (airBaseAttack.getStage2() != null) {
Stage2 stage2 = airBaseAttack.getStage2();
stage.add(new BattleDetailPhaseStage2(stage2, ""));
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane.setText("()");
phasePane.setExpanded(false);
phases.add(phasePane);
}
}
}
/**
* ()
* @param ps
* @param phases
*/
private void injectionKouku(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IKouku) {
if (((IKouku) this.battle).getInjectionKouku() != null) {
ps.applyInjectionKouku((IKouku) this.battle);
List<Node> stage = new ArrayList<>();
Kouku kouku = ((IKouku) this.battle).getInjectionKouku();
if (kouku.getStage1() != null) {
Stage1 stage1 = kouku.getStage1();
stage.add(new BattleDetailPhaseStage1(stage1, ""));
}
if (kouku.getStage2() != null) {
Stage2 stage2 = kouku.getStage2();
stage.add(new BattleDetailPhaseStage2(stage2, ""));
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane = new BattleDetailPhase(ps);
phasePane.setText("()");
phasePane.setExpanded(false);
phases.add(phasePane);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void airBaseAttack(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IAirBaseAttack) {
if (((IAirBaseAttack) this.battle).getAirBaseAttack() != null) {
ps.applyAirBaseAttack((IAirBaseAttack) this.battle);
List<Node> stage = new ArrayList<>();
for (AirBaseAttack airBaseAttack : ((IAirBaseAttack) this.battle).getAirBaseAttack()) {
if (airBaseAttack.getStage1() != null) {
stage.add(new BattleDetailPhaseStage1(airBaseAttack.getStage1(), ""));
}
if (airBaseAttack.getStage2() != null) {
stage.add(new BattleDetailPhaseStage2(airBaseAttack.getStage2(), ""));
}
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void kouku(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IKouku) {
if (((IKouku) this.battle).getKouku() != null) {
ps.applyKouku((IKouku) this.battle);
List<Node> stage = new ArrayList<>();
Kouku kouku = ((IKouku) this.battle).getKouku();
if (kouku.getStage1() != null) {
Stage1 stage1 = kouku.getStage1();
stage.add(new BattleDetailPhaseStage1(stage1, ""));
}
if (kouku.getStage2() != null) {
Stage2 stage2 = kouku.getStage2();
stage.add(new BattleDetailPhaseStage2(stage2, ""));
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void support(PhaseState ps, List<Node> phases) {
if (this.battle instanceof ISupport) {
SupportInfo support = ((ISupport) this.battle).getSupportInfo();
if (support != null) {
ps.applySupport((ISupport) this.battle);
this.setSupportPhase(ps, phases, support);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void sortieHougeki(PhaseState ps, List<Node> phases) {
if (this.battle instanceof ISortieHougeki) {
ps.applySortieHougeki((ISortieHougeki) this.battle);
BattleDetailPhase phasePane = new BattleDetailPhase(ps);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
ps.getAttackDetails().clear();
}
/**
*
* @param ps
* @param phases
*/
private void airbattle(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IAirbattle) {
if (((IAirbattle) this.battle).getKouku2() != null) {
ps.applyAirbattle((IAirbattle) this.battle);
List<Node> stage = new ArrayList<>();
Kouku kouku = ((IAirbattle) this.battle).getKouku2();
if (kouku.getStage1() != null) {
Stage1 stage1 = kouku.getStage1();
stage.add(new BattleDetailPhaseStage1(stage1, ""));
}
if (kouku.getStage2() != null) {
Stage2 stage2 = kouku.getStage2();
stage.add(new BattleDetailPhaseStage2(stage2, ""));
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void nSupport(PhaseState ps, List<Node> phases) {
if (this.battle instanceof INSupport) {
SupportInfo support = ((INSupport) this.battle).getNSupportInfo();
if (support != null) {
ps.applySupport((INSupport) this.battle);
this.setSupportPhase(ps, phases, support);
}
}
}
/**
*
* @param ps
* @param phases
*/
private void midnightBattle(PhaseState ps, List<Node> phases) {
if (this.battle instanceof IMidnightBattle) {
ps.applyMidnightBattle((IMidnightBattle) this.battle);
BattleDetailPhase phasePane = new BattleDetailPhase(ps);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
if (this.battle instanceof INightToDayBattle) {
ps.applyMidnightBattle((INightToDayBattle) this.battle);
BattleDetailPhase phasePane = new BattleDetailPhase(ps);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
ps.getAttackDetails().clear();
}
/**
* ()
* @param ps
* @param phases
*/
private void friendlyHougeki(PhaseState ps, List<Node> phases) {
if (this.midnight != null && this.midnight.getFriendlyInfo() != null) {
ps.applyFriendlyHougeki(this.midnight);
BattleDetailPhase phasePane = new BattleDetailPhase(ps, null, true);
phasePane.setText("()");
phasePane.setExpanded(false);
phases.add(phasePane);
}
ps.getAttackDetails().clear();
}
/**
*
* @param ps
* @param phases
*/
private void midnight(PhaseState ps, List<Node> phases) {
if (this.midnight != null) {
ps.applyMidnightBattle(this.midnight);
BattleDetailPhase phasePane = new BattleDetailPhase(ps);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
ps.getAttackDetails().clear();
}
/**
*
* @param ps
* @param phases
* @param support
*/
private void setSupportPhase(PhaseState ps, List<Node> phases, SupportInfo support) {
SupportAiratack supportAir = support.getSupportAiratack();
List<Node> stage = new ArrayList<>();
if (supportAir != null) {
if (supportAir.getStage1() != null) {
Stage1 stage1 = supportAir.getStage1();
stage.add(new BattleDetailPhaseStage1(stage1, ""));
}
if (supportAir.getStage2() != null) {
Stage2 stage2 = supportAir.getStage2();
stage.add(new BattleDetailPhaseStage2(stage2, ""));
}
}
BattleDetailPhase phasePane = new BattleDetailPhase(ps, stage);
phasePane.setText("");
phasePane.setExpanded(false);
phases.add(phasePane);
}
/**
*
*
* @param e WindowEvent
*/
@Override
protected void onWindowHidden(WindowEvent e) {
if (this.timeline != null) {
this.timeline.stop();
}
}
private static class Judge {
private double beforeFriendTotalHp;
private int beforeFriendAliveCount;
private double beforeEnemyTotalHp;
private int beforeEnemyAliveCount;
private double afterFriendTotalHp;
private int afterFriendAliveCount;
private double afterEnemyTotalHp;
private int afterEnemyAliveCount;
@Getter
private double friendDamageRatio;
@Getter
private double enemyDamageRatio;
@Getter
private Rank rank;
/**
*
* @param ps
*/
public void setBefore(PhaseState ps) {
this.beforeFriendTotalHp = ps.friendTotalHp();
this.beforeFriendAliveCount = ps.friendAliveCount();
this.beforeEnemyTotalHp = ps.enemyTotalHp();
this.beforeEnemyAliveCount = ps.enemydAliveCount();
}
/**
*
* @param ps
*/
public void setAfter(PhaseState ps, IFormation battle) {
this.afterFriendTotalHp = ps.friendTotalHp();
this.afterFriendAliveCount = ps.friendAliveCount();
this.afterEnemyTotalHp = ps.enemyTotalHp();
this.afterEnemyAliveCount = ps.enemydAliveCount();
this.friendDamageRatio = this.damageRatio(this.beforeFriendTotalHp, this.afterFriendTotalHp);
this.enemyDamageRatio = this.damageRatio(this.beforeEnemyTotalHp, this.afterEnemyTotalHp);
this.rank = this.judge(ps, battle);
}
/**
*
* @param ps
* @param battle
* @return
*/
private Rank judge(PhaseState ps, IFormation battle) {
if (battle instanceof ILdAirbattle || battle instanceof ILdShooting) {
if (this.friendDamageRatio <= 0) {
return Rank.S;
}
if (this.friendDamageRatio < 10) {
return Rank.A;
}
if (this.friendDamageRatio < 20) {
return Rank.B;
}
if (this.friendDamageRatio < 50) {
return Rank.C;
}
if (this.friendDamageRatio < 80) {
return Rank.D;
}
return Rank.E;
} else {
if (this.beforeFriendAliveCount == this.afterFriendAliveCount) {
if (this.afterEnemyAliveCount == 0) {
if (this.afterFriendTotalHp >= this.beforeFriendTotalHp) {
return Rank.S;
} else {
return Rank.S;
}
} else if (this.beforeEnemyAliveCount > 1
&& (this.beforeEnemyAliveCount
- this.afterEnemyAliveCount) >= (int) (this.beforeEnemyAliveCount * 0.7D)) {
return Rank.A;
}
}
if (Ships.isLost(ps.getAfterEnemy().get(0))
&& (this.beforeFriendAliveCount - this.afterFriendAliveCount) < (this.beforeEnemyAliveCount
- this.afterEnemyAliveCount)) {
return Rank.B;
}
if (this.beforeFriendAliveCount == 1 && Ships.isBadlyDamage(ps.getAfterFriend().get(0))) {
return Rank.D;
}
if (this.enemyDamageRatio > 2.5 * this.friendDamageRatio) {
return Rank.B;
}
if (this.enemyDamageRatio > 0.9 * this.friendDamageRatio) {
return Rank.C;
}
if (this.beforeFriendAliveCount > this.afterFriendAliveCount && this.afterFriendAliveCount == 1) {
return Rank.E;
}
return Rank.D;
}
}
/**
*
* @param before HP
* @param after HP
* @return
*/
private double damageRatio(double before, double after) {
return (int) ((before - after) / before * 100);
}
}
} |
package mil.dds.anet.database;
import java.util.Arrays;
import java.util.List;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Location;
import mil.dds.anet.beans.lists.AnetBeanList;
import mil.dds.anet.beans.search.LocationSearchQuery;
import mil.dds.anet.database.mappers.LocationMapper;
import mil.dds.anet.utils.DaoUtils;
import ru.vyarus.guicey.jdbi3.tx.InTransaction;
public class LocationDao extends AnetBaseDao<Location, LocationSearchQuery> {
public static final String TABLE_NAME = "locations";
@Override
public Location getByUuid(String uuid) {
return getByIds(Arrays.asList(uuid)).get(0);
}
static class SelfIdBatcher extends IdBatcher<Location> {
private static final String sql =
"/* batch.getLocationsByUuids */ SELECT * from locations where uuid IN ( <uuids> )";
public SelfIdBatcher() {
super(sql, "uuids", new LocationMapper());
}
}
@Override
public List<Location> getByIds(List<String> uuids) {
final IdBatcher<Location> idBatcher =
AnetObjectEngine.getInstance().getInjector().getInstance(SelfIdBatcher.class);
return idBatcher.getByIds(uuids);
}
@Override
public Location insertInternal(Location l) {
getDbHandle().createUpdate(
"/* locationInsert */ INSERT INTO locations (uuid, name, status, lat, lng, \"createdAt\", "
+ "\"updatedAt\", \"customFields\") VALUES (:uuid, :name, :status, :lat, :lng, :createdAt, "
+ ":updatedAt, :customFields)")
.bindBean(l).bind("createdAt", DaoUtils.asLocalDateTime(l.getCreatedAt()))
.bind("updatedAt", DaoUtils.asLocalDateTime(l.getUpdatedAt()))
.bind("status", DaoUtils.getEnumId(l.getStatus())).execute();
return l;
}
@Override
public int updateInternal(Location l) {
return getDbHandle().createUpdate("/* updateLocation */ UPDATE locations "
+ "SET name = :name, status = :status, lat = :lat, lng = :lng, \"updatedAt\" = :updatedAt, "
+ "\"customFields\" = :customFields WHERE uuid = :uuid").bindBean(l)
.bind("updatedAt", DaoUtils.asLocalDateTime(l.getUpdatedAt()))
.bind("status", DaoUtils.getEnumId(l.getStatus())).execute();
}
@Override
public AnetBeanList<Location> search(LocationSearchQuery query) {
return AnetObjectEngine.getInstance().getSearcher().getLocationSearcher().runSearch(query);
}
@InTransaction
public int mergeLocations(Location loserLocation, Location winnerLocation) {
final String loserLocationUuid = loserLocation.getUuid();
final String winnerLocationUuid = winnerLocation.getUuid();
// Update Locations
getDbHandle().createUpdate("/* updateMergeLocations */ UPDATE locations "
+ "SET name = :name, status = :status, lat = :lat, lng = :lng, \"updatedAt\" = :updatedAt, "
+ "\"customFields\" = :customFields WHERE uuid = :uuid")
.bind("name", winnerLocation.getName())
.bind("status", DaoUtils.getEnumId(winnerLocation.getStatus()))
.bind("lat", winnerLocation.getLat()).bind("lng", winnerLocation.getLng())
.bind("updatedAt", DaoUtils.asLocalDateTime(winnerLocation.getUpdatedAt()))
.bind("customFields", winnerLocation.getCustomFields()).bind("uuid", winnerLocationUuid)
.execute();
// Update reports location
updateForMerge("reports", "locationUuid", winnerLocationUuid, loserLocationUuid);
// update positions location
updateForMerge("positions", "locationUuid", winnerLocationUuid, loserLocationUuid);
// update noteRelatedObjects location
updateM2mForMerge("noteRelatedObjects", "noteUuid", "relatedObjectUuid", winnerLocationUuid,
loserLocationUuid);
// finally delete the location!
return deleteForMerge("locations", "uuid", loserLocationUuid);
}
// TODO: Don't delete any location if any references exist.
} |
package net.imagej.ops.coloc;
import java.util.Random;
import net.imglib2.AbstractInterval;
import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.Localizable;
import net.imglib2.Point;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.Sampler;
import net.imglib2.View;
import net.imglib2.util.IntervalIndexer;
import net.imglib2.view.Views;
/**
* Randomly shuffles an image blockwise.
*
* @author Curtis Rueden
* @author Ellen T Arena
* @param <T> Type of image to be shuffled.
*/
public class ShuffledView<T> extends AbstractInterval implements
RandomAccessibleInterval<T>, View
{
private Random rng;
private final RandomAccessibleInterval<T> image;
private int[] blockIndices;
private int[] blockSize;
private int[] blockDims;
public ShuffledView(final RandomAccessibleInterval<T> image,
final int[] blockSize, final long seed)
{
this(image, blockSize, null, seed);
}
private ShuffledView(final RandomAccessibleInterval<T> image,
final int[] blockSize, final int[] blockIndices, final long seed)
{
super(image); // uses same bounds as the input image
this.image = image;
this.blockSize = blockSize;
// compute some info about our block sizes
final int numDims = image.numDimensions();
blockDims = new int[numDims];
long totalBlocks = 1;
for (int d = 0; d < numDims; d++) {
final long blockDim = image.dimension(d) / blockSize[d];
if (blockDim * blockSize[d] != image.dimension(d)) {
throw new IllegalArgumentException("Image dimension
" is not evenly divisible by block size:" + blockSize[d] +
"; Please call a ShuffledView.cropAt method to adjust the input.");
}
if (blockDim > Integer.MAX_VALUE) {
throw new UnsupportedOperationException("Block dimension
" is too large: " + blockDim);
}
blockDims[d] = (int) blockDim;
totalBlocks *= blockDims[d];
}
if (totalBlocks > Integer.MAX_VALUE) {
throw new UnsupportedOperationException("Too many blocks: " +
totalBlocks);
}
if (blockIndices == null) {
this.blockIndices = createBlocks((int) totalBlocks);
rng = new Random(seed);
shuffleBlocks();
}
else {
this.blockIndices = blockIndices;
}
}
private static int[] createBlocks(final int blockCount) {
// generate the identity mapping of indices
final int[] blocks = new int[blockCount];
for (int b = 0; b < blockCount; b++)
blocks[b] = b;
return blocks;
}
public void shuffleBlocks() {
if (rng == null) {
throw new IllegalStateException("No seed provided. Cannot shuffle.");
}
ColocUtil.shuffle(blockIndices, rng);
}
@Override
public RandomAccess<T> randomAccess() {
return new ShuffledRandomAccess();
}
@Override
public RandomAccess<T> randomAccess(final Interval interval) {
return randomAccess(); // FIXME
}
private class ShuffledRandomAccess extends Point implements RandomAccess<T> {
private final RandomAccess<T> imageRA;
private final long[] blockPos;
private final long[] blockOffset;
private final long[] shuffledBlockPos;
public ShuffledRandomAccess() {
super(image.numDimensions());
imageRA = image.randomAccess();
blockPos = new long[position.length];
blockOffset = new long[position.length];
shuffledBlockPos = new long[position.length];
}
@Override
public T get() {
// Convert from image coordinates to block coordinates.
for (int d = 0; d < position.length; d++) {
blockPos[d] = position[d] / blockSize[d];
blockOffset[d] = position[d] % blockSize[d];
}
// Convert N-D block coordinates to 1D block index.
final int blockIndex = IntervalIndexer.positionToIndex(blockPos,
blockDims);
// Map block index to shuffled block index.
final int shuffledBlockIndex = blockIndices[blockIndex];
// Now convert our 1D shuffled block index back to N-D block
// coordinates.
IntervalIndexer.indexToPosition(shuffledBlockIndex, blockDims,
shuffledBlockPos);
// Finally, position the original image according to our shuffled
// position.
for (int d = 0; d < position.length; d++) {
final long pd = shuffledBlockPos[d] * blockSize[d] + blockOffset[d];
imageRA.setPosition(pd, d);
}
return imageRA.get();
}
@Override
public Sampler<T> copy() {
throw new UnsupportedOperationException();
}
@Override
public RandomAccess<T> copyRandomAccess() {
throw new UnsupportedOperationException();
}
}
public static <T> RandomAccessibleInterval<T> cropAtMin(
final RandomAccessibleInterval<T> image, final int[] blockSize)
{
return cropAt(image, blockSize, new Point(image.numDimensions()));
}
public static <T> RandomAccessibleInterval<T> cropAtMax(
final RandomAccessibleInterval<T> image, final int[] blockSize)
{
final long[] pos = new long[image.numDimensions()];
for (int d = 0; d < pos.length; d++) {
pos[d] = image.dimension(d) % blockSize[d];
}
return cropAt(image, blockSize, new Point(pos));
}
public static <T> RandomAccessibleInterval<T> cropAtCenter(
final RandomAccessibleInterval<T> image, final int[] blockSize)
{
final long[] pos = new long[image.numDimensions()];
for (int d = 0; d < pos.length; d++) {
pos[d] = (image.dimension(d) % blockSize[d]) / 2;
}
return cropAt(image, blockSize, new Point(pos));
}
private static <T> RandomAccessibleInterval<T> cropAt(
final RandomAccessibleInterval<T> image, final int[] blockSize,
final Localizable offset)
{
final int numDims = image.numDimensions();
final long[] minsize = new long[numDims * 2];
for (int d = 0; d < numDims; d++) {
minsize[d] = offset.getLongPosition(d);
final long shaveSize = image.dimension(d) % blockSize[d];
minsize[numDims + d] = image.dimension(d) - shaveSize;
}
return Views.interval(image, FinalInterval.createMinSize(minsize));
}
} |
package net.imagej.ops.math;
import java.util.Random;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.MathOps;
import net.imagej.ops.OpMethod;
import net.imglib2.IterableInterval;
import net.imglib2.IterableRealInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.img.basictypeaccess.array.DoubleArray;
import net.imglib2.img.planar.PlanarImg;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.real.DoubleType;
/**
* The math namespace contains arithmetic operations.
*
* @author Curtis Rueden
*/
public class MathNamespace extends AbstractNamespace {
// -- Math namespace ops --
@OpMethod(op = net.imagej.ops.MathOps.Abs.class)
public Object abs(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Abs.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAbs.class)
public int abs(final int a) {
final int result =
(Integer) ops()
.run(net.imagej.ops.math.PrimitiveMath.IntegerAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAbs.class)
public long abs(final long a) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAbs.class)
public float abs(final float a) {
final float result =
(Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAbs.class)
public double abs(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAbs.class)
public <I extends RealType<I>, O extends RealType<O>> O abs(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAbs.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Add.class)
public Object add(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Add.class, args);
}
@OpMethod(ops = {
net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayByteImageP.class,
net.imagej.ops.arithmetic.add.AddConstantToArrayByteImage.class })
public ArrayImg<ByteType, ByteArray> add(
final ArrayImg<ByteType, ByteArray> image, final byte value)
{
@SuppressWarnings("unchecked")
final ArrayImg<ByteType, ByteArray> result =
(ArrayImg<ByteType, ByteArray>) ops().run(MathOps.Add.NAME, image, value);
return result;
}
@OpMethod(
ops = {
net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayDoubleImageP.class,
net.imagej.ops.arithmetic.add.AddConstantToArrayDoubleImage.class })
public
ArrayImg<DoubleType, DoubleArray> add(
final ArrayImg<DoubleType, DoubleArray> image, final double value)
{
@SuppressWarnings("unchecked")
final ArrayImg<DoubleType, DoubleArray> result =
(ArrayImg<DoubleType, DoubleArray>) ops().run(MathOps.Add.NAME, image,
value);
return result;
}
@OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.AddOp.class)
public Object add(final Object result, final Object a, final Object b) {
final Object result_op =
ops().run(net.imagej.ops.onthefly.ArithmeticOp.AddOp.class, result, a, b);
return result_op;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAdd.class)
public int add(final int a, final int b) {
final int result =
(Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAdd.class,
a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAdd.class)
public long add(final long a, final long b) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAdd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAdd.class)
public float add(final float a, final float b) {
final float result =
(Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAdd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAdd.class)
public double add(final double a, final double b) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAdd.class, a,
b);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAdd.class)
public <I extends RealType<I>, O extends RealType<O>> RealType<O> add(
final RealType<O> out, final RealType<I> in, final double constant)
{
@SuppressWarnings("unchecked")
final RealType<O> result =
(RealType<O>) ops().run(net.imagej.ops.arithmetic.real.RealAdd.class,
out, in, constant);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class)
public
<T extends NumericType<T>> IterableInterval<T> add(
final IterableInterval<T> a, final RandomAccessibleInterval<T> b)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops()
.run(
net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class,
a, b);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class)
public PlanarImg<DoubleType, DoubleArray> add(
final PlanarImg<DoubleType, DoubleArray> image, final double value)
{
@SuppressWarnings("unchecked")
final PlanarImg<DoubleType, DoubleArray> result =
(PlanarImg<DoubleType, DoubleArray>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class,
image, value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class)
public <T extends NumericType<T>> IterableRealInterval<T> add(
final IterableRealInterval<T> image, final T value)
{
@SuppressWarnings("unchecked")
final IterableRealInterval<T> result =
(IterableRealInterval<T>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class, image,
value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class)
public <T extends NumericType<T>> T add(final T in, final T value) {
@SuppressWarnings("unchecked")
final T result =
(T) ops()
.run(net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, in,
value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class)
public <T extends NumericType<T>> T
add(final T out, final T in, final T value)
{
@SuppressWarnings("unchecked")
final T result =
(T) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, out, in,
value);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class)
public <T extends NumericType<T>> RandomAccessibleInterval<T> add(
final RandomAccessibleInterval<T> out, final IterableInterval<T> in,
final T value)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class, out,
in, value);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.AddNoise.class)
public Object addnoise(final Object... args) {
return ops().run(net.imagej.ops.MathOps.AddNoise.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAddNoise.class)
public <I extends RealType<I>, O extends RealType<O>> O addnoise(final O out,
final I in, final double rangeMin, final double rangeMax,
final double rangeStdDev, final Random rng)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAddNoise.class, out, in,
rangeMin, rangeMax, rangeStdDev, rng);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.And.class)
public Object and(final Object... args) {
return ops().run(net.imagej.ops.MathOps.And.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAnd.class)
public int and(final int a, final int b) {
final int result =
(Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAnd.class,
a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAnd.class)
public long and(final long a, final long b) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAnd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAndConstant.class)
public <I extends RealType<I>, O extends RealType<O>> O and(final O out,
final I in, final long constant)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAndConstant.class, out,
in, constant);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccos.class)
public Object arccos(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccos.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArccos.class)
public double arccos(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArccos.class,
a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccos.class)
public <I extends RealType<I>, O extends RealType<O>> O arccos(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccos.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccosh.class)
public Object arccosh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccosh.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccosh.class)
public <I extends RealType<I>, O extends RealType<O>> O arccosh(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccosh.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccot.class)
public Object arccot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccot.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arccoth.class)
public Object arccoth(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccoth.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arccsc.class)
public Object arccsc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccsc.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arccsch.class)
public Object arccsch(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccsch.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsec.class)
public Object arcsec(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsec.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsech.class)
public Object arcsech(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsech.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsin.class)
public Object arcsin(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsin.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsinh.class)
public Object arcsinh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsinh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arctan.class)
public Object arctan(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arctan.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Arctanh.class)
public Object arctanh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arctanh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Ceil.class)
public Object ceil(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Ceil.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Complement.class)
public Object complement(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Complement.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Copy.class)
public Object copy(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Copy.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Cos.class)
public Object cos(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cos.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Cosh.class)
public Object cosh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cosh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Cot.class)
public Object cot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cot.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Coth.class)
public Object coth(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Coth.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Csc.class)
public Object csc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Csc.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Csch.class)
public Object csch(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Csch.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.CubeRoot.class)
public Object cuberoot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.CubeRoot.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Divide.class)
public Object divide(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Divide.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Exp.class)
public Object exp(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Exp.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.ExpMinusOne.class)
public Object expminusone(final Object... args) {
return ops().run(net.imagej.ops.MathOps.ExpMinusOne.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Floor.class)
public Object floor(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Floor.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Gamma.class)
public Object gamma(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Gamma.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.GaussianRandom.class)
public Object gaussianrandom(final Object... args) {
return ops().run(net.imagej.ops.MathOps.GaussianRandom.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Invert.class)
public Object invert(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Invert.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.LeftShift.class)
public Object leftshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.LeftShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log.class)
public Object log(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log2.class)
public Object log2(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log2.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log10.class)
public Object log10(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log10.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.LogOnePlusX.class)
public Object logoneplusx(final Object... args) {
return ops().run(net.imagej.ops.MathOps.LogOnePlusX.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Max.class)
public Object max(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Max.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Min.class)
public Object min(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Min.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Multiply.class)
public Object multiply(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Multiply.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.NearestInt.class)
public Object nearestint(final Object... args) {
return ops().run(net.imagej.ops.MathOps.NearestInt.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Negate.class)
public Object negate(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Negate.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Or.class)
public Object or(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Or.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Power.class)
public Object power(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Power.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Reciprocal.class)
public Object reciprocal(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Reciprocal.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Remainder.class)
public Object remainder(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Remainder.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.RightShift.class)
public Object rightshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.RightShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Round.class)
public Object round(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Round.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sec.class)
public Object sec(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sec.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sech.class)
public Object sech(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sech.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Signum.class)
public Object signum(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Signum.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sin.class)
public Object sin(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sin.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sinc.class)
public Object sinc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sinc.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.SincPi.class)
public Object sincpi(final Object... args) {
return ops().run(net.imagej.ops.MathOps.SincPi.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sinh.class)
public Object sinh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sinh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sqr.class)
public Object sqr(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sqr.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sqrt.class)
public Object sqrt(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sqrt.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Step.class)
public Object step(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Step.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Subtract.class)
public Object subtract(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Subtract.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Tan.class)
public Object tan(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Tan.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Tanh.class)
public Object tanh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Tanh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Ulp.class)
public Object ulp(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Ulp.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.UniformRandom.class)
public Object uniformrandom(final Object... args) {
return ops().run(net.imagej.ops.MathOps.UniformRandom.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.UnsignedRightShift.class)
public Object unsignedrightshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.UnsignedRightShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Xor.class)
public Object xor(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Xor.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Zero.class)
public Object zero(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Zero.class, args);
}
// -- Named methods --
@Override
public String getName() {
return "math";
}
} |
package net.sf.jabref.gui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import net.sf.jabref.Globals;
import net.sf.jabref.gui.importer.fetcher.EntryFetchers;
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.logic.CustomEntryTypesManager;
import net.sf.jabref.logic.importer.FetcherException;
import net.sf.jabref.logic.importer.IdBasedFetcher;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.EntryTypes;
import net.sf.jabref.model.database.BibDatabaseContext;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.IEEETranEntryTypes;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.swingx.VerticalLayout;
/**
* Dialog that prompts the user to choose a type for an entry.
* Returns null if canceled.
*/
public class EntryTypeDialog extends JDialog implements ActionListener {
private static final Log LOGGER = LogFactory.getLog(EntryTypeDialog.class);
private EntryType type;
private SwingWorker<Optional<BibEntry>, Void> fetcherWorker = new FetcherWorker();
private JButton generateButton;
private JTextField idTextField;
private JComboBox<String> comboBox;
private final JabRefFrame frame;
private static final int COLUMN = 3;
private final boolean biblatexMode;
private final CancelAction cancelAction = new CancelAction();
private final BibDatabaseContext bibDatabaseContext;
static class TypeButton extends JButton implements Comparable<TypeButton> {
private final EntryType type;
TypeButton(String label, EntryType type) {
super(label);
this.type = type;
}
@Override
public int compareTo(TypeButton o) {
return type.getName().compareTo(o.type.getName());
}
public EntryType getType() {
return type;
}
}
public EntryTypeDialog(JabRefFrame frame) {
// modal dialog
super(frame, true);
this.frame = frame;
bibDatabaseContext = frame.getCurrentBasePanel().getBibDatabaseContext();
biblatexMode = bibDatabaseContext.isBiblatexMode();
setTitle(Localization.lang("Select entry type"));
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cancelAction.actionPerformed(null);
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(createCancelButtonBarPanel(), BorderLayout.SOUTH);
getContentPane().add(createEntryGroupsPanel(), BorderLayout.CENTER);
pack();
setResizable(false);
}
private JPanel createEntryGroupsPanel() {
JPanel panel = new JPanel();
panel.setLayout(new VerticalLayout());
if (biblatexMode) {
panel.add(createEntryGroupPanel("BibLateX", EntryTypes.getAllValues(bibDatabaseContext.getMode())));
} else {
panel.add(createEntryGroupPanel("BibTeX", BibtexEntryTypes.ALL));
panel.add(createEntryGroupPanel("IEEETran", IEEETranEntryTypes.ALL));
if (!CustomEntryTypesManager.ALL.isEmpty()) {
panel.add(createEntryGroupPanel(Localization.lang("Custom"), CustomEntryTypesManager.ALL));
}
}
panel.add(createIdFetcherPanel());
return panel;
}
private JPanel createCancelButtonBarPanel() {
JButton cancel = new JButton(Localization.lang("Cancel"));
cancel.addActionListener(this);
// Make ESC close dialog, equivalent to clicking Cancel.
cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
cancel.getActionMap().put("close", cancelAction);
JPanel buttons = new JPanel();
ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
bb.addGlue();
bb.addButton(cancel);
bb.addGlue();
return buttons;
}
private JPanel createEntryGroupPanel(String groupTitle, Collection<EntryType> entries) {
JPanel panel = new JPanel();
GridBagLayout bagLayout = new GridBagLayout();
panel.setLayout(bagLayout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(4, 4, 4, 4);
// column count
int col = 0;
for (EntryType entryType : entries) {
TypeButton entryButton = new TypeButton(entryType.getName(), entryType);
entryButton.addActionListener(this);
// Check if we should finish the row.
col++;
if (col == EntryTypeDialog.COLUMN) {
col = 0;
constraints.gridwidth = GridBagConstraints.REMAINDER;
} else {
constraints.gridwidth = 1;
}
bagLayout.setConstraints(entryButton, constraints);
panel.add(entryButton);
}
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), groupTitle));
return panel;
}
private JPanel createIdFetcherPanel() {
JLabel fetcherLabel = new JLabel(Localization.lang("ID type"));
JLabel idLabel = new JLabel(Localization.lang("ID"));
generateButton = new JButton(Localization.lang("Generate"));
idTextField = new JTextField("");
comboBox = new JComboBox<>();
EntryFetchers.getIdFetchers().forEach(fetcher -> comboBox.addItem(fetcher.getName()));
generateButton.addActionListener(action -> {
fetcherWorker.execute();
});
comboBox.addActionListener(e -> {
idTextField.requestFocus();
idTextField.selectAll();
});
idTextField.addActionListener(event -> fetcherWorker.execute());
JPanel jPanel = new JPanel();
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(4,4,4,4);
GridBagLayout layout = new GridBagLayout();
jPanel.setLayout(layout);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
jPanel.add(fetcherLabel, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 2;
jPanel.add(comboBox, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
jPanel.add(idLabel, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.weightx = 2;
jPanel.add(idTextField, constraints);
constraints.gridy = 2;
constraints.gridx = 0;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.NONE;
jPanel.add(generateButton, constraints);
jPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), Localization.lang("ID-based_entry_generator")));
SwingUtilities.invokeLater(() -> idTextField.requestFocus());
return jPanel;
}
private void stopFetching() {
if (fetcherWorker.getState() == SwingWorker.StateValue.STARTED) {
fetcherWorker.cancel(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof TypeButton) {
type = ((TypeButton) e.getSource()).getType();
}
stopFetching();
dispose();
}
public EntryType getChoice() {
return type;
}
class CancelAction extends AbstractAction {
public CancelAction() {
super("Cancel");
}
@Override
public void actionPerformed(ActionEvent e) {
stopFetching();
dispose();
}
}
private class FetcherWorker extends SwingWorker<Optional<BibEntry>, Void> {
private boolean fetcherException = false;
private String fetcherExceptionMessage = "";
private IdBasedFetcher fetcher = null;
private String searchID = "";
@Override
protected Optional<BibEntry> doInBackground() throws Exception {
Optional<BibEntry> bibEntry = Optional.empty();
SwingUtilities.invokeLater(() -> {
generateButton.setEnabled(false);
generateButton.setText(Localization.lang("Searching..."));
});
searchID = idTextField.getText().trim();
fetcher = EntryFetchers.getIdFetchers().get(comboBox.getSelectedIndex());
if (!searchID.isEmpty()) {
try {
bibEntry = fetcher.performSearchById(searchID);
} catch (FetcherException e) {
LOGGER.error(e.getMessage(), e);
fetcherException = true;
fetcherExceptionMessage = e.getMessage();
}
}
return bibEntry;
}
@Override
protected void done() {
try {
Optional<BibEntry> result = get();
if (result.isPresent()) {
frame.getCurrentBasePanel().insertEntry(result.get());
dispose();
} else if (searchID.trim().isEmpty()) {
JOptionPane.showMessageDialog(frame, Localization.lang("The given search ID was empty."), Localization.lang("Empty search ID"), JOptionPane.WARNING_MESSAGE);
} else if (!fetcherException) {
JOptionPane.showMessageDialog(frame, Localization.lang("Fetcher_'%0'_did_not_find_an_entry_for_id_'%1'.", fetcher.getName(), searchID)+ "\n" + fetcherExceptionMessage, Localization.lang("No files found."), JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame,
Localization.lang("Error while fetching from %0", fetcher.getName()) +"." + "\n" + fetcherExceptionMessage,
Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
}
fetcherWorker = new FetcherWorker();
SwingUtilities.invokeLater(() -> {
idTextField.requestFocus();
idTextField.selectAll();
generateButton.setText(Localization.lang("Generate"));
generateButton.setEnabled(true);
});
} catch (ExecutionException | InterruptedException e) {
LOGGER.error(String.format("Exception during fetching when using fetcher '%s' with entry id '%s'.", searchID, fetcher.getName()), e);
}
}
}
} |
package net.spy.memcached;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedSelectorException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.AuthThreadMonitor;
import net.spy.memcached.auth.PlainCallbackHandler;
import net.spy.memcached.compat.SpyThread;
import net.spy.memcached.internal.BulkFuture;
import net.spy.memcached.internal.BulkGetFuture;
import net.spy.memcached.internal.GetFuture;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.internal.SingleElementInfiniteIterator;
import net.spy.memcached.ops.CASOperationStatus;
import net.spy.memcached.ops.CancelledOperationStatus;
import net.spy.memcached.ops.ConcatenationType;
import net.spy.memcached.ops.DeleteOperation;
import net.spy.memcached.ops.GetAndTouchOperation;
import net.spy.memcached.ops.GetOperation;
import net.spy.memcached.ops.GetlOperation;
import net.spy.memcached.ops.GetsOperation;
import net.spy.memcached.ops.Mutator;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatsOperation;
import net.spy.memcached.ops.StoreType;
import net.spy.memcached.transcoders.TranscodeService;
import net.spy.memcached.transcoders.Transcoder;
import net.spy.memcached.vbucket.ConfigurationException;
import net.spy.memcached.vbucket.ConfigurationProvider;
import net.spy.memcached.vbucket.ConfigurationProviderHTTP;
import net.spy.memcached.vbucket.Reconfigurable;
import net.spy.memcached.vbucket.config.Bucket;
import net.spy.memcached.vbucket.config.Config;
import net.spy.memcached.vbucket.config.ConfigType;
* } catch (Exception e) { /* /
* // Since we don't need this, go ahead and cancel the operation.
* // This is not strictly necessary, but it'll save some work on
* // the server. It is okay to cancel it if running.
* f.cancel(true);
* // Do other timeout related stuff
* }
* </pre>
*/
public class MemcachedClient extends SpyThread
implements MemcachedClientIF, ConnectionObserver, Reconfigurable {
private volatile boolean running=true;
private volatile boolean shuttingDown=false;
private final long operationTimeout;
private final MemcachedConnection conn;
final OperationFactory opFact;
final Transcoder<Object> transcoder;
final TranscodeService tcService;
final AuthDescriptor authDescriptor;
private final AuthThreadMonitor authMonitor = new AuthThreadMonitor();
private volatile boolean reconfiguring = false;
private ConfigurationProvider configurationProvider;
/**
* Get a memcache client operating on the specified memcached locations.
*
* @param ia the memcached locations
* @throws IOException if connections cannot be established
*/
public MemcachedClient(InetSocketAddress... ia) throws IOException {
this(new DefaultConnectionFactory(), Arrays.asList(ia));
}
/**
* Get a memcache client over the specified memcached locations.
*
* @param addrs the socket addrs
* @throws IOException if connections cannot be established
*/
public MemcachedClient(List<InetSocketAddress> addrs)
throws IOException {
this(new DefaultConnectionFactory(), addrs);
}
/**
* Get a memcache client over the specified memcached locations.
*
* @param cf the connection factory to configure connections for this client
* @param addrs the socket addresses
* @throws IOException if connections cannot be established
*/
public MemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs)
throws IOException {
if(cf == null) {
throw new NullPointerException("Connection factory required");
}
if(addrs == null) {
throw new NullPointerException("Server list required");
}
if(addrs.isEmpty()) {
throw new IllegalArgumentException(
"You must have at least one server to connect to");
}
if(cf.getOperationTimeout() <= 0) {
throw new IllegalArgumentException(
"Operation timeout must be positive.");
}
tcService = new TranscodeService(cf.isDaemon());
transcoder=cf.getDefaultTranscoder();
opFact=cf.getOperationFactory();
assert opFact != null : "Connection factory failed to make op factory";
conn=cf.createConnection(addrs);
assert conn != null : "Connection factory failed to make a connection";
operationTimeout = cf.getOperationTimeout();
authDescriptor = cf.getAuthDescriptor();
if(authDescriptor != null) {
addObserver(this);
}
setName("Memcached IO over " + conn);
setDaemon(cf.isDaemon());
start();
}
/**
* Get a MemcachedClient based on the REST response from a Membase server
* where the username is different than the bucket name.
*
* To connect to the "default" special bucket for a given cluster, use an
* empty string as the password.
*
* If a password has not been assigned to the bucket, it is typically an
* empty string.
*
* @param baseList the URI list of one or more servers from the cluster
* @param bucketName the bucket name in the cluster you wish to use
* @param usr the username for the bucket; this nearly always be the same
* as the bucket name
* @param pwd the password for the bucket
* @throws IOException if connections could not be made
* @throws ConfigurationException if the configuration provided by the
* server has issues or is not compatible
*/
public MemcachedClient(final List<URI> baseList, final String bucketName,
final String usr, final String pwd) throws IOException, ConfigurationException {
this(new BinaryConnectionFactory(), baseList, bucketName, usr, pwd);
}
/**
* Get a MemcachedClient based on the REST response from a Membase server
* where the username is different than the bucket name.
*
* Note that when specifying a ConnectionFactory you must specify a
* BinaryConnectionFactory. Also the ConnectionFactory's protocol
* and locator values are always overwritten. The protocol will always
* be binary and the locator will be chosen based on the bucket type you
* are connecting to.
*
* To connect to the "default" special bucket for a given cluster, use an
* empty string as the password.
*
* If a password has not been assigned to the bucket, it is typically an
* empty string.
*
* @param cf the ConnectionFactory to use to create connections
* @param baseList the URI list of one or more servers from the cluster
* @param bucketName the bucket name in the cluster you wish to use
* @param usr the username for the bucket; this nearly always be the same
* as the bucket name
* @param pwd the password for the bucket
* @throws IOException if connections could not be made
* @throws ConfigurationException if the configuration provided by the
* server has issues or is not compatible
*/
public MemcachedClient(ConnectionFactory cf, final List<URI> baseList,
final String bucketName, final String usr, final String pwd)
throws IOException, ConfigurationException {
ConnectionFactoryBuilder cfb = new ConnectionFactoryBuilder(cf);
for (URI bu : baseList) {
if (!bu.isAbsolute()) {
throw new IllegalArgumentException("The base URI must be absolute");
}
}
this.configurationProvider = new ConfigurationProviderHTTP(baseList, usr, pwd);
Bucket bucket = this.configurationProvider.getBucketConfiguration(bucketName);
Config config = bucket.getConfig();
if (cf != null && !(cf instanceof BinaryConnectionFactory)) {
throw new IllegalArgumentException("ConnectionFactory must be of type " +
"BinaryConnectionFactory");
}
if (config.getConfigType() == ConfigType.MEMBASE) {
cfb.setFailureMode(FailureMode.Retry)
.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
.setHashAlg(HashAlgorithm.KETAMA_HASH)
.setLocatorType(ConnectionFactoryBuilder.Locator.VBUCKET)
.setVBucketConfig(bucket.getConfig());
} else if (config.getConfigType() == ConfigType.MEMCACHE) {
cfb.setFailureMode(FailureMode.Retry)
.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
.setHashAlg(HashAlgorithm.KETAMA_HASH)
.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
} else {
throw new ConfigurationException("Bucket type not supported or JSON response unexpected");
}
if (!this.configurationProvider.getAnonymousAuthBucket().equals(bucketName) && usr != null) {
AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"},
new PlainCallbackHandler(usr, pwd));
cfb.setAuthDescriptor(ad);
}
cf = cfb.build();
List<InetSocketAddress> addrs = AddrUtil.getAddresses(bucket.getConfig().getServers());
if(cf == null) {
throw new NullPointerException("Connection factory required");
}
if(addrs == null) {
throw new NullPointerException("Server list required");
}
if(addrs.isEmpty()) {
throw new IllegalArgumentException(
"You must have at least one server to connect to");
}
if(cf.getOperationTimeout() <= 0) {
throw new IllegalArgumentException(
"Operation timeout must be positive.");
}
tcService = new TranscodeService(cf.isDaemon());
transcoder=cf.getDefaultTranscoder();
opFact=cf.getOperationFactory();
assert opFact != null : "Connection factory failed to make op factory";
conn=cf.createConnection(addrs);
assert conn != null : "Connection factory failed to make a connection";
operationTimeout = cf.getOperationTimeout();
authDescriptor = cf.getAuthDescriptor();
if(authDescriptor != null) {
addObserver(this);
}
setName("Memcached IO over " + conn);
setDaemon(cf.isDaemon());
this.configurationProvider.subscribe(bucketName, this);
start();
}
/**
* Get a MemcachedClient based on the REST response from a Membase server.
*
* This constructor is merely a convenience for situations where the bucket
* name is the same as the user name. This is commonly the case.
*
* To connect to the "default" special bucket for a given cluster, use an
* empty string as the password.
*
* If a password has not been assigned to the bucket, it is typically an
* empty string.
*
* @param baseList the URI list of one or more servers from the cluster
* @param bucketName the bucket name in the cluster you wish to use
* @param pwd the password for the bucket
* @throws IOException if connections could not be made
* @throws ConfigurationException if the configuration provided by the
* server has issues or is not compatible
*/
public MemcachedClient(List<URI> baseList,
String bucketName,
String pwd) throws IOException, ConfigurationException {
this(baseList, bucketName, bucketName, pwd);
}
public void reconfigure(Bucket bucket) {
reconfiguring = true;
try {
conn.reconfigure(bucket);
} catch (IllegalArgumentException ex) {
getLogger().warn("Failed to reconfigure client, staying with previous configuration.", ex);
} finally {
reconfiguring = false;
}
}
/**
* Get the addresses of available servers.
*
* <p>
* This is based on a snapshot in time so shouldn't be considered
* completely accurate, but is a useful for getting a feel for what's
* working and what's not working.
* </p>
*
* @return point-in-time view of currently available servers
*/
public Collection<SocketAddress> getAvailableServers() {
ArrayList<SocketAddress> rv=new ArrayList<SocketAddress>();
for(MemcachedNode node : conn.getLocator().getAll()) {
if(node.isActive()) {
rv.add(node.getSocketAddress());
}
}
return rv;
}
/**
* Get the addresses of unavailable servers.
*
* <p>
* This is based on a snapshot in time so shouldn't be considered
* completely accurate, but is a useful for getting a feel for what's
* working and what's not working.
* </p>
*
* @return point-in-time view of currently available servers
*/
public Collection<SocketAddress> getUnavailableServers() {
ArrayList<SocketAddress> rv=new ArrayList<SocketAddress>();
for(MemcachedNode node : conn.getLocator().getAll()) {
if(!node.isActive()) {
rv.add(node.getSocketAddress());
}
}
return rv;
}
/**
* Get a read-only wrapper around the node locator wrapping this instance.
*
* @return this instance's NodeLocator
*/
public NodeLocator getNodeLocator() {
return conn.getLocator().getReadonlyCopy();
}
/**
* Get the default transcoder that's in use.
*
* @return this instance's Transcoder
*/
public Transcoder<Object> getTranscoder() {
return transcoder;
}
private void validateKey(String key) {
byte[] keyBytes=KeyUtil.getKeyBytes(key);
if(keyBytes.length > MAX_KEY_LENGTH) {
throw new IllegalArgumentException("Key is too long (maxlen = "
+ MAX_KEY_LENGTH + ")");
}
if(keyBytes.length == 0) {
throw new IllegalArgumentException(
"Key must contain at least one character.");
}
// Validate the key
for(byte b : keyBytes) {
if(b == ' ' || b == '\n' || b == '\r' || b == 0) {
throw new IllegalArgumentException(
"Key contains invalid characters: ``" + key + "''");
}
}
}
private void checkState() {
if(shuttingDown) {
throw new IllegalStateException("Shutting down");
}
assert isAlive() : "IO Thread is not running.";
}
/**
* (internal use) Add a raw operation to a numbered connection.
* This method is exposed for testing.
*
* @param which server number
* @param op the operation to perform
* @return the Operation
*/
Operation addOp(final String key, final Operation op) {
validateKey(key);
checkState();
conn.addOperation(key, op);
return op;
}
CountDownLatch broadcastOp(final BroadcastOpFactory of) {
return broadcastOp(of, conn.getLocator().getAll(), true);
}
CountDownLatch broadcastOp(final BroadcastOpFactory of,
Collection<MemcachedNode> nodes) {
return broadcastOp(of, nodes, true);
}
private CountDownLatch broadcastOp(BroadcastOpFactory of,
Collection<MemcachedNode> nodes,
boolean checkShuttingDown) {
if(checkShuttingDown && shuttingDown) {
throw new IllegalStateException("Shutting down");
}
return conn.broadcastOperation(of, nodes);
}
private <T> OperationFuture<Boolean> asyncStore(StoreType storeType, String key,
int exp, T value, Transcoder<T> tc) {
CachedData co=tc.encode(value);
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(key, latch,
operationTimeout);
Operation op=opFact.store(storeType, key, co.getFlags(),
exp, co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
private OperationFuture<Boolean> asyncStore(StoreType storeType,
String key, int exp, Object value) {
return asyncStore(storeType, key, exp, value, transcoder);
}
private <T> OperationFuture<Boolean> asyncCat(
ConcatenationType catType, long cas, String key,
T value, Transcoder<T> tc) {
CachedData co=tc.encode(value);
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(key, latch,
operationTimeout);
Operation op=opFact.cat(catType, cas, key, co.getData(),
new OperationCallback() {
public void receivedStatus(OperationStatus val) {
rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public <T> OperationFuture<Boolean> touch(final String key, final int exp) {
return touch(key, exp, transcoder);
}
public <T> OperationFuture<Boolean> touch(final String key, final int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(key, latch,
operationTimeout);
Operation op=opFact.touch(key, exp, new OperationCallback() {
public void receivedStatus(OperationStatus status) {
rv.set(status.isSuccess(), status);
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public OperationFuture<Boolean> append(long cas, String key, Object val) {
return append(cas, key, val, transcoder);
}
public <T> OperationFuture<Boolean> append(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.append, cas, key, val, tc);
}
public OperationFuture<Boolean> prepend(long cas, String key, Object val) {
return prepend(cas, key, val, transcoder);
}
public <T> OperationFuture<Boolean> prepend(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.prepend, cas, key, val, tc);
}
public <T> Future<CASResponse> asyncCAS(String key, long casId, T value,
Transcoder<T> tc) {
return asyncCAS(key, casId, 0, value, tc);
}
public <T> Future<CASResponse> asyncCAS(String key, long casId, int exp, T value,
Transcoder<T> tc) {
CachedData co=tc.encode(value);
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASResponse> rv=new OperationFuture<CASResponse>(
key, latch, operationTimeout);
Operation op=opFact.cas(StoreType.set, key, casId, co.getFlags(), exp,
co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
if(val instanceof CASOperationStatus) {
rv.set(((CASOperationStatus)val).getCASResponse(), val);
} else if(val instanceof CancelledOperationStatus) {
// Cancelled, ignore and let it float up
} else {
throw new RuntimeException(
"Unhandled state: " + val);
}
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public Future<CASResponse> asyncCAS(String key, long casId, Object value) {
return asyncCAS(key, casId, value, transcoder);
}
public <T> CASResponse cas(String key, long casId, T value,
Transcoder<T> tc) {
return cas(key, casId, 0, value, tc);
}
public <T> CASResponse cas(String key, long casId, int exp, T value,
Transcoder<T> tc) {
try {
return asyncCAS(key, casId, exp, value, tc).get(operationTimeout,
TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException("Timeout waiting for value", e);
}
}
public CASResponse cas(String key, long casId, Object value) {
return cas(key, casId, value, transcoder);
}
public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.add, key, exp, o, tc);
}
public OperationFuture<Boolean> add(String key, int exp, Object o) {
return asyncStore(StoreType.add, key, exp, o, transcoder);
}
public <T> OperationFuture<Boolean> set(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.set, key, exp, o, tc);
}
public OperationFuture<Boolean> set(String key, int exp, Object o) {
return asyncStore(StoreType.set, key, exp, o, transcoder);
}
public <T> OperationFuture<Boolean> replace(String key, int exp, T o,
Transcoder<T> tc) {
return asyncStore(StoreType.replace, key, exp, o, tc);
}
public OperationFuture<Boolean> replace(String key, int exp, Object o) {
return asyncStore(StoreType.replace, key, exp, o, transcoder);
}
public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final GetFuture<T> rv=new GetFuture<T>(latch, operationTimeout, key);
Operation op=opFact.get(key,
new GetOperation.Callback() {
private Future<T> val=null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void gotData(String k, int flags, byte[] data) {
assert key.equals(k) : "Wrong key returned";
val=tcService.decode(tc,
new CachedData(flags, data, tc.getMaxSize()));
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public GetFuture<Object> asyncGet(final String key) {
return asyncGet(key, transcoder);
}
public <T> OperationFuture<CASValue<T>> asyncGets(final String key,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASValue<T>> rv=
new OperationFuture<CASValue<T>>(key, latch, operationTimeout);
Operation op=opFact.gets(key,
new GetsOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void gotData(String k, int flags, long cas, byte[] data) {
assert key.equals(k) : "Wrong key returned";
assert cas > 0 : "CAS was less than zero: " + cas;
val=new CASValue<T>(cas, tc.decode(
new CachedData(flags, data, tc.getMaxSize())));
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public OperationFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
}
public <T> CASValue<T> gets(String key, Transcoder<T> tc) {
try {
return asyncGets(key, tc).get(
operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException("Timeout waiting for value", e);
}
}
public <T> CASValue<T> getAndTouch(String key, int exp, Transcoder<T> tc) {
try {
return asyncGetAndTouch(key, exp, tc).get(operationTimeout,
TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException("Timeout waiting for value", e);
}
}
public CASValue<Object> getAndTouch(String key, int exp) {
return getAndTouch(key, exp, transcoder);
}
public CASValue<Object> gets(String key) {
return gets(key, transcoder);
}
public <T> T get(String key, Transcoder<T> tc) {
try {
return asyncGet(key, tc).get(
operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException("Timeout waiting for value", e);
}
}
public Object get(String key) {
return get(key, transcoder);
}
public <T> OperationFuture<CASValue<T>> asyncGetAndLock(final String key, int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASValue<T>> rv=
new OperationFuture<CASValue<T>>(key, latch, operationTimeout);
Operation op=opFact.getl(key, exp,
new GetlOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void gotData(String k, int flags, long cas, byte[] data) {
assert key.equals(k) : "Wrong key returned";
assert cas > 0 : "CAS was less than zero: " + cas;
val=new CASValue<T>(cas, tc.decode(
new CachedData(flags, data, tc.getMaxSize())));
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public OperationFuture<CASValue<Object>> asyncGetAndLock(final String key, int exp) {
return asyncGetAndLock(key, exp, transcoder);
}
public <T> BulkFuture<Map<String, T>> asyncGetBulk(Collection<String> keys,
Iterator<Transcoder<T>> tc_iter) {
final Map<String, Future<T>> m=new ConcurrentHashMap<String, Future<T>>();
// This map does not need to be a ConcurrentHashMap
// because it is fully populated when it is used and
// used only to read the transcoder for a key.
final Map<String, Transcoder<T>> tc_map = new HashMap<String, Transcoder<T>>();
// Break the gets down into groups by key
final Map<MemcachedNode, Collection<String>> chunks
=new HashMap<MemcachedNode, Collection<String>>();
final NodeLocator locator=conn.getLocator();
Iterator<String> key_iter=keys.iterator();
while (key_iter.hasNext() && tc_iter.hasNext()) {
String key=key_iter.next();
tc_map.put(key, tc_iter.next());
validateKey(key);
final MemcachedNode primaryNode=locator.getPrimary(key);
MemcachedNode node=null;
if(primaryNode.isActive()) {
node=primaryNode;
} else {
for(Iterator<MemcachedNode> i=locator.getSequence(key);
node == null && i.hasNext();) {
MemcachedNode n=i.next();
if(n.isActive()) {
node=n;
}
}
if(node == null) {
node=primaryNode;
}
}
assert node != null : "Didn't find a node for " + key;
Collection<String> ks=chunks.get(node);
if(ks == null) {
ks=new ArrayList<String>();
chunks.put(node, ks);
}
ks.add(key);
}
final CountDownLatch latch=new CountDownLatch(chunks.size());
final Collection<Operation> ops=new ArrayList<Operation>(chunks.size());
final BulkGetFuture<T> rv = new BulkGetFuture<T>(m, ops, latch);
GetOperation.Callback cb=new GetOperation.Callback() {
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
rv.setStatus(status);
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful get: %s", status);
}
}
public void gotData(String k, int flags, byte[] data) {
Transcoder<T> tc = tc_map.get(k);
m.put(k, tcService.decode(tc,
new CachedData(flags, data, tc.getMaxSize())));
}
public void complete() {
latch.countDown();
}
};
// Now that we know how many servers it breaks down into, and the latch
// is all set up, convert all of these strings collections to operations
final Map<MemcachedNode, Operation> mops=
new HashMap<MemcachedNode, Operation>();
for(Map.Entry<MemcachedNode, Collection<String>> me
: chunks.entrySet()) {
Operation op=opFact.get(me.getValue(), cb);
mops.put(me.getKey(), op);
ops.add(op);
}
assert mops.size() == chunks.size();
checkState();
conn.addOperations(mops);
return rv;
}
public <T> BulkFuture<Map<String, T>> asyncGetBulk(Collection<String> keys,
Transcoder<T> tc) {
return asyncGetBulk(keys, new SingleElementInfiniteIterator<Transcoder<T>>(tc));
}
public BulkFuture<Map<String, Object>> asyncGetBulk(Collection<String> keys) {
return asyncGetBulk(keys, transcoder);
}
public <T> BulkFuture<Map<String, T>> asyncGetBulk(Transcoder<T> tc,
String... keys) {
return asyncGetBulk(Arrays.asList(keys), tc);
}
public BulkFuture<Map<String, Object>> asyncGetBulk(String... keys) {
return asyncGetBulk(Arrays.asList(keys), transcoder);
}
public OperationFuture<CASValue<Object>> asyncGetAndTouch(final String key, final int exp) {
return asyncGetAndTouch(key, exp, transcoder);
}
public <T> OperationFuture<CASValue<T>> asyncGetAndTouch(final String key, final int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASValue<T>> rv=new OperationFuture<CASValue<T>>(key, latch,
operationTimeout);
Operation op=opFact.getAndTouch(key, exp, new GetAndTouchOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void complete() {
latch.countDown();
}
public void gotData(String key, int flags, long cas, byte[] data) {
assert key.equals(key) : "Wrong key returned";
assert cas > 0 : "CAS was less than zero: " + cas;
val=new CASValue<T>(cas, tc.decode(
new CachedData(flags, data, tc.getMaxSize())));
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public <T> Map<String, T> getBulk(Collection<String> keys,
Transcoder<T> tc) {
try {
return asyncGetBulk(keys, tc).get(
operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted getting bulk values", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed getting bulk values", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException(
"Timeout waiting for bulkvalues", e);
}
}
public Map<String, Object> getBulk(Collection<String> keys) {
return getBulk(keys, transcoder);
}
public <T> Map<String, T> getBulk(Transcoder<T> tc, String... keys) {
return getBulk(Arrays.asList(keys), tc);
}
public Map<String, Object> getBulk(String... keys) {
return getBulk(Arrays.asList(keys), transcoder);
}
public Map<SocketAddress, String> getVersions() {
final Map<SocketAddress, String>rv=
new ConcurrentHashMap<SocketAddress, String>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
final SocketAddress sa=n.getSocketAddress();
return opFact.version(
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
rv.put(sa, s.getMessage());
}
public void complete() {
latch.countDown();
}
});
}});
try {
blatch.await(operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for versions", e);
}
return rv;
}
public Map<SocketAddress, Map<String, String>> getStats() {
return getStats(null);
}
public Map<SocketAddress, Map<String, String>> getStats(final String arg) {
final Map<SocketAddress, Map<String, String>> rv
=new HashMap<SocketAddress, Map<String, String>>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
final SocketAddress sa=n.getSocketAddress();
rv.put(sa, new HashMap<String, String>());
return opFact.stats(arg,
new StatsOperation.Callback() {
public void gotStat(String name, String val) {
rv.get(sa).put(name, val);
}
@SuppressWarnings("synthetic-access") // getLogger()
public void receivedStatus(OperationStatus status) {
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful stat fetch: %s",
status);
}
}
public void complete() {
latch.countDown();
}});
}});
try {
blatch.await(operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for stats", e);
}
return rv;
}
private long mutate(Mutator m, String key, int by, long def, int exp) {
final AtomicLong rv=new AtomicLong();
final CountDownLatch latch=new CountDownLatch(1);
addOp(key, opFact.mutate(m, key, by, def, exp, new OperationCallback() {
public void receivedStatus(OperationStatus s) {
// XXX: Potential abstraction leak.
// The handling of incr/decr in the binary protocol
// Allows us to avoid string processing.
rv.set(new Long(s.isSuccess()?s.getMessage():"-1"));
}
public void complete() {
latch.countDown();
}}));
try {
if (!latch.await(operationTimeout, TimeUnit.MILLISECONDS)) {
throw new OperationTimeoutException(
"Mutate operation timed out, unable to modify counter ["
+ key + "]");
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted", e);
}
getLogger().debug("Mutation returned %s", rv);
return rv.get();
}
public <T> CASValue<T> getAndLock(String key, int exp, Transcoder<T> tc) {
try {
return asyncGetAndLock(key, exp, tc).get(
operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException("Timeout waiting for value", e);
}
}
public CASValue<Object> getAndLock(String key, int exp) {
return getAndLock(key, exp, transcoder);
}
public long incr(String key, int by) {
return mutate(Mutator.incr, key, by, 0, -1);
}
public long decr(String key, int by) {
return mutate(Mutator.decr, key, by, 0, -1);
}
public long incr(String key, int by, long def, int exp) {
return mutateWithDefault(Mutator.incr, key, by, def, exp);
}
public long decr(String key, int by, long def, int exp) {
return mutateWithDefault(Mutator.decr, key, by, def, exp);
}
private long mutateWithDefault(Mutator t, String key,
int by, long def, int exp) {
long rv=mutate(t, key, by, def, exp);
// The ascii protocol doesn't support defaults, so I added them
// manually here.
if(rv == -1) {
Future<Boolean> f=asyncStore(StoreType.add,
key, exp, String.valueOf(def));
try {
if(f.get(operationTimeout, TimeUnit.MILLISECONDS)) {
rv=def;
} else {
rv=mutate(t, key, by, 0, exp);
assert rv != -1 : "Failed to mutate or init value";
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for store", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed waiting for store", e);
} catch (TimeoutException e) {
throw new OperationTimeoutException(
"Timeout waiting to mutate or init value", e);
}
}
return rv;
}
private OperationFuture<Long> asyncMutate(Mutator m, String key, int by, long def,
int exp) {
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Long> rv = new OperationFuture<Long>(key,
latch, operationTimeout);
Operation op = addOp(key, opFact.mutate(m, key, by, def, exp,
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1"), s);
}
public void complete() {
latch.countDown();
}
}));
rv.setOperation(op);
return rv;
}
public OperationFuture<Long> asyncIncr(String key, int by) {
return asyncMutate(Mutator.incr, key, by, 0, -1);
}
public OperationFuture<Long> asyncDecr(String key, int by) {
return asyncMutate(Mutator.decr, key, by, 0, -1);
}
public long incr(String key, int by, long def) {
return mutateWithDefault(Mutator.incr, key, by, def, 0);
}
public long decr(String key, int by, long def) {
return mutateWithDefault(Mutator.decr, key, by, def, 0);
}
/**
* Delete the given key from the cache.
*
* <p>
* The hold argument specifies the amount of time in seconds (or Unix time
* until which) the client wishes the server to refuse "add" and "replace"
* commands with this key. For this amount of item, the item is put into a
* delete queue, which means that it won't possible to retrieve it by the
* "get" command, but "add" and "replace" command with this key will also
* fail (the "set" command will succeed, however). After the time passes,
* the item is finally deleted from server memory.
* </p>
*
* @param key the key to delete
* @param hold how long the key should be unavailable to add commands
*
* @return whether or not the operation was performed
* @deprecated Hold values are no longer honored.
*/
@Deprecated
public OperationFuture<Boolean> delete(String key, int hold) {
return delete(key);
}
public OperationFuture<Boolean> delete(String key) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(key, latch,
operationTimeout);
DeleteOperation op=opFact.delete(key,
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
rv.set(s.isSuccess(), s);
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
public OperationFuture<Boolean> flush(final int delay) {
final AtomicReference<Boolean> flushResult=
new AtomicReference<Boolean>(null);
final ConcurrentLinkedQueue<Operation> ops=
new ConcurrentLinkedQueue<Operation>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
Operation op=opFact.flush(delay, new OperationCallback(){
public void receivedStatus(OperationStatus s) {
flushResult.set(s.isSuccess());
}
public void complete() {
latch.countDown();
}});
ops.add(op);
return op;
}});
return new OperationFuture<Boolean>(null, blatch, flushResult,
operationTimeout) {
@Override
public boolean cancel(boolean ign) {
boolean rv=false;
for(Operation op : ops) {
op.cancel();
rv |= op.getState() == OperationState.WRITING;
}
return rv;
}
@Override
public Boolean get(long duration, TimeUnit units) throws InterruptedException,
TimeoutException, ExecutionException {
status = new OperationStatus(true, "OK");
return super.get(duration, units);
}
@Override
public boolean isCancelled() {
boolean rv=false;
for(Operation op : ops) {
rv |= op.isCancelled();
}
return rv;
}
@Override
public boolean isDone() {
boolean rv=true;
for(Operation op : ops) {
rv &= op.getState() == OperationState.COMPLETE;
}
return rv || isCancelled();
}
};
}
public OperationFuture<Boolean> flush() {
return flush(-1);
}
public Set<String> listSaslMechanisms() {
final ConcurrentMap<String, String> rv
= new ConcurrentHashMap<String, String>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory() {
public Operation newOp(MemcachedNode n,
final CountDownLatch latch) {
return opFact.saslMechs(new OperationCallback() {
public void receivedStatus(OperationStatus status) {
for(String s : status.getMessage().split(" ")) {
rv.put(s, s);
}
}
public void complete() {
latch.countDown();
}
});
}
});
try {
blatch.await();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
return rv.keySet();
}
private void logRunException(Exception e) {
if(shuttingDown) {
// There are a couple types of errors that occur during the
// shutdown sequence that are considered OK. Log at debug.
getLogger().debug("Exception occurred during shutdown", e);
} else {
getLogger().warn("Problem handling memcached IO", e);
}
}
/**
* Infinitely loop processing IO.
*/
@Override
public void run() {
while(running) {
if (!reconfiguring) {
try {
conn.handleIO();
} catch (IOException e) {
logRunException(e);
} catch (CancelledKeyException e) {
logRunException(e);
} catch (ClosedSelectorException e) {
logRunException(e);
} catch (IllegalStateException e) {
logRunException(e);
}
}
}
getLogger().info("Shut down memcached client");
}
/**
* Shut down immediately.
*/
public void shutdown() {
shutdown(-1, TimeUnit.MILLISECONDS);
}
/**
* Shut down this client gracefully.
*
* @param timeout the amount of time time for shutdown
* @param unit the TimeUnit for the timeout
* @return result of the shutdown request
*/
public boolean shutdown(long timeout, TimeUnit unit) {
// Guard against double shutdowns (bug 8).
if(shuttingDown) {
getLogger().info("Suppressing duplicate attempt to shut down");
return false;
}
shuttingDown=true;
String baseName=getName();
setName(baseName + " - SHUTTING DOWN");
boolean rv=false;
try {
// Conditionally wait
if(timeout > 0) {
setName(baseName + " - SHUTTING DOWN (waiting)");
rv=waitForQueues(timeout, unit);
}
} finally {
// But always begin the shutdown sequence
try {
setName(baseName + " - SHUTTING DOWN (telling client)");
running=false;
conn.shutdown();
setName(baseName + " - SHUTTING DOWN (informed client)");
tcService.shutdown();
if (configurationProvider != null) {
configurationProvider.shutdown();
}
} catch (IOException e) {
getLogger().warn("exception while shutting down configuration provider", e);
}
}
return rv;
}
public boolean waitForQueues(long timeout, TimeUnit unit) {
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
return opFact.noop(
new OperationCallback() {
public void complete() {
latch.countDown();
}
public void receivedStatus(OperationStatus s) {
// Nothing special when receiving status, only
// necessary to complete the interface
}
});
}}, conn.getLocator().getAll(), false);
try {
// and the check retried.
return blatch.await(timeout, unit);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for queues", e);
}
}
/**
* Add a connection observer.
*
* If connections are already established, your observer will be called
* with the address and -1.
*
* @param obs the ConnectionObserver you wish to add
* @return true if the observer was added.
*/
public boolean addObserver(ConnectionObserver obs) {
boolean rv = conn.addObserver(obs);
if(rv) {
for(MemcachedNode node : conn.getLocator().getAll()) {
if(node.isActive()) {
obs.connectionEstablished(node.getSocketAddress(), -1);
}
}
}
return rv;
}
/**
* Remove a connection observer.
*
* @param obs the ConnectionObserver you wish to add
* @return true if the observer existed, but no longer does
*/
public boolean removeObserver(ConnectionObserver obs) {
return conn.removeObserver(obs);
}
public void connectionEstablished(SocketAddress sa, int reconnectCount) {
if(authDescriptor != null) {
if (authDescriptor.authThresholdReached()) {
this.shutdown();
}
authMonitor.authConnection(conn, opFact, authDescriptor, findNode(sa));
}
}
private MemcachedNode findNode(SocketAddress sa) {
MemcachedNode node = null;
for(MemcachedNode n : conn.getLocator().getAll()) {
if(n.getSocketAddress().equals(sa)) {
node = n;
}
}
assert node != null : "Couldn't find node connected to " + sa;
return node;
}
public void connectionLost(SocketAddress sa) {
// Don't care.
}
} |
package org.animotron.statement.query;
import javolution.util.FastList;
import javolution.util.FastMap;
import javolution.util.FastSet;
import org.animotron.Executor;
import org.animotron.graph.AnimoGraph;
import org.animotron.graph.GraphOperation;
import org.animotron.graph.index.Order;
import org.animotron.io.PipedInput;
import org.animotron.manipulator.Evaluator;
import org.animotron.manipulator.OnQuestion;
import org.animotron.manipulator.PFlow;
import org.animotron.manipulator.QCAVector;
import org.animotron.statement.Statement;
import org.animotron.statement.Statements;
import org.animotron.statement.operator.*;
import org.animotron.statement.relation.SHALL;
import org.jetlang.channels.Subscribable;
import org.jetlang.core.DisposingExecutor;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.traversal.Evaluation;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import org.neo4j.kernel.Uniqueness;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.animotron.Properties.RID;
import static org.neo4j.graphdb.Direction.OUTGOING;
import static org.animotron.graph.RelationshipTypes.RESULT;
/**
* Query operator 'Get'. Return 'have' relations on provided context.
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class GET extends AbstractQuery implements Shift {
public static final GET _ = new GET();
private static boolean debug = true;
private GET() { super("get", "<~"); }
protected GET(String... name) {
super(name);
}
TraversalDescription td = Traversal.description().
depthFirst().uniqueness(Uniqueness.RELATIONSHIP_PATH);
private static TraversalDescription td_eval_ic =
Traversal.description().
breadthFirst().
relationships(AN._, OUTGOING).
relationships(SHALL._, OUTGOING);
public OnQuestion onCalcQuestion() {
return question;
}
private OnQuestion question = new OnQuestion() {
@Override
public void onMessage(final PFlow pf) {
final Relationship op = pf.getOP();
final Node node = op.getEndNode();
final Set<Relationship> visitedREFs = new FastSet<Relationship>();
final Set<Node> thes = new FastSet<Node>();
Relationship r = null;
for (QCAVector theNode : AN.getREFs(pf, op)) {
r = theNode.getAnswer();
if (r.isType(AN._)) {
try {
for (QCAVector rr : Utils.eval(pf, theNode)) {
thes.add(rr.getAnswer().getEndNode());
}
} catch (IOException e) {
pf.sendException(e);
return;
}
} else
thes.add(r.getEndNode());
}
evalGet(pf, op, node, thes, visitedREFs);
pf.await();
pf.done();
}
private void evalGet(
final PFlow pf,
final Relationship op,
final Node node,
final Set<Node> thes,
final Set<Relationship> visitedREFs) {
//Utils.debug(GET._, op, thes);
//check, maybe, result was already calculated
if (!Utils.results(pf)) {
//no pre-calculated result, calculate it
Subscribable<QCAVector> onContext = new Subscribable<QCAVector>() {
@Override
public void onMessage(QCAVector vector) {
if (debug) System.out.println("GET ["+op+"] vector "+vector);
if (vector == null) {
pf.countDown();
return;
}
final Set<QCAVector> rSet = get(pf, op, vector, thes, visitedREFs);
if (rSet != null) {
for (QCAVector v : rSet) {
pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN
}
}
}
@Override
public DisposingExecutor getQueue() {
return Executor.getFiber();
}
};
pf.answerChannel().subscribe(onContext);
if (Utils.haveContext(pf)) {
super.onMessage(pf);
} else {
if (debug) System.out.println("GET ["+op+"] empty ");
boolean first = true;
Set<QCAVector> rSet = null;
for (QCAVector vector : pf.getPFlowPath()) {
//System.out.println("CHECK PFLOW "+vector);
if (first) {
first = false;
if (vector.getContext() == null) continue;
Set<QCAVector> refs = new FastSet<QCAVector>();
for (QCAVector v : vector.getContext()) {
refs.add(v);
}
rSet = get(pf, op, refs, thes, visitedREFs);
} else {
rSet = get(pf, op, vector, thes, visitedREFs);
}
if (rSet != null) {
for (QCAVector v : rSet) {
pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN
}
break;
}
}
}
}
};
};
public Set<QCAVector> get(PFlow pf, Relationship op, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) {
Set<QCAVector> refs = new FastSet<QCAVector>();
refs.add(vector);
return get(pf, op, refs, thes, visitedREFs);
}
public Set<QCAVector> get(final PFlow pf, Relationship op, Node ref, final Set<Node> thes, final Set<Relationship> visitedREFs) {
Set<QCAVector> set = new FastSet<QCAVector>();
Relationship[] have = searchForHAVE(pf, null, ref, thes);
if (have != null) {
for (int i = 0; i < have.length; i++) {
if (!pf.isInStack(have[i]))
set.add(new QCAVector(pf.getOP(), have[i]));
}
}
if (!set.isEmpty()) return set;
Set<QCAVector> newREFs = new FastSet<QCAVector>();
getOutgoingReferences(pf, pf.getVector(), null, ref, newREFs, null);
return get(pf, op, newREFs, thes, visitedREFs);
}
private boolean check(Set<QCAVector> set, final PFlow pf, final Relationship op, final QCAVector v, final Relationship toCheck, final Set<Node> thes, Set<Relationship> visitedREFs) {
if (toCheck == null) return false;
visitedREFs.add(toCheck);
Relationship[] have = searchForHAVE(pf, toCheck, v, thes);
if (have != null) {
boolean added = false;
for (int i = 0; i < have.length; i++) {
if (!pf.isInStack(have[i])) {
set.add(new QCAVector(op, v, have[i]));
added = true;
}
}
return added;
}
return false;
}
public Set<QCAVector> get(
final PFlow pf,
final Relationship op,
final Set<QCAVector> REFs,
final Set<Node> thes,
Set<Relationship> visitedREFs) {
//System.out.println("GET context = "+ref);
if (visitedREFs == null) visitedREFs = new FastSet<Relationship>();
Set<QCAVector> set = new FastSet<QCAVector>();
Set<QCAVector> nextREFs = new FastSet<QCAVector>();
nextREFs.addAll(REFs);
//boolean first = true;
Relationship t = null;
while (true) {
if (debug) System.out.println("nextREFs ");//+Arrays.toString(nextREFs.toArray()));
for (QCAVector v : nextREFs) {
if (debug) System.out.println("checking "+v);
QCAVector next = v;
while (next != null) {
if (!check(set, pf, op, v, v.getUnrelaxedAnswer(), thes, visitedREFs)) {
check(set, pf, op, v, v.getQuestion(), thes, visitedREFs);
}
next = next.getPrecedingSibling();
}
}
if (set.size() > 0) return set;
Set<QCAVector> newREFs = new FastSet<QCAVector>();
for (QCAVector vector : nextREFs) {
List<QCAVector> cs = vector.getContext();
if (cs != null) {
for (QCAVector c : cs) {
t = c.getUnrelaxedAnswer();
if (t != null && !visitedREFs.contains(t))
newREFs.add(c);
else {
t = c.getQuestion();
if (!visitedREFs.contains(t))
newREFs.add(c);
}
}
}
QCAVector next = vector;
while (next != null) {
t = next.getUnrelaxedAnswer();
if (t != null) {
if (! t.isType(AN._))
getOutgoingReferences(pf, next, t, t.getStartNode(), newREFs, visitedREFs);
getOutgoingReferences(pf, next, t, t.getEndNode(), newREFs, visitedREFs);
}
next = next.getPrecedingSibling();
}
}
if (newREFs.size() == 0) return null;
nextREFs = newREFs;
}
}
private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) {
QCAVector prev = null;
IndexHits<Relationship> it = Order.queryDown(node);
try {
boolean first = rr == null || !rr.isType(REF._);
for (Relationship r : it) {
//System.out.println(r);
if (first) {
first = false;
continue;
}
if (r.isType(REF._)) continue;
prev = vector.question(r, prev);
Statement st = Statements.relationshipType(r);
if (st instanceof AN) {
//System.out.println(r);
for (QCAVector v : AN.getREFs(pf, r)) {
Relationship t = v.getAnswer();
prev.addAnswer(v);
//System.out.println(t);
if (visitedREFs != null && !visitedREFs.contains(t)) {
v.setPrecedingSibling(prev);
prev = v;
newREFs.add(v);
}
}
} else if (st instanceof Reference) {
if (!pf.isInStack(r)) {
try {
PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf), prev);
for (QCAVector v : in) {
prev.addAnswer(v);
if (visitedREFs != null && !visitedREFs.contains(v.getAnswer()))
newREFs.add(v);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
pf.sendException(e);
} finally {
it.close();
}
}
private Relationship[] searchForHAVE(
final PFlow pf,
final Relationship ref,
final QCAVector v,
final Set<Node> thes) {
if (ref.isType(REF._) && thes.contains(ref.getEndNode())) {
return new Relationship[] {v.getQuestion()};
}
boolean checkStart = true;
if (ref.isType(AN._)) {
checkStart = false;
}
Relationship[] have = null;
//search for inside 'HAVE'
//return searchForHAVE(pf, ref, ref.getEndNode(), thes);
have = getByHave(pf, ref, ref.getEndNode(), thes);
if (have != null) return have;
//search for local 'HAVE'
if (checkStart) {
have = getByHave(pf, null, ref.getStartNode(), thes);
if (have != null) return have;
}
return null;
}
private Relationship[] searchForHAVE(final PFlow pflow, Relationship op, final Node ref, final Set<Node> thes) {
Relationship[] have = null;
//search for inside 'HAVE'
have = getByHave(pflow, op, ref, thes);
if (have != null) return have;
//search 'IC' by 'IS' topology
for (Relationship tdR : Utils.td_eval_IS.traverse(ref).relationships()) {
//System.out.println("GET IC -> IS "+tdR);
Relationship r = getShall(tdR.getEndNode(), thes);
if (r != null) {
final Node sNode = ref;
final Node eNode = r.getEndNode();
final long id = r.getId();
return new Relationship[] {
AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(eNode, AN._);
RID.set(res, id);
return res;
}
})
};
}
//search for have
have = getByHave(pflow, tdR, tdR.getEndNode(), thes);
if (have != null) return have;
}
return null;
}
//XXX: in-use by SELF
public Relationship[] getBySELF(final PFlow pf, Node context, final Set<Node> thes) {
//System.out.println("GET get context = "+context);
//search for local 'HAVE'
Relationship[] have = getByHave(pf, null, context, thes);
if (have != null) return have;
Node instance = Utils.getSingleREF(context);
if (instance != null) {
//change context to the-instance by REF
context = instance;
//search for have
have = getByHave(pf, null, context, thes);
if (have != null) return have;
}
Relationship prevTHE = null;
//search 'IC' by 'IS' topology
for (Relationship tdR : td_eval_ic.traverse(context).relationships()) {
Statement st = Statements.relationshipType(tdR);
if (st instanceof AN) {
//System.out.println("GET IC -> IS "+tdR);
if (prevTHE != null) {
//search for have
have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes);
if (have != null) return have;
}
prevTHE = tdR;
} else if (st instanceof SHALL) {
//System.out.print("GET IC -> "+tdR);
if (thes.contains(Utils.getSingleREF(tdR.getEndNode()))) {
//System.out.println(" MATCH");
//store
final Node sNode = context;
final Relationship r = tdR;
return new Relationship[] {
AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(r.getEndNode(), AN._);
//RID.set(res, r.getId());
return res;
}
})
};
//in-memory
//Relationship res = new InMemoryRelationship(context, tdR.getEndNode(), AN._.relationshipType());
//RID.set(res, tdR.getId());
//return res;
//as it
//return tdR;
}
//System.out.println();
}
}
if (prevTHE != null) {
//search for have
have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes);
if (have != null) return have;
}
return null;
}
private Relationship relaxReference(PFlow pf, QCAVector vector) {
if (!vector.getQuestion().isType(ANY._))
return vector.getQuestion();
System.out.println("Relaxing ....");
try {
PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf), vector);
for (QCAVector v : in) {
return v.getAnswer();
}
} catch (IOException e) {
pf.sendException(e);
}
return null;
}
private Relationship[] getByHave(final PFlow pf, Relationship op, final Node context, final Set<Node> thes) {
if (context == null) return null;
TraversalDescription trav = td.
relationships(ANY._, OUTGOING).
relationships(AN._, OUTGOING).
relationships(REF._, OUTGOING).
relationships(SHALL._, OUTGOING).
evaluator(new Searcher(){
@Override
public Evaluation evaluate(Path path) {
//System.out.println(path);
return _evaluate_(path, thes);
}
});
Map<Relationship, Path> paths = new FastMap<Relationship, Path>();
for (Path path : trav.traverse(context)) {
System.out.println("* "+path);
if (path.length() == 1) {
if (op == null) {
System.out.println("WARNING: DONT KNOW OP");
continue;
}
paths.put(op, path);
//break;
}
if (path.length() == 2) {
//UNDERSTAND: should we check context
Relationship r = path.relationships().iterator().next();
r = relaxReference(pf, pf.getVector().question(r));
if (r != null)
return new Relationship[] {r};
}
Relationship fR = path.relationships().iterator().next();
Path p = paths.get(fR);
if (p == null || p.length() > path.length()) {
paths.put(fR, path);
}
}
Relationship startBy = null;
Relationship res = null;
List<Relationship> resByHAVE = new FastList<Relationship>();
List<Relationship> resByIS = new FastList<Relationship>();
for (Path path : paths.values()) {
for (Relationship r : path.relationships()) {
if (startBy == null)
startBy = r;
if (!pf.isInStack(r)) {
if (r.isType(AN._)) {
if (Utils.haveContext(r.getEndNode())) {
res = r;
//break;
} else if (res == null && (startBy.isType(REF._) || (op != null && (op.isType(REF._) || op.isType(RESULT))))) {
res = r;
//break;
}
} else if (r.isType(SHALL._)) {
res = r;
//break;
}
}
}
if (res != null) {
if (startBy != null && startBy.isType(REF._))
resByIS.add(res);
else
resByHAVE.add(res);
}
startBy = null;
}
if (!resByHAVE.isEmpty())
return resByHAVE.toArray(new Relationship[resByHAVE.size()]);
return resByIS.toArray(new Relationship[resByIS.size()]);
}
private Relationship getShall(final Node context, final Set<Node> thes) {
// TraversalDescription trav = td.
// evaluator(new Searcher(){
// @Override
// public Evaluation evaluate(Path path) {
// return _evaluate_(path, thes); //, IC._
// Relationship res = null;
// for (Path path : trav.traverse(context)) {
// //TODO: check that this is only one answer
// //System.out.println(path);
// for (Relationship r : path.relationships()) {
// res = r;
// break;
for (Relationship r : context.getRelationships(OUTGOING, SHALL._)) {
for (QCAVector rr : Utils.getByREF(null, r)) {
if (thes.contains(rr.getAnswer().getEndNode()))
return r;
}
}
return null;
}
} |
package org.animotron.statement.query;
import javolution.util.FastMap;
import javolution.util.FastSet;
import javolution.util.FastTable;
import org.animotron.Executor;
import org.animotron.graph.index.Order;
import org.animotron.io.PipedInput;
import org.animotron.manipulator.Evaluator;
import org.animotron.manipulator.OnContext;
import org.animotron.manipulator.OnQuestion;
import org.animotron.manipulator.PFlow;
import org.animotron.manipulator.QCAVector;
import org.animotron.statement.Statement;
import org.animotron.statement.Statements;
import org.animotron.statement.operator.*;
import org.animotron.statement.relation.SHALL;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.traversal.Evaluation;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import org.neo4j.kernel.Uniqueness;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import static org.neo4j.graphdb.Direction.OUTGOING;
import static org.animotron.graph.RelationshipTypes.RESULT;
/**
* Query operator 'Get'. Return 'have' relations on provided context.
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class GET extends AbstractQuery implements Shift {
public static final GET _ = new GET();
private static boolean debug = true;
private GET() { super("get", "<~"); }
protected GET(String... name) {
super(name);
}
public OnQuestion onCalcQuestion() {
return question;
}
private OnQuestion question = new OnQuestion() {
@Override
public void act(final PFlow pf) {
//if (debug) System.out.println("GET "+Thread.currentThread());
final Relationship op = pf.getOP();
final Node node = op.getEndNode();
final FastSet<Relationship> visitedREFs = FastSet.newInstance();
final FastSet<Node> thes = FastSet.newInstance();
try {
Relationship r = null;
for (QCAVector theNode : AN.getREFs(pf, pf.getVector())) {
r = theNode.getClosest();
if (r.isType(AN._)) {
try {
for (QCAVector rr : Utils.eval(theNode)) {
thes.add(rr.getClosest().getEndNode());
}
} catch (Exception e) {
pf.sendException(e);
return;
}
} else
thes.add(r.getEndNode());
}
evalGet(pf, op, node, thes, visitedREFs);
} finally {
FastSet.recycle(thes);
FastSet.recycle(visitedREFs);
}
}
private void evalGet(
final PFlow pf,
final Relationship op,
final Node node,
final Set<Node> thes,
final Set<Relationship> visitedREFs) {
if (debug) {
Utils.debug(GET._, op, thes);
System.out.println(pf.getVector());
}
//check, maybe, result was already calculated
if (!Utils.results(pf)) {
//no pre-calculated result, calculate it
OnContext onContext = new OnContext(Executor.getFiber()) {
@Override
public void onMessage(QCAVector vector) {
super.onMessage(vector);
if (debug) System.out.println("GET on context "+Thread.currentThread());
if (debug) System.out.println("GET ["+op+"] vector "+vector);
if (vector == null) {
pf.countDown();
return;
}
get(pf, vector, thes, visitedREFs);
}
};
//pf.answerChannel().subscribe(onContext);
if (Utils.haveContext(pf)) {
Evaluator.sendQuestion(onContext, pf.getVector(), node);
} else {
if (debug) System.out.println("\nGET ["+op+"] empty ");
FastSet<QCAVector> refs = FastSet.newInstance();
try {
QCAVector vector = pf.getVector();
if (vector.getContext() != null) {
for (QCAVector v : vector.getContext()) {
refs.add(v);
}
}
vector = vector.getPrecedingSibling();
while (vector != null) {
refs.add(vector);
vector = vector.getPrecedingSibling();
}
get(pf, refs, thes, visitedREFs);
} finally {
FastSet.recycle(refs);
}
}
}
};
};
public boolean get(PFlow pf, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) {
FastSet<QCAVector> refs = FastSet.newInstance();
try {
refs.add(vector);
return get(pf, refs, thes, visitedREFs);
} finally {
FastSet.recycle(refs);
}
}
private boolean check(final PFlow pf, final QCAVector v, final Relationship toCheck, final Set<Node> thes, final Set<Relationship> visitedREFs) {
if (toCheck == null) return false;
if (visitedREFs.contains(toCheck)) return false;
//if (toCheck.isType(REF._) && visitedREFs.contains(v.getQuestion())) return false;
visitedREFs.add(toCheck);
if (searchForHAVE(pf, toCheck, v, thes))
return true;
//if (!pf.isInStack(have[i])) {
//set.add(new QCAVector(op, v, have[i]));
return false;
}
public boolean get(
final PFlow pf,
final Set<QCAVector> REFs,
final Set<Node> thes,
Set<Relationship> visitedREFs) {
//System.out.println("GET context = "+ref);
if (visitedREFs == null) visitedREFs = new FastSet<Relationship>();
FastSet<QCAVector> nextREFs = FastSet.newInstance();
FastSet<QCAVector> newREFs = FastSet.newInstance();
FastSet<QCAVector> tmp = null;
try {
nextREFs.addAll(REFs);
boolean found = false;
Relationship t = null;
while (true) {
if (debug) System.out.println("["+pf.getOP()+"] nextREFs ");//+Arrays.toString(nextREFs.toArray()));
QCAVector v = null;
for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) {
v = nextREFs.valueOf(r);
if (debug) System.out.println("checking "+v);
QCAVector next = v;
while (next != null) {
if (next.getQuestion() != null && next.haveAnswer())
if (!check(pf, next, next.getUnrelaxedAnswer(), thes, visitedREFs)) {
for (QCAVector vv : next.getAnswers()) {
if (check(pf, next, vv.getUnrelaxedAnswer(), thes, visitedREFs))
found = true;
}
} else {
found = true;
}
visitedREFs.add(next.getQuestion());
next = next.getPrecedingSibling();
}
}
if (found) return true;
//newREFs = new FastSet<QCAVector>();
for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) {
v = nextREFs.valueOf(r);
List<QCAVector> cs = v.getContext();
if (cs != null) {
for (QCAVector c : cs) {
checkVector(c, newREFs, visitedREFs);
}
}
QCAVector next = v;
while (next != null) {
t = next.getUnrelaxedAnswer();
if (t != null && !t.equals(next.getQuestion())) {
if (! t.isType(AN._))
getOutgoingReferences(pf, next, t, t.getStartNode(), newREFs, visitedREFs);
getOutgoingReferences(pf, next, t, t.getEndNode(), newREFs, visitedREFs);
}
//cs = next.getContext();
//if (cs != null) {
// for (QCAVector c : cs) {
// checkVector(c, newREFs, visitedREFs);
next = next.getPrecedingSibling();
}
}
if (newREFs.size() == 0) return false;
//swap
tmp = nextREFs;
nextREFs = newREFs;
newREFs = tmp;
newREFs.clear();
}
} finally {
FastSet.recycle(nextREFs);
FastSet.recycle(newREFs);
}
}
private void checkVector(final QCAVector c, final Set<QCAVector> newREFs, final Set<Relationship> visitedREFs) {
Relationship t = c.getUnrelaxedAnswer();
if (t != null && !visitedREFs.contains(t))
newREFs.add(c);
else {
t = c.getQuestion();
if (!visitedREFs.contains(t))
newREFs.add(c);
}
}
private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) {
QCAVector prev = null;
IndexHits<Relationship> it = Order.context(node);
try {
for (Relationship r : it) {
//if (debug) System.out.println(r);
if (visitedREFs != null && visitedREFs.contains(r)) {
continue;
}
prev = vector.question(r, prev);
Statement st = Statements.relationshipType(r);
if (st instanceof AN) {
//System.out.println(r);
for (QCAVector v : AN.getREFs(pf, prev)) {
Relationship t = v.getClosest();
prev.addAnswer(v);
//System.out.println(t);
if (visitedREFs != null && !visitedREFs.contains(t)) {
//v.setPrecedingSibling(prev);
//prev = v;
newREFs.add(v);
}
}
} else if (st instanceof Reference) {
if (!pf.isInStack(r)) {
try {
//System.out.println("["+pf.getOP()+"] evaluate "+prev);
PipedInput<QCAVector> in = Evaluator._.execute(prev);
for (QCAVector v : in) {
prev.addAnswer(v);
if (visitedREFs != null && !visitedREFs.contains(v.getAnswer()))
newREFs.add(v);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
pf.sendException(e);
} finally {
it.close();
}
}
private boolean searchForHAVE(
final PFlow pf,
final Relationship ref,
final QCAVector v,
final Set<Node> thes) {
// if ((ref.isType(REF._) || ref.isType(THE._)) && thes.contains(ref.getEndNode())) {
// if (!pf.isInStack(ref)) {
// pf.sendAnswer(pf.getVector().answered(ref, v), AN._);
// return true;
// return false;
//search for inside 'HAVE'
//return searchForHAVE(pf, ref, ref.getEndNode(), thes);
if (getByHave(pf, v, ref, ref.getEndNode(), thes))
return true;
//search for local 'HAVE'
if (ref.isType(REF._)) {
if (getByHave(pf, v, v.getQuestion(), ref.getStartNode(), thes))
return true;
}
return false;
}
private boolean relaxReference(PFlow pf, QCAVector vector, Relationship op) {
if (!op.isType(ANY._)) {
if (debug)
System.out.println("["+pf.getOP()+"] answered "+op);
pf.sendAnswer(pf.getVector().answered(op, vector), RESULT);
return true;
}
if (debug)
System.out.println("["+pf.getOP()+"] Relaxing "+op+" @ "+vector);
try {
PipedInput<QCAVector> in = Evaluator._.execute(vector.question(op));
if (!in.hasNext()) return false;
boolean answered = false;
Relationship res = null;
for (QCAVector v : in) {
res = v.getAnswer();
if (!pf.isInStack(res)) {
if (debug)
System.out.println("["+pf.getOP()+"] Relaxing answered "+v.getAnswer());
pf.sendAnswer(vector.answered(v.getAnswer(), v), RESULT);
answered = true;
}
}
return answered;
} catch (IOException e) {
pf.sendException(e);
}
return false;
}
private static TraversalDescription prepared =
Traversal.description().
depthFirst().
uniqueness(Uniqueness.RELATIONSHIP_PATH).
relationships(ANY._, OUTGOING).
relationships(AN._, OUTGOING).
relationships(REF._, OUTGOING).
relationships(SHALL._, OUTGOING);
private boolean getByHave(final PFlow pf, QCAVector vector, Relationship op, final Node context, final Set<Node> thes) {
if (context == null) return false;
TraversalDescription trav = prepared.
evaluator(new Searcher(){
@Override
public Evaluation evaluate(Path path) {
//System.out.println(path);
return _evaluate_(path, thes);
}
});
FastMap<Relationship, Path> paths = FastMap.newInstance();
try {
for (Path path : trav.traverse(context)) {
if (debug) System.out.println("["+pf.getOP()+"] * "+path);
if (path.length() == 1) {
if (op == null) {
System.out.println("WARNING: DONT KNOW OP");
continue;
}
if (pf.getOP().equals(op))
continue;
paths.put(op, path);
continue;
}
if (path.length() == 2) {
//UNDERSTAND: should we check context
if (relaxReference(pf, vector, path.relationships().iterator().next()))
return true;
}
Relationship fR = path.relationships().iterator().next();
Path p = paths.get(fR);
if (p == null || p.length() > path.length()) {
paths.put(fR, path);
}
}
if (paths.isEmpty()) return false;
Relationship startBy = null;
Relationship res = null;
FastTable<Relationship> resByHAVE = FastTable.newInstance();
FastTable<Relationship> resByIS = FastTable.newInstance();
try {
for (Path path : paths.values()) {
for (Relationship r : path.relationships()) {
if (startBy == null)
startBy = r;
if (!pf.isInStack(r)) {
if (r.isType(AN._)) {
if (Utils.haveContext(r.getEndNode())) {
res = r;
//break;
} else if (res == null && (startBy.isType(REF._) || (op != null && (op.isType(REF._) || op.isType(RESULT))))) {
res = r;
//break;
}
} else if (r.isType(ANY._)) {
res = r;
} else if (r.isType(SHALL._)) {
res = r;
} else if (r.isType(REF._) && path.length() == 1) {
res = op;
}
}
}
if (res != null) {
if (startBy != null && startBy.isType(REF._))
resByIS.add(res);
else
resByHAVE.add(res);
}
startBy = null;
}
if (!resByHAVE.isEmpty()) {
for (Relationship r : resByHAVE) {
relaxReference(pf, vector, r);
}
} else {
if (resByIS.isEmpty())
return false;
for (Relationship r : resByIS) {
relaxReference(pf, vector, r);
}
}
} finally{
FastTable.recycle(resByHAVE);
FastTable.recycle(resByIS);
}
return true;
} finally {
FastMap.recycle(paths);
}
}
} |
package org.b3log.symphony.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Latkes;
import org.b3log.latke.ioc.LatkeBeanManagerImpl;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.LangPropsServiceImpl;
import org.b3log.latke.util.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import static org.parboiled.common.Preconditions.checkArgNotNull;
import org.pegdown.DefaultVerbatimSerializer;
import org.pegdown.Extensions;
import org.pegdown.LinkRenderer;
import org.pegdown.PegDownProcessor;
import org.pegdown.Printer;
import org.pegdown.VerbatimSerializer;
import org.pegdown.ast.AbbreviationNode;
import org.pegdown.ast.AnchorLinkNode;
import org.pegdown.ast.AutoLinkNode;
import org.pegdown.ast.BlockQuoteNode;
import org.pegdown.ast.BulletListNode;
import org.pegdown.ast.CodeNode;
import org.pegdown.ast.DefinitionListNode;
import org.pegdown.ast.DefinitionNode;
import org.pegdown.ast.DefinitionTermNode;
import org.pegdown.ast.ExpImageNode;
import org.pegdown.ast.ExpLinkNode;
import org.pegdown.ast.HeaderNode;
import org.pegdown.ast.HtmlBlockNode;
import org.pegdown.ast.InlineHtmlNode;
import org.pegdown.ast.ListItemNode;
import org.pegdown.ast.MailLinkNode;
import org.pegdown.ast.Node;
import org.pegdown.ast.OrderedListNode;
import org.pegdown.ast.ParaNode;
import org.pegdown.ast.QuotedNode;
import org.pegdown.ast.RefImageNode;
import org.pegdown.ast.RefLinkNode;
import org.pegdown.ast.ReferenceNode;
import org.pegdown.ast.RootNode;
import org.pegdown.ast.SimpleNode;
import org.pegdown.ast.SpecialTextNode;
import org.pegdown.ast.StrikeNode;
import org.pegdown.ast.StrongEmphSuperNode;
import org.pegdown.ast.SuperNode;
import org.pegdown.ast.TableBodyNode;
import org.pegdown.ast.TableCaptionNode;
import org.pegdown.ast.TableCellNode;
import org.pegdown.ast.TableColumnNode;
import org.pegdown.ast.TableHeaderNode;
import org.pegdown.ast.TableNode;
import org.pegdown.ast.TableRowNode;
import org.pegdown.ast.TaskListNode;
import org.pegdown.ast.TextNode;
import org.pegdown.ast.VerbatimNode;
import org.pegdown.ast.Visitor;
import org.pegdown.ast.WikiLinkNode;
import org.pegdown.plugins.ToHtmlSerializerPlugin;
public final class Markdowns {
/**
* Language service.
*/
public static final LangPropsService LANG_PROPS_SERVICE
= LatkeBeanManagerImpl.getInstance().getReference(LangPropsServiceImpl.class);
/**
* Gets the safe HTML content of the specified content.
*
* @param content the specified content
* @param baseURI the specified base URI, the relative path value of href will starts with this URL
* @return safe HTML content
*/
public static String clean(final String content, final String baseURI) {
final Document.OutputSettings outputSettings = new Document.OutputSettings();
outputSettings.prettyPrint(false);
final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed().
addAttributes(":all", "id", "target", "class").
addTags("span", "hr", "kbd", "samp", "tt").
addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight").
addAttributes("audio", "controls", "src").
addAttributes("video", "controls", "src", "width", "height").
addAttributes("source", "src", "media", "type").
addAttributes("object", "width", "height", "data", "type").
addAttributes("param", "name", "value").
addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"),
outputSettings);
final Document doc = Jsoup.parse(tmp, baseURI, Parser.xmlParser());
final Elements ps = doc.getElementsByTag("p");
for (final Element p : ps) {
p.removeAttr("style");
}
final Elements as = doc.getElementsByTag("a");
for (final Element a : as) {
a.attr("rel", "nofollow");
final String href = a.attr("href");
if (href.startsWith(Latkes.getServePath())) {
continue;
}
a.attr("target", "_blank");
}
final Elements audios = doc.getElementsByTag("audio");
for (final Element audio : audios) {
audio.attr("preload", "none");
}
final Elements videos = doc.getElementsByTag("video");
for (final Element video : videos) {
video.attr("preload", "none");
}
return doc.html();
}
/**
* Converts the specified markdown text to HTML.
*
* @param markdownText the specified markdown text
* @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
* 'markdownErrorLabel' if exception
*/
public static String toHTML(final String markdownText) {
if (Strings.isEmptyOrNull(markdownText)) {
return "";
}
String formated = formatMarkdown(markdownText, "**");
// formated = formatMarkdown(formated, "_");
final PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS, 5000);
// String ret = pegDownProcessor.markdownToHtml(markdownText);
final RootNode node = pegDownProcessor.parseMarkdown(formated.toCharArray());
String ret = new ToHtmlSerializer(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(),
Arrays.asList(new ToHtmlSerializerPlugin[0])).toHtml(node);
if (!StringUtils.startsWith(ret, "<p>")) {
ret = "<p>" + ret + "</p>";
}
return ret;
}
private static String formatMarkdown(final String markdownText, final String tag) {
final StringBuilder result = new StringBuilder();
final String[] mds = markdownText.split("\n");
for (String md : mds) {
final String change = StringUtils.substringBetween(md, tag);
final String replace = " " + tag + change + tag + " ";
md = StringUtils.replace(md, tag, "");
result.append("\n" + StringUtils.replace(md, change, replace));
}
return result.toString();
}
/**
* Private constructor.
*/
private Markdowns() {
}
/**
* Enhanced with {@link Pangu} for text node.
*/
private static class ToHtmlSerializer implements Visitor {
protected Printer printer = new Printer();
protected final Map<String, ReferenceNode> references = new HashMap<String, ReferenceNode>();
protected final Map<String, String> abbreviations = new HashMap<String, String>();
protected final LinkRenderer linkRenderer;
protected final List<ToHtmlSerializerPlugin> plugins;
protected TableNode currentTableNode;
protected int currentTableColumn;
protected boolean inTableHeader;
protected Map<String, VerbatimSerializer> verbatimSerializers;
public ToHtmlSerializer(LinkRenderer linkRenderer) {
this(linkRenderer, Collections.<ToHtmlSerializerPlugin>emptyList());
}
public ToHtmlSerializer(LinkRenderer linkRenderer, List<ToHtmlSerializerPlugin> plugins) {
this(linkRenderer, Collections.<String, VerbatimSerializer>emptyMap(), plugins);
}
public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers) {
this(linkRenderer, verbatimSerializers, Collections.<ToHtmlSerializerPlugin>emptyList());
}
public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers, final List<ToHtmlSerializerPlugin> plugins) {
this.linkRenderer = linkRenderer;
this.verbatimSerializers = new HashMap<>(verbatimSerializers);
if (!this.verbatimSerializers.containsKey(VerbatimSerializer.DEFAULT)) {
this.verbatimSerializers.put(VerbatimSerializer.DEFAULT, DefaultVerbatimSerializer.INSTANCE);
}
this.plugins = plugins;
}
public String toHtml(RootNode astRoot) {
checkArgNotNull(astRoot, "astRoot");
astRoot.accept(this);
return printer.getString();
}
public void visit(RootNode node) {
for (ReferenceNode refNode : node.getReferences()) {
visitChildren(refNode);
references.put(normalize(printer.getString()), refNode);
printer.clear();
}
for (AbbreviationNode abbrNode : node.getAbbreviations()) {
visitChildren(abbrNode);
String abbr = printer.getString();
printer.clear();
abbrNode.getExpansion().accept(this);
String expansion = printer.getString();
abbreviations.put(abbr, expansion);
printer.clear();
}
visitChildren(node);
}
public void visit(AbbreviationNode node) {
}
public void visit(AnchorLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(AutoLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(BlockQuoteNode node) {
printIndentedTag(node, "blockquote");
}
public void visit(BulletListNode node) {
printIndentedTag(node, "ul");
}
public void visit(CodeNode node) {
printTag(node, "code");
}
public void visit(DefinitionListNode node) {
printIndentedTag(node, "dl");
}
public void visit(DefinitionNode node) {
printConditionallyIndentedTag(node, "dd");
}
public void visit(DefinitionTermNode node) {
printConditionallyIndentedTag(node, "dt");
}
public void visit(ExpImageNode node) {
String text = printChildrenToString(node);
printImageTag(linkRenderer.render(node, text));
}
public void visit(ExpLinkNode node) {
String text = printChildrenToString(node);
printLink(linkRenderer.render(node, text));
}
public void visit(HeaderNode node) {
printBreakBeforeTag(node, "h" + node.getLevel());
}
public void visit(HtmlBlockNode node) {
String text = node.getText();
if (text.length() > 0) {
printer.println();
}
printer.print(text);
}
public void visit(InlineHtmlNode node) {
printer.print(node.getText());
}
public void visit(ListItemNode node) {
if (node instanceof TaskListNode) {
// vsch: #185 handle GitHub style task list items, these are a bit messy because the <input> checkbox needs to be
// included inside the optional <p></p> first grand-child of the list item, first child is always RootNode
// because the list item text is recursively parsed.
Node firstChild = node.getChildren().get(0).getChildren().get(0);
boolean firstIsPara = firstChild instanceof ParaNode;
int indent = node.getChildren().size() > 1 ? 2 : 0;
boolean startWasNewLine = printer.endsWithNewLine();
printer.println().print("<li class=\"task-list-item\">").indent(indent);
if (firstIsPara) {
printer.println().print("<p>");
printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>");
visitChildren((SuperNode) firstChild);
// render the other children, the p tag is taken care of here
visitChildrenSkipFirst(node);
printer.print("</p>");
} else {
printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>");
visitChildren(node);
}
printer.indent(-indent).printchkln(indent != 0).print("</li>")
.printchkln(startWasNewLine);
} else {
printConditionallyIndentedTag(node, "li");
}
}
public void visit(MailLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(OrderedListNode node) {
printIndentedTag(node, "ol");
}
public void visit(ParaNode node) {
printBreakBeforeTag(node, "p");
}
public void visit(QuotedNode node) {
switch (node.getType()) {
case DoubleAngle:
printer.print("«");
visitChildren(node);
printer.print("»");
break;
case Double:
printer.print("“");
visitChildren(node);
printer.print("”");
break;
case Single:
printer.print("‘");
visitChildren(node);
printer.print("’");
break;
}
}
public void visit(ReferenceNode node) {
// reference nodes are not printed
}
public void visit(RefImageNode node) {
String text = printChildrenToString(node);
String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text;
ReferenceNode refNode = references.get(normalize(key));
if (refNode == null) { // "fake" reference image link
printer.print("![").print(text).print(']');
if (node.separatorSpace != null) {
printer.print(node.separatorSpace).print('[');
if (node.referenceKey != null) {
printer.print(key);
}
printer.print(']');
}
} else {
printImageTag(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text));
}
}
public void visit(RefLinkNode node) {
String text = printChildrenToString(node);
String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text;
ReferenceNode refNode = references.get(normalize(key));
if (refNode == null) { // "fake" reference link
printer.print('[').print(text).print(']');
if (node.separatorSpace != null) {
printer.print(node.separatorSpace).print('[');
if (node.referenceKey != null) {
printer.print(key);
}
printer.print(']');
}
} else {
printLink(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text));
}
}
public void visit(SimpleNode node) {
switch (node.getType()) {
case Apostrophe:
printer.print("’");
break;
case Ellipsis:
printer.print("…");
break;
case Emdash:
printer.print("—");
break;
case Endash:
printer.print("–");
break;
case HRule:
printer.println().print("<hr/>");
break;
case Linebreak:
printer.print("<br/>");
break;
case Nbsp:
printer.print(" ");
break;
default:
throw new IllegalStateException();
}
}
public void visit(StrongEmphSuperNode node) {
if (node.isClosed()) {
if (node.isStrong()) {
printTag(node, "strong");
} else {
printTag(node, "em");
}
} else {
//sequence was not closed, treat open chars as ordinary chars
printer.print(node.getChars());
visitChildren(node);
}
}
public void visit(StrikeNode node) {
printTag(node, "del");
}
public void visit(TableBodyNode node) {
printIndentedTag(node, "tbody");
}
@Override
public void visit(TableCaptionNode node) {
printer.println().print("<caption>");
visitChildren(node);
printer.print("</caption>");
}
public void visit(TableCellNode node) {
String tag = inTableHeader ? "th" : "td";
List<TableColumnNode> columns = currentTableNode.getColumns();
TableColumnNode column = columns.get(Math.min(currentTableColumn, columns.size() - 1));
printer.println().print('<').print(tag);
column.accept(this);
if (node.getColSpan() > 1) {
printer.print(" colspan=\"").print(Integer.toString(node.getColSpan())).print('"');
}
printer.print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>');
currentTableColumn += node.getColSpan();
}
public void visit(TableColumnNode node) {
switch (node.getAlignment()) {
case None:
break;
case Left:
printer.print(" align=\"left\"");
break;
case Right:
printer.print(" align=\"right\"");
break;
case Center:
printer.print(" align=\"center\"");
break;
default:
throw new IllegalStateException();
}
}
public void visit(TableHeaderNode node) {
inTableHeader = true;
printIndentedTag(node, "thead");
inTableHeader = false;
}
public void visit(TableNode node) {
currentTableNode = node;
printIndentedTag(node, "table");
currentTableNode = null;
}
public void visit(TableRowNode node) {
currentTableColumn = 0;
printIndentedTag(node, "tr");
}
public void visit(VerbatimNode node) {
VerbatimSerializer serializer = lookupSerializer(node.getType());
serializer.serialize(node, printer);
}
protected VerbatimSerializer lookupSerializer(final String type) {
if (type != null && verbatimSerializers.containsKey(type)) {
return verbatimSerializers.get(type);
} else {
return verbatimSerializers.get(VerbatimSerializer.DEFAULT);
}
}
public void visit(WikiLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(TextNode node) {
if (abbreviations.isEmpty()) {
printer.print(Pangu.spacingText(node.getText()));
} else {
printWithAbbreviations(node.getText());
}
}
public void visit(SpecialTextNode node) {
printer.printEncoded(node.getText());
}
public void visit(SuperNode node) {
visitChildren(node);
}
public void visit(Node node) {
for (ToHtmlSerializerPlugin plugin : plugins) {
if (plugin.visit(node, this, printer)) {
return;
}
}
// override this method for processing custom Node implementations
throw new RuntimeException("Don't know how to handle node " + node);
}
// helpers
protected void visitChildren(SuperNode node) {
for (Node child : node.getChildren()) {
child.accept(this);
}
}
// helpers
protected void visitChildrenSkipFirst(SuperNode node) {
boolean first = true;
for (Node child : node.getChildren()) {
if (!first) {
child.accept(this);
}
first = false;
}
}
protected void printTag(TextNode node, String tag) {
printer.print('<').print(tag).print('>');
printer.printEncoded(node.getText());
printer.print('<').print('/').print(tag).print('>');
}
protected void printTag(SuperNode node, String tag) {
printer.print('<').print(tag).print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>');
}
protected void printBreakBeforeTag(SuperNode node, String tag) {
boolean startWasNewLine = printer.endsWithNewLine();
printer.println();
printTag(node, tag);
if (startWasNewLine) {
printer.println();
}
}
protected void printIndentedTag(SuperNode node, String tag) {
printer.println().print('<').print(tag).print('>').indent(+2);
visitChildren(node);
printer.indent(-2).println().print('<').print('/').print(tag).print('>');
}
protected void printConditionallyIndentedTag(SuperNode node, String tag) {
if (node.getChildren().size() > 1) {
printer.println().print('<').print(tag).print('>').indent(+2);
visitChildren(node);
printer.indent(-2).println().print('<').print('/').print(tag).print('>');
} else {
boolean startWasNewLine = printer.endsWithNewLine();
printer.println().print('<').print(tag).print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>').printchkln(startWasNewLine);
}
}
protected void printImageTag(LinkRenderer.Rendering rendering) {
printer.print("<img");
printAttribute("src", rendering.href);
// shouldn't include the alt attribute if its empty
if (!rendering.text.equals("")) {
printAttribute("alt", rendering.text);
}
for (LinkRenderer.Attribute attr : rendering.attributes) {
printAttribute(attr.name, attr.value);
}
printer.print(" />");
}
protected void printLink(LinkRenderer.Rendering rendering) {
printer.print('<').print('a');
printAttribute("href", rendering.href);
for (LinkRenderer.Attribute attr : rendering.attributes) {
printAttribute(attr.name, attr.value);
}
printer.print('>').print(rendering.text).print("</a>");
}
protected void printAttribute(String name, String value) {
printer.print(' ').print(name).print('=').print('"').print(value).print('"');
}
protected String printChildrenToString(SuperNode node) {
Printer priorPrinter = printer;
printer = new Printer();
visitChildren(node);
String result = printer.getString();
printer = priorPrinter;
return result;
}
protected String normalize(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
switch (c) {
case ' ':
case '\n':
case '\t':
continue;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
protected void printWithAbbreviations(String string) {
Map<Integer, Map.Entry<String, String>> expansions = null;
for (Map.Entry<String, String> entry : abbreviations.entrySet()) {
String abbr = entry.getKey();
int ix = 0;
while (true) {
int sx = string.indexOf(abbr, ix);
if (sx == -1) {
break;
}
// only allow whole word matches
ix = sx + abbr.length();
if (sx > 0 && Character.isLetterOrDigit(string.charAt(sx - 1))) {
continue;
}
if (ix < string.length() && Character.isLetterOrDigit(string.charAt(ix))) {
continue;
}
if (expansions == null) {
expansions = new TreeMap<Integer, Map.Entry<String, String>>();
}
expansions.put(sx, entry);
}
}
if (expansions != null) {
int ix = 0;
for (Map.Entry<Integer, Map.Entry<String, String>> entry : expansions.entrySet()) {
int sx = entry.getKey();
String abbr = entry.getValue().getKey();
String expansion = entry.getValue().getValue();
printer.printEncoded(string.substring(ix, sx));
printer.print("<abbr");
if (org.parboiled.common.StringUtils.isNotEmpty(expansion)) {
printer.print(" title=\"");
printer.printEncoded(expansion);
printer.print('"');
}
printer.print('>');
printer.printEncoded(abbr);
printer.print("</abbr>");
ix = sx + abbr.length();
}
printer.print(string.substring(ix));
} else {
printer.print(string);
}
}
}
} |
package org.buddycloud.channelserver;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.xmpp.component.ComponentException;
public class Main
{
private static Logger LOGGER = Logger.getLogger(Main.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
Logger.getLogger(Main.class).setLevel(Level.DEBUG);
TopicsComponent topicsComponent;
XmppComponent xmppComponent;
LOGGER.info("Starting Buddycloud channel mockup version...");
Configuration conf = Configuration.getInstance();
LOGGER.info("Connecting to '" + conf.getProperty("xmpp.host") + ":"
+ conf.getProperty("xmpp.port")
+ "' and trying to claim address '"
+ conf.getProperty("xmpp.subdomain") + "'.");
try {
xmppComponent = new XmppComponent(conf, conf.getProperty("server.domain.channels"));
xmppComponent.run();
topicsComponent = new TopicsComponent(conf, conf.getProperty("server.domain.topics"));
topicsComponent.run();
} catch (ComponentException e1) {
LOGGER.error(e1);
}
run();
}
private static void run()
{
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
LOGGER.error(e);
}
}
}
} |
package org.deeplearning4j.cnn;
import org.apache.commons.io.FileUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.storage.StorageLevel;
import org.canova.api.records.reader.RecordReader;
import org.canova.api.split.FileSplit;
import org.canova.image.recordreader.ImageRecordReader;
import org.deeplearning4j.datasets.canova.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.conf.layers.setup.ConvolutionLayerSetup;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.spark.impl.multilayer.SparkDl4jMultiLayer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
/**
* @author Vannahz
*/
public class CifarEpoch {
private static final int WIDTH = 32;
private static final int HEIGHT = 32;
private static final int CHANNELS = 3;
private static final int BATCH_SIZE = 6;
private static final int ITERATIONS = 1;
private static final int SEED = 123;
private static final List<String> LABELS = Arrays.asList("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck");
private static final Logger log = LoggerFactory.getLogger(CifarEpoch.class);
public static void main(String[] args) throws Exception {
int nCores = 10;
int nEpochs = 1;
SparkConf sparkConf = new SparkConf();
// sparkConf.setMaster("local[" + nCores + "]");
sparkConf.setAppName("CIFAR");
sparkConf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true));
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
sparkConf.set("spark.kryo.registrationRequired", "true");
sparkConf.set("spark.default.parallelism", "" + nCores * 3);
sparkConf.set("spark.kryo.registrator", "util.HydraKryoSerializer");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
//Load data into memory
log.info("****************Load data****************");
String labeledPath = System.getProperty("user.home") + "/cifar/test";
RecordReader recordReader = new ImageRecordReader(WIDTH, HEIGHT, CHANNELS, true, LABELS);
recordReader.initialize(new FileSplit(new File(labeledPath)));
DataSetIterator iter = new RecordReaderDataSetIterator(recordReader,
1, WIDTH * HEIGHT * CHANNELS, LABELS.size());
List<DataSet> train = new ArrayList<>();
while (iter.hasNext()) {
train.add(iter.next());
}
Collections.shuffle(train, new Random(12345));
JavaRDD<DataSet> sparkDataTrain = sc.parallelize(train);
sparkDataTrain.persist(StorageLevel.MEMORY_AND_DISK());
MultiLayerNetwork net;
File f = new File("model/c_coefficients.bin");
if (f.exists() && !f.isDirectory()) {
log.info("load model...");
INDArray newParams;
try (DataInputStream dis = new DataInputStream(new FileInputStream("model/c_coefficients.bin"))) {
newParams = Nd4j.read(dis);
}
//Load network configuration from disk:
MultiLayerConfiguration confFromJson = MultiLayerConfiguration
.fromJson(FileUtils.readFileToString(new File("model/c_conf.json")));
//Create a MultiLayerNetwork from the saved configuration and parameters
net = new MultiLayerNetwork(confFromJson);
net.init();
net.setParameters(newParams);
//Load the updater:
org.deeplearning4j.nn.api.Updater updater;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("model/c_updater.bin"))) {
updater = (org.deeplearning4j.nn.api.Updater) ois.readObject();
}
//Set the updater in the network
net.setUpdater(updater);
} else {
//Set up network configuration
log.info("Build model....");
MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder()
.seed(SEED)
.miniBatch(true)
.iterations(ITERATIONS)
.regularization(true).l1(1e-1).l2(2e-4)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(Updater.ADAGRAD)
.list(6)
.layer(0, new ConvolutionLayer.Builder(5, 5)
.nIn(CHANNELS)
.nOut(5)
.dropOut(0.5)
.weightInit(WeightInit.XAVIER)
.activation("relu")
.build())
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX, new int[]{2, 2})
.build())
.layer(2, new ConvolutionLayer.Builder(3, 3)
.nOut(10)
.dropOut(0.5)
.weightInit(WeightInit.UNIFORM)
.activation("relu")
.build())
.layer(3, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.AVG, new int[]{2, 2})
.build())
.layer(4, new DenseLayer.Builder()
.activation("relu")
.nOut(100)
.build())
.layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(LABELS.size())
.weightInit(WeightInit.UNIFORM)
.activation("softmax")
.build())
.backprop(true)
.pretrain(false);
new ConvolutionLayerSetup(builder, WIDTH, HEIGHT, CHANNELS);
MultiLayerConfiguration conf = builder.build();
net = new MultiLayerNetwork(conf);
net.init();
net.setUpdater(null);
}
SparkDl4jMultiLayer sparkNetwork = new SparkDl4jMultiLayer(sc, net);
log.info("****************Starting network training****************");
//Run learning. Here, we are training with approximately 'batchSize' examples on each executor
for (int i = 0; i < nEpochs; i++) {
log.info("Epoch " + i + "Start");
net = sparkNetwork.fitDataSet(sparkDataTrain, nCores * BATCH_SIZE);
log.info("****************Starting Evaluation********************");
Evaluation eval = new Evaluation();
for (DataSet ds : train) {
INDArray output = net.output(ds.getFeatureMatrix());
// if(j > 25000)
// System.out.println(output);
eval.eval(ds.getLabels(), output);
}
log.info(eval.stats());
log.info("****************Save configure files****************");
try (DataOutputStream dos = new DataOutputStream(Files.newOutputStream(Paths.get("model/c_coefficients.bin")))) {
Nd4j.write(net.params(), dos);
}
FileUtils.write(new File("model/c_conf.json"), net.getLayerWiseConfigurations().toJson());
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("model/c_updater.bin"))) {
oos.writeObject(net.getUpdater());
}
}
}
} |
package org.fiteagle.api.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.concurrent.ManagedThreadFactory;
import org.apache.jena.atlas.web.HttpException;
import org.fiteagle.api.tripletStoreAccessor.TripletStoreAccessor;
import org.fiteagle.api.tripletStoreAccessor.TripletStoreAccessor.ResourceRepositoryException;
import com.hp.hpl.jena.shared.NotFoundException;
@Singleton
@Startup
public class TimerHelper{
private static final Logger LOGGER = Logger.getLogger(TimerHelper.class.getName());
private Callable<Void> task;
long delay;
private int failureCounter = 0;
private Timer timer;
private Random random = new Random();
@Resource
private ManagedThreadFactory threadFactory;
@Resource
private ManagedExecutorService executorService;
@Resource
private TimerService timerService;
Map list = new HashMap<String,Callable<Void>>();
ThreadGroup group = new ThreadGroup("timer");
public TimerHelper() {
// TODO Auto-generated constructor stub
}
public TimerHelper(Callable<Void> task) {
delay = 500;
}
public void setNewTimer(Callable<Void> task){
this.task = task;
timerService.createIntervalTimer(0, 5000, new TimerConfig());
}
@Timeout
public void timerMethod(Timer timer) {
if(failureCounter <10){
try{
Future<Void> future = executorService.submit(task);
future.get();
LOGGER.log(Level.INFO, "Added something to RDF-Database");
failureCounter =0;
timer.cancel();
}catch(Exception e){
failureCounter++;
LOGGER.log(Level.WARNING, "Errored while adding something to Database - will try again " + (10 -failureCounter) +" times");
}
}else{
timer.cancel();
LOGGER.log(Level.SEVERE, "Tried to add something to Database several times, but failed. Please check the OpenRDF-Database");
}
}
} |
package org.jboss.logmanager;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.MessageFormat;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.LogRecord;
/**
* An extended log record, which includes additional information including MDC/NDC and correct
* caller location (even in the presence of a logging facade).
*/
public class ExtLogRecord extends LogRecord {
private static final long serialVersionUID = -9174374711278052369L;
/**
* The format style to use.
*/
public enum FormatStyle {
/**
* Format the message using the {@link java.text.MessageFormat} parameter style.
*/
MESSAGE_FORMAT,
/**
* Format the message using the {@link java.util.Formatter} (also known as {@code printf()}) parameter style.
*/
PRINTF,
}
/**
* Construct a new instance. Grabs the current NDC immediately. MDC is deferred.
*
* @param level a logging level value
* @param msg the raw non-localized logging message (may be null)
* @param loggerClassName the name of the logger class
*/
public ExtLogRecord(final java.util.logging.Level level, final String msg, final String loggerClassName) {
super(level, msg);
this.loggerClassName = loggerClassName;
ndc = NDC.get();
setUnknownCaller();
threadName = Thread.currentThread().getName();
}
/**
* Construct a new instance. Grabs the current NDC immediately. MDC is deferred.
*
* @param level a logging level value
* @param msg the raw non-localized logging message (may be null)
* @param formatStyle the parameter format style to use
* @param loggerClassName the name of the logger class
*/
public ExtLogRecord(final java.util.logging.Level level, final String msg, final FormatStyle formatStyle, final String loggerClassName) {
super(level, msg);
this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;
this.loggerClassName = loggerClassName;
ndc = NDC.get();
setUnknownCaller();
threadName = Thread.currentThread().getName();
}
/**
* Construct a new instance by copying an original record.
*
* @param original the record to copy
*/
public ExtLogRecord(final LogRecord original, final String loggerClassName) {
this(original.getLevel(), original.getMessage(), loggerClassName);
setLoggerName(original.getLoggerName());
setMillis(original.getMillis());
setParameters(original.getParameters());
setResourceBundle(original.getResourceBundle());
setResourceBundleName(original.getResourceBundleName());
setSequenceNumber(original.getSequenceNumber());
// todo - find a way to not infer caller info if not already inferred?
final String originalSourceClassName = original.getSourceClassName();
if (originalSourceClassName != null) setSourceClassName(originalSourceClassName);
final String originalSourceMethodName = original.getSourceMethodName();
if (originalSourceMethodName != null) setSourceMethodName(originalSourceMethodName);
// todo sourceLineNumber
setThreadID(original.getThreadID());
setThrown(original.getThrown());
}
private final String ndc;
private transient final String loggerClassName;
private transient boolean calculateCaller = true;
private FormatStyle formatStyle = FormatStyle.MESSAGE_FORMAT;
private Map<String, String> mdcCopy;
private int sourceLineNumber = -1;
private String sourceFileName;
private String formattedMessage;
private String threadName;
private void writeObject(ObjectOutputStream oos) throws IOException {
copyAll();
oos.defaultWriteObject();
}
/**
* Copy all fields and prepare this object to be passed to another thread or to be serialized. Calling this method
* more than once has no additional effect and will not incur extra copies.
*/
public void copyAll() {
copyMdc();
calculateCaller();
getFormattedMessage();
}
/**
* Copy the MDC. Call this method before passing this log record to another thread. Calling this method
* more than once has no additional effect and will not incur extra copies.
*/
public void copyMdc() {
if (mdcCopy == null) {
mdcCopy = MDC.copy();
}
}
/**
* Get the value of an MDC property.
*
* @param key the property key
* @return the property value
*/
public String getMdc(String key) {
final Map<String, String> mdcCopy = this.mdcCopy;
return mdcCopy != null ? mdcCopy.get(key) : MDC.get(key);
}
/**
* Get the NDC for this log record.
*
* @return the NDC
*/
public String getNdc() {
return ndc;
}
/**
* Get the class name of the logger which created this record.
*
* @return the class name
*/
public String getLoggerClassName() {
return loggerClassName;
}
/**
* Find the first stack frame below the call to the logger, and populate the log record with that information.
*/
private void calculateCaller() {
if (! calculateCaller) {
return;
}
calculateCaller = false;
final StackTraceElement[] stack = new Throwable().getStackTrace();
boolean found = false;
for (StackTraceElement element : stack) {
final String className = element.getClassName();
if (found && ! loggerClassName.equals(className)) {
setSourceClassName(className);
setSourceMethodName(element.getMethodName());
setSourceLineNumber(element.getLineNumber());
setSourceFileName(element.getFileName());
return;
} else {
found = loggerClassName.equals(className);
}
}
setUnknownCaller();
}
private void setUnknownCaller() {
setSourceClassName("<unknown>");
setSourceMethodName("<unknown>");
setSourceLineNumber(-1);
setSourceFileName("<unknown>");
}
/**
* Get the source line number for this log record.
* <p/>
* Note that this line number is not verified and may be spoofed. This information may either have been
* provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the
* latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.
* May be -1 if no information could be obtained.
*
* @return the source line number
*/
public int getSourceLineNumber() {
calculateCaller();
return sourceLineNumber;
}
/**
* Set the source line number for this log record.
*
* @param sourceLineNumber the source line number
*/
public void setSourceLineNumber(final int sourceLineNumber) {
calculateCaller = false;
this.sourceLineNumber = sourceLineNumber;
}
/**
* Get the source file name for this log record.
* <p/>
* Note that this file name is not verified and may be spoofed. This information may either have been
* provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the
* latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.
* May be {@code null} if no information could be obtained.
*
* @return the source file name
*/
public String getSourceFileName() {
calculateCaller();
return sourceFileName;
}
/**
* Set the source file name for this log record.
*
* @param sourceFileName the source file name
*/
public void setSourceFileName(final String sourceFileName) {
calculateCaller = false;
this.sourceFileName = sourceFileName;
}
/** {@inheritDoc} */
public String getSourceClassName() {
calculateCaller();
return super.getSourceClassName();
}
/** {@inheritDoc} */
public void setSourceClassName(final String sourceClassName) {
calculateCaller = false;
super.setSourceClassName(sourceClassName);
}
/** {@inheritDoc} */
public String getSourceMethodName() {
calculateCaller();
return super.getSourceMethodName();
}
/** {@inheritDoc} */
public void setSourceMethodName(final String sourceMethodName) {
calculateCaller = false;
super.setSourceMethodName(sourceMethodName);
}
/**
* Get the fully formatted log record, with resources resolved and parameters applied.
*
* @return the formatted log record
*/
public String getFormattedMessage() {
if (formattedMessage == null) {
formattedMessage = formatRecord();
}
return formattedMessage;
}
private String formatRecord() {
final ResourceBundle bundle = getResourceBundle();
String msg = getMessage();
if (bundle != null) {
try {
msg = bundle.getString(msg);
} catch (MissingResourceException ex) {
// ignore
}
}
final Object[] parameters = getParameters();
if (parameters == null || parameters.length == 0) {
return msg;
}
switch (formatStyle) {
case PRINTF: {
return String.format(msg, parameters);
}
case MESSAGE_FORMAT: {
return msg.indexOf('{') >= 0 ? MessageFormat.format(msg, parameters) : msg;
}
}
// should be unreachable
return msg;
}
/**
* Get the thread name of this logging event.
*
* @return the thread name
*/
public String getThreadName() {
return threadName;
}
/**
* Set the thread name of this logging event.
*
* @param threadName the thread name
*/
public void setThreadName(final String threadName) {
this.threadName = threadName;
}
/**
* Set the raw message. Any cached formatted message is discarded. The parameter format is set to be
* {@link java.text.MessageFormat}-style.
*
* @param message the new raw message
*/
public void setMessage(final String message) {
setMessage(message, FormatStyle.MESSAGE_FORMAT);
}
/**
* Set the raw message. Any cached formatted message is discarded. The parameter format is set according to the
* given argument.
*
* @param message the new raw message
* @param formatStyle the format style to use
*/
public void setMessage(final String message, final FormatStyle formatStyle) {
this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;
formattedMessage = null;
super.setMessage(message);
}
/**
* Set the parameters to the log message. Any cached formatted message is discarded.
*
* @param parameters the log message parameters. (may be null)
*/
public void setParameters(final Object[] parameters) {
formattedMessage = null;
super.setParameters(parameters);
}
/**
* Set the localization resource bundle. Any cached formatted message is discarded.
*
* @param bundle localization bundle (may be null)
*/
public void setResourceBundle(final ResourceBundle bundle) {
formattedMessage = null;
super.setResourceBundle(bundle);
}
/**
* Set the localization resource bundle name. Any cached formatted message is discarded.
*
* @param name localization bundle name (may be null)
*/
public void setResourceBundleName(final String name) {
formattedMessage = null;
super.setResourceBundleName(name);
}
} |
package org.myrobotlab.service;
import java.util.HashMap;
import java.util.Map;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
public class LcdDisplay extends Service {
public LcdDisplay(String reservedKey) {
super(reservedKey);
setReady(false);
}
public final static Logger log = LoggerFactory.getLogger(LcdDisplay.class);
private static final long serialVersionUID = 1L;
private Pcf8574 pcf8574;
private final byte LCD_CLEARDISPLAY = (byte) 0x01;
private final byte LCD_RETURNHOME = (byte) 0x02;
private final byte LCD_ENTRYMODESET = (byte) 0x04;
private final byte LCD_DISPLAYCONTROL = (byte) 0x08;
private final byte LCD_CURSORSHIFT = (byte) 0x10;
private final byte LCD_FUNCTIONSET = (byte) 0x20;
private final byte LCD_SETCGRAMADDR = (byte) 0x40;
private final byte LCD_SETDDRAMADDR = (byte) 0x80;
// flags for display entry mode
private final byte LCD_ENTRYRIGHT = (byte) 0x00;
private final byte LCD_ENTRYLEFT = (byte) 0x02;
private final byte LCD_ENTRYSHIFTINCREMENT = (byte) 0x01;
private final byte LCD_ENTRYSHIFTDECREMENT = (byte) 0x00;
// flags for display on/off control
private final byte LCD_DISPLAYON = (byte) 0x04;
private final byte LCD_DISPLAYOFF = (byte) 0x00;
private final byte LCD_CURSORON = (byte) 0x02;
private final byte LCD_CURSOROFF = (byte) 0x00;
private final byte LCD_BLINKON = (byte) 0x01;
private final byte LCD_BLINKOFF = (byte) 0x00;
// flags for display/cursor shift
private final byte LCD_DISPLAYMOVE = (byte) 0x08;
private final byte LCD_CURSORMOVE = (byte) 0x00;
private final byte LCD_MOVERIGHT = (byte) 0x04;
private final byte LCD_MOVELEFT = (byte) 0x00;
// flags for function set
private final byte LCD_8BITMODE = (byte) 0x10;
private final byte LCD_4BITMODE = (byte) 0x00;
private final byte LCD_2LINE = (byte) 0x08;
private final byte LCD_1LINE = (byte) 0x00;
private final byte LCD_5x10DOTS = (byte) 0x04;
private final byte LCD_5x8DOTS = (byte) 0x00;
// flags for backlight control
private final byte LCD_BACKLIGHT = (byte) 0x08;
private final byte LCD_NOBACKLIGHT = (byte) 0x00;
private final byte En = (byte) 0b00000100; // Enable bit
private final byte Rw = (byte) 0b00000010; // Read/Write bit
private final byte Rs = (byte) 0b00000001; // Register select bit
private boolean backLight;
public Map<Integer, String> screenContent = new HashMap<Integer, String>();
public void attach(Pcf8574 pcf8574) {
// we need more checkup here...
if (pcf8574.isAttached) {
this.pcf8574 = pcf8574;
setReady(true);
log.info("{} attach {}", getName(), pcf8574.getName());
} else {
log.error("Cannot attach {} to {}", getName(), pcf8574.getName());
}
}
/**
* INIT LCD panel
*/
public void init() {
log.info("Init I2C Display");
lcdWrite((byte) 0x03);
lcdWrite((byte) 0x03);
lcdWrite((byte) 0x03);
lcdWrite((byte) 0x02);
lcdWrite((byte) (LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE));
lcdWrite((byte) (LCD_DISPLAYCONTROL | LCD_DISPLAYON));
lcdWrite((byte) (LCD_CLEARDISPLAY));
lcdWrite((byte) (LCD_ENTRYMODESET | LCD_ENTRYLEFT));
}
/**
* Send byte to PCF controller
* @param cmd
*/
public void writeRegister(byte cmd) {
if (isReady()) {
pcf8574.writeRegister(cmd);
} else {
log.error("LCD is not ready / attached !");
}
}
/**
* Turn ON/OFF LCD backlight
* @param status
*/
public void setBackLight(boolean status) {
if (status == true) {
writeRegister(LCD_BACKLIGHT);
} else {
writeRegister(LCD_NOBACKLIGHT);
}
backLight = status;
log.info("LCD backlight set to {}", status);
broadcastState();
}
public boolean getBackLight() {
return backLight;
}
/**
* Display string on LCD, by line
* @param string
* @param line
*/
public void display(String string, int line) {
screenContent.put(line, string);
broadcastState();
switch (line) {
case 1:
lcdWrite((byte) 0x80);
break;
case 2:
lcdWrite((byte) 0xC0);
break;
case 3:
lcdWrite((byte) 0x94);
break;
case 4:
lcdWrite((byte) 0xD4);
break;
}
for (int i = 0; i < string.length(); i++) {
lcdWrite((byte) string.charAt(i), Rs);
}
}
private void lcdStrobe(byte data) {
pcf8574.writeRegister((byte) (data | En | LCD_BACKLIGHT));
pcf8574.writeRegister((byte) ((data & ~En) | LCD_BACKLIGHT));
}
private void lcdWriteFourBits(byte data) {
pcf8574.writeRegister((byte) (data | LCD_BACKLIGHT));
lcdStrobe(data);
}
private void lcdWrite(byte cmd, byte mode) {
lcdWriteFourBits((byte) (mode | (cmd & 0xF0)));
lcdWriteFourBits((byte) (mode | ((cmd << 4) & 0xF0)));
}
// write a command to lcd
private void lcdWrite(byte cmd) {
lcdWrite(cmd, (byte) 0);
}
/**
* clear lcd and set to home
*/
public void clear() {
lcdWrite((byte) LCD_CLEARDISPLAY);
lcdWrite((byte) LCD_RETURNHOME);
screenContent.clear();
log.info("LCD content cleared");
}
@Override
public void preShutdown() {
if (isReady()) {
clear();
setBackLight(false);
}
super.stopService();
}
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(LcdDisplay.class.getCanonicalName());
meta.addDescription("I2C LCD Display driver");
meta.addCategory("i2c", "display");
return meta;
}
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
Pcf8574 pcf8574t = (Pcf8574) Runtime.start("pcf8574t", "Pcf8574");
Runtime.start("gui", "SwingGui");
Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
mega.connect("COM4");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pcf8574t.attach(mega, "1", "0x27");
LcdDisplay lcd = (LcdDisplay) Runtime.start("lcd", "LcdDisplay");
lcd.attach(pcf8574t);
lcd.init();
lcd.setBackLight(true);
lcd.display("Spot is ready !", 1);
lcd.display("* MyRobotLab *", 2);
}
} |
package org.scijava.sjep;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class ExpressionParser {
private final List<Operator> operators;
/** Creates an expression parser with the default set of operators. */
public ExpressionParser() {
this(Operators.standardList());
}
/**
* Creates an expression parser with the given set of operators.
*
* @param operators The collection of operators available to expressions.
*/
public ExpressionParser(final Collection<? extends Operator> operators) {
this.operators = new ArrayList<Operator>(operators);
// NB: Ensure operators with longer symbols come first.
// This prevents e.g. '-' from being matched before '-=' and '--'.
Collections.sort(this.operators, new Comparator<Operator>() {
@Override
public int compare(final Operator o1, final Operator o2) {
final String t1 = o1.getToken();
final String t2 = o2.getToken();
final int len1 = t1.length();
final int len2 = t2.length();
if (len1 > len2) return -1; // o1 is longer, so o1 comes first.
if (len1 < len2) return 1; // o2 is longer, so o2 comes first.
return t1.compareTo(t2);
}
});
}
// -- ExpressionParser methods --
public SyntaxTree parseTree(final String expression) {
return new ParseOperation(expression).parseTree();
}
public LinkedList<Object> parsePostfix(final String expression) {
return new ParseOperation(expression).parsePostfix();
}
// -- Helper classes --
/** A stateful parsing operation. */
private class ParseOperation {
private final String expression;
private final Position pos = new Position();
private final Deque<Object> stack = new ArrayDeque<Object>();
private final LinkedList<Object> outputQueue = new LinkedList<Object>();
/**
* State flag for parsing context.
* <ul>
* <li>If true, we are expecting an infix or postfix operator next.</li>
* <li>If false, we are expecting a prefix operator or non-operator token
* (e.g., variable, literal or function) next.</li>
* </ul>
*/
private boolean infix;
public ParseOperation(final String expression) {
this.expression = expression;
}
/** Parses the expression into a syntax tree. */
public SyntaxTree parseTree() {
return new SyntaxTree(parsePostfix());
}
public LinkedList<Object> parsePostfix() {
// While there are tokens to be read...
while (pos.get() < expression.length()) {
parseWhitespace();
// If next token is a literal, add it to the output queue.
final Object literal = parseLiteral();
if (literal != null) {
outputQueue.add(literal);
// Update the state flag.
infix = true;
continue;
}
// If next token is a function, push it onto the stack.
final Function func = parseFunction();
if (func != null) {
stack.push(func);
// Update the state flag.
infix = false;
continue;
}
// If next token is a function argument separator (i.e., a comma)...
final Character separator = parseComma();
if (separator != null) {
// Pop from stack to output queue until function found.
while (true) {
if (stack.isEmpty()) {
pos.die("Misplaced separator or mismatched parentheses");
}
if (Tokens.isFunction(stack.peek())) {
// Count the completed function argument in the function's arity.
((Function) stack.peek()).incArity();
break;
}
outputQueue.add(stack.pop());
}
// Update the state flag.
infix = false;
continue;
}
// If next token is a statement separator (i.e., a semicolon)...
final Character semicolon = parseSemicolon();
if (semicolon != null) {
// Flush the stack and begin a new statement.
flushStack();
infix = false;
continue;
}
// If the token is an operator...
final Operator o1 = parseOperator();
if (o1 != null) {
// While there is an operator token, o2, at the top of the stack...
final double p1 = o1.getPrecedence();
while (!stack.isEmpty() && Tokens.isOperator(stack.peek())) {
final Operator o2 = (Operator) stack.peek();
final double p2 = o2.getPrecedence();
// ...and o1 has lower precedence than o2...
if (o1.isLeftAssociative() && p1 <= p2 ||
o1.isRightAssociative() && p1 < p2)
{
// Pop o2 off the stack, onto the output queue.
outputQueue.add(stack.pop());
}
else break;
}
// Push o1 onto the stack.
stack.push(o1);
// Update the state flag.
if (o1.isPrefix() || o1.isInfix()) infix = false;
else if (o1.isPostfix()) infix = true;
else pos.fail("Impenetrable operator '" + o1 + "'");
continue;
}
// If the token is a left parenthesis, then push it onto the stack.
final Character leftParen = parseLeftParen();
if (leftParen != null) {
stack.push(leftParen);
// Update the state flag.
infix = false;
continue;
}
// If the token is a right parenthesis...
final Character rightParen = parseRightParen();
if (rightParen != null) {
// Pop from stack to output queue until left parenthesis found.
while (true) {
if (stack.isEmpty()) {
// No left parenthesis found: mismatched parentheses!
pos.die("Mismatched parentheses");
}
if (Tokens.isLeftParen(stack.peek())) {
// Pop the left parenthesis, but not onto the output queue.
stack.pop();
break;
}
// If token is a function, it implicitly has a left parenthesis.
if (Tokens.isFunction(stack.peek())) {
// Count the completed function argument in the function's arity.
if (infix) ((Function) stack.peek()).incArity();
// Pop the function onto the output queue.
outputQueue.add(stack.pop());
break;
}
outputQueue.add(stack.pop());
}
// Update the state flag.
infix = true;
continue;
}
// If next token is a variable, add it to the output queue.
final Variable variable = parseVariable();
if (variable != null) {
outputQueue.add(variable);
// Update the state flag.
infix = true;
continue;
}
pos.die("Invalid character");
}
// No more tokens to read!
flushStack();
return outputQueue;
}
public char currentChar() {
return futureChar(0);
}
public char futureChar(final int offset) {
return pos.ch(expression, offset);
}
// -- State methods --
public boolean isPrefixOK() {
return !infix;
}
public boolean isPostfixOK() {
return infix;
}
public boolean isInfixOK() {
return infix;
}
// -- Parsing methods --
/** Skips past any whitespace to the next interesting character. */
public void parseWhitespace() {
while (Character.isWhitespace(currentChar()))
pos.inc();
}
/**
* Attempts to parse a numeric literal.
*
* @return The parsed literal, or null if the next token is not one.
* @see Literals#parseLiteral
*/
public Object parseLiteral() {
// Only accept a literal in the appropriate context.
// This avoids confusing e.g. the unary and binary minus
// operators, or a quoted string with a quote operator.
if (infix) return null;
return Literals.parseLiteral(expression, pos);
}
/**
* Attempts to parse a function.
*
* @return The parsed function name, or null if the next token is not one.
*/
public Function parseFunction() {
final int length = parseIdentifier();
if (length == 0) return null;
// Skip any intervening whitespace.
int offset = length;
while (Character.isWhitespace(futureChar(offset)))
offset++;
// NB: Token is considered a function _iff_ it is
// an identifier followed by a left parenthesis.
if (!Tokens.isLeftParen(futureChar(offset))) return null;
// Consume the function token.
final String token = parseToken(length);
// Consume the following whitespace and associated left parenthesis.
parseWhitespace();
pos.assertThat(Tokens.isLeftParen(parseLeftParen()),
"Left parenthesis expected after function");
return new Function(token);
}
/**
* Attempts to parse a variable.
*
* @return The parsed variable name, or null if the next token is not one.
*/
public Variable parseVariable() {
final int length = parseIdentifier();
if (length == 0) return null;
return new Variable(parseToken(length));
}
/**
* Attempts to parse an identifier, as defined by
* {@link Character#isUnicodeIdentifierStart(char)} and
* {@link Character#isUnicodeIdentifierPart(char)}.
*
* @return The <em>length</em> of the parsed identifier, or 0 if the next
* token is not one.
*/
public int parseIdentifier() {
// Only accept an identifier in the appropriate context.
if (infix) return 0;
if (!Character.isUnicodeIdentifierStart(currentChar())) return 0;
int length = 0;
while (true) {
final char next = futureChar(length);
if (next == '\0') break;
if (!Character.isUnicodeIdentifierPart(next)) break;
length++;
}
return length;
}
/**
* Attempts to parse an operator.
*
* @return The parsed operator, or null if the next token is not one.
*/
public Operator parseOperator() {
for (final Operator operator : operators) {
final String symbol = operator.getToken();
if (!expression.startsWith(symbol, pos.get())) continue;
// Ensure the operator is appropriate to the current context.
if (isPrefixOK() && operator.isPrefix() ||
isPostfixOK() && operator.isPostfix() ||
isInfixOK() && operator.isInfix())
{
pos.inc(symbol.length());
return operator;
}
}
return null;
}
/**
* Attempts to parse a comma character.
*
* @return The comma, or null if the next token is not one.
*/
public Character parseComma() {
// Only accept a comma in the appropriate context.
if (!infix) return null;
return parseChar(',');
}
/**
* Attempts to parse a left parenthesis character.
*
* @return The left parenthesis, or null if the next token is not one.
*/
public Character parseLeftParen() {
return parseChar('(');
}
/**
* Attempts to parse a right parenthesis character.
*
* @return The right parenthesis, or null if the next token is not one.
*/
public Character parseRightParen() {
return parseChar(')');
}
/**
* Attempts to parse a semicolon character.
*
* @return The semicolon, or null if the next token is not one.
*/
public Character parseSemicolon() {
return parseChar(';');
}
/**
* Attempts to parse the given character.
*
* @return The character, or null if the next token is not that character.
*/
public Character parseChar(final char c) {
if (currentChar() == c) {
pos.inc();
return c;
}
return null;
}
/**
* Parses a token of the given length.
*
* @return The parsed token.
*/
public String parseToken(final int length) {
final int offset = pos.get();
final String token = expression.substring(offset, offset + length);
pos.inc(length);
return token;
}
// -- Object methods --
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(expression);
sb.append("\n");
for (int i = 0; i < pos.get(); i++) {
sb.append(" ");
}
sb.append("^");
return sb.toString();
}
// -- Helper methods --
private void flushStack() {
// While there are still operator tokens in the stack...
while (!stack.isEmpty()) {
final Object token = stack.pop();
// There shouldn't be any parentheses left.
if (Tokens.isParen(token)) pos.die("Mismatched parentheses");
// Pop the operator onto the output queue.
outputQueue.add(token);
}
}
}
} |
/**
* @author Khalid Alharbi
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The relative directory path to the embedding resources icons for the GUIs.
*/
public static final String RESOURCES_ICON_DIR="/org/sikuli/slides/gui/icons/";
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The slides directory that contains the slide notes.
*/
public static final String SLIDE_NOTES_DIRECTORY=File.separator+"ppt"+File.separator+"notesSlides";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The key name for maximum wait time to find target on the screen.
*/
public static final String MAX_WAIT_TIME_MS = "max_wait_time_ms";
/**
* The default key value for maximum wait time in milliseconds to find target on the screen.
*/
public static int MAX_WAIT_TIME_MS_DEFAULT = 15000;
/**
* The key name for the time to display canvas around the target on the screen.
*/
public static final String CANVAS_DISPLAY_TIME_SEC = "canvas_display_time_sec";
/**
* The default key value for the time, in seconds, to display canvas around the target on the screen.
*/
public static final int CANVAS_DISPLAY_TIME_SEC_DEFAULT = 3;
/**
* Screen id. Use this constant to run the test on a secondary monitor,
* 0 means the default monitor and 1 means the secondary monitor.
*/
public static int ScreenId=0;
/**
* This control how fuzzy the image search is. A value of 1 means the search
* is very precise and less fuzzy
*/
public static double MinScore=0.7;
public static boolean UseOldSyntax=false;
/**
* Desktop input events
*/
public enum DesktopEvent {
LEFT_CLICK, RIGHT_CLICK, DOUBLE_CLICK, DRAG_N_DROP, KEYBOARD_TYPING, LAUNCH_BROWSER,
EXIST, NOT_EXIST, WAIT
}
/**
* Running modes
*/
public static boolean ACTION_MODE=false;
public static boolean HELP_MODE=false;
public static boolean TUTORIAL_MODE=false;
public static boolean DEVELOPMENT_MODE=false;
/**
* Execution start time in milliseconds.
*/
public static long Execution_Start_Time;
/**
* Tutorial mode previous step.
*/
public static boolean IsPreviousStep=false;
/**
* Tutorial mode next step.
*/
public static boolean IsNextStep=false;
/**
* Wait action.
*/
public static boolean IsWaitAction=false;
/**
* Total steps in the tutorial mode
*/
public static int Steps_Total=0;
/**
* The font size of the label in the tutorial mode
*/
public static int Label_Font_Size=18;
/**
* Tutorial mode navigation status
*/
public enum NavigationStatus {
NEXT, PREVIOUS
}
} |
package org.smoothbuild.vm.job;
import static org.smoothbuild.lang.base.type.api.VarBounds.varBounds;
import static org.smoothbuild.util.collect.Lists.list;
import static org.smoothbuild.util.collect.Lists.map;
import static org.smoothbuild.util.collect.Lists.zip;
import static org.smoothbuild.vm.job.job.TaskKind.CALL;
import static org.smoothbuild.vm.job.job.TaskKind.COMBINE;
import static org.smoothbuild.vm.job.job.TaskKind.INTERNAL;
import static org.smoothbuild.vm.job.job.TaskKind.LITERAL;
import static org.smoothbuild.vm.job.job.TaskKind.SELECT;
import java.util.Map;
import javax.inject.Inject;
import org.smoothbuild.bytecode.obj.base.ObjB;
import org.smoothbuild.bytecode.obj.expr.CallB;
import org.smoothbuild.bytecode.obj.expr.CombineB;
import org.smoothbuild.bytecode.obj.expr.IfB;
import org.smoothbuild.bytecode.obj.expr.InvokeB;
import org.smoothbuild.bytecode.obj.expr.MapB;
import org.smoothbuild.bytecode.obj.expr.OrderB;
import org.smoothbuild.bytecode.obj.expr.ParamRefB;
import org.smoothbuild.bytecode.obj.expr.SelectB;
import org.smoothbuild.bytecode.obj.val.ArrayB;
import org.smoothbuild.bytecode.obj.val.BlobB;
import org.smoothbuild.bytecode.obj.val.BoolB;
import org.smoothbuild.bytecode.obj.val.FuncB;
import org.smoothbuild.bytecode.obj.val.IntB;
import org.smoothbuild.bytecode.obj.val.StringB;
import org.smoothbuild.bytecode.obj.val.ValB;
import org.smoothbuild.bytecode.type.TypingB;
import org.smoothbuild.bytecode.type.base.TypeB;
import org.smoothbuild.bytecode.type.val.ArrayTB;
import org.smoothbuild.bytecode.type.val.CallableTB;
import org.smoothbuild.bytecode.type.val.FuncTB;
import org.smoothbuild.bytecode.type.val.TupleTB;
import org.smoothbuild.lang.base.define.Loc;
import org.smoothbuild.lang.base.define.Nal;
import org.smoothbuild.lang.base.define.NalImpl;
import org.smoothbuild.lang.base.type.api.VarBounds;
import org.smoothbuild.util.IndexedScope;
import org.smoothbuild.util.TriFunction;
import org.smoothbuild.vm.java.MethodLoader;
import org.smoothbuild.vm.job.algorithm.CombineAlgorithm;
import org.smoothbuild.vm.job.algorithm.ConvertAlgorithm;
import org.smoothbuild.vm.job.algorithm.InvokeAlgorithm;
import org.smoothbuild.vm.job.algorithm.OrderAlgorithm;
import org.smoothbuild.vm.job.algorithm.SelectAlgorithm;
import org.smoothbuild.vm.job.job.CallJob;
import org.smoothbuild.vm.job.job.IfJob;
import org.smoothbuild.vm.job.job.Job;
import org.smoothbuild.vm.job.job.LazyJob;
import org.smoothbuild.vm.job.job.MapJob;
import org.smoothbuild.vm.job.job.Task;
import org.smoothbuild.vm.job.job.TaskInfo;
import org.smoothbuild.vm.job.job.ValJob;
import org.smoothbuild.vm.job.job.VirtualJob;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
public class JobCreator {
private static final Nal UNKNOWN_NAL = new NalImpl("?", Loc.internal());
private final MethodLoader methodLoader;
private final TypingB typing;
private final ImmutableMap<ObjB, Nal> nals;
private final Map<Class<?>, Handler<?>> handler;
@Inject
public JobCreator(MethodLoader methodLoader, TypingB typing, ImmutableMap<ObjB, Nal> nals) {
this.methodLoader = methodLoader;
this.typing = typing;
this.nals = nals;
this.handler = createHandlers();
}
private ImmutableMap<Class<?>, Handler<?>> createHandlers() {
return ImmutableMap.<Class<?>, Handler<?>>builder()
.put(ArrayB.class, new Handler<>(this::valueLazy, this::valueEager))
.put(BoolB.class, new Handler<>(this::valueLazy, this::valueEager))
.put(BlobB.class, new Handler<>(this::valueLazy, this::valueEager))
.put(CallB.class, new Handler<>(this::callLazy, this::callEager))
.put(CombineB.class, new Handler<>(this::combineLazy, this::combineEager))
.put(FuncB.class, new Handler<>(this::valueLazy, this::valueEager))
.put(IfB.class, new Handler<>(this::ifLazy, this::ifEager))
.put(IntB.class, new Handler<>(this::valueLazy, this::valueEager))
.put(MapB.class, new Handler<>(this::mapLazy, this::mapEager))
.put(InvokeB.class, new Handler<>(this::invokeLazy, this::invokeEager))
.put(OrderB.class, new Handler<>(this::orderLazy, this::orderEager))
.put(ParamRefB.class, new Handler<>(this::paramRefLazy, this::paramRefLazy))
.put(SelectB.class, new Handler<>(this::selectLazy, this::selectEager))
.put(StringB.class, new Handler<>(this::valueLazy, this::valueEager))
.build();
}
public Job eagerJobFor(ObjB obj) {
return eagerJobFor(new IndexedScope<>(list()), varBounds(), obj);
}
private ImmutableList<Job> eagerJobsFor(
IndexedScope<Job> scope, VarBounds<TypeB> vars, ImmutableList<? extends ObjB> objs) {
return map(objs, e -> eagerJobFor(scope, vars, e));
}
private Job jobFor(IndexedScope<Job> scope, VarBounds<TypeB> vars, ObjB expr,
boolean eager) {
return handlerFor(expr).job(eager).apply(expr, scope, vars);
}
private Job eagerJobFor(IndexedScope<Job> scope, VarBounds<TypeB> vars, ObjB expr) {
return handlerFor(expr).eagerJob().apply(expr, scope, vars);
}
private Job lazyJobFor(IndexedScope<Job> scope, VarBounds<TypeB> vars, ObjB expr) {
return handlerFor(expr).lazyJob().apply(expr, scope, vars);
}
private <T> Handler<T> handlerFor(ObjB obj) {
@SuppressWarnings("unchecked")
Handler<T> result = (Handler<T>) handler.get(obj.getClass());
if (result == null) {
System.out.println("expression.getClass() = " + obj.getClass());
}
return result;
}
// Call
private Job callLazy(CallB call, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
return callJob(call, false, scope, vars);
}
private Job callEager(CallB call, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
return callJob(call, true, scope, vars);
}
private Job callJob(CallB call, boolean eager, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var callData = call.data();
var funcJ = jobFor(scope, vars, callData.callable(), eager);
var argsJ = map(callData.args().items(), a -> lazyJobFor(scope, vars, a));
var loc = nalFor(call).loc();
var newVars = inferVarsInCall(funcJ, map(argsJ, Job::type));
var evalT = typing.mapVarsLower(call.type(), vars);
return callJob(evalT, funcJ, argsJ, loc, eager, scope, newVars);
}
private Job callJob(TypeB evalT, Job func, ImmutableList<Job> args, Loc loc, boolean eager,
IndexedScope<Job> scope, VarBounds<TypeB> vars) {
if (eager) {
return callEagerJob(evalT, func, args, loc, scope, vars);
} else {
var funcT = (FuncTB) func.type();
var actualResT = typing.mapVarsLower(funcT.res(), vars);
return new LazyJob(evalT, loc,
() -> callEagerJob(evalT, actualResT, func, args, loc, scope, vars));
}
}
public Job callEagerJob(TypeB evalT, Job func, ImmutableList<Job> args, Loc loc,
IndexedScope<Job> scope) {
var vars = inferVarsInCall(func, map(args, Job::type));
return callEagerJob(evalT, func, args, loc, scope, vars);
}
private Job callEagerJob(TypeB evalT, Job func, ImmutableList<Job> args, Loc loc,
IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var funcT = (FuncTB) func.type();
var actualResT = typing.mapVarsLower(funcT.res(), vars);
return callEagerJob(evalT, actualResT, func, args, loc, scope, vars);
}
private Job callEagerJob(TypeB evalT, TypeB actualResT, Job func, ImmutableList<Job> args,
Loc loc, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var callJ = new CallJob(actualResT, func, args, loc, vars, scope, JobCreator.this);
return convertIfNeeded(evalT, callJ);
}
private VarBounds<TypeB> inferVarsInCall(Job func, ImmutableList<TypeB> argTs) {
var funcT = (CallableTB) func.type();
return typing.inferVarBoundsLower(funcT.params(), argTs);
}
// Combine
private Job combineLazy(CombineB combine, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(combine);
var loc = nal.loc();
return new LazyJob(combine.type(), loc,
() -> combineEager(scope, vars, combine, nal));
}
private Job combineEager(CombineB combine, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(combine);
return combineEager(scope, vars, combine, nal);
}
private Job combineEager(
IndexedScope<Job> scope, VarBounds<TypeB> vars, CombineB combine, Nal nal) {
var itemJs = eagerJobsFor(scope, vars, combine.items());
var info = new TaskInfo(COMBINE, nal);
var convertedItemJs = zip(combine.type().items(), itemJs, this::convertIfNeeded);
var algorithm = new CombineAlgorithm(combine.type());
return new Task(convertedItemJs, info, algorithm);
}
private Job ifLazy(IfB if_, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(if_);
return new LazyJob(if_.type(), nal.loc(),
() -> ifEager(if_, nal, scope, vars));
}
private Job ifEager(IfB if_, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(if_);
return ifEager(if_, nal, scope, vars);
}
private Job ifEager(IfB if_, Nal nal, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var ifData = if_.data();
var conditionJ = eagerJobFor(scope, vars, ifData.condition());
var thenJ = lazyJobFor(scope, vars, ifData.then());
var elseJ = lazyJobFor(scope, vars, ifData.else_());
return new IfJob(if_.type(), conditionJ, thenJ, elseJ, nal.loc());
}
// Invoke
private Job invokeLazy(InvokeB invoke, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(invoke);
return new LazyJob(invoke.type(), nal.loc(),
() -> invokeEager(invoke, nal, scope, vars));
}
private Job invokeEager(InvokeB invoke, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(invoke);
return invokeEager(invoke, nal, scope, vars);
}
private Task invokeEager(
InvokeB invoke, Nal nal, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var name = nal.name();
var actualType = typing.mapVarsLower(invoke.type(), vars);
var invokeData = invoke.data();
var algorithm = new InvokeAlgorithm(actualType, name, invokeData.method(), methodLoader);
var info = new TaskInfo(INTERNAL, name, nal.loc());
var argsJ = eagerJobsFor(scope, vars, invokeData.args().items());
return new Task(argsJ, info, algorithm);
}
// Map
private Job mapLazy(MapB map, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(map);
return new LazyJob(map.type(), nal.loc(),
() -> mapEager(map, nal, scope, vars));
}
private Job mapEager(MapB map, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
Nal nal = nalFor(map);
return mapEager(map, nal, scope, vars);
}
private Job mapEager(MapB mapB, Nal nal, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
MapB.Data data = mapB.data();
var arrayJ = eagerJobFor(scope, vars, data.array());
var funcJ = eagerJobFor(scope, vars, data.func());
TypeB actualType = typing.mapVarsLower(mapB.type(), vars);
return new MapJob(actualType, arrayJ, funcJ, nal.loc(), scope, this);
}
// Order
private Job orderLazy(OrderB order, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(order);
return new LazyJob(order.type(), nal.loc(),
() -> orderEager(order, scope, vars));
}
private Job orderEager(OrderB order, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(order);
return orderEager(order, nal, scope, vars);
}
private Task orderEager(OrderB order, Nal nal, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var type = order.type();
var actualT = (ArrayTB) typing.mapVarsLower(type, vars);
var elemsJ = map(order.elems(), e -> eagerJobFor(scope, vars, e));
var info = new TaskInfo(LITERAL, nal);
return orderEager(actualT, elemsJ, info);
}
public Task orderEager(ArrayTB arrayTB, ImmutableList<Job> elemJs, TaskInfo info) {
var convertedElemJs = convertIfNeeded(arrayTB.elem(), elemJs);
var algorithm = new OrderAlgorithm(arrayTB);
return new Task(convertedElemJs, info, algorithm);
}
// ParamRef
private Job paramRefLazy(ParamRefB paramRef, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
return scope.get(paramRef.value().intValue());
}
// Select
private Job selectLazy(SelectB select, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(select);
return new LazyJob(select.type(), nal.loc(),
() -> selectEager(select, nal, scope, vars));
}
private Job selectEager(SelectB select, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
return selectEager(select, nalFor(select), scope, vars);
}
private Job selectEager(
SelectB select, Nal nal, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var data = select.data();
var selectableJ = eagerJobFor(scope, vars, data.selectable());
var indexJ = eagerJobFor(data.index());
var actualEvalT = typing.mapVarsLower(select.type(), vars);
var algorithmT = ((TupleTB) selectableJ.type()).items().get(data.index().toJ().intValue());
var algorithm = new SelectAlgorithm(algorithmT);
var info = new TaskInfo(SELECT, nal);
var task = new Task(list(selectableJ, indexJ), info, algorithm);
return convertIfNeeded(actualEvalT, task);
}
// Value
private Job valueLazy(ValB val, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(val);
var loc = nal.loc();
return new LazyJob(val.cat(), loc, () -> new ValJob(val, nal));
}
private Job valueEager(ValB val, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var nal = nalFor(val);
return new ValJob(val, nal);
}
// helper methods
public Job callFuncEagerJob(TypeB actualResT, FuncB func, ImmutableList<Job> args,
Loc loc, IndexedScope<Job> scope, VarBounds<TypeB> vars) {
var job = eagerJobFor(new IndexedScope<>(scope, args), vars, func.body());
var name = nalFor(func).name();
return new VirtualJob(job, new TaskInfo(CALL, name, loc));
}
private ImmutableList<Job> convertIfNeeded(TypeB type, ImmutableList<Job> elemJs) {
return map(elemJs, j -> convertIfNeeded(type, j));
}
private Job convertIfNeeded(TypeB type, Job job) {
if (job.type().equals(type)) {
return job;
} else {
var algorithm = new ConvertAlgorithm(type, typing);
return new Task(list(job), new TaskInfo(INTERNAL, job), algorithm);
}
}
private Nal nalFor(ObjB obj) {
return nals.getOrDefault(obj, UNKNOWN_NAL);
}
public record Handler<E>(
TriFunction<E, IndexedScope<Job>, VarBounds<TypeB>, Job> lazyJob,
TriFunction<E, IndexedScope<Job>, VarBounds<TypeB>, Job> eagerJob) {
public TriFunction<E, IndexedScope<Job>, VarBounds<TypeB>, Job> job(boolean eager) {
return eager ? eagerJob : lazyJob;
}
}
} |
package pl.datamatica.traccar.api;
import com.google.gson.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.*;
import pl.datamatica.traccar.api.dtos.AnnotationExclusionStrategy;
public class Context {
private static final Context INSTANCE = new Context();
public static Context getInstance() {
return INSTANCE;
}
private final EntityManagerFactory emf;
private final EntityManagerFactory emfMetadata;
private final Gson gson;
private Context() {
emf = Persistence.createEntityManagerFactory("release");
Map<String, String> properties = getApiConnectionData();
if (properties.size() > 0) {
// Use properties obtained from 'debug.xml' or '/org/traccar/conf/traccar.xml' if possible
emfMetadata = Persistence.createEntityManagerFactory("traccar_api_metadata_persistence", properties);
} else {
// Otherwise settings from 'persistence.xml' will be used
emfMetadata = Persistence.createEntityManagerFactory("traccar_api_metadata_persistence");
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat(Application.DATE_FORMAT);
gsonBuilder.setExclusionStrategies(new AnnotationExclusionStrategy());
if(isInDevMode())
gsonBuilder.setPrettyPrinting();
gson = gsonBuilder.create();
}
public boolean isInDevMode() {
return true;
}
private Map<String, String> getApiConnectionData() {
Map<String, String> properties = new HashMap<>();
String pass = null;
try {
final Class<?> configClass;
configClass = Class.forName("org.traccar.Config");
Object configObject = configClass.newInstance();
Method loadMethod = configClass.getMethod("load", String.class);
Method getStringMethod = configClass.getMethod("getString", String.class);
try {
loadMethod.invoke(configObject, "/opt/traccar/conf/traccar.xml");
} catch (Exception e1) {
loadMethod.invoke(configObject, "debug.xml");
}
String driver = (String)getStringMethod.invoke(configObject, "api.database.driver");
String url = (String)getStringMethod.invoke(configObject, "api.database.url");
String password = (String)getStringMethod.invoke(configObject, "api.database.password");
String user = (String)getStringMethod.invoke(configObject, "api.database.user");
if (driver != null) {
properties.put("hibernate.connection.driver_class", driver);
}
if (url != null) {
properties.put("hibernate.connection.url", url);
}
if (user != null) {
properties.put("hibernate.connection.username", user);
}
if (password != null) {
properties.put("hibernate.connection.password", password);
}
} catch (Exception e) {
// TODO: Log exception
}
return properties;
}
public Gson getGson() {
return gson;
}
public EntityManager createEntityManager() {
return emf.createEntityManager();
}
public EntityManager createMetadataEntityManager() {
return emfMetadata.createEntityManager();
}
} |
package ru.taximaxim.pgsqlblocks;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import ru.taximaxim.pgsqlblocks.dbcdata.*;
import ru.taximaxim.pgsqlblocks.process.Process;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeContentProvider;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeLabelProvider;
import ru.taximaxim.pgsqlblocks.ui.AddDbcDataDlg;
import ru.taximaxim.pgsqlblocks.ui.FilterDlg;
import ru.taximaxim.pgsqlblocks.ui.SettingsDlg;
import ru.taximaxim.pgsqlblocks.ui.UIAppender;
import ru.taximaxim.pgsqlblocks.utils.FilterProcess;
import ru.taximaxim.pgsqlblocks.utils.Images;
import ru.taximaxim.pgsqlblocks.utils.PathBuilder;
import ru.taximaxim.pgsqlblocks.utils.Settings;
import java.io.IOException;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.*;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class MainForm extends ApplicationWindow implements IUpdateListener {
private static final Logger LOG = Logger.getLogger(MainForm.class);
private static final String APP_NAME = "pgSqlBlocks";
private static final String SORT_DIRECTION = "sortDirection";
private static final String PID = " pid=";
private static final int ZERO_MARGIN = 0;
private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20};
private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88};
private static final int SASH_WIDTH = 2;
// some problem with 512px: (SWT:4175): Gdk-WARNING **: gdk_window_set_icon_list: icons too large
private static final int[] ICON_SIZES = { 32, 48, 256/*, 512*/ };
private static Display display;
private volatile DbcData selectedDbcData;
private Process selectedProcess;
private Text procText;
private SashForm caTreeSf;
private TableViewer caServersTable;
private TreeViewer caMainTree;
private Composite procComposite;
private TableViewer bhServersTable;
private TreeViewer bhMainTree;
private Action addDb;
private Action deleteDB;
private Action editDB;
private Action connectDB;
private Action disconnectDB;
private Action update;
private Action autoUpdate;
private Action cancelUpdate;
private Action onlyBlocked;
private ToolItem cancelProc;
private ToolItem terminateProc;
private TrayItem trayItem;
private ToolTip tip;
private static SortColumn sortColumn = SortColumn.BLOCKED_COUNT;
private static SortDirection sortDirection = SortDirection.UP;
private Settings settings = Settings.getInstance();
private FilterProcess filterProcess = FilterProcess.getInstance();
private final ScheduledExecutorService mainService = Executors.newScheduledThreadPool(1);
private final DbcDataListBuilder dbcDataBuilder = DbcDataListBuilder.getInstance(this);
private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<>();
private MenuManager serversTableMenuMgr = new MenuManager();
private boolean haveBlocks = dbcDataBuilder.getDbcDataList().stream().anyMatch(DbcData::hasBlockedProcess);
private int[] caMainTreeColsSize = new int[]{80, 110, 150, 110, 110, 110, 145, 145, 145, 55, 145, 70, 70, 70, 150, 80};
private String[] caMainTreeColsName = new String[]{
"pid", "blocked_count", "application_name", "datname", "usename", "client", "backend_start", "query_start",
"xact_stat", "state", "state_change", "blocked", "locktype", "relation", "query" , "slowquery"};
private String[] caColName = {"PID", "BLOCKED_COUNT", "APPLICATION_NAME", "DATNAME", "USENAME", "CLIENT", "BACKEND_START", "QUERY_START",
"XACT_STAT", "STATE", "STATE_CHANGE", "BLOCKED", "LOCKTYPE", "RELATION", "QUERY", "SLOWQUERY"};
public static void main(String[] args) {
try {
display = new Display();
MainForm wwin = new MainForm();
wwin.setBlockOnOpen(true);
wwin.open();
display.dispose();
} catch (Exception e) {
LOG.error("Произошла ошибка:", e);
}
}
public MainForm() {
super(null);
addToolBar(SWT.RIGHT | SWT.FLAT);
}
// TODO temporary getter, should not be used outside this class
public static SortColumn getSortColumn() {
return sortColumn;
}
// TODO temporary getter, should not be used outside this class
public static SortDirection getSortDirection() {
return sortDirection;
}
public ScheduledExecutorService getMainService() {
return mainService;
}
@Override
protected void constrainShellSize() {
super.constrainShellSize();
getShell().setMaximized( true );
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(APP_NAME);
shell.setImages(loadIcons());
}
private Image[] loadIcons() {
Image[] icons = new Image[ICON_SIZES.length];
for (int i = 0; i < ICON_SIZES.length; ++i) {
icons[i] = new Image(null,
getClass().getClassLoader().getResourceAsStream(MessageFormat.format("images/block-{0}x{0}.png",
ICON_SIZES[i])));
}
return icons;
}
@Override
protected boolean canHandleShellCloseEvent() {
if (!MessageDialog.openQuestion(getShell(), "Подтверждение действия",
"Вы действительно хотите выйти из pgSqlBlocks?")) {
return false;
}
mainService.shutdown();
return super.canHandleShellCloseEvent();
}
@Override
protected Control createContents(Composite parent)
{
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = ZERO_MARGIN;
gridLayout.marginWidth = ZERO_MARGIN;
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
SashForm verticalSf = new SashForm(composite, SWT.VERTICAL);
{
verticalSf.setLayout(gridLayout);
verticalSf.setLayoutData(gridData);
verticalSf.SASH_WIDTH = SASH_WIDTH;
verticalSf.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Composite topComposite = new Composite(verticalSf, SWT.NONE);
topComposite.setLayout(gridLayout);
TabFolder tabPanel = new TabFolder(topComposite, SWT.BORDER);
{
tabPanel.setLayoutData(gridData);
TabItem currentActivityTi = new TabItem(tabPanel, SWT.NONE);
{
currentActivityTi.setText("Текущая активность");
SashForm currentActivitySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
currentActivitySf.setLayout(gridLayout);
currentActivitySf.setLayoutData(gridData);
currentActivitySf.SASH_WIDTH = SASH_WIDTH;
currentActivitySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
caServersTable = new TableViewer(currentActivitySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
caServersTable.getTable().setHeaderVisible(true);
caServersTable.getTable().setLayoutData(gridData);
TableViewerColumn tvColumn = new TableViewerColumn(caServersTable, SWT.NONE);
tvColumn.getColumn().setText("Сервер");
tvColumn.getColumn().setWidth(200);
caServersTable.setContentProvider(new DbcDataListContentProvider());
caServersTable.setLabelProvider(new DbcDataListLabelProvider());
caServersTable.setInput(dbcDataBuilder.getDbcDataList());
}
Menu mainMenu = serversTableMenuMgr.createContextMenu(caServersTable.getControl());
serversTableMenuMgr.addMenuListener(manager -> {
if (caServersTable.getSelection() instanceof IStructuredSelection) {
manager.add(cancelUpdate);
manager.add(update);
manager.add(connectDB);
manager.add(disconnectDB);
manager.add(addDb);
manager.add(editDB);
manager.add(deleteDB);
}
});
serversTableMenuMgr.setRemoveAllWhenShown(true);
caServersTable.getControl().setMenu(mainMenu);
caTreeSf = new SashForm(currentActivitySf, SWT.VERTICAL);
{
caMainTree = new TreeViewer(caTreeSf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
caMainTree.getTree().setHeaderVisible(true);
caMainTree.getTree().setLinesVisible(true);
caMainTree.getTree().setLayoutData(gridData);
for(int i=0;i<caMainTreeColsName.length;i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(caMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
treeColumn.getColumn().setData("colName",caColName[i]);
treeColumn.getColumn().setData(SORT_DIRECTION, SortDirection.UP);
}
caMainTree.setContentProvider(new ProcessTreeContentProvider());
caMainTree.setLabelProvider(new ProcessTreeLabelProvider());
ViewerFilter[] filters = new ViewerFilter[1];
filters[0] = new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof Process) || filterProcess.isFiltered((Process) element);
}
};
caMainTree.setFilters(filters);
procComposite = new Composite(caTreeSf, SWT.BORDER);
{
procComposite.setLayout(gridLayout);
GridData procCompositeGd = new GridData(SWT.FILL, SWT.FILL, true, true);
procComposite.setLayoutData(procCompositeGd);
procComposite.setVisible(false);
ToolBar pcToolBar = new ToolBar(procComposite, SWT.FLAT | SWT.RIGHT);
pcToolBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
terminateProc = new ToolItem(pcToolBar, SWT.PUSH);
terminateProc.setText("Уничтожить процесс");
terminateProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
terminate(selectedProcess);
}
});
cancelProc = new ToolItem(pcToolBar, SWT.PUSH);
cancelProc.setText("Послать сигнал отмены процесса");
cancelProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
cancel(selectedProcess);
}
});
procText = new Text(procComposite, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
procText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
}
}
caTreeSf.setWeights(VERTICAL_WEIGHTS);
}
currentActivitySf.setWeights(HORIZONTAL_WEIGHTS);
currentActivityTi.setControl(currentActivitySf);
}
TabItem blocksHistoryTi = new TabItem(tabPanel, SWT.NONE);
{
blocksHistoryTi.setText("История блокировок");
SashForm blocksHistorySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
blocksHistorySf.setLayout(gridLayout);
blocksHistorySf.setLayoutData(gridData);
blocksHistorySf.SASH_WIDTH = SASH_WIDTH;
blocksHistorySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
bhServersTable = new TableViewer(blocksHistorySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhServersTable.getTable().setHeaderVisible(true);
bhServersTable.getTable().setLinesVisible(true);
bhServersTable.getTable().setLayoutData(gridData);
TableViewerColumn serversTc = new TableViewerColumn(bhServersTable, SWT.NONE);
serversTc.getColumn().setText("Сервер");
serversTc.getColumn().setWidth(200);
bhServersTable.setContentProvider(new DbcDataListContentProvider());
bhServersTable.setLabelProvider(new DbcDataListLabelProvider());
}
bhMainTree = new TreeViewer(blocksHistorySf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhMainTree.getTree().setHeaderVisible(true);
bhMainTree.getTree().setLinesVisible(true);
bhMainTree.getTree().setLayoutData(gridData);
for(int i = 0; i < caMainTreeColsName.length; i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(bhMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
}
bhMainTree.setContentProvider(new ProcessTreeContentProvider());
bhMainTree.setLabelProvider(new ProcessTreeLabelProvider());
}
}
blocksHistorySf.setWeights(HORIZONTAL_WEIGHTS);
blocksHistoryTi.setControl(blocksHistorySf);
}
}
Composite logComposite = new Composite(verticalSf, SWT.NONE);
{
logComposite.setLayout(gridLayout);
}
verticalSf.setWeights(VERTICAL_WEIGHTS);
UIAppender uiAppender = new UIAppender(logComposite);
uiAppender.setThreshold(Level.INFO);
Logger.getRootLogger().addAppender(uiAppender);
Composite statusBar = new Composite(composite, SWT.NONE);
{
statusBar.setLayout(gridLayout);
statusBar.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
Label appVersionLabel = new Label(statusBar, SWT.HORIZONTAL);
appVersionLabel.setText("pgSqlBlocks v." + getAppVersion());
}
dbcDataBuilder.getDbcDataList().stream().filter(DbcData::isEnabled)
.forEach(dbcDataBuilder::addOnceScheduledUpdater);
}
caMainTree.addSelectionChangedListener(event -> {
if (!caMainTree.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedProcess = (Process) selected.getFirstElement();
if(!procComposite.isVisible()) {
procComposite.setVisible(true);
caTreeSf.layout(true, true);
}
procText.setText(String.format("pid=%s%n%s", selectedProcess.getPid(), selectedProcess.getQuery()));
}
});
caServersTable.addSelectionChangedListener(event -> {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
DbcData newSelection = (DbcData) selected.getFirstElement();
if (selectedDbcData != newSelection){
selectedDbcData = newSelection;
if(procComposite.isVisible()) {
procComposite.setVisible(false);
caTreeSf.layout(false, false);
}
serversToolBarState();
caMainTree.setInput(selectedDbcData.getProcess());
updateUi();
}
}
});
for (TreeColumn column : caMainTree.getTree().getColumns()) {
column.addListener(SWT.Selection, event -> {
if (selectedDbcData != null) {
caMainTree.getTree().setSortColumn(column);
column.setData(SORT_DIRECTION, ((SortDirection)column.getData(SORT_DIRECTION)).getOpposite());
sortDirection = (SortDirection)column.getData(SORT_DIRECTION);
caMainTree.getTree().setSortDirection(sortDirection.getSwtData());
sortColumn = SortColumn.valueOf((String)column.getData("colName"));
if (settings.isOnlyBlocked()){
selectedDbcData.getOnlyBlockedProcessTree(false);
} else {
selectedDbcData.getProcessTree(false);
}
updateUi();
}
});
}
caServersTable.addDoubleClickListener(event -> {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedDbcData = (DbcData) selected.getFirstElement();
if (selectedDbcData.getStatus() == DbcStatus.CONNECTED) {
dbcDataDisconnect();
} else {
dbcDataConnect();
}
}
});
tip = new ToolTip(getShell(), SWT.BALLOON | SWT.ICON_WARNING);
tip.setText("pgSqlBlocks");
tip.setMessage("В одной из БД имеется блокировка!");
tip.setAutoHide(true);
tip.setVisible(false);
final Tray tray = display.getSystemTray();
if (tray == null) {
LOG.warn("The system tray is not available");
tip.setLocation(10, 10);
} else {
trayItem = new TrayItem(tray, SWT.NONE);
trayItem.setImage(getIconImage());
trayItem.setToolTipText("pgSqlBlocks v." + getAppVersion());
final Menu trayMenu = new Menu(getShell(), SWT.POP_UP);
MenuItem trayMenuItem = new MenuItem(trayMenu, SWT.PUSH);
trayMenuItem.setText("Выход");
trayMenuItem.addListener(SWT.Selection, event -> getShell().close());
trayItem.addListener(SWT.MenuDetect, event -> trayMenu.setVisible(true));
trayItem.setToolTip(tip);
}
return parent;
}
private Image getIconImage() {
if (dbcDataBuilder.getDbcDataList().stream().anyMatch(DbcData::hasBlockedProcess)) {
return getImage(Images.BLOCKED);
}
return getImage(Images.UNBLOCKED);
}
protected ToolBarManager createToolBarManager(int style) {
ToolBarManager toolBarManager = new ToolBarManager(style);
addDb = new Action(Images.ADD_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.ADD_DATABASE))) {
@Override
public void run() {
AddDbcDataDlg addDbcDlg = new AddDbcDataDlg(getShell(), null, dbcDataBuilder.getDbcDataList());
if (Window.OK == addDbcDlg.open()) {
selectedDbcData = addDbcDlg.getNewDbcData();
if (selectedDbcData != null) {
dbcDataBuilder.add(selectedDbcData);
caServersTable.getTable().setSelection(dbcDataBuilder.getDbcDataList().indexOf(selectedDbcData));
}
serversToolBarState();
updateUi();
}
}
};
toolBarManager.add(addDb);
deleteDB = new Action(Images.DELETE_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DELETE_DATABASE))) {
@Override
public void run() {
if (MessageDialog.openQuestion(getShell(),
"Подтверждение действия",
String.format("Вы действительно хотите удалить %s?", selectedDbcData.getName()))) {
dbcDataBuilder.delete(selectedDbcData);
selectedDbcData = null;
caMainTree.setInput(null);
updateUi();
}
}
};
deleteDB.setEnabled(false);
toolBarManager.add(deleteDB);
editDB = new Action(Images.EDIT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EDIT_DATABASE))) {
@Override
public void run() {
AddDbcDataDlg editDbcDlg = new AddDbcDataDlg(getShell(), selectedDbcData, dbcDataBuilder.getDbcDataList());
if (Window.OK == editDbcDlg.open()) {
DbcData oldOne = editDbcDlg.getEditedDbcData();
DbcData newOne = editDbcDlg.getNewDbcData();
dbcDataBuilder.edit(oldOne, newOne);
updateUi();
}
}
};
editDB.setEnabled(false);
toolBarManager.add(editDB);
toolBarManager.add(new Separator());
connectDB = new Action(Images.CONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.CONNECT_DATABASE))) {
@Override
public void run() {
dbcDataConnect();
}
};
connectDB.setEnabled(false);
toolBarManager.add(connectDB);
disconnectDB = new Action(Images.DISCONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DISCONNECT_DATABASE))) {
@Override
public void run() {
dbcDataDisconnect();
}
};
disconnectDB.setEnabled(false);
toolBarManager.add(disconnectDB);
toolBarManager.add(new Separator());
update = new Action(Images.UPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.UPDATE))) {
@Override
public void run() {
if (selectedDbcData != null) {
runUpdate(selectedDbcData);
}
}
};
toolBarManager.add(update);
autoUpdate = new Action(Images.AUTOUPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.AUTOUPDATE))) {
@Override
public void run() {
if (autoUpdate.isChecked()) {
dbcDataBuilder.getDbcDataList().stream()
.filter(x -> x.isConnected() || x.isEnabled())
.filter(x -> x.getStatus() != DbcStatus.CONNECTION_ERROR)
.forEach(dbcDataBuilder::addScheduledUpdater);
} else {
dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeScheduledUpdater);
}
settings.setAutoUpdate(autoUpdate.isChecked());
}
};
autoUpdate.setChecked(settings.isAutoUpdate());
toolBarManager.add(autoUpdate);
cancelUpdate = new Action(Images.CANCEL_UPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.CANCEL_UPDATE))) {
@Override
public void run() {
if (selectedDbcData != null) {
dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData);
if (selectedDbcData.isConnected()){
selectedDbcData.setStatus(DbcStatus.CONNECTED);
}
}
}
};
cancelUpdate.setEnabled(false);
toolBarManager.add(new Separator());
Action filterSetting = new Action(Images.FILTER.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.FILTER))) {
@Override
public void run() {
FilterDlg filterDlg = new FilterDlg(getShell(), filterProcess);
filterDlg.open();
updateUi();
}
};
toolBarManager.add(filterSetting);
onlyBlocked = new Action(Images.VIEW_ONLY_BLOCKED.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.VIEW_ONLY_BLOCKED))) {
@Override
public void run() {
settings.setOnlyBlocked(onlyBlocked.isChecked());
runUpdateForAllEnabled();
updateUi();
}
};
onlyBlocked.setChecked(settings.isOnlyBlocked());
toolBarManager.add(onlyBlocked);
toolBarManager.add(new Separator());
Action exportBlocks = new Action(Images.EXPORT_BLOCKS.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EXPORT_BLOCKS))) {
@Override
public void run() {
if (dbcDataBuilder.getDbcDataList().stream()
.filter(DbcData::hasBlockedProcess).count() > 0) {
BlocksHistory.getInstance().save(dbcDataBuilder.getDbcDataList());
LOG.info("Блокировка сохранена...");
} else {
LOG.info("Не найдено блокировок для сохранения");
}
}
};
toolBarManager.add(exportBlocks);
Action importBlocks = new Action(Images.IMPORT_BLOCKS.getDescription()) {
@Override
public void run() {
FileDialog dialog = new FileDialog(getShell());
dialog.setFilterPath(PathBuilder.getInstance().getBlockHistoryDir().toString());
dialog.setText("Открыть историю блокировок");
dialog.setFilterExtensions(new String[]{"*.xml"});
List<DbcData> blockedDbsDataList = BlocksHistory.getInstance().open(dialog.open());
if (!blockedDbsDataList.isEmpty()) {
bhServersTable.setInput(blockedDbsDataList);
bhMainTree.setInput(blockedDbsDataList.get(0).getProcess());
bhMainTree.refresh();
bhServersTable.refresh();
}
}
};
importBlocks.setImageDescriptor(ImageDescriptor.createFromImage(getImage(Images.IMPORT_BLOCKS)));
toolBarManager.add(importBlocks);
toolBarManager.add(new Separator());
Action settingsAction = new Action(Images.SETTINGS.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.SETTINGS))) {
@Override
public void run() {
SettingsDlg settingsDlg = new SettingsDlg(getShell(), settings);
if (Window.OK == settingsDlg.open()) {
updateUi();
runUpdateForAllEnabled();
}
}
};
toolBarManager.add(settingsAction);
return toolBarManager;
}
private void runUpdateForAllEnabled() {
dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeScheduledUpdater);
dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeOnceScheduledUpdater);
if (autoUpdate.isChecked()) {
dbcDataBuilder.getDbcDataList().stream()
.filter(x -> x.isConnected() || x.isEnabled())
.filter(x -> x.getStatus() != DbcStatus.CONNECTION_ERROR)
.forEach(dbcDataBuilder::addScheduledUpdater);
} else {
dbcDataBuilder.getDbcDataList().stream()
.filter(x -> x.isConnected() || x.isEnabled())
.forEach(dbcDataBuilder::addOnceScheduledUpdater);
}
}
private void runUpdate(DbcData dbcData) {
dbcDataBuilder.removeScheduledUpdater(dbcData);
dbcDataBuilder.removeOnceScheduledUpdater(dbcData);
if (settings.isAutoUpdate()) {
LOG.debug(MessageFormat.format("Add dbcData \"{0}\" to updaterList",
dbcData.getName()));
dbcDataBuilder.addScheduledUpdater(dbcData);
} else {
dbcDataBuilder.addOnceScheduledUpdater(dbcData);
}
}
private void checkBlocks() {
boolean current = dbcDataBuilder.getDbcDataList().stream().anyMatch(DbcData::hasBlockedProcess);
if (current != haveBlocks) {
haveBlocks = current;
tip.setVisible(haveBlocks);
}
}
private Image getImage(Images type) {
return imagesMap.computeIfAbsent(type.toString(),
k -> new Image(null, getClass().getClassLoader().getResourceAsStream(type.getImageAddr())));
}
private String getAppVersion() {
URL manifestPath = MainForm.class.getClassLoader().getResource("META-INF/MANIFEST.MF");
Manifest manifest = null;
try {
manifest = new Manifest(manifestPath != null ? manifestPath.openStream() : null);
} catch (IOException e) {
LOG.error("Ошибка при чтении манифеста", e);
}
Attributes manifestAttributes = manifest != null ? manifest.getMainAttributes() : null;
String appVersion = manifestAttributes != null ? manifestAttributes.getValue("Implementation-Version") : null;
if(appVersion == null) {
return "";
}
return appVersion;
}
private void terminate(Process process) {
String term = "select pg_terminate_backend(?);";
boolean kill = false;
int pid = process.getPid();
try (PreparedStatement termPs = selectedDbcData.getConnection().prepareStatement(term)) {
termPs.setInt(1, pid);
try (ResultSet resultSet = termPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is terminated.");
runUpdate(selectedDbcData);
} else {
LOG.info(selectedDbcData.getName() + " failed to terminate " + PID + pid);
}
}
private void cancel(Process process) {
String cancel = "select pg_cancel_backend(?);";
int pid = process.getPid();
boolean kill = false;
try (PreparedStatement cancelPs = selectedDbcData.getConnection().prepareStatement(cancel)) {
cancelPs.setInt(1, pid);
try (ResultSet resultSet = cancelPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is canceled.");
runUpdate(selectedDbcData);
} else {
LOG.info(selectedDbcData.getName() + " failed to cancel " + PID + pid);
}
}
private void dbcDataConnect() {
synchronized (selectedDbcData) {
caMainTree.setInput(selectedDbcData.getProcess());
runUpdate(selectedDbcData);
connectState();
}
}
private void dbcDataDisconnect() {
synchronized (selectedDbcData) {
LOG.debug(MessageFormat.format("Remove dbcData on disconnect \"{0}\" from updaterList",
selectedDbcData.getName()));
selectedDbcData.disconnect();
dbcDataBuilder.removeScheduledUpdater(selectedDbcData);
dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData);
disconnectState();
}
updateUi();
}
private void serversToolBarState() {
if (selectedDbcData != null &&
(selectedDbcData.getStatus() == DbcStatus.CONNECTION_ERROR ||
selectedDbcData.getStatus() == DbcStatus.DISABLED)) {
disconnectState();
} else {
connectState();
}
}
private void connectState() {
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
cancelUpdate.setEnabled(true);
cancelProc.setEnabled(true);
terminateProc.setEnabled(true);
}
private void disconnectState() {
deleteDB.setEnabled(true);
editDB.setEnabled(true);
connectDB.setEnabled(true);
disconnectDB.setEnabled(false);
cancelUpdate.setEnabled(false);
cancelProc.setEnabled(false);
terminateProc.setEnabled(false);
}
private void updateUi() {
display.asyncExec(() -> {
if (!display.isDisposed()) {
caServersTable.refresh();
serversToolBarState();
caMainTree.refresh();
bhMainTree.refresh();
}
trayItem.setImage(getIconImage());
checkBlocks();
});
}
@Override
public void serverUpdated() {
updateUi();
}
} |
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.IncorrectCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.commands.OpenCommand;
import seedu.address.logic.commands.SaveCommand;
import seedu.address.logic.commands.SelectCommand;
import seedu.address.logic.commands.UndoCommand;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return new AddCommandParser().parse(arguments);
case EditCommand.COMMAND_WORD:
return new EditCommandParser().parse(arguments);
case SelectCommand.COMMAND_WORD:
return new SelectCommandParser().parse(arguments);
case DeleteCommand.COMMAND_WORD:
return new DeleteCommandParser().parse(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return new FindCommandParser().parse(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
//@@author A0125221Y
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
//@@author
case SaveCommand.COMMAND_WORD:
return new SaveCommandParser().parse(arguments);
case OpenCommand.COMMAND_WORD:
return new OpenCommandParser().parse(arguments);
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
} |
package server.security;
import org.pac4j.core.credentials.Credentials;
import org.pac4j.core.util.CommonHelper;
import static server.util.StringUtils.capitalizeName;
public class IdCardCredentials extends Credentials {
private final String serial;
private final String firstName;
private final String lastName;
private final String issuer;
private final String country;
// SERIALNUMBER=\d{11},
// GIVENNAME=(firstName),
// SURNAME=(lastName),
// CN="(lastName),(firstName),\d{11}",
// OU=authentication,
// O=(issuer),
// C=(country)
public IdCardCredentials(String subjectDN) {
String[] data = subjectDN.split(", ");
serial = getItem(data, 0);
firstName = capitalizeName(getItem(data, 1));
lastName = capitalizeName(getItem(data, 2));
issuer = getItem(data, 5);
country = getItem(data, 6);
setClientName(IdCardClient.class.getSimpleName());
}
private String getItem(String[] data, int location) {
return data[location].split("=")[1];
}
public String getSerial() {
return serial;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIssuer() {
return issuer;
}
public String getCountry() {
return country;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final IdCardCredentials that = (IdCardCredentials) o;
if (serial != null ? !serial.equals(that.serial) : that.serial != null) {
return false;
} else if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) {
return false;
} else if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) {
return false;
} else if (issuer != null ? !issuer.equals(that.serial) : that.issuer != null) {
return false;
} else if (country != null ? !country.equals(that.country) : that.country != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = serial != null ? serial.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (issuer != null ? issuer.hashCode() : 0);
result = 31 * result + (country != null ? country.hashCode() : 0);
return result;
}
@Override
public String toString() {
return CommonHelper.toString(this.getClass(),
"SerialNumber", serial,
"Firstname", firstName,
"Lastname", lastName,
"Issuer", issuer,
"Country", country,
"clientName", getClientName());
}
} |
package sizebay.catalog.client;
import java.util.*;
import lombok.NonNull;
import sizebay.catalog.client.http.*;
import sizebay.catalog.client.model.*;
import sizebay.catalog.client.model.filters.*;
/**
* A Basic wrapper on generated Swagger client.
*
* @author Miere L. Teixeira
*/
public class CatalogAPI {
final static String
DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/",
ENDPOINT_DASHBOARD = "/dashboard",
ENDPOINT_BRAND = "/brands",
ENDPOINT_MODELING = "/modelings",
ENDPOINT_PRODUCT = "/products",
ENDPOINT_CATEGORIES = "/categories",
ENDPOINT_TENANTS = "/tenants",
ENDPOINT_TENANTS_DETAILS = "/tenants/details",
ENDPOINT_TENANTS_BASIC_DETAILS = "/tenants/details/basic",
ENDPOINT_USER = "/user",
ENDPOINT_SIZE_STYLE = "/style",
ENDPOINT_DEVOLUTION = "/devolution",
ENDPOINT_IMPORTATION_ERROR = "/importations",
ENDPOINT_STRONG_CATEGORY = "/categories/strong",
ENDPOINT_STRONG_SUBCATEGORY = "/categories/strong/sub",
ENDPOINT_STRONG_MODEL = "models/strong",
ENDPOINT_STRONG_MODELING = "/modelings/strong",
SEARCH_BY_TEXT = "/search/all?text=";
final RESTClient client;
/**
* Constructs the Catalog API.
*
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) {
this(DEFAULT_BASE_URL, applicationToken, securityToken);
}
/**
* Constructs the Catalog API.
*
* @param basePath
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) {
final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken );
final MimeType mimeType = new JSONMimeType();
client = new RESTClient( basePath, mimeType, authentication );
}
/**
* Starting dashboard management
*/
public List<Dashboard> retrieveDashboard() {
return client.getList(ENDPOINT_DASHBOARD, Dashboard.class);
}
public Dashboard retrieveDashboardByTenant(Long tenantId) {
return client.getSingle(ENDPOINT_DASHBOARD + "/single/" + tenantId, Dashboard.class);
}
/**
* End dashboard management
*/
public ProductBasicInformationToVFR retrieveProductBasicInformationToVFR(String permalink) {
return client.getSingle(ENDPOINT_PRODUCT + "/basic-info-to-vfr?"
+ "permalink=" + permalink, ProductBasicInformationToVFR.class);
}
/**
* Starting user profile management
*/
public void insertUser (UserProfile userProfile) {
client.post(ENDPOINT_USER, userProfile);
}
public UserProfile retrieveUser (String userId) {
return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class);
}
public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){
return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class);
}
public UserProfile retrieveUserByFacebook(String facebookToken) {
return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class);
}
public UserProfile retrieveUserByGoogle(String googleToken) {
return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class);
}
public UserProfile retrieveUserByApple(String appleUserId) {
return client.getSingle(ENDPOINT_USER + "/social/apple/" + appleUserId, UserProfile.class);
}
public Profile retrieveProfile (long profileId) {
return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class);
}
public void updateUserFacebookToken(String userId, String facebookToken) {
client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken);
}
public void updateUserGoogleToken(String userId, String googleToken) {
client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken);
}
public void updateUserAppleId(String userId, String appleUserId) {
client.put(ENDPOINT_USER + "/social/apple/" + userId, appleUserId);
}
public void insertProfile (Profile profile) {
client.post(ENDPOINT_USER + "/profile", profile);
}
public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); }
/* User history */
public long insertProductInUserHistory(String userId, UserHistory newProductToUserHistory) {
return client.post(ENDPOINT_USER + "/history/single/"+ userId, newProductToUserHistory);
}
public List<UserHistory> retrieveUserHistory(int page, String userId) {
return client.getList(ENDPOINT_USER + "/history/all/" + userId + "?page=" + page, UserHistory.class);
}
public void deleteUserHistoryProduct(String userId, Long userHistoryId) {
client.delete(ENDPOINT_USER + "/history/single/" + userId + "?userHistoryId=" + userHistoryId);
}
/* User liked products */
public long insertLikeInTheProduct(String userId, LikedProduct likedProduct) {
return client.post(ENDPOINT_USER + "/liked-products/single/"+ userId, likedProduct);
}
public List<LikedProduct> retrieveLikedProductsByUser(int page, String userId) {
return client.getList(ENDPOINT_USER + "/liked-products/all/" + userId + "?page=" + page, LikedProduct.class);
}
public void deleteLikeInTheProduct(String userId, Long likedProductId) {
client.delete(ENDPOINT_USER + "/liked-products/single/" + userId + "?likedProductId=" + likedProductId);
}
/*
* End user profile management
*/
/*
* Starting size style management
*/
public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) {
return client.getList(ENDPOINT_SIZE_STYLE + "?" + filter.createQuery(), SizeStyle.class);
}
public SizeStyle getSingleSizeStyle(long id) {
return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class);
}
public long insertSizeStyle(SizeStyle sizeStyle) {
return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle);
}
public void updateWeightStyle(long id, SizeStyle sizeStyle) {
client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle);
}
public void bulkUpdateWeight(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/weight", bulkUpdateSizeStyle);
}
public void bulkUpdateModeling(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/modeling", bulkUpdateSizeStyle);
}
public void deleteSizeStyle(long id) {
client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id);
}
public void deleteSizeStyles(List<Integer> ids) {
client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids);
}
/*
* End size style management
*/
/*
* Starting devolution management
*/
public List<DevolutionError> retrieveDevolutionErrors() {
return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class);
}
public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) {
return client.getList(ENDPOINT_DEVOLUTION + "/errors?" + filter.createQuery(), DevolutionError.class);
}
public long insertDevolutionError(DevolutionError devolution) {
return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution);
}
public void deleteDevolutionErrors() {
client.delete(ENDPOINT_DEVOLUTION + "/errors");
}
public DevolutionSummary retrieveDevolutionSummaryLastBy() {
return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class);
}
public long insertDevolutionSummary(DevolutionSummary devolutionSummary) {
return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary);
}
public void deleteDevolutionSummary() {
client.delete(ENDPOINT_DEVOLUTION + "/summary");
}
/*
* End devolution management
*/
/*
* Starting user (MySizebay) management
*/
public long insertTenantPlatformStore(TenantPlatformStore tenantPlatformStore) {
return client.post(ENDPOINT_TENANTS + "/platform/tenant", tenantPlatformStore);
}
public void updateTenantPlatformStore(Long tenantId, TenantPlatformStore tenantPlatformStore) {
client.put(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, tenantPlatformStore);
}
public UserTenants authenticateAndRetrieveUser(UserAuthenticationDTO userAuthentication) {
return client.post( "/users/authenticate/user", userAuthentication, UserTenants.class );
}
public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) {
return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class );
}
public List<UserTenants> retrieveAllUsersBy(String privilege) {
return client.getList( "/privileges/users?privilege=" + privilege, UserTenants.class );
}
/*
* End user (MySizebay) management
*/
/*
* Starting product management
*/
public List<Product> getProducts(int page) {
return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class);
}
public List<Product> getProducts(ProductFilter filter) {
return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class);
}
public Product getProduct(long id) {
return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class);
}
public Long getProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink,
Long.class);
}
public ProductCount retrieveProductCount() {
return client.getSingle(ENDPOINT_PRODUCT + "/count", ProductCount.class);
}
public ProductSlug retrieveProductSlugByPermalink(String permalink, String sizeLabel){
return client.getSingle(ENDPOINT_PRODUCT + "/slug"
+ "?permalink=" + permalink
+ "&size=" + sizeLabel,
ProductSlug.class);
}
public Long getAvailableProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink
+ "&onlyAvailable=true",
Long.class);
}
public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id"
+ "/" + tenantId
+ "/" + feedProductId,
ProductIntegration.class);
}
public ProductBasicInformation retrieveProductByBarcode(Long barcode) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfo(long id){
return client.getSingle(ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info",
ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){
return client.getSingle( ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info-filter-sizes"
+ "?sizes=" + sizes,
ProductBasicInformation.class);
}
public long insertProduct(Product product) {
return client.post(ENDPOINT_PRODUCT + "/single", product);
}
public void insertProductIntegration(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration", product);
}
public void insertProductIntegrationPlatform(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration/platform", product);
}
public long insertMockedProduct(String permalink) {
return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class);
}
public void updateProduct(long id, Product product) {
client.put(ENDPOINT_PRODUCT + "/single/" + id, product);
}
public void updateProduct(long id, Product product, boolean isAutomaticUpdate) {
client.put(ENDPOINT_PRODUCT + "/single/" + id + "?isAutomaticUpdate=" + isAutomaticUpdate, product);
}
public void bulkUpdateProducts(BulkUpdateProducts products) {
client.patch(ENDPOINT_PRODUCT, products);
}
public void deleteProducts() {
client.delete(ENDPOINT_PRODUCT);
}
public void deleteProduct(long id) {
client.delete(ENDPOINT_PRODUCT + "/single/" + id);
}
public void deleteProductByFeedProductId(long feedProductId) {
client.delete(ENDPOINT_PRODUCT + "/single/feedProduct/" + feedProductId);
}
public void deleteProducts(List<Integer> ids) {
client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids);
}
/*
* End product management
*/
/*
* Starting brand management
*/
public List<Brand> searchForBrands(String text){
return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class);
}
public List<Brand> getBrands(BrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "?" + filter.createQuery(), Brand.class);
}
public List<Brand> getBrands(int page) {
return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class);
}
public List<Brand> getBrands(int page, String name) {
return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class);
}
public Brand getBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class);
}
public long insertBrand(Brand brand) {
return client.post(ENDPOINT_BRAND + "/single", brand);
}
public void associateBrandsWithStrongBrand() {
client.getSingle(ENDPOINT_BRAND + "/sync/associate-brand-with-strong-brand");
}
public void createStrongBrandBasedOnBrands(List<Integer> ids) {
client.post(ENDPOINT_BRAND + "/sync/create-strong-brand", ids);
}
public void updateBrand(long id, Brand brand) {
client.put(ENDPOINT_BRAND + "/single/" + id, brand);
}
public void updateBulkBrandAssociation(BulkUpdateBrandAssociation bulkUpdateBrandAssociation) { client.patch(ENDPOINT_BRAND, bulkUpdateBrandAssociation); }
public void deleteBrands() {
client.delete(ENDPOINT_BRAND);
}
public void deleteBrand(long id) {
client.delete(ENDPOINT_BRAND + "/single/" + id);
}
public void deleteBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/bulk/some", ids);
}
/*
* End brand management
*/
/*
* Starting category management
*/
public List<Category> getCategories() {
return client.getList(ENDPOINT_CATEGORIES, Category.class);
}
public List<Category> getCategories(int page) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class);
}
public List<Category> getCategories(int page, String name) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class);
}
public List<Category> getCategories(CategoryFilter filter) {
return client.getList(ENDPOINT_CATEGORIES + "?" + filter.createQuery(), Category.class);
}
public List<Category> searchForCategories(CategoryFilter filter){
return client.getList(ENDPOINT_CATEGORIES + "/search/all?" + filter.createQuery(), Category.class);
}
public Category getCategory(long id) {
return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class);
}
public long insertCategory(Category brand) {
return client.post(ENDPOINT_CATEGORIES + "/single", brand);
}
public void updateCategory(long id, Category brand) {
client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand);
}
public void bulkUpdateCategories(BulkUpdateCategories categories) {
client.patch(ENDPOINT_CATEGORIES, categories);
}
public void deleteCategories() {
client.delete(ENDPOINT_CATEGORIES);
}
public void deleteCategory(long id) {
client.delete(ENDPOINT_CATEGORIES + "/single/" + id);
}
public void deleteCategories(List<Integer> ids) {
client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids);
}
/*
* End category management
*/
/*
* Starting modeling management
*/
public List<Modeling> searchForModelings(long brandId, String gender) {
return searchForModelings(String.valueOf(brandId), gender);
}
public List<Modeling> searchForModelings(String brandId, String gender){
return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class);
}
public List<Modeling> getModelings(int page){
return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class);
}
public List<Modeling> getModelings(ModelingFilter filter) {
return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class);
}
public List<Modeling> getAllSimplifiedModeling() {
return client.getList(ENDPOINT_MODELING + "/simplified/all", Modeling.class);
}
public Modeling getSingleSimplifiedModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/simplified/single/" + id, Modeling.class);
}
public Modeling getModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class);
}
public long insertModeling(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single", modeling);
}
public long insertModelingWithPopulationOfDomainsAutomatically(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single/automatically", modeling);
}
public void updateModeling(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=false", modeling);
}
public void updateModeling(long id, Modeling modeling, boolean force) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=" + force, modeling);
}
public void updateModelingWithPopulationOfDomainsAutomatically(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "/automatically", modeling);
}
public void deleteModelings() {
client.delete(ENDPOINT_MODELING);
}
public void deleteModeling(long id) {
client.delete(ENDPOINT_MODELING + "/single/" + id);
}
public void deleteModelings(List<Integer> ids) {
client.delete(ENDPOINT_MODELING + "/bulk/some", ids);
}
/*
* End modeling management
*/
/*
* Starting importation error management
*/
public List<ImportationError> getImportationErrors(String page){
return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class);
}
public long insertImportationError(ImportationError importationError){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError);
}
public void deleteImportationErrors() {
client.delete(ENDPOINT_PRODUCT + "/importation-errors/all");
}
public ImportationSummary getImportationSummary(){
return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class);
}
public long insertImportationSummary(ImportationSummary importationSummary){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary);
}
public void deleteImportationSummary() {
client.delete(ENDPOINT_IMPORTATION_ERROR);
}
/*
* End importation error management
*/
/*
* Starting strong brand management
*/
public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class);
}
public StrongBrand getSingleBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class);
}
public long insertStrongBrand(StrongBrand strongBrand){
return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand);
}
public void updateStrongBrand(long id, StrongBrand strongBrand) {
client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand);
}
public void deleteStrongBrand(long id) {
client.delete(ENDPOINT_BRAND + "/strong/single/" + id);
}
public void deleteStrongBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids);
}
/*
* End strong brand management
*/
/*
* Starting strong category management
*/
public List<StrongCategory> getAllStrongCategories(){
return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class);
}
public List<StrongCategory> getAllStrongCategories(String page, String categoryName, String type){
String condition;
condition = categoryName == null ? "" : "&name=" + categoryName;
condition += type == null ? "" : "&type=" + type;
return client.getList(ENDPOINT_STRONG_CATEGORY + "?page=" + page + condition, StrongCategory.class);
}
public StrongCategory getSingleStrongCategory(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class);
}
public long insertStrongCategory(StrongCategory strongCategory){
return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory);
}
public void updateStrongCategory(long id, StrongCategory strongCategory) {
client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory);
}
public void deleteStrongCategory(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id);
}
/*
* End strong category management
*/
/*
* Starting strong subcategory management
*/
public List<StrongSubcategory> getStrongSubcategories(StrongSubcategoryFilter filter){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?" + filter.createQuery(), StrongSubcategory.class);
}
public List<StrongSubcategory> getStrongSubcategories(int page){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class);
}
public StrongSubcategory getSingleStrongSubcategory(long id) {
return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class);
}
public long insertStrongSubcategory(StrongSubcategory strongSubcategory){
return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory);
}
public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) {
client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory);
}
public void deleteStrongSubcategory(long id) {
client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id);
}
/*
* End strong subcategory management
*/
/*
* Starting strong model management
*/
public List<StrongModel> getAllStrongModels(String page){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class);
}
public List<StrongModel> getAllStrongModels(String page, String modelName){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class);
}
public StrongModel getSingleStrongModel(long id) {
return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class);
}
public long insertStrongModel(StrongModel strongModel){
return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel);
}
public void updateStrongModel(long id, StrongModel strongModel) {
client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel);
}
public void deleteStrongModel(long id) {
client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id);
}
/*
* End strong model management
*/
/*
* Starting strong modeling management
*/
public List<StrongModeling> getStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "?" + filter.createQuery(), StrongModeling.class);
}
public List<Long> retrieveAllOrganicTableIds(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/organic/ids" , Long.class);
}
public StrongModeling getSingleStrongModeling(long id) {
return client.getSingle(ENDPOINT_STRONG_MODELING + "/single/" + id, StrongModeling.class);
}
public List<StrongModeling> getAllSimplifiedStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/simplified" + "?" + filter.createQuery(), StrongModeling.class);
}
public long insertStrongModeling(StrongModeling strongModeling){
return client.post(ENDPOINT_STRONG_MODELING + "/single", strongModeling);
}
public void createStrongModelingsBasedOnBrands(String sizeSystem, List<Integer> ids) {
client.post(ENDPOINT_STRONG_MODELING + "/sync/create-strong-modelings?sizeSystem=" + sizeSystem, ids);
}
public void syncStrongModelingsWithSlugs() {
client.post(ENDPOINT_STRONG_MODELING + "/sync", null);
}
public void updateStrongModeling(long id, StrongModeling strongModeling) {
client.put(ENDPOINT_STRONG_MODELING + "/single/" + id, strongModeling);
}
public void deleteStrongModeling(long id) {
client.delete(ENDPOINT_STRONG_MODELING + "/single/" + id);
}
public void deleteStrongModelings(List<Integer> ids) {
client.delete(ENDPOINT_STRONG_MODELING + "/bulk/some", ids);
}
/*
* End strong modeling management
*/
/*
* Starting tenant management
*/
public Tenant getTenant( String appToken ){
return client.getSingle( ENDPOINT_TENANTS+ "/single/" + appToken, Tenant.class );
}
public void inactivateTenant() {
client.put(ENDPOINT_TENANTS + "/inactivate", null);
}
public TenantPlatformStore retrieveTenantPlatformStoreByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/store/" + platform + "/" + storeId, TenantPlatformStore.class);
}
public TenantPlatformStore retrieveTenantPlatformStoreByTenantId(Long tenantId) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, TenantPlatformStore.class);
}
public void deleteTenantPlatformStoreByTenantId(long tenantId) {
client.delete(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId);
}
public Tenant retrieveTenantByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/tenant/store/" + platform + "/" + storeId, Tenant.class);
}
public Tenant getTenantInfo() {
return client.getSingle( ENDPOINT_TENANTS+ "/info/", Tenant.class);
}
public List<TenantDetails> retrieveAllTenantDetails(TenantDetailsFilter filter) {
return client.getList(ENDPOINT_TENANTS_DETAILS + "?" + filter.createQuery(), TenantDetails.class);
}
public List<Tenant> retrieveAllTenants(){
return client.getList( ENDPOINT_TENANTS, Tenant.class );
}
public List<Tenant> retrieveAllTenants(final String domain){
return client.getList( ENDPOINT_TENANTS + "?domain=" + domain, Tenant.class );
}
public List<Tenant> searchTenants(TenantFilter filter) {
return client.getList( ENDPOINT_TENANTS + "/search?monitored=" + filter.getMonitored(), Tenant.class);
}
public List<Tenant> searchAllTenants() {
return client.getList( ENDPOINT_TENANTS + "/search/all", Tenant.class);
}
public Long insertTenant(Tenant tenant) {
return client.post(ENDPOINT_TENANTS, tenant);
}
public void updateTenant(long id, Tenant tenant) {
client.put(ENDPOINT_TENANTS + "/single/" + id, tenant);
}
public void updateTenantIntegration(TenantIntegration tenantIntegration) {
client.put(ENDPOINT_TENANTS + "/integration/", tenantIntegration);
}
public void updateHashXML(String hash) {
client.put(ENDPOINT_TENANTS + "/hash", hash);
}
public void updateFeedXMLHasUpdated(Boolean hasUpdated) {
client.post(ENDPOINT_TENANTS + "/xmlHasUpdated", hasUpdated);
}
public void deleteTenant(long id) {
client.delete(ENDPOINT_TENANTS + "/" + id);
}
public TenantDetails retrieveTenantDetails(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/details/single/" + id, TenantDetails.class);
}
public void updateTenantDetails(TenantDetails tenantDetails) {
client.put(ENDPOINT_TENANTS + "/details/",tenantDetails);
}
public void updateTenantDetailsOnboard(TenantOnboardDetailsDTO tenantOnboardDetailsDTO) {
client.put(ENDPOINT_TENANTS + "/details/onboard", tenantOnboardDetailsDTO);
}
public void updateTenantDetailsLogo(String tenantLogoUrl) {
client.put(ENDPOINT_TENANTS + "/details/logo/",tenantLogoUrl);
}
public void patchUpdateTenantBasicDetails(TenantBasicDetails tenantBasicDetails) {
client.patch(ENDPOINT_TENANTS_BASIC_DETAILS, tenantBasicDetails);
}
/*
* End tenant management
*/
/*
* Starting tenant management
*/
public List<MySizebayUser> attachedUsersToTenant(long id) {
return client.getList(ENDPOINT_TENANTS + "/" + id + "/users", MySizebayUser.class);
}
public void attachUserToTenant(long id, String email) {
client.getSingle(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
public void detachUserToTenant(long id, String email) {
client.delete(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
/*
* End tenant management
*/
/*
* Starting importation rules management
*/
public String retrieveImportRules(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/" + id + "/rules", String.class);
}
public Long insertImportationRules(long id, ImportationRules rules) {
return client.post(ENDPOINT_TENANTS + "/" + id + "/rules", rules);
}
/*
* End importation rules management
*/
/*
* Starting my sizebay user management
*/
public MySizebayUser getMySizebayUser(String username){
return client.getSingle( "/users/" + username, MySizebayUser.class);
}
public Long insertMySizebayUser(MySizebayUser user){
return client.post("/users/", user);
}
public Long insertMySizebayUserCS(MySizebayUser user){
return client.post("/users/cs", user);
}
public void deleteMySizebayUser(Long userId) {
client.delete("/users/" + userId);
}
public void updateMySizebayUser(Long userId, MySizebayUser user) {
client.put("/tenants/users/single/" + userId, user);
}
public void updatePasswordUser(Long userId, MySizebayUserResetPassword user) {
client.patch("/tenants/users/password/" + userId, user);
}
public void updateUserAcceptanceTerms(UserTerms userTerms) {
client.patch("/user-terms/acceptance/", userTerms);
}
public UserTerms retrieveUseTerms(Long userId){
return client.getSingle( "/user-terms/" + userId, UserTerms.class);
}
/*
* End my sizebay user management
*/
public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) {
client.post( "/importations/tenantId/"+tenantId, importationSummary );
}
/*
* Starting product manipulation rules management
*/
public ProductManipulationRules retrieveProductManipulationRules() {
return client.getSingle(ENDPOINT_PRODUCT + "/manipulations/rules", ProductManipulationRules.class);
}
public void insertProductManipulationRules(ProductManipulationRules productManipulationRules) {
client.post(ENDPOINT_PRODUCT + "/manipulations/rules/single", productManipulationRules);
}
/*
* End product manipulation rules management
*/
} |
package solutions;
import java.util.ArrayList;
import java.util.List;
public class ValidPalindromeSolution {
public boolean isPalindrome(String s) {
String target = s.trim();
if (target.isEmpty()) {
return true;
}
String[] words = extractWords(target);
for (int i = 0; i < words.length / 2; i++) {
if (!words[i].equals(words[words.length - 1 - i])) {
return false;
}
}
return true;
}
private String[] extractWords(String s) {
String[] chars = s.toLowerCase().split("|");
List<String> words = new ArrayList<>(chars.length);
for (String c : chars) {
if (Character.isLetterOrDigit(c.charAt(0))) {
words.add(c);
}
}
return words.toArray(new String[words.size()]);
}
} |
package modules.admin.Group;
import java.util.List;
import org.skyve.CORE;
import org.skyve.metadata.model.document.Bizlet.DomainValue;
import modules.admin.User.UserBizlet;
import modules.admin.domain.Group;
import modules.admin.domain.GroupRole;
/**
* Synthesize Group Roles from metadata.
* @author mike
*/
public class GroupExtension extends Group {
private static final long serialVersionUID = 2678377209921744911L;
private boolean determinedCandidateRoles = false;
@Override
public List<GroupRole> getCandidateRoles() {
if (! determinedCandidateRoles) {
List<GroupRole> candidates = super.getCandidateRoles();
candidates.clear();
candidates.addAll(getRoles());
for (DomainValue value : UserBizlet.getCustomerRoleValues(CORE.getUser())) {
if (! candidates.stream().anyMatch(c -> c.getRoleName().equals(value.getCode()))) {
GroupRole role = GroupRole.newInstance();
role.setRoleName(value.getCode());
role.setParent(this);
role.originalValues().clear();
candidates.add(role);
}
}
determinedCandidateRoles = true;
}
return super.getCandidateRoles();
}
void resetCandidateRoles() {
determinedCandidateRoles = false;
}
} |
package com.brstf.simplelife;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.WindowManager;
import com.brstf.simplelife.controls.LifeController;
import com.brstf.simplelife.data.HistoryInt;
import com.brstf.simplelife.data.LifeDbAdapter;
import com.brstf.simplelife.widgets.LifeView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class LifeCount extends SlidingFragmentActivity implements
OnSharedPreferenceChangeListener {
private LifeController p1Controller;
private LifeController p2Controller;
private HistoryInt p1Life;
private HistoryInt p2Life;
private SlidingMenuLogListFragment mLogFragRight;
private SlidingMenuLogListFragment mLogFragLeft;
private SharedPreferences mPrefs;
private LifeDbAdapter mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
setupPreferences();
int theme_id = mPrefs.getInt(
getResources().getString(R.string.key_theme),
R.style.AppBaseThemeLight);
this.setTheme(theme_id);
super.onCreate(savedInstanceState);
mDbHelper = new LifeDbAdapter(this);
// Restore life histories
int start_total = mPrefs.getInt(getString(R.string.key_total),
getResources().getInteger(R.integer.default_total));
long interval = getResources().getInteger(R.integer.update_interval);
p1Life = new HistoryInt(start_total, interval);
p2Life = new HistoryInt(start_total, interval);
p1Controller = new LifeController(p1Life);
p2Controller = new LifeController(p2Life);
initializeLife(savedInstanceState);
// Don't turn screen off
setWakeFlag(mPrefs.getBoolean(getString(R.string.key_wake), true));
setContentView(R.layout.life_count);
// Initialize Player 1:
LifeView p1 = (LifeView) findViewById(R.id.player1_lv);
p1.setLifeController(p1Controller);
p1.setInversed(false);
// Initialize Player 2:
LifeView p2 = (LifeView) findViewById(R.id.player2_lv);
p2.setInversed(mPrefs.getBoolean(getString(R.string.key_invert), true));
p2.setLifeController(p2Controller);
// Set poison visibility
setPoisonVisible(mPrefs.getBoolean(getString(R.string.key_poison),
false));
setBigmodChanged(mPrefs
.getBoolean(getString(R.string.key_bigmod), true));
// Set background
if (mPrefs.getInt(getString(R.string.key_theme), R.style.AppBaseThemeLight) == R.style.AppBaseThemeMana){
setBackgroundChanged(mPrefs.getInt(getString(R.string.key_background), ManaType.NONE));
} else {
setBackgroundChanged(ManaType.NONE);
}
setBehindContentView(R.layout.sliding_menu_frame);
getSlidingMenu().setSecondaryMenu(R.layout.sliding_menu_frame2);
// Make sliding menu fragments
createSlidingMenus();
}
@Override
public void onResume() {
super.onResume();
// Register this activity as a listener for preference changes
mPrefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
if (mLogFragLeft.getFragmentManager().getBackStackEntryCount()
+ mLogFragRight.getFragmentManager()
.getBackStackEntryCount() == 0) {
this.showMenu();
this.mLogFragLeft.showOptions();
} else {
this.showContent();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Setup a SharedPreferences with default values if it doesn't exist, then
* read preferences used for setup.
*/
private void setupPreferences() {
mPrefs = getPreferences(Context.MODE_PRIVATE);
// Fill SharedPreferences with default information if they don't exist
if (mPrefs.getAll().size() == 0) {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean(getString(R.string.key_invert), true);
edit.putInt(getString(R.string.key_total), getResources()
.getInteger(R.integer.default_total));
edit.putInt(getString(R.string.key_uppernum), getResources()
.getInteger(R.integer.default_upper));
edit.putInt(getString(R.string.key_changes), getResources()
.getInteger(R.integer.default_changes));
edit.putBoolean(getString(R.string.key_poison), false);
edit.putBoolean(getString(R.string.key_wake), true);
edit.putBoolean(getString(R.string.key_quick), false);
edit.putFloat(getString(R.string.key_entry), 2.0f);
edit.putBoolean(getString(R.string.key_bigmod), true);
edit.putInt(getString(R.string.key_dice_sides), 6);
edit.putInt(getString(R.string.key_dice_num), 2);
edit.putInt(getString(R.string.key_theme),
R.style.AppBaseThemeLight);
edit.putInt(getString(R.string.key_background), ManaType.PLAINS);
edit.commit();
}
}
/**
* Create the life HistoryInt's, restoring their histories from the saved
* bundle if any.
*
* @param savedInstanceState
* Bundle with histories saved
*/
private void initializeLife(Bundle savedInstanceState) {
// If there's no saved instance state, restore from database
mDbHelper.open();
int p1count = mDbHelper.getRowCount(LifeDbAdapter.getP1Table());
int p2count = mDbHelper.getRowCount(LifeDbAdapter.getP2Table());
if (p1count != 0 && p2count != 0) {
mDbHelper.restoreLife(LifeDbAdapter.getP1Table(), p1Controller);
mDbHelper.restoreLife(LifeDbAdapter.getP2Table(), p2Controller);
}
mDbHelper.close();
if (p1Controller.getHistory().size() == 0
|| p2Controller.getHistory().size() == 0) {
reset();
}
}
@Override
protected void onPause() {
super.onPause();
// On activity destruction, write the life totals to the database
mDbHelper.open();
mDbHelper.clear();
mDbHelper.addLife(LifeDbAdapter.getP1Table(), p1Controller);
mDbHelper.addLife(LifeDbAdapter.getP2Table(), p2Controller);
mDbHelper.close();
// Unregister preference listener
mPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
/**
* Create the sliding menus for this activity. If savedInstanceState is not
* null, the menu fragment can simply be retrieved from the fragment
* manager.
*
* @param savedInstanceState
* If the activity is being re-initialized after previously being
* shut down then this Bundle contains the data it most recently
* supplied in onSaveInstanceState(Bundle). Note: Otherwise it is
* null.
*/
private void createSlidingMenus() {
SlidingMenu menu = getSlidingMenu();
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setFadeDegree(0.35f);
menu.setMenu(R.layout.sliding_menu_frame);
menu.setBehindOffsetRes(R.dimen.sliding_menu_offset);
menu.setShadowDrawable(R.drawable.sliding_menu_shadow);
menu.setShadowWidthRes(R.dimen.sliding_menu_shadow_width);
menu.setMode(SlidingMenu.LEFT_RIGHT);
menu.setSecondaryShadowDrawable(R.drawable.sliding_menu_shadow_right);
menu.setOnClosedListener(new OnClosedListener() {
@Override
public void onClosed() {
closeOptions();
}
});
Fragment optionsLeft = getFragmentManager().findFragmentByTag(
"LEFT_OPTIONS");
Fragment optionsRight = getFragmentManager().findFragmentByTag(
"RIGHT_OPTIONS");
mLogFragRight = (SlidingMenuLogListFragment) getFragmentManager()
.findFragmentByTag("RIGHT");
mLogFragLeft = (SlidingMenuLogListFragment) getFragmentManager()
.findFragmentByTag("LEFT");
FragmentTransaction ft;
// Only create new fragments if they don't exist
if (mLogFragRight == null || mLogFragLeft == null) {
mLogFragRight = new SlidingMenuLogListFragment();
mLogFragLeft = new SlidingMenuLogListFragment();
ft = getFragmentManager().beginTransaction();
ft = ft.replace(R.id.sliding_menu_frame2, mLogFragRight, "RIGHT");
ft = ft.replace(R.id.sliding_menu_frame, mLogFragLeft, "LEFT");
ft.commit();
}
ft = getFragmentManager().beginTransaction();
mLogFragRight.setControllers(p1Controller, p2Controller);
mLogFragLeft.setControllers(p1Controller, p2Controller);
// Restore the options fragments if they exist
if (optionsRight != null) {
ft = ft.replace(R.id.sliding_menu_frame2, optionsRight,
"RIGHT_OPTIONS");
}
if (optionsLeft != null) {
ft = ft.replace(R.id.sliding_menu_frame, optionsLeft,
"LEFT_OPTIONS");
}
// If there are any changes to be done, commit them
if (!ft.isEmpty()) {
ft.commit();
}
getFragmentManager().executePendingTransactions();
// set the fragments to be inverted as necessary
mLogFragRight.setUpperInverted(mPrefs.getBoolean(
getString(R.string.key_invert), true));
mLogFragLeft.setUpperInverted(mPrefs.getBoolean(
getString(R.string.key_invert), true));
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& getSlidingMenu().isMenuShowing()) {
// Try to close options before the sliding menu
if (!closeOptions()) {
// Otherwise, close the sliding menu as normal
showContent();
}
return true;
}
return super.onKeyUp(keyCode, event);
}
private boolean closeOptions() {
FragmentManager fml = mLogFragLeft.getFragmentManager();
FragmentManager fmr = mLogFragRight.getFragmentManager();
// Check if settings are showing, if they are just pop it off
if (fmr != null
&& mLogFragRight.getFragmentManager().getBackStackEntryCount() > 0) {
mLogFragRight.getFragmentManager().popBackStack();
return true;
}
if (fml != null
&& mLogFragLeft.getFragmentManager().getBackStackEntryCount() > 0) {
mLogFragLeft.getFragmentManager().popBackStack();
return true;
}
return false;
}
/**
* Get the SharedPreferences of this Activity.
*
* @return SharedPreferences object associated with this Activtiy.
*/
public SharedPreferences getPrefs() {
return mPrefs;
}
/**
* Get the LifeController for player 1.
*
* @return LifeController for player 1
*/
public LifeController getP1Controller() {
return p1Controller;
}
/**
* Get the LifeController for player 2.
*
* @return LifeController for player 2
*/
public LifeController getP2Controller() {
return p2Controller;
}
/**
* Resets both life totals to their starting values.
*/
public void reset() {
saveStats();
int rval = mPrefs.getInt(getString(R.string.key_total), 20);
p1Controller.reset(rval);
p2Controller.reset(rval);
}
/**
* Resets both life totals to the given value.
*
* @param resetval
* Value to reset the life totals to
*/
public void reset(int resetval) {
saveStats();
p1Controller.reset(resetval);
p2Controller.reset(resetval);
}
/**
* Save the stats of the current life controllers to their respective
* tables.
*/
private void saveStats() {
mDbHelper.open();
mDbHelper.addStatsFromTo(p1Controller, LifeDbAdapter.getP1StatsTable());
mDbHelper.addStatsFromTo(p2Controller, LifeDbAdapter.getP2StatsTable());
mDbHelper.close();
}
/**
* Sets whether or not the upper display is inverted. Typically called from
* the settings fragment.
*
* @param invert
* True if the upper display should be inverted, false otherwise.
*/
private void setUpperInverted(boolean invert) {
((LifeView) findViewById(R.id.player2_lv)).setInversed(invert);
mLogFragRight.setUpperInverted(invert);
mLogFragLeft.setUpperInverted(invert);
}
/**
* Sets whether or not the poison counters / toggle button are visible.
*
* @param visible
* True if the poison items would be visible, false otherwise
*/
private void setPoisonVisible(boolean visible) {
((LifeView) findViewById(R.id.player2_lv)).setPoisonVisible(visible);
((LifeView) findViewById(R.id.player1_lv)).setPoisonVisible(visible);
}
/**
* Sets or clears the wake flag to keep screen on or let it turn off.
*
* @param wake
* True if screen should stay on, false otherwise
*/
private void setWakeFlag(boolean wake) {
if (wake) {
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
/**
* Set the entry interval time (in seconds), the time until a modification
* to a life total is "locked-in".
*
* @param interval
* Entry interval time (in seconds)
*/
private void setEntryInterval(float interval) {
long entrytime = (long) (interval * 1000.0);
p1Life.setInterval(entrytime);
p2Life.setInterval(entrytime);
}
/**
* Set whether or not the "Quick-Reset" option is enabled.
*
* @param quick
* True if quick-reset should be enabled, false otherwise
*/
private void setQuickReset(boolean quick) {
mLogFragRight.setQuickReset(quick);
mLogFragLeft.setQuickReset(quick);
}
/**
* Set whether or not the "+5/-5" buttons are enabled.
*
* @param bigmod
* True if +5/-5 buttons should be enabled, false otherwise
*/
private void setBigmodChanged(boolean bigmod) {
((LifeView) findViewById(R.id.player2_lv)).setBigmodEnabled(bigmod);
((LifeView) findViewById(R.id.player1_lv)).setBigmodEnabled(bigmod);
}
/**
* Set or clear background.
*
* @param manaType
* int representing manaType for background choice. ManaType.NONE or 0 clears background.
*/
private void setBackgroundChanged(int manaType) {
int resid;
switch (manaType) {
case ManaType.NONE:
resid = 0;
break;
case ManaType.PLAINS:
resid = R.drawable.background_image;
break;
case ManaType.ISLAND:
resid = R.drawable.background_image;
break;
case ManaType.SWAMP:
resid = R.drawable.background_image;
break;
case ManaType.MOUNTAIN:
resid = R.drawable.background_image;
break;
case ManaType.FOREST:
resid = R.drawable.background_image;
break;
default:
resid = 0;
}
//Log.d("BACKGROUND_CHANGED", "manaType: " + manaType + ", resid: " + resid);
this.findViewById(R.id.lifecount_rl).setBackgroundResource(resid);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// Properly respond depending on which preference was changed
if (key == getString(R.string.key_poison)) {
// Poison Changed
setPoisonVisible(mPrefs.getBoolean(key, false));
} else if (key == getString(R.string.key_invert)) {
// Inverted upper life view changed
setUpperInverted(mPrefs.getBoolean(key, true));
} else if (key == getString(R.string.key_wake)) {
// Wake lock setting changed
setWakeFlag(mPrefs.getBoolean(key, true));
} else if (key == getString(R.string.key_quick)) {
// Quick reset setting changed
setQuickReset(mPrefs.getBoolean(key, false));
} else if (key == getString(R.string.key_entry)) {
// Entry time changed
setEntryInterval(mPrefs.getFloat(key, 2.0f));
} else if (key == getString(R.string.key_bigmod)) {
// Bigmod preference changed
setBigmodChanged(mPrefs.getBoolean(key, true));
} else if (key == getString(R.string.key_theme)) {
// Theme changed
this.recreate();
} else if (key == getString(R.string.key_background)) {
// Background preference changed
setBackgroundChanged(mPrefs.getInt(key, ManaType.NONE));
}
}
} |
package com.kickstarter.models;
import android.content.Context;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.StringDef;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import com.kickstarter.R;
import com.kickstarter.libs.CurrencyOptions;
import com.kickstarter.libs.NumberUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
@ParcelablePlease
public class Project implements Parcelable {
public Integer backers_count = null;
public String blurb = null;
public Category category = null;
public Integer comments_count = null;
public String country = null; // e.g.: US
public DateTime created_at = null;
public String currency = null; // e.g.: USD
public String currency_symbol = null;
public Boolean currency_trailing_code = false;
public DateTime deadline = null;
public Float goal = null;
public Integer id = null; // in the Kickstarter app, this is project.pid not project.id
public DateTime launched_at = null;
public Location location = null;
public String name = null;
public Float pledged = null;
public Photo photo = null;
public Video video = null;
public DateTime potd_at = null;
public @State String state = null;
public String slug = null;
public User creator = null;
public Integer updates_count = null;
public Urls urls = null;
public List<Reward> rewards = null;
public DateTime updated_at = null;
public Integer backersCount() { return backers_count; }
public String formattedBackersCount() {
return NumberUtils.numberWithDelimiter(backers_count);
}
public String blurb() { return blurb; }
public Category category() { return category; }
public User creator() { return creator; }
public String formattedCommentsCount() {
return NumberUtils.numberWithDelimiter(comments_count);
}
public String country() { return country; }
public String currency() { return currency; }
public String currencySymbol() { return currency_symbol; }
public Boolean currencyTrailingCode() { return currency_trailing_code; }
public DateTime deadline() { return deadline; }
public Float goal() { return goal; }
public Integer id() { return id; }
public DateTime launchedAt() { return launched_at; }
public Location location() { return location; }
public String name() { return name; }
public Float pledged() { return pledged; }
public Photo photo() { return photo; }
public @State String state() { return state; }
public Video video() { return video; }
public String slug() { return slug; }
public String formattedUpdatesCount() {
return NumberUtils.numberWithDelimiter(updates_count);
}
public Urls urls() { return urls; }
public String creatorBioUrl() {
return urls().web().creatorBio();
}
public String descriptionUrl() {
return urls().web().description();
}
public String webProjectUrl() { return urls().web().project(); }
public String updatesUrl() {
return urls().web().updates();
}
public static final String STATE_STARTED = "started";
public static final String STATE_SUBMITTED = "submitted";
public static final String STATE_LIVE = "live";
public static final String STATE_SUCCESSFUL = "successful";
public static final String STATE_FAILED = "failed";
public static final String STATE_CANCELED = "canceled";
public static final String STATE_SUSPENDED = "suspended";
public static final String STATE_PURGED = "purged";
@Retention(RetentionPolicy.SOURCE)
@StringDef({STATE_STARTED, STATE_SUBMITTED, STATE_LIVE, STATE_SUCCESSFUL, STATE_FAILED, STATE_CANCELED, STATE_SUSPENDED, STATE_PURGED})
public @interface State {}
public List<Reward> rewards() {
return rewards;
}
static public Project createFromParam(final String param) {
final Project project = new Project();
try {
project.id = Integer.parseInt(param);
} catch (NumberFormatException e) {
project.slug = param;
}
return project;
}
@ParcelablePlease
public static class Urls implements Parcelable {
public Web web = null;
public Api api = null;
public Web web() {
return web;
}
public Api api() {
return api;
}
@ParcelablePlease
public static class Web implements Parcelable {
public String project = null;
public String rewards = null;
public String updates = null;
public String creatorBio() { return Uri.parse(project()).buildUpon().appendEncodedPath("/creator_bio").toString(); }
public String description() { return Uri.parse(project()).buildUpon().appendEncodedPath("/description").toString(); }
public String project() { return project; }
public String rewards() { return rewards; }
public String updates() { return updates; }
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {com.kickstarter.models.WebParcelablePlease.writeToParcel(this, dest, flags);}
public static final Creator<Web> CREATOR = new Creator<Web>() {
public Web createFromParcel(Parcel source) {
Web target = new Web();
com.kickstarter.models.WebParcelablePlease.readFromParcel(target, source);
return target;
}
public Web[] newArray(int size) {return new Web[size];}
};
}
@ParcelablePlease
public static class Api implements Parcelable {
public String comments = null;
public String comments() { return comments; }
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {com.kickstarter.models.ApiParcelablePlease.writeToParcel(this, dest, flags);}
public static final Creator<Api> CREATOR = new Creator<Api>() {
public Api createFromParcel(Parcel source) {
Api target = new Api();
com.kickstarter.models.ApiParcelablePlease.readFromParcel(target, source);
return target;
}
public Api[] newArray(int size) {return new Api[size];}
};
}
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {com.kickstarter.models.UrlsParcelablePlease.writeToParcel(this, dest, flags);}
public static final Creator<Urls> CREATOR = new Creator<Urls>() {
public Urls createFromParcel(Parcel source) {
Urls target = new Urls();
com.kickstarter.models.UrlsParcelablePlease.readFromParcel(target, source);
return target;
}
public Urls[] newArray(int size) {return new Urls[size];}
};
}
public CurrencyOptions currencyOptions() {
return new CurrencyOptions(country, currency_symbol, currency);
}
/** Returns whether the project is in a canceled state. */
public boolean isCanceled() {
return STATE_CANCELED.equals(state);
}
/** Returns whether the project is in a failed state. */
public boolean isFailed() {
return STATE_FAILED.equals(state);
}
/** Returns whether the project is in a live state. */
public boolean isLive() {
return STATE_LIVE.equals(state);
}
public boolean isPotdToday() {
if (potd_at == null) {
return false;
}
final DateTime startOfDayUTC = new DateTime(DateTimeZone.UTC).withTime(0, 0, 0, 0);
return startOfDayUTC.isEqual(potd_at.withZone(DateTimeZone.UTC));
}
/** Returns whether the project is in a purged state. */
public boolean isPurged() {
return STATE_PURGED.equals(state);
}
/** Returns whether the project is in a live state. */
public boolean isStarted() {
return STATE_STARTED.equals(state);
}
/** Returns whether the project is in a submitted state. */
public boolean isSubmitted() {
return STATE_SUBMITTED.equals(state);
}
/** Returns whether the project is in a suspended state. */
public boolean isSuspended() {
return STATE_SUSPENDED.equals(state);
}
/** Returns whether the project is in a successful state. */
public boolean isSuccessful() {
return STATE_SUCCESSFUL.equals(state);
}
public Float percentageFunded() {
if (goal > 0.0f) {
return (pledged / goal) * 100.0f;
}
return 0.0f;
}
/**
* Returns a String describing the time remaining for a project, e.g.
* 25 minutes to go, 8 days to go.
*
* @param context an Android context.
* @return the String time remaining.
*/
public String timeToGo(final Context context) {
return new StringBuilder(deadlineCountdown(context))
.append(context.getString(R.string._to_go))
.toString();
}
/**
* Returns time until project reaches deadline along with the unit,
* e.g. 25 minutes, 8 days.
*
* @param context an Android context.
* @return the String time remaining.
*/
public String deadlineCountdown(final Context context) {
return new StringBuilder().append(deadlineCountdownValue())
.append(" ")
.append(deadlineCountdownUnit(context))
.toString();
}
/**
* Returns time until project reaches deadline in seconds, or 0 if the
* project has already finished.
*
* @return the Long number of seconds remaining.
*/
public Long timeInSecondsUntilDeadline() {
return Math.max(0L,
new Duration(new DateTime(), deadline).getStandardSeconds());
}
/**
* Returns time remaining until project reaches deadline in either seconds,
* minutes, hours or days. A time unit is chosen such that the number is
* readable, e.g. 5 minutes would be preferred to 300 seconds.
*
* @return the Integer time remaining.
*/
public Integer deadlineCountdownValue() {
final Long seconds = timeInSecondsUntilDeadline();
if (seconds <= 120.0) {
return seconds.intValue(); // seconds
} else if (seconds <= 120.0 * 60.0) {
return (int) Math.floor(seconds / 60.0); // minutes
} else if (seconds < 72.0 * 60.0 * 60.0) {
return (int) Math.floor(seconds / 60.0 / 60.0); // hours
}
return (int) Math.floor(seconds / 60.0 / 60.0 / 24.0); // days
}
/**
* Returns the most appropriate unit for the time remaining until the project
* reaches its deadline.
*
* @param context an Android context.
* @return the String unit.
*/
public String deadlineCountdownUnit(final Context context) {
final Long seconds = timeInSecondsUntilDeadline();
if (seconds <= 1.0 && seconds > 0.0) {
return context.getString(R.string.secs);
} else if (seconds <= 120.0) {
return context.getString(R.string.secs);
} else if (seconds <= 120.0 * 60.0) {
return context.getString(R.string.mins);
} else if (seconds <= 72.0 * 60.0 * 60.0) {
return context.getString(R.string.hours);
}
return context.getString(R.string.days);
}
public boolean isDisplayable() {
return created_at != null;
}
public String param() {
return id != null ? id.toString() : slug;
}
public String secureWebProjectUrl() {
// TODO: Just use http with local env
return Uri.parse(webProjectUrl()).buildUpon().scheme("https").build().toString();
}
public String newPledgeUrl() {
return Uri.parse(secureWebProjectUrl()).buildUpon().appendEncodedPath("pledge/new").toString();
}
public String editPledgeUrl() {
return Uri.parse(secureWebProjectUrl()).buildUpon().appendEncodedPath("pledge/edit").toString();
}
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {ProjectParcelablePlease.writeToParcel(this, dest, flags);}
public static final Creator<Project> CREATOR = new Creator<Project>() {
public Project createFromParcel(Parcel source) {
Project target = new Project();
ProjectParcelablePlease.readFromParcel(target, source);
return target;
}
public Project[] newArray(int size) {return new Project[size];}
};
} |
package com.xlythe.sms;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.xlythe.sms.adapter.MessageAdapter;
import com.xlythe.sms.fragment.CameraFragment;
import com.xlythe.sms.fragment.StickerFragment;
import com.xlythe.sms.fragment.GalleryFragment;
import com.xlythe.sms.fragment.MicFragment;
import com.xlythe.sms.receiver.Notifications;
import com.xlythe.sms.util.ActionBarUtils;
import com.xlythe.sms.util.ColorUtils;
import com.xlythe.textmanager.text.Status;
import com.xlythe.textmanager.text.TextReceiver;
import com.xlythe.textmanager.text.concurrency.Future;
import com.xlythe.textmanager.text.util.MessageUtils;
import com.xlythe.sms.view.ExtendedEditText;
import com.xlythe.textmanager.MessageObserver;
import com.xlythe.textmanager.text.Attachment;
import com.xlythe.textmanager.text.Contact;
import com.xlythe.textmanager.text.Text;
import com.xlythe.textmanager.text.TextManager;
import com.xlythe.textmanager.text.Thread;
import com.xlythe.textmanager.text.util.Utils;
import java.util.Set;
public class MessageActivity extends AppCompatActivity implements MessageAdapter.OnClickListener {
private static final String TAG = TextManager.class.getSimpleName();
private static final boolean DEBUG = true;
public static final String EXTRA_THREAD = "thread";
/* ChooserTargetService cannot send Parcelables, so we make do with just the id */
public static final String EXTRA_THREAD_ID = "thread_id";
private static Thread sActiveThread = null;
public static boolean isVisible(String threadId) {
if (sActiveThread != null) {
return threadId.equals(sActiveThread.getId());
}
return false;
}
// Keyboard hack
private int mScreenSize;
private int mKeyboardSize;
private boolean mAdjustNothing;
private boolean mKeyboardOpen;
private AppBarLayout mAppbar;
private View mAttachView;
private ExtendedEditText mEditText;
private ImageView mSendButton;
private Thread mThread;
private TextManager mManager;
private RecyclerView mRecyclerView;
private MessageAdapter mAdapter;
private final MessageObserver mMessageObserver = new MessageObserver() {
@Override
public void notifyDataChanged() {
boolean scroll = isScrolledToBottom(mRecyclerView);
mAdapter.swapCursor(mManager.getMessageCursor(mThread));
mManager.markAsRead(mThread);
if (scroll) {
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
private boolean isScrolledToBottom(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION) {
if (lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1) {
// The last item is visible. Fully (or at least mostly) scrolled.
return true;
}
}
}
return false;
}
};
private ActionModeCallback mActionModeCallback = new ActionModeCallback();
private ActionMode mActionMode;
private ImageView mGalleryAttachments;
private ImageView mCameraAttachments;
private ImageView mStickerAttachments;
private ImageView mMicAttachments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Window rootWindow = getWindow();
final View root = rootWindow.getDecorView().findViewById(android.R.id.content);
// Seems redundant to set as ADJUST_NOTHING in manifest and then immediately to ADJUST_RESIZE
// but it seems that the input gets reset to a default on keyboard dismissal if not set otherwise.
rootWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
Rect r = new Rect();
View view = rootWindow.getDecorView();
view.getWindowVisibleDisplayFrame(r);
if (mScreenSize != 0 && mScreenSize != r.bottom) {
mKeyboardSize = mScreenSize - r.bottom;
mAttachView.getLayoutParams().height = mKeyboardSize;
rootWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
if (mKeyboardOpen) {
mAttachView.setVisibility(View.VISIBLE);
}
mAdjustNothing = true;
} else {
mScreenSize = r.bottom;
}
}
});
mAppbar = (AppBarLayout) findViewById(R.id.appbar);
mAttachView = findViewById(R.id.fragment_container);
mEditText = (ExtendedEditText) findViewById(R.id.edit_text);
mSendButton = (ImageView) findViewById(R.id.send);
setSendable(false);
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send();
}
});
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
send();
return true;
}
return false;
}
});
mEditText.setOnDismissKeyboardListener(new ExtendedEditText.OnDismissKeyboardListener() {
@Override
public void onDismissed() {
mEditText.clearFocus();
onAttachmentHidden();
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setSendable(s.length() > 0);
}
@Override
public void afterTextChanged(Editable s) {}
});
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
mKeyboardOpen = hasFocus;
if(hasFocus) {
clearAttachmentSelection();
if (!mAdjustNothing) {
onAttachmentHidden();
} else {
// Just because it has focus doesnt mean the keyboard actually opened
// This seems like an easier fix than not showing the attachview
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mEditText, 0);
mAttachView.setVisibility(View.VISIBLE);
}
}
}
});
mManager = TextManager.getInstance(getBaseContext());
mThread = getIntent().getParcelableExtra(EXTRA_THREAD);
if (mThread == null) {
String id = getIntent().getStringExtra(EXTRA_THREAD_ID);
mThread = mManager.getThread(id).get();
}
if (DEBUG) {
Log.d(TAG, "Opening Activity for thread " + mThread);
}
String name = Utils.join(", ", mThread.getLatestMessage(this).get().getMembersExceptMe(this).get(), new Utils.Rule<Contact>() {
@Override
public String toString(Contact contact) {
return contact.getDisplayName();
}
});
getSupportActionBar().setTitle(ColorUtils.color(0x212121, name));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarUtils.grayUpArrow(this);
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(ColorUtils.getDarkColor(mThread.getIdAsLong()));
}
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setHasFixedSize(false);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
// maybe add transcript mode, and show a notification of new messages
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new MessageAdapter(this, mManager.getMessageCursor(mThread));
mAdapter.setOnClickListener(this);
mRecyclerView.setAdapter(mAdapter);
mManager.registerObserver(mMessageObserver);
// It bothers me when the keyboard doesnt collapse, remove it if you want
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState > 0) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
mEditText.clearFocus();
onAttachmentHidden();
}
}
});
mGalleryAttachments = (ImageView) findViewById(R.id.gallery);
mCameraAttachments = (ImageView) findViewById(R.id.camera);
mStickerAttachments = (ImageView) findViewById(R.id.sticker);
mMicAttachments = (ImageView) findViewById(R.id.mic);
// Hide the camera fragment if the device has no camera
mCameraAttachments.setVisibility(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) ? View.VISIBLE : View.GONE);
// TODO: Unhide when support is ready
mMicAttachments.setVisibility(View.GONE);
if (savedInstanceState == null) {
// This is the first time this Activity is launched. Lets check the intent to prepopulate the message.
Text text = MessageUtils.parse(this, getIntent());
if (text != null) {
if (text.getAttachment() != null) {
// The text has an attachment. Send immediately.
mManager.send(text);
} else {
mEditText.setText(text.getBody());
}
}
}
}
public void setSendable(boolean sendable){
mSendButton.setEnabled(sendable);
if (sendable) {
mSendButton.setColorFilter(ColorUtils.getColor(mThread.getIdAsLong()), PorterDuff.Mode.SRC_ATOP);
} else {
mSendButton.clearColorFilter();
}
}
public void onAttachmentClicked(View view){
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
mEditText.clearFocus();
mAttachView.setVisibility(View.VISIBLE);
clearAttachmentSelection();
int color = ColorUtils.getColor(mThread.getIdAsLong());
((ImageView) view).setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Text text = mThread.getLatestMessage(this).get();
switch (view.getId()) {
case R.id.gallery:
transaction.replace(R.id.fragment_container, GalleryFragment.newInstance(text, color)).commit();
mGalleryAttachments.setEnabled(false);
break;
case R.id.camera:
transaction.replace(R.id.fragment_container, CameraFragment.newInstance(text)).commit();
mCameraAttachments.setEnabled(false);
break;
case R.id.sticker:
transaction.replace(R.id.fragment_container, StickerFragment.newInstance(text)).commit();
mStickerAttachments.setEnabled(false);
break;
case R.id.mic:
transaction.replace(R.id.fragment_container, new MicFragment()).commit();
mMicAttachments.setEnabled(false);
break;
}
}
public void onAttachmentHidden(){
Fragment activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (activeFragment != null) {
getSupportFragmentManager().beginTransaction().remove(activeFragment).commit();
}
mAttachView.setVisibility(View.GONE);
clearAttachmentSelection();
}
private void clearAttachmentSelection() {
mGalleryAttachments.clearColorFilter();
mCameraAttachments.clearColorFilter();
mStickerAttachments.clearColorFilter();
mMicAttachments.clearColorFilter();
mGalleryAttachments.setEnabled(true);
mCameraAttachments.setEnabled(true);
mStickerAttachments.setEnabled(true);
mMicAttachments.setEnabled(true);
}
@Override
protected void onDestroy() {
mAdapter.destroy();
mManager.unregisterObserver(mMessageObserver);
super.onDestroy();
}
@Override
public void onItemClicked(Text text) {
if (mActionMode != null) {
toggleSelection(text);
} else if (MessageAdapter.hasFailed(text)) {
if (text.isIncoming()) {
mManager.downloadAttachment(text);
} else {
mManager.send(text);
}
}
}
@Override
public void onAttachmentClicked(Text text) {
if (MessageAdapter.hasFailed(text)) {
if (text.isIncoming()) {
mManager.downloadAttachment(text);
} else {
mManager.send(text);
}
} else if (text.getAttachment() != null
&& (text.getAttachment().getType() == Attachment.Type.IMAGE
|| text.getAttachment().getType() == Attachment.Type.VIDEO)) {
Intent i = new Intent(getBaseContext(), MediaActivity.class);
i.putExtra(MediaActivity.EXTRA_TEXT, text);
startActivity(i);
}
}
@Override
public boolean onItemLongClicked(Text text) {
if (mActionMode == null) {
mActionMode = startSupportActionMode(mActionModeCallback);
}
toggleSelection(text);
return true;
}
private void toggleSelection(Text text) {
mAdapter.toggleSelection(text);
int count = mAdapter.getSelectedItemCount();
if (count == 0) {
mActionMode.finish();
} else {
mActionMode.setTitle(getString(R.string.title_selection, count));
mActionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate (R.menu.menu_message, menu);
menu.findItem(R.id.menu_remove).setVisible(mManager.isDefaultSmsPackage());
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mRecyclerView.setNestedScrollingEnabled(false);
mAppbar.setExpanded(true);
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Set<Text> texts = mAdapter.getSelectedItems();
switch (item.getItemId()) {
case R.id.menu_remove:
mManager.delete(texts);
mAdapter.clearSelection();
mode.finish();
return true;
case R.id.menu_copy:
StringBuilder copy = new StringBuilder();
for (Text text : texts) {
if (copy.length() > 0) {
copy.append("\n");
}
if (!TextUtils.isEmpty(text.getBody())) {
copy.append(text.getBody());
}
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(getString(R.string.app_name), copy);
clipboard.setPrimaryClip(clip);
Toast.makeText(getBaseContext(), R.string.message_text_copied, Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mode.finish();
mAdapter.clearSelection();
mActionMode = null;
mRecyclerView.setNestedScrollingEnabled(true);
}
}
@Override
public void onBackPressed() {
if (mAttachView.getVisibility() == View.VISIBLE) {
onAttachmentHidden();
} else {
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
Notifications.dismissNotification(getApplicationContext(), mThread);
mManager.markAsRead(mThread);
sActiveThread = mThread;
if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) == null) {
onAttachmentHidden();
}
}
@Override
protected void onPause() {
sActiveThread = null;
super.onPause();
}
public void log(String message){
if (DEBUG) {
Log.d(TAG, message);
}
}
protected void send() {
final String message = mEditText.getText().toString();
mThread.getLatestMessage(getBaseContext()).get(new Future.Callback<Text>() {
@Override
public void get(Text instance) {
instance.getMembersExceptMe(getBaseContext()).get(new Future.Callback<Set<Contact>>() {
@Override
public void get(Set<Contact> instance) {
mManager.send(new Text.Builder()
.message(message)
.addRecipients(instance)
.build());
}
});
}
});
mEditText.setText(null);
}
} |
package org.smajko.watapp;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.edmodo.cropper.CropImageView;
import java.io.File;
import java.io.FileOutputStream;
public class CropActivity extends Activity {
private static final int GUIDELINES_ON_TOUCH = 1;
private Uri fileUri; // file URI to store image/video
private String outputFilePath;
boolean cropped;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
outputFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myimage.png";
fileUri = Uri.fromFile(new File(outputFilePath));
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_crop);
cropped = false;
captureImage();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
try {
// Initialize Views.
final ToggleButton fixedAspectRatioToggleButton = (ToggleButton) findViewById(R.id.fixedAspectRatioToggle);
final TextView aspectRatioXTextView = (TextView) findViewById(R.id.aspectRatioX);
final SeekBar aspectRatioXSeekBar = (SeekBar) findViewById(R.id.aspectRatioXSeek);
final TextView aspectRatioYTextView = (TextView) findViewById(R.id.aspectRatioY);
final SeekBar aspectRatioYSeekBar = (SeekBar) findViewById(R.id.aspectRatioYSeek);
final Spinner guidelinesSpinner = (Spinner) findViewById(R.id.showGuidelinesSpin);
final CropImageView cropImageView = (CropImageView) findViewById(R.id.CropImageView);
final ImageView croppedImageView = (ImageView) findViewById(R.id.croppedImageView);
final Button cropButton = (Button) findViewById(R.id.Button_crop);
final Button doneButton = (Button) findViewById(R.id.Button_done);
// Initializes fixedAspectRatio toggle button.
fixedAspectRatioToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
cropImageView.setFixedAspectRatio(isChecked);
cropImageView.setAspectRatio(aspectRatioXSeekBar.getProgress(), aspectRatioYSeekBar.getProgress());
aspectRatioXSeekBar.setEnabled(isChecked);
aspectRatioYSeekBar.setEnabled(isChecked);
}
});
try {
Matrix matrix = new Matrix();
ExifInterface ei = new ExifInterface(outputFilePath);
// Get orientation of the photograph
int orientation = ei.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
// In case image is rotated, we rotate it back
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(270);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
matrix.postRotate(90);
break;
}
// Now we get bitmap from the photograph and apply the rotation matrix above
BitmapFactory.Options options = new BitmapFactory.Options();
// down-sizing image as it can throw OutOfMemory Exception for
// larger images
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(outputFilePath,
options);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//Bitmap bitmap = BitmapFactory.decodeFile(path);
cropImageView.setImageBitmap(rotatedBitmap);
} catch (Exception e) {
e.printStackTrace();
Bitmap bitmap = BitmapFactory.decodeFile(outputFilePath);
cropImageView.setImageBitmap(bitmap);
}
// Set seek bars to be disabled until toggle button is checked.
aspectRatioXSeekBar.setEnabled(false);
aspectRatioYSeekBar.setEnabled(false);
aspectRatioXTextView.setText(String.valueOf(aspectRatioXSeekBar.getProgress()));
aspectRatioYTextView.setText(String.valueOf(aspectRatioXSeekBar.getProgress()));
// Initialize aspect ratio X SeekBar.
aspectRatioXSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar aspectRatioXSeekBar, int progress, boolean fromUser) {
if (progress < 1) {
aspectRatioXSeekBar.setProgress(1);
}
cropImageView.setAspectRatio(aspectRatioXSeekBar.getProgress(), aspectRatioYSeekBar.getProgress());
aspectRatioXTextView.setText(String.valueOf(aspectRatioXSeekBar.getProgress()));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
});
// Initialize aspect ratio Y SeekBar.
aspectRatioYSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar aspectRatioYSeekBar, int progress, boolean fromUser) {
if (progress < 1) {
aspectRatioYSeekBar.setProgress(1);
}
cropImageView.setAspectRatio(aspectRatioXSeekBar.getProgress(), aspectRatioYSeekBar.getProgress());
aspectRatioYTextView.setText(String.valueOf(aspectRatioYSeekBar.getProgress()));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
});
// Set up the Guidelines Spinner.
guidelinesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
cropImageView.setGuidelines(i);
}
public void onNothingSelected(AdapterView<?> adapterView) {
// Do nothing.
}
});
guidelinesSpinner.setSelection(GUIDELINES_ON_TOUCH);
// Initialize the Crop button.
cropButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Bitmap croppedImage = cropImageView.getCroppedImage();
croppedImageView.setImageBitmap(croppedImage);
setPicture(croppedImage);
}
});
// Initialize the Done button.
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult();
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
finish();
}
}
private void setResult() {
Intent intent = new Intent();
if (cropped){
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED, intent);
Toast.makeText(CropActivity.this, "Picture not cropped!",
Toast.LENGTH_LONG).show();
}
finish();
}
private void setPicture(Bitmap image) {
try {
FileOutputStream out = new FileOutputStream(outputFilePath);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
cropped = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void captureImage() {
// First check if we have a camera
boolean deviceHasCamera = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
// Our phone has a camera. Lets start the native camera
if (deviceHasCamera) {
// Create intent to take a picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Tell the intent that we need the camera to store the photo in
// our file defined earlier
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the activity with the intent created above
startActivityForResult(intent, 1);
} else {
Toast.makeText(CropActivity.this, "Camera not found!",
Toast.LENGTH_LONG).show();
finish();
}
}
} |
package game_data;
import java.util.List;
import engine.Entity;
import engine.game.Level;
/**
* @author Elliott Bolzan
*
*/
public class Game {
private String name;
private List<Level> levels;
private List<Entity> defaults;
private String songPath;
public Game() {
// TODO Auto-generated constructor stub
}
public List<Level> getLevels() {
return levels;
}
public void setLevels(List<Level> levels) {
this.levels = levels;
}
public List<Entity> getDefaults() {
return defaults;
}
public void setDefaults(List<Entity> defaults) {
this.defaults = defaults;
}
public String getSongPath() {
return songPath;
}
public void setSongPath(String songPath) {
this.songPath = songPath;
}
} |
package org.nick.wwwjdic;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class TtsManager implements TextToSpeech.OnInitListener {
public interface TtsEnabled {
Locale getSpeechLocale();
void showTtsButtons();
void hideTtsButtons();
boolean wantsTts();
void setWantsTts(boolean wantsTts);
}
private static final String TAG = TtsManager.class.getSimpleName();
private static final String MARKET_URL_TEMPLATE = "market://details?id=%s";
private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
private static final boolean IS_ICS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
private static Method tts_getDefaultEngine;
private static Method tts_setEngineByPackageName;
private static Constructor<TextToSpeech> tts_packageNameCtor;
static {
try {
tts_getDefaultEngine = TextToSpeech.class.getMethod(
"getDefaultEngine", (Class[]) null);
tts_setEngineByPackageName = TextToSpeech.class.getMethod(
"setEngineByPackageName", new Class[] { String.class });
if (IS_ICS) {
tts_packageNameCtor = TextToSpeech.class.getConstructor(
Context.class, TextToSpeech.OnInitListener.class,
String.class);
}
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}
}
private Context context;
private TtsEnabled ttsActivitiy;
private boolean showInstallDialog = false;
private String ttsEnginePackage;
private TextToSpeech tts;
public TtsManager(Context context, TtsEnabled ttsActivitiy,
String ttsEnginePackage, boolean showInstallDialog) {
this.context = context;
this.ttsActivitiy = ttsActivitiy;
this.ttsEnginePackage = ttsEnginePackage;
this.showInstallDialog = showInstallDialog;
}
public TtsManager(Context context, TtsEnabled ttsActivitiy,
String ttsEnginePackage) {
this(context, ttsActivitiy, ttsEnginePackage, true);
}
public void checkTtsAvailability() {
boolean available = isPackageInstalled(ttsEnginePackage);
if (available) {
if (tts == null) {
if (IS_ICS && ttsEnginePackage != null) {
try {
tts = tts_packageNameCtor.newInstance(context, this,
ttsEnginePackage);
} catch (InvocationTargetException e) {
disableTts(e);
} catch (IllegalArgumentException e) {
disableTts(e);
} catch (InstantiationException e) {
disableTts(e);
} catch (IllegalAccessException e) {
disableTts(e);
}
} else {
tts = new TextToSpeech(context, this);
}
} else {
if (showInstallDialog && ttsActivitiy.wantsTts()) {
Dialog dialog = createInstallTtsDataDialog();
dialog.show();
} else {
ttsActivitiy.hideTtsButtons();
}
}
}
}
private void disableTts(Exception e) {
Log.e(TAG, "Failed to initialize TTS: " + e.getMessage(), e);
tts = null;
ttsActivitiy.hideTtsButtons();
}
@Override
public void onInit(int status) {
if (tts == null) {
Log.w(TAG, "TTS not found or failed to initialize");
return;
}
if (status != TextToSpeech.SUCCESS) {
ttsActivitiy.hideTtsButtons();
return;
}
// XXX -- use default engine when null?
if (ttsEnginePackage != null && IS_FROYO && !IS_ICS) {
try {
String defaultEngine = (String) tts_getDefaultEngine.invoke(
tts, (Object[]) null);
if (!defaultEngine.equals(ttsEnginePackage)) {
int rc = (Integer) tts_setEngineByPackageName.invoke(tts,
new Object[] { ttsEnginePackage });
if (rc == TextToSpeech.ERROR) {
Log.w(TAG, ttsEnginePackage + " not available?");
tts.shutdown();
tts = null;
ttsActivitiy.hideTtsButtons();
return;
}
}
} catch (InvocationTargetException e) {
disableTts(e);
} catch (IllegalAccessException e) {
disableTts(e);
}
}
Locale locale = ttsActivitiy.getSpeechLocale();
if (locale == null) {
Log.w(TAG, "TTS locale " + locale + "not recognized");
ttsActivitiy.hideTtsButtons();
return;
}
if (isLanguageAvailable(locale)) {
tts.setLanguage(locale);
ttsActivitiy.showTtsButtons();
} else {
Log.w(TAG, "TTS locale " + locale + " not available");
ttsActivitiy.hideTtsButtons();
}
}
private boolean isPackageInstalled(String packageName) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi != null;
} catch (NameNotFoundException e) {
Log.w(TAG, packageName + " not found", e);
return false;
}
}
public Dialog createInstallTtsDataDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.install_tts_data_message)
.setTitle(R.string.install_tts_data_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
ttsActivitiy.setWantsTts(true);
Intent installIntent = new Intent(
Intent.ACTION_VIEW);
installIntent.setData(Uri.parse(String.format(
MARKET_URL_TEMPLATE, ttsEnginePackage)));
dialog.dismiss();
context.startActivity(installIntent);
dialog.dismiss();
}
})
.setNegativeButton(R.string.not_now,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
ttsActivitiy.hideTtsButtons();
dialog.dismiss();
}
})
.setNeutralButton(R.string.dont_ask_again,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
ttsActivitiy.hideTtsButtons();
ttsActivitiy.setWantsTts(false);
dialog.dismiss();
}
});
return builder.create();
}
public void speak(String text) {
if (tts == null) {
return;
}
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
public void setLanguage(Locale speechLocale) {
tts.setLanguage(speechLocale);
}
public boolean isLanguageAvailable(Locale speechLocale) {
return tts.isLanguageAvailable(speechLocale) != TextToSpeech.LANG_MISSING_DATA
&& tts.isLanguageAvailable(speechLocale) != TextToSpeech.LANG_NOT_SUPPORTED;
}
public void shutdown() {
if (tts != null) {
tts.shutdown();
}
}
} |
package ph.pakete.view;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import ph.pakete.BackHandledFragment;
import ph.pakete.PackageTrackHistoryAdapter;
import ph.pakete.R;
import ph.pakete.databinding.FragmentPackageBinding;
import ph.pakete.model.MixpanelHelper;
import ph.pakete.viewmodel.ItemPackageViewModel;
import ph.pakete.viewmodel.PackagesViewModel;
public class PackageFragment extends BackHandledFragment {
private FragmentPackageBinding binding;
private PackagesViewModel packagesViewModel;
private ItemPackageViewModel packageViewModel;
public static PackageFragment newInstance(ItemPackageViewModel packageViewModel, PackagesViewModel packagesViewModel) {
final PackageFragment fragment = new PackageFragment();
fragment.packageViewModel = packageViewModel;
fragment.packagesViewModel = packagesViewModel;
return fragment;
}
public PackageFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItem = menu.findItem(R.id.action_settings);
menuItem.setVisible(false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_package, container, false);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(binding.toolbar);
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(packageViewModel.getName());
// add back button
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());
binding.toolbarEditButton.setOnClickListener(v -> editPackage());
binding.textPackageTrackingNumber.setText(packageViewModel.getTrackingNumber());
binding.textPackageCourierName.setText(packageViewModel.getCourierName());
setupRecyclerView(binding.trackHistoryRecyclerView);
// track mixpanel
MixpanelHelper.getMixpanel(getActivity()).track("Package View");
return binding.getRoot();
}
@Override
public boolean onBackPressed() {
if (getFragmentManager() != null) {
getFragmentManager().popBackStack();
// show fab
((MainActivity) getActivity()).showFAB();
return true;
}
return false;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
packageViewModel.getPackage().subscribe(aPackage1 -> {
if (getActivity() == null) { return; }
TextView noAvailableInformationYetText = (TextView) getActivity().findViewById(R.id.no_information_available_yet_text);
if (packageViewModel.getPackage().getValue().getTrackHistory().size() > 0) {
noAvailableInformationYetText.setVisibility(View.GONE);
} else {
noAvailableInformationYetText.setVisibility(View.VISIBLE);
}
binding.trackHistoryRecyclerView.getAdapter().notifyDataSetChanged();
});
}
private void editPackage() {
AddPackageFragment editPackageFragment = AddPackageFragment.newEditInstance(packagesViewModel, packageViewModel.getPackage());
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.root_layout, editPackageFragment)
.addToBackStack(null)
.commit();
}
private void setupRecyclerView(RecyclerView recyclerView) {
PackageTrackHistoryAdapter adapter = new PackageTrackHistoryAdapter();
adapter.setPackageTrackHistory(packageViewModel.getTrackHistory(), getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
} |
package utmg.android_interface;
//import org.apache.commons.logging.Log;
import android.util.Log;
import org.ros.concurrent.CancellableLoop;
import org.ros.message.MessageListener;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import java.util.ArrayList;
import geometry_msgs.Pose;
import geometry_msgs.PoseArray;
import nav_msgs.Path;
import geometry_msgs.TransformStamped;
public class ROSNode extends AbstractNodeMain implements NodeMain {
private ArrayList<Float> xes;
private ArrayList<Float> yes;
private ArrayList<Float> zes;
private double quadx = 0;
private double quady = 0;
private double quadz = 0;
private double swordx = 0;
private double swordy = 0;
private double swordz = 0;
private boolean publishToggle = false;
private int seq = 0;
private static final String TAG = ROSNode.class.getSimpleName();
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("utmg_android");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
//final Publisher<std_msgs.String> publisher = connectedNode.newPublisher(GraphName.of("time"), std_msgs.String._TYPE);
final Publisher<geometry_msgs.PoseArray> publisher1 = connectedNode.newPublisher(GraphName.of("android_quad_trajectory"), PoseArray._TYPE);
//final Publisher<nav_msgs.Path> publisherPath = connectedNode.newPublisher(GraphName.of("android_quad_trajectory"), Path._TYPE);
final CancellableLoop loop = new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
// retrieve current system time
//String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
//Log.i(TAG, "publishing the current time: " + time);
// create and publish a simple string message
//std_msgs.String str = publisher.newMessage();
//str.setData("The current time is: " + time);
//publisher.publish(str);
// trajectory publisher
geometry_msgs.PoseArray mPoseArray = publisher1.newMessage();
//nav_msgs.Path xyPath = publisherPath.newMessage();
mPoseArray.getHeader().setFrameId("world");
mPoseArray.getHeader().setSeq(seq);
mPoseArray.getHeader().setStamp(new Time());
// xyPath.getHeader().setFrameId("world");
// xyPath.getHeader().setSeq(0);
// xyPath.getHeader().setStamp(new Time());
ArrayList<Pose> poses = new ArrayList<>();
if (xes == null || yes == null) {
//Log.i("Traj","Null arrays");
} else {
for (int i = 0; i < xes.size(); i++) {
geometry_msgs.Pose mPose = connectedNode.getTopicMessageFactory().newFromType(geometry_msgs.Pose._TYPE);
geometry_msgs.Point mPoint = connectedNode.getTopicMessageFactory().newFromType(geometry_msgs.Point._TYPE);
mPoint.setX(xes.get(i));
mPoint.setY(yes.get(i));
mPoint.setZ(zes.get(i));
mPose.setPosition(mPoint);
poses.add(mPose);
}
mPoseArray.setPoses(poses);
if (publishToggle == true) {
publisher1.publish(mPoseArray);
seq = seq + 1;
}
publishToggle = false;
}
// listener
//final Log log = connectedNode.getLog();
Subscriber<TransformStamped> subscriberQuad = connectedNode.newSubscriber("vicon/Quad7/Quad7", geometry_msgs.TransformStamped._TYPE);
// rotated vicon -90 degrees
subscriberQuad.addMessageListener(new MessageListener<geometry_msgs.TransformStamped>() {
@Override
public void onNewMessage(geometry_msgs.TransformStamped message) {
quadx = message.getTransform().getTranslation().getX();
quady = message.getTransform().getTranslation().getY();
quadz = message.getTransform().getTranslation().getZ();
}
});
Subscriber<TransformStamped> subscriberSword = connectedNode.newSubscriber("vicon/sword/sword", geometry_msgs.TransformStamped._TYPE);
subscriberSword.addMessageListener(new MessageListener<geometry_msgs.TransformStamped>() {
@Override
public void onNewMessage(geometry_msgs.TransformStamped message) {
swordx = message.getTransform().getTranslation().getX();
swordy = message.getTransform().getTranslation().getY();
swordz = message.getTransform().getTranslation().getZ();
//Log.i("QuadPos", Double.toString(quadx) + "\t\t" + Double.toString(quady) + "\t\t" + Double.toString(quadz));
}
});
// go to sleep for one second
Thread.sleep(1000);
}
};
connectedNode.executeCancellableLoop(loop);
}
void setTraj(ArrayList<Float> x, ArrayList<Float> y, ArrayList<Float> z) {
xes = x;
yes = y;
zes = z;
publishToggle = true;
Log.i("Traj","Arrays transferred to node");
}
double getQuadPosX() { return quadx; }
double getQuadPosY() { return quady; }
double getQuadPosZ() { return quadz; }
double getSwordPosX() { return swordx; }
double getSwordPosY() { return swordy; }
double getSwordPosZ() { return swordz; }
} |
package org.commcare.activities;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.CommCareApplication;
import org.commcare.android.database.user.models.ACase;
import org.commcare.fragments.BreadcrumbBarFragment;
import org.commcare.fragments.ContainerFragment;
import org.commcare.fragments.TaskConnectorFragment;
import org.commcare.interfaces.WithUIController;
import org.commcare.logic.DetailCalloutListenerDefaultImpl;
import org.commcare.preferences.LocalePreferences;
import org.commcare.session.SessionFrame;
import org.commcare.session.SessionInstanceBuilder;
import org.commcare.suite.model.CalloutData;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.StackFrameStep;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.tasks.templates.CommCareTaskConnector;
import org.commcare.util.LogTypes;
import org.commcare.utils.AndroidUtil;
import org.commcare.utils.ConnectivityStatus;
import org.commcare.utils.DetailCalloutListener;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.SessionStateUninitException;
import org.commcare.utils.StringUtils;
import org.commcare.views.ManagedUiFramework;
import org.commcare.views.dialogs.AlertDialogFragment;
import org.commcare.views.dialogs.CommCareAlertDialog;
import org.commcare.views.dialogs.CustomProgressDialog;
import org.commcare.views.dialogs.DialogController;
import org.commcare.views.dialogs.StandardAlertDialog;
import org.commcare.views.media.AudioController;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.NoLocalizedTextException;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* Base class for CommCareActivities to simplify
* common localization and workflow tasks
*
* @author ctsims
*/
public abstract class CommCareActivity<R> extends AppCompatActivity
implements CommCareTaskConnector<R>, DialogController, OnGestureListener, DetailCalloutListener {
private static final String TAG = CommCareActivity.class.getSimpleName();
private static final String KEY_PROGRESS_DIALOG_FRAG = "progress-dialog-fragment";
private static final String KEY_ALERT_DIALOG_FRAG = "alert-dialog-fragment";
private int invalidTaskIdMessageThrown = -2;
private TaskConnectorFragment<R> stateHolder;
CompositeDisposable disposableEventHost = new CompositeDisposable();
// Fields for implementing task transitions for CommCareTaskConnector
private boolean inTaskTransition;
/**
* Used to indicate that the (progress) dialog associated with a task
* should be dismissed because the task has completed or been canceled.
*/
private boolean dismissLastDialogAfterTransition = true;
private AlertDialogFragment alertDialogToShowOnResume;
private GestureDetector mGestureDetector;
protected String lastQueryString;
/**
* Activity has been put in the background. Flag prevents dialogs
* from being shown while activity isn't active.
*/
private boolean areFragmentsPaused = true;
/**
* Mark when task tried to show progress dialog before fragments have resumed,
* so that the dialog can be shown when fragments have fully resumed.
*/
private boolean triedBlockingWhilePaused;
private boolean triedDismissingWhilePaused;
/**
* Store the id of a task progress dialog so it can be disabled/enabled
* on activity pause/resume.
*/
private int dialogId = -1;
private ContainerFragment<Bundle> managedUiState;
private boolean isMainScreenBlocked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = this.getSupportFragmentManager();
stateHolder = (TaskConnectorFragment<R>)fm.findFragmentByTag("state");
// stateHolder and its previous state aren't null if the activity is
// being created due to an orientation change.
if (stateHolder == null) {
stateHolder = new TaskConnectorFragment<>();
fm.beginTransaction().add(stateHolder, "state").commit();
// entering new activity, not just rotating one, so release old
// media
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
// For activities using a uiController, this must be called before persistManagedUiState()
if (usesUIController()) {
((WithUIController)this).initUIController();
}
persistManagedUiState(fm);
if (getSupportActionBar() != null) {
getSupportActionBar().setLogo(org.commcare.dalvik.R.mipmap.ic_launcher);
}
if (shouldShowBreadcrumbBar()) {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowCustomEnabled(true);
}
// Add breadcrumb bar
BreadcrumbBarFragment bar = (BreadcrumbBarFragment)fm.findFragmentByTag("breadcrumbs");
// If the state holder is null, create a new one for this activity
if (bar == null) {
bar = new BreadcrumbBarFragment();
fm.beginTransaction().add(bar, "breadcrumbs").commit();
}
}
mGestureDetector = new GestureDetector(this, this);
}
private void persistManagedUiState(FragmentManager fm) {
if (isManagedUiActivity()) {
managedUiState = (ContainerFragment)fm.findFragmentByTag("ui-state");
if (managedUiState == null) {
managedUiState = new ContainerFragment<>();
fm.beginTransaction().add(managedUiState, "ui-state").commit();
loadUiElementState(null);
} else {
loadUiElementState(managedUiState.getData());
}
}
}
private void loadUiElementState(Bundle savedInstanceState) {
ManagedUiFramework.setContentView(this);
if (savedInstanceState != null) {
ManagedUiFramework.restoreUiElements(this, savedInstanceState);
} else {
ManagedUiFramework.loadUiElements(this);
}
}
/**
* Call this method from an implementing activity to request a new event trigger for any time
* the available space for the core content view changes significantly, for instance when the
* soft keyboard is displayed or hidden.
*
* This method will also be reliably triggered upon the end of the first layout pass, so it
* can be used to do the initial setup for adaptive layouts as well as their updates.
*
* After this is called, major layout size changes will be triggered in the onMajorLayoutChange
* method.
*/
protected void requestMajorLayoutUpdates() {
final View decorView = getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int mPreviousDecorViewFrameHeight = 0;
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that are visible after the
//recent change.
decorView.getWindowVisibleDisplayFrame(r);
int mainContentHeight = r.height();
int previousMeasurementDifference = Math.abs(mainContentHeight - mPreviousDecorViewFrameHeight);
if (previousMeasurementDifference > 100) {
onMajorLayoutChange(r);
}
mPreviousDecorViewFrameHeight = mainContentHeight;
}
});
}
/**
* This method is called when the root view size available to the activity has changed
* significantly. It is the appropriate place to trigger adaptive layout behaviors.
*
* Note for performance that changes to declarative view properties here will trigger another
* layout pass.
*
* This callback is only triggered if the parent view has called requestMajorLayoutUpdates
*
* @param newRootViewDimensions The dimensions of the new root screen view that is available
* to the activity.
*/
protected void onMajorLayoutChange(Rect newRootViewDimensions) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (!isFinishing()) {
this.onBackPressed();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected boolean isTopNavEnabled() {
return false;
}
/**
* If a message for the user has been set in CommCareApplication, show it and then clear it
*/
private void showPendingUserMessage() {
String[] messageAndTitle = CommCareApplication.instance().getPendingUserMessage();
if (messageAndTitle != null) {
showAlertDialog(StandardAlertDialog.getBasicAlertDialog(
this, messageAndTitle[1], messageAndTitle[0], null));
CommCareApplication.instance().clearPendingUserMessage();
}
}
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// In honeycomb and above the fragment takes care of this
this.setTitle(getTitle(this, getActivityTitle()));
}
AudioController.INSTANCE.playPreviousAudio();
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
areFragmentsPaused = false;
syncTaskBlockingWithDialogFragment();
showPendingAlertDialog();
}
@Override
protected void onPause() {
super.onPause();
if (isManagedUiActivity()) {
managedUiState.setData(ManagedUiFramework.saveUiStateToBundle(this));
}
areFragmentsPaused = true;
AudioController.INSTANCE.systemInducedPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
disposableEventHost.dispose();
}
/**
* Attaches a reactivex disposable to the lifecycle of this activity, so the disposable
* will be cancelled / halted when this activity is destroyed.
*/
public void attachDisposableToLifeCycle(Disposable subscribe) {
disposableEventHost.add(subscribe);
}
@Override
public <A, B, C> void connectTask(CommCareTask<A, B, C, R> task) {
stateHolder.connectTask(task, this);
// If we've left an old dialog showing during the task transition and it was from the same
// task as the one that is starting, we want to just leave it up for the next task too
CustomProgressDialog currDialog = getCurrentProgressDialog();
if (currDialog != null && currDialog.getTaskId() == task.getTaskId()) {
dismissLastDialogAfterTransition = false;
}
}
/**
* @return wakelock level for an activity with a running task attached to
* it; defaults to not using wakelocks.
*/
public int getWakeLockLevel() {
return CommCareTask.DONT_WAKELOCK;
}
/**
* Sync progress dialog fragment with any task state changes that may have
* occurred while the activity was paused.
*/
private void syncTaskBlockingWithDialogFragment() {
if (triedDismissingWhilePaused) {
triedDismissingWhilePaused = false;
dismissProgressDialog();
} else if (triedBlockingWhilePaused) {
triedBlockingWhilePaused = false;
showNewProgressDialog();
}
}
@Override
public void startBlockingForTask(int id) {
dialogId = id;
if (areFragmentsPaused) {
// post-pone dialog transactions until after fragments have fully resumed.
triedBlockingWhilePaused = true;
} else {
showNewProgressDialog();
}
}
private void showNewProgressDialog() {
// Only show a new dialog if we chose to dismiss the old one; If
// dismissLastDialogAfterTransition is false, that means we left the last dialog up and do
// not need to create a new one
if (dismissLastDialogAfterTransition) {
dismissProgressDialog();
showProgressDialog(dialogId);
}
}
@Override
public void stopBlockingForTask(int id) {
dialogId = -1;
if (id >= 0) {
if (inTaskTransition) {
dismissLastDialogAfterTransition = true;
} else {
dismissProgressDialog();
}
}
stateHolder.releaseWakeLock();
}
@Override
public R getReceiver() {
return (R)this;
}
@Override
public void startTaskTransition() {
inTaskTransition = true;
}
@Override
public void stopTaskTransition() {
inTaskTransition = false;
if (dismissLastDialogAfterTransition) {
dismissProgressDialog();
// Re-set shouldDismissDialog to true after this transition cycle is over
dismissLastDialogAfterTransition = true;
}
}
/**
* Display exception details as a pop-up to the user.
*/
private void displayException(String title, String message) {
DialogInterface.OnClickListener listener = (dialog, i) -> {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
}
};
showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this, title,
message, android.R.drawable.ic_dialog_info, listener));
}
public void displayCaseListLoadException(Exception e) {
displayException(
Localization.get("notification.case.predicate.title"),
Localization.get("notification.case.predicate.action", new String[]{e.getMessage()}));
}
@Override
public void taskCancelled() {
}
public void cancelCurrentTask() {
stateHolder.cancelTask();
}
protected void restoreLastQueryString() {
lastQueryString = (String)CommCareApplication.instance().getCurrentSession().getCurrentFrameStepExtra(SessionInstanceBuilder.KEY_LAST_QUERY_STRING);
}
protected void saveLastQueryString() {
CommCareApplication.instance().getCurrentSession().addExtraToCurrentFrameStep(SessionInstanceBuilder.KEY_LAST_QUERY_STRING, lastQueryString);
}
//Graphical stuff below, needs to get modularized
protected void transplantStyle(TextView target, int resource) {
//get styles from here
TextView tv = (TextView)View.inflate(this, resource, null);
int[] padding = {target.getPaddingLeft(), target.getPaddingTop(), target.getPaddingRight(), target.getPaddingBottom()};
target.setTextColor(tv.getTextColors().getDefaultColor());
target.setTypeface(tv.getTypeface());
target.setBackgroundDrawable(tv.getBackground());
target.setPadding(padding[0], padding[1], padding[2], padding[3]);
}
/**
* The right-hand side of the title associated with this activity.
* <p/>
* This will update dynamically as the activity loads/updates, but if
* it will ever have a value it must return a blank string when one
* isn't available.
*/
protected String getActivityTitle() {
return null;
}
public static String getTopLevelTitleName(Context c) {
try {
return Localization.get("app.display.name");
} catch (NoLocalizedTextException nlte) {
return c.getString(org.commcare.dalvik.R.string.title_bar_name);
}
}
protected static String getTitle(Context c, String local) {
String topLevel = getTopLevelTitleName(c);
String[] stepTitles = new String[0];
try {
stepTitles = CommCareApplication.instance().getCurrentSession().getHeaderTitles();
//See if we can insert any case hacks
int i = 0;
for (StackFrameStep step : CommCareApplication.instance().getCurrentSession().getFrame().getSteps()) {
try {
if (SessionFrame.STATE_DATUM_VAL.equals(step.getType())) {
//Haaack
if (step.getId() != null && step.getId().contains("case_id")) {
ACase foundCase = CommCareApplication.instance().getUserStorage(ACase.STORAGE_KEY, ACase.class).getRecordForValue(ACase.INDEX_CASE_ID, step.getValue());
stepTitles[i] = Localization.get("title.datum.wrapper", new String[]{foundCase.getName()});
}
}
} catch (Exception e) {
//TODO: Your error handling is bad and you should feel bad
}
++i;
}
} catch (SessionStateUninitException e) {
}
StringBuilder titleBuf = new StringBuilder(topLevel);
for (String title : stepTitles) {
if (title != null) {
titleBuf.append(" > ").append(title);
}
}
if (local != null) {
titleBuf.append(" > ").append(local);
}
return titleBuf.toString();
}
protected boolean isNetworkNotConnected() {
return !ConnectivityStatus.isNetworkAvailable(this);
}
// region - All methods for implementation of DialogController
@Override
public void updateProgress(String newMessage, String newTitle, int taskId) {
updateDialogContent(newMessage, newTitle, taskId);
}
@Override
public void updateProgress(String newMessage, int taskId) {
updateDialogContent(newMessage, null, taskId);
}
private void updateDialogContent(String newMessage, String newTitle, int taskId) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
if (mProgressDialog.getTaskId() == taskId) {
mProgressDialog.updateMessage(newMessage);
if (newTitle != null) {
mProgressDialog.updateTitle(newTitle);
}
} else {
warnInvalidProgressUpdate(taskId);
}
}
}
@Override
public void hideTaskCancelButton() {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null) {
mProgressDialog.removeCancelButton();
}
}
@Override
public void updateProgressBarVisibility(boolean visible) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
mProgressDialog.updateProgressBarVisibility(visible);
}
}
@Override
public void updateProgressBar(int progress, int max, int taskId) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
if (mProgressDialog.getTaskId() == taskId) {
mProgressDialog.updateProgressBar(progress, max);
} else {
warnInvalidProgressUpdate(taskId);
}
}
}
private void warnInvalidProgressUpdate(int taskId) {
String message = "Attempting to update a progress dialog whose taskId (" + taskId +
" does not match the task for which the update message was intended.";
if (invalidTaskIdMessageThrown != taskId) {
invalidTaskIdMessageThrown = taskId;
Logger.log(LogTypes.TYPE_ERROR_ASSERTION, message);
} else {
Log.w(TAG, message);
}
}
@Override
public void showProgressDialog(int taskId) {
if (taskId >= 0) {
CustomProgressDialog dialog = generateProgressDialog(taskId);
if (dialog != null) {
dialog.show(getSupportFragmentManager(), KEY_PROGRESS_DIALOG_FRAG);
}
}
}
@Override
public CustomProgressDialog getCurrentProgressDialog() {
return (CustomProgressDialog)getSupportFragmentManager().
findFragmentByTag(KEY_PROGRESS_DIALOG_FRAG);
}
@Override
public void dismissProgressDialog() {
CustomProgressDialog progressDialog = getCurrentProgressDialog();
if (progressDialog != null && progressDialog.isAdded()) {
if (areFragmentsPaused) {
triedDismissingWhilePaused = true;
} else {
progressDialog.dismiss();
}
}
}
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
//dummy method for compilation, implementation handled in those subclasses that need it
return null;
}
@Override
public AlertDialogFragment getCurrentAlertDialog() {
return (AlertDialogFragment)getSupportFragmentManager().
findFragmentByTag(KEY_ALERT_DIALOG_FRAG);
}
@Override
public void showPendingAlertDialog() {
if (alertDialogToShowOnResume != null) {
alertDialogToShowOnResume.show(getSupportFragmentManager(), KEY_ALERT_DIALOG_FRAG);
alertDialogToShowOnResume = null;
} else {
showPendingUserMessage();
}
}
@Override
public void dismissAlertDialog() {
DialogFragment alertDialog = getCurrentAlertDialog();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
@Override
public void showAlertDialog(CommCareAlertDialog d) {
AlertDialogFragment dialog = AlertDialogFragment.fromCommCareAlertDialog(d);
if (areFragmentsPaused) {
alertDialogToShowOnResume = dialog;
} else {
if (getCurrentAlertDialog() != null) {
// replace existing dialog by dismissing it
dismissAlertDialog();
}
dialog.show(getSupportFragmentManager(), KEY_ALERT_DIALOG_FRAG);
}
}
// endregion
public Pair<Detail, TreeReference> requestEntityContext() {
return null;
}
public boolean aTaskInProgress() {
return stateHolder != null && stateHolder.isCurrentTaskRunning();
}
/**
* Interface to perform additional setup code when adding an ActionBar
*/
public interface ActionBarInstantiator {
void onActionBarFound(MenuItem searchItem, SearchView searchView, MenuItem barcodeItem);
}
/**
* Tries to add a SearchView action to the app bar of the current Activity. If it is added,
* the alternative search widget is removed, and ActionBarInstantiator is run, if it exists.
* Used in EntitySelectActivity and FormRecordListActivity.
*
* @param activity Current activity
* @param menu Menu passed through onCreateOptionsMenu
* @param instantiator Optional ActionBarInstantiator for additional setup code.
*/
protected void tryToAddSearchActionToAppBar(AppCompatActivity activity, Menu menu,
ActionBarInstantiator instantiator) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(org.commcare.dalvik.R.menu.action_bar_search_view, menu);
MenuItem searchMenuItem = menu.findItem(org.commcare.dalvik.R.id.search_action_bar);
SearchView searchView = (SearchView)searchMenuItem.getActionView();
MenuItem barcodeItem = menu.findItem(org.commcare.dalvik.R.id.barcode_scan_action_bar);
if (searchView != null) {
if (instantiator != null) {
instantiator.onActionBarFound(searchMenuItem, searchView, barcodeItem);
}
}
View bottomSearchWidget = activity.findViewById(org.commcare.dalvik.R.id.searchfooter);
if (bottomSearchWidget != null) {
bottomSearchWidget.setVisibility(View.GONE);
}
}
/**
* Whether or not the "Back" action makes sense for this activity.
*
* @return True if "Back" is a valid concept for the Activity and should be shown
* in the action bar if available. False otherwise.
*/
public boolean isBackEnabled() {
return true;
}
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
return !(mGestureDetector == null || !mGestureDetector.onTouchEvent(mv)) || super.dispatchTouchEvent(mv);
}
@Override
public boolean onDown(MotionEvent arg0) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (isHorizontalSwipe(this, e1, e2) && !isMainScreenBlocked) {
if (LocalePreferences.isLocaleRTL()) {
if (velocityX <= 0) {
return onBackwardSwipe();
}
return onForwardSwipe();
} else {
if (velocityX <= 0) {
return onForwardSwipe();
}
return onBackwardSwipe();
}
}
return false;
}
/**
* Action to take when user swipes forward during activity.
*
* @return Whether or not the swipe was handled
*/
protected boolean onForwardSwipe() {
return false;
}
/**
* Action to take when user swipes backward during activity.
*
* @return Whether or not the swipe was handled
*/
protected boolean onBackwardSwipe() {
return false;
}
@Override
public void onBackPressed() {
FragmentManager fm = this.getSupportFragmentManager();
BreadcrumbBarFragment bar = (BreadcrumbBarFragment)fm.findFragmentByTag("breadcrumbs");
if (bar != null) {
if (bar.collapseTileIfExpanded(this)) {
return;
}
}
super.onBackPressed();
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
@Override
public void onLongPress(MotionEvent arg0) {
// ignore
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// ignore
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
return false;
}
/**
* Decide if two given MotionEvents represent a swipe.
*
* @return True iff the movement is a definitive horizontal swipe.
*/
private static boolean isHorizontalSwipe(AppCompatActivity activity, MotionEvent e1, MotionEvent e2) {
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
//details of the motion itself
float xMov = Math.abs(e1.getX() - e2.getX());
float yMov = Math.abs(e1.getY() - e2.getY());
double angleOfMotion = ((Math.atan(yMov / xMov) / Math.PI) * 180);
// for all screens a swipe is left/right of at least .25" and at an angle of no more than 30
//degrees
int xPixelLimit = (int)(dm.xdpi * .25);
return xMov > xPixelLimit && angleOfMotion < 30;
}
/**
* Rebuild the activity's menu options based on the current state of the activity.
*/
@SuppressLint("RestrictedApi")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void rebuildOptionsMenu() {
if (CommCareApplication.instance().getCurrentApp() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
invalidateOptionsMenu();
} else {
supportInvalidateOptionsMenu();
}
}
}
public Spannable localize(String key) {
return MarkupUtil.localizeStyleSpannable(this, key);
}
public Spannable localize(String key, String arg) {
return MarkupUtil.localizeStyleSpannable(this, key, arg);
}
public Spannable localize(String key, String[] args) {
return MarkupUtil.localizeStyleSpannable(this, key, args);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void refreshActionBar() {
if (shouldShowBreadcrumbBar()) {
FragmentManager fm = this.getSupportFragmentManager();
BreadcrumbBarFragment bar = (BreadcrumbBarFragment)fm.findFragmentByTag("breadcrumbs");
bar.refresh(this);
}
}
/**
* Activity has been put in the background. Useful in knowing when to not
* perform dialog or fragment transactions
*/
protected boolean areFragmentsPaused() {
return areFragmentsPaused;
}
public void setMainScreenBlocked(boolean isBlocked) {
isMainScreenBlocked = isBlocked;
}
protected boolean usesUIController() {
return this instanceof WithUIController;
}
public Object getUIManager() {
if (usesUIController()) {
return ((WithUIController)this).getUIController();
} else {
return this;
}
}
private boolean isManagedUiActivity() {
return ManagedUiFramework.isManagedUi(getUIManager().getClass());
}
public void setStateHolder(TaskConnectorFragment<R> stateHolder) {
this.stateHolder = stateHolder;
}
protected String getLastQueryString() {
return lastQueryString;
}
protected void setLastQueryString(String lastQueryString) {
this.lastQueryString = lastQueryString;
}
protected boolean shouldShowBreadcrumbBar() {
return true;
}
@Override
public void callRequested(String phoneNumber) {
DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber);
}
@Override
public void addressRequested(String address) {
DetailCalloutListenerDefaultImpl.addressRequested(this, address);
}
@Override
public void playVideo(String videoRef) {
DetailCalloutListenerDefaultImpl.playVideo(this, videoRef);
}
@Override
public void performCallout(CalloutData callout, int id) {
DetailCalloutListenerDefaultImpl.performCallout(this, callout, id);
}
protected void showToast(int stringResource) {
Toast.makeText(this, getLocalizedString(stringResource), Toast.LENGTH_LONG).show();
}
protected String getLocalizedString(int stringResource) {
return StringUtils.getStringRobust(this, stringResource);
}
} |
package org.jasig.portal.layout.channels;
import java.io.InputStream;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.IPrivileged;
import org.jasig.portal.IUserLayoutStore;
import org.jasig.portal.IUserPreferencesManager;
import org.jasig.portal.PortalControlStructures;
import org.jasig.portal.PortalException;
import org.jasig.portal.PortalSessionManager;
import org.jasig.portal.UserLayoutStoreFactory;
import org.jasig.portal.UserPreferences;
import org.jasig.portal.channels.BaseChannel;
import org.jasig.portal.utils.XSLT;
import org.xml.sax.ContentHandler;
/**
* A channel for selecting skins.
* @author Michael Ivanov
* @version $Revision$
*/
public class CSkinSelector extends BaseChannel implements IPrivileged {
private static final String SKINS_PATH = "media/org/jasig/portal/layout/AL_TabColumn/integratedModes";
private static final String sslLocation = "/org/jasig/portal/channels/CSkinSelector/CSkinSelector.ssl";
private PortalControlStructures controlStructures;
private static IUserPreferencesManager upm;
private static IUserLayoutStore store = UserLayoutStoreFactory.getUserLayoutStoreImpl();
public CSkinSelector() {
super();
}
/**
* Passes portal control structure to the channel.
* @see PortalControlStructures
*/
public void setPortalControlStructures(PortalControlStructures pcs) throws PortalException {
controlStructures = pcs;
if ( upm == null )
upm = controlStructures.getUserPreferencesManager();
}
public void setRuntimeData (ChannelRuntimeData rd) throws PortalException {
runtimeData = rd;
String action = runtimeData.getParameter("action");
if (action != null) {
if (runtimeData.getParameter("submitSave")!=null) {
String skinName = runtimeData.getParameter("skinName");
UserPreferences userPrefs = upm.getUserPreferences();
userPrefs.getThemeStylesheetUserPreferences().putParameterValue("skin",skinName);
saveUserPreferences(userPrefs);
}
}
}
private void saveUserPreferences ( UserPreferences userPrefs ) throws PortalException {
try {
store.putUserPreferences(staticData.getPerson(), userPrefs);
} catch (Exception e) {
throw new PortalException(e.getMessage(), e);
}
}
public void renderXML (ContentHandler out) throws PortalException {
InputStream xmlStream = PortalSessionManager.getResourceAsStream(SKINS_PATH + "/skinList.xml");
UserPreferences userPrefs = upm.getUserPreferences();
String currentSkin = userPrefs.getThemeStylesheetUserPreferences().getParameterValue("skin");
XSLT xslt = new XSLT (this);
xslt.setXML(xmlStream);
xslt.setXSL(sslLocation, "skinSelector", runtimeData.getBrowserInfo());
xslt.setTarget(out);
xslt.setStylesheetParameter("skinsPath", SKINS_PATH);
xslt.setStylesheetParameter("baseActionURL", runtimeData.getBaseActionURL());
if(currentSkin!=null)
xslt.setStylesheetParameter("currentSkin", currentSkin);
xslt.transform();
}
} |
package io.bootique;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.ProvisionException;
import io.bootique.command.CommandOutcome;
import io.bootique.env.DefaultEnvironment;
import io.bootique.log.BootLogger;
import io.bootique.log.DefaultBootLogger;
import io.bootique.shutdown.DefaultShutdownManager;
import io.bootique.shutdown.ShutdownManager;
import joptsimple.OptionException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import static java.util.stream.Collectors.joining;
/**
* A main launcher class of Bootique. To start a Bootique app, you may write your main method as follows:
* <pre>
* public static void main(String[] args) {
* Bootique.app(args).modules(...).exec().exit();
* }
* </pre>
* or
* <pre>
* public static void main(String[] args) {
* Bootique.app(args).autoLoadModules().exec().exit();
* }
* </pre>
* or just use this class as the main app class.
*/
public class Bootique {
private Collection<BQModuleProvider> providers;
private String[] args;
private boolean autoLoadModules;
private BootLogger bootLogger;
private ShutdownManager shutdownManager;
private Bootique(String[] args) {
this.args = args;
this.providers = new ArrayList<>();
this.autoLoadModules = false;
this.bootLogger = createBootLogger();
this.shutdownManager = createShutdownManager();
}
static Module createModule(Class<? extends Module> moduleType) {
try {
return moduleType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Error instantiating Module of type: " + moduleType.getName(), e);
}
}
/**
* A generic main method that auto-loads available modules and runs Bootique stack. Useful for apps that don't
* care to customize their "main()".
*
* @param args app arguments passed by the shell.
* @since 0.17
*/
public static void main(String[] args) {
Bootique.app(args).autoLoadModules().exec().exit();
}
/**
* Starts a builder of Bootique runtime.
*
* @param args command-line arguments.
* @return Bootique object that can be customized and then executed as an
* app via {@link #exec()} method.
*/
public static Bootique app(String... args) {
if (args == null) {
args = new String[0];
}
return new Bootique(args);
}
/**
* Starts a builder of Bootique runtime, initializing it with provided
* command-line arguments.
*
* @param args command-line arguments.
* @return Bootique object that can be customized and then executed as an
* app via {@link #exec()} method.
* @since 0.17
*/
public static Bootique app(Collection<String> args) {
if (args == null) {
args = Collections.emptyList();
}
return app(BootiqueUtils.toArray(Objects.requireNonNull(args)));
}
/**
* Optionally overrides Bootique's BootLogger.
*
* @param bootLogger a custom BootLogger. Has to be non-null.
* @return this instance of Bootique.
* @since 0.12
*/
public Bootique bootLogger(BootLogger bootLogger) {
this.bootLogger = Objects.requireNonNull(bootLogger);
return this;
}
/**
* Optionally overrides Bootique's ShutdownManager.
*
* @param shutdownManager a custom {@link ShutdownManager} to use in this execution of Bootique. Has to be non-null.
* @return this instance of Bootique.
* @since 0.23
*/
public Bootique shutdownManager(ShutdownManager shutdownManager) {
this.shutdownManager = Objects.requireNonNull(shutdownManager);
return this;
}
/**
* Appends extra values to Bootique CLI arguments.
*
* @param args extra args to pass to Bootique.
* @return this instance of Bootique
* @since 0.17
*/
public Bootique args(String... args) {
if (args != null) {
this.args = BootiqueUtils.mergeArrays(this.args, args);
}
return this;
}
/**
* Appends extra values to Bootique CLI arguments.
*
* @param args extra args to pass to Bootique.
* @return this instance of Bootique
* @since 0.17
*/
public Bootique args(Collection<String> args) {
if (args != null) {
this.args = BootiqueUtils.mergeArrays(this.args, BootiqueUtils.toArray(args));
}
return this;
}
/**
* Instructs Bootique to load any modules available on class-path that
* expose {@link BQModuleProvider} provider. Auto-loaded modules will be
* used in default configuration. Factories within modules will of course be
* configured dynamically from YAML.
* <p>
* <i>Use with caution, you may load more modules than you expected. Make
* sure only needed Bootique dependencies are included on class-path. If in
* doubt, switch to explicit Module loading via
* {@link #modules(Class...)}</i>.
*
* @return this Bootique instance
* @see BQModuleProvider
*/
public Bootique autoLoadModules() {
this.autoLoadModules = true;
return this;
}
/**
* @param moduleType custom Module class to add to Bootique DI runtime.
* @return this Bootique instance
* @see #autoLoadModules()
* @since 0.8
*/
public Bootique module(Class<? extends Module> moduleType) {
Objects.requireNonNull(moduleType);
providers.add(() -> createModule(moduleType));
return this;
}
/**
* Adds an array of Module types to the Bootique DI runtime. Each type will
* be instantiated by Bootique and added to the Guice DI container.
*
* @param moduleTypes custom Module classes to add to Bootique DI runtime.
* @return this Bootique instance
* @see #autoLoadModules()
* @since 0.8
*/
@SafeVarargs
public final Bootique modules(Class<? extends Module>... moduleTypes) {
Arrays.asList(moduleTypes).forEach(m -> module(m));
return this;
}
public Bootique module(Module m) {
Objects.requireNonNull(m);
providers.add(new BQModuleProvider() {
@Override
public Module module() {
return m;
}
@Override
public String name() {
return "Bootique";
}
});
return this;
}
/**
* Adds an array of Modules to the Bootique DI runtime.
*
* @param modules an array of modules to add to Bootiqie DI runtime.
* @return this instance of {@link Bootique}.
*/
public Bootique modules(Module... modules) {
Arrays.asList(modules).forEach(this::module);
return this;
}
/**
* Adds a Module generated by the provider. Provider may optionally specify
* that the Module overrides services in some other Module.
*
* @param moduleProvider a provider of Module and override spec.
* @return this instance of {@link Bootique}.
* @since 0.12
*/
public Bootique module(BQModuleProvider moduleProvider) {
Objects.requireNonNull(moduleProvider);
providers.add(moduleProvider);
return this;
}
/**
* Starts an API call chain to override an array of Modules.
*
* @param overriddenTypes an array of modules whose bindings should be overridden.
* @return {@link BQModuleOverrideBuilder} object to specify a Module
* overriding other modules.
*/
@SafeVarargs
public final BQModuleOverrideBuilder<Bootique> override(Class<? extends Module>... overriddenTypes) {
return new BQModuleOverrideBuilder<Bootique>() {
@Override
public Bootique with(Class<? extends Module> moduleType) {
providers.add(new BQModuleProvider() {
@Override
public Module module() {
return createModule(moduleType);
}
@Override
public Collection<Class<? extends Module>> overrides() {
return Arrays.asList(overriddenTypes);
}
});
return Bootique.this;
}
@Override
public Bootique with(Module module) {
providers.add(new BQModuleProvider() {
@Override
public Module module() {
return module;
}
@Override
public Collection<Class<? extends Module>> overrides() {
return Arrays.asList(overriddenTypes);
}
});
return Bootique.this;
}
};
}
/**
* Creates and returns an instance of {@link BQRuntime} that contains all Bootique services, commands, etc.
* This method is only needed if you are managing Bootique execution sequence manually. Normally you'd be using
* {@link #exec()} method instead of this method.
*
* @return a new {@link BQRuntime} instance that contains all Bootique services, commands, etc.
* @since 0.13
*/
public BQRuntime createRuntime() {
Injector injector = createInjector();
return createRuntime(injector);
}
/**
* Executes Bootique application, exiting the JVM at the end.
* <p>
* If you don't want your app to shutdown after executing Bootique, call {@link #exec()} instead.
*
* @deprecated since 0.23 in favor of {@link #exec()} followed by {@link CommandOutcome#exit()}.
*/
@Deprecated
public void run() {
exec().exit();
}
/**
* Executes this Bootique application, returning the outcome object.
*
* @return an outcome of the app command execution.
* @since 0.23
*/
public CommandOutcome exec() {
CommandOutcome o;
try {
// In case the app gets killed when command is running, let's use an explicit shutdown hook for cleanup.
Thread shutdownThread = createJVMShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownThread);
try {
o = createRuntime().run();
// block exit if there are remaining tasks...
if (o.forkedToBackground()) {
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
// interruption of a running daemon is a normal event, so return success
}
}
} finally {
// run shutdown explicitly...
shutdown(shutdownManager, bootLogger);
Runtime.getRuntime().removeShutdownHook(shutdownThread);
}
}
// unwrap standard Guice exceptions...
catch (CreationException ce) {
o = processExceptions(ce.getCause(), ce);
} catch (ProvisionException pe) {
o = processExceptions(pe.getCause(), pe);
} catch (Throwable th) {
o = processExceptions(th, th);
}
// report error
if (!o.isSuccess()) {
if (o.getMessage() != null) {
bootLogger.stderr(String.format("Error running command '%s': %s", getArgsAsString(), o.getMessage()), o.getException());
} else {
bootLogger.stderr(String.format("Error running command '%s'", getArgsAsString()), o.getException());
}
}
return o;
}
private Thread createJVMShutdownHook() {
// resolve all services needed for shutdown eagerly and outside shutdown thread to ensure that shutdown hook
// will not fail due to misconfiguration, etc.
ShutdownManager shutdownManager = this.shutdownManager;
BootLogger logger = this.bootLogger;
return new Thread("bootique-shutdown") {
@Override
public void run() {
shutdown(shutdownManager, logger);
}
};
}
private void shutdown(ShutdownManager shutdownManager, BootLogger logger) {
shutdownManager.shutdown().forEach((s, th) -> {
logger.stderr(String.format("Error performing shutdown of '%s': %s", s.getClass().getSimpleName(),
th.getMessage()));
});
}
private CommandOutcome processExceptions(Throwable th, Throwable parentTh) {
if (th instanceof BootiqueException) {
CommandOutcome originalOutcome = ((BootiqueException) th).getOutcome();
// BootiqueException should be stripped of the exception cause and reported on a single line
// TODO: should we still print the stack trace via logger.trace?
return CommandOutcome.failed(originalOutcome.getExitCode(), originalOutcome.getMessage());
}
String thMessage = th != null ? th.getMessage() : null;
String message = thMessage != null ? "Command exception: '" + thMessage + "'." : "Command exception.";
return CommandOutcome.failed(1, message, parentTh);
}
private String getArgsAsString() {
return Arrays.stream(args).collect(joining(" "));
}
/**
* @param runtime runtime started by Bootique.
* @return the outcome of the command execution.
* @deprecated since 0.23. Previously this method existed to catch and process run exceptions, but it doesn't
* have wide enough scope for this, so exception processing was moved to {@link #exec()}.
*/
@Deprecated
private CommandOutcome run(BQRuntime runtime) {
try {
return runtime.getRunner().run();
}
// handle startup Guice exceptions
catch (ProvisionException e) {
// TODO: a dependency on JOPT OptionException shouldn't be here
return (e.getCause() instanceof OptionException) ? CommandOutcome.failed(1, e.getCause().getMessage())
: CommandOutcome.failed(1, e);
}
}
private BQRuntime createRuntime(Injector injector) {
return new BQRuntime(injector);
}
private BootLogger createBootLogger() {
return new DefaultBootLogger(System.getProperty(DefaultEnvironment.TRACE_PROPERTY) != null);
}
private ShutdownManager createShutdownManager() {
return new DefaultShutdownManager(Duration.ofMillis(10000L));
}
Injector createInjector() {
DeferredModulesSource modulesSource = new DeferredModulesSource();
Collection<BQModule> bqModules = new ArrayList<>();
// note that 'moduleMetadata' is invalid at this point; it will be initialized later in this method, which
bqModules.add(coreModuleProvider(modulesSource).moduleBuilder().build());
BootiqueUtils.moduleProviderDependencies(builderProviders())
.forEach(p -> bqModules.add(p.moduleBuilder().build()));
if (autoLoadModules) {
autoLoadedProviders().forEach(p -> bqModules.add(p.moduleBuilder().build()));
}
// now that all modules are collected, finish 'moduleMetadata' initialization
modulesSource.init(bqModules);
// convert to Guice modules respecting overrides, etc.
Collection<Module> modules = new RuntimeModuleMerger(bootLogger).toGuiceModules(bqModules);
return Guice.createInjector(modules);
}
private Collection<BQModuleProvider> builderProviders() {
return providers;
}
private BQModuleProvider coreModuleProvider(Supplier<Collection<BQModule>> moduleSource) {
return new BQModuleProvider() {
@Override
public Module module() {
return BQCoreModule.builder().args(args)
.bootLogger(bootLogger)
.shutdownManager(shutdownManager)
.moduleSource(moduleSource).build();
}
@Override
public String name() {
return "Bootique";
}
@Override
public BQModule.Builder moduleBuilder() {
return BQModuleProvider.super
.moduleBuilder()
.description("The core of Bootique runtime.");
}
};
}
Collection<BQModuleProvider> autoLoadedProviders() {
Collection<BQModuleProvider> modules = new ArrayList<>();
ServiceLoader.load(BQModuleProvider.class).forEach(p -> modules.add(p));
return modules;
}
} |
package ork.sevenstates.apng;
public class Consts {
public static final byte ZERO = 0;
public static final int IHDR_SIG = 0x49484452;
public static final int acTL_SIG = 0x6163544c;
public static final int IDAT_SIG = 0x49444154;
public static final int fdAT_SIG = 0x66644154;
public static final int fcTL_SIG = 0x6663544c;
public static final int IEND_SIG = 0x49454e44;
public static final int CHUNK_DELTA =
4 //chunk len
+ 4 //header
+ 4;//CRC
public static final int IHDR_DATA_LEN = 13;
public static final int IHDR_TOTAL_LEN = IHDR_DATA_LEN + CHUNK_DELTA;
public static final int fcTL_DATA_LEN = 26;
public static final int fcTL_TOTAL_LEN = fcTL_DATA_LEN + CHUNK_DELTA;
private static final byte[] PNG_SIG = new byte[] {(byte) 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; //http://www.w3.org/TR/PNG/#5PNG-file-signature
private static final byte[] IEND_ARR = new byte[] {
0, 0, 0, 0,
'I', 'E', 'N', 'D',
(byte) 0xae, 0x42,
0x60, (byte) 0x82 //ae4260820
};
private static final byte[] acTL_ARR = new byte[] {
0, 0, 0, 8,
'a', 'c', 'T', 'L',
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
public static byte[] getacTLArr() {
return acTL_ARR.clone();
}
public static byte[] getIENDArr() {
return IEND_ARR.clone();
}
public static byte[] getPNGSIGArr() {
return PNG_SIG.clone();
}
} |
package controllers;
import models.Project;
import models.User;
import models.enumeration.Operation;
import org.apache.tika.Tika;
import org.codehaus.jackson.node.ObjectNode;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.joda.time.DateTime;
import org.tmatesoft.svn.core.SVNException;
import play.Logger;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import playRepository.RepositoryService;
import utils.AccessControl;
import utils.ErrorViews;
import views.html.code.view;
import views.html.code.nohead;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class CodeApp extends Controller {
public static String hostName;
public static Result codeBrowser(String userName, String projectName)
throws IOException, UnsupportedOperationException, ServletException {
Project project = ProjectApp.getProject(userName, projectName);
if (project == null) {
return notFound(ErrorViews.NotFound.render("error.notfound"));
}
if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
if (!RepositoryService.VCS_GIT.equals(project.vcs) && !RepositoryService.VCS_SUBVERSION.equals(project.vcs)) {
return status(Http.Status.NOT_IMPLEMENTED, project.vcs + " is not supported!");
}
List<String> branches = RepositoryService.getRepository(project).getBranches();
if (RepositoryService.VCS_GIT.equals(project.vcs) && branches.size() == 0) {
return ok(nohead.render(project));
}
return ok(view.render(project, branches));
}
public static Result codeBrowserWithBranch(String userName, String projectName, String branch)
throws IOException, UnsupportedOperationException, ServletException {
Project project = ProjectApp.getProject(userName, projectName);
if (!RepositoryService.VCS_GIT.equals(project.vcs) && !RepositoryService.VCS_SUBVERSION.equals(project.vcs)) {
return status(Http.Status.NOT_IMPLEMENTED, project.vcs + " is not supported!");
}
List<String> branches = RepositoryService.getRepository(project).getBranches();
return ok(view.render(project, branches));
}
public static Result ajaxRequest(String userName, String projectName, String path) throws Exception{
ObjectNode findFileInfo = RepositoryService.getMetaDataFrom(userName, projectName, path);
if(findFileInfo != null) {
return ok(findFileInfo);
} else {
return notFound();
}
}
public static Result ajaxRequestWithBranch(String userName, String projectName, String branch, String path)
throws UnsupportedOperationException, IOException, SVNException, GitAPIException, ServletException{
CodeApp.hostName = request().host();
ObjectNode findFileInfo = RepositoryService.getMetaDataFrom(userName, projectName, path, branch);
if(findFileInfo != null) {
return ok(findFileInfo);
} else {
return notFound();
}
}
public static Result showRawFile(String userName, String projectName, String path) throws Exception{
return ok(RepositoryService.getFileAsRaw(userName, projectName, path));
}
public static Result showImageFile(String userName, String projectName, String path) throws Exception{
final byte[] fileAsRaw = RepositoryService.getFileAsRaw(userName, projectName, path);
String mimeType = tika.detect(fileAsRaw);
return ok(fileAsRaw).as(mimeType);
}
private static Tika tika = new Tika();
public static String getURL(String ownerName, String projectName) {
Project project = ProjectApp.getProject(ownerName, projectName);
return getURL(project);
}
public static String getURL(Project project) {
if (project == null) {
return null;
} else if (RepositoryService.VCS_GIT.equals(project.vcs)) {
return utils.Url.create(Arrays.asList(project.owner, project.name), request().host());
} else if (RepositoryService.VCS_SUBVERSION.equals(project.vcs)) {
return utils.Url.create(Arrays.asList("svn", project.owner, project.name), request().host());
} else {
return null;
}
}
public static String getURLWithLoginId(Project project) {
String url = getURL(project);
if(url != null && project.vcs.equals(RepositoryService.VCS_GIT)) {
String loginId = session().get(UserApp.SESSION_LOGINID);
if(loginId != null && !loginId.isEmpty()) {
url = url.replace("://", "://" + loginId + "@");
}
}
return url;
}
} |
package controllers;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;
import com.avaje.ebean.annotation.Transactional;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.feth.play.module.mail.Mailer;
import com.feth.play.module.mail.Mailer.Mail;
import com.feth.play.module.mail.Mailer.Mail.Body;
import com.feth.play.module.pa.PlayAuthenticate;
import controllers.annotation.AnonymousCheck;
import jxl.write.WriteException;
import models.*;
import models.enumeration.Operation;
import models.enumeration.UserState;
import models.support.LdapUser;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.util.ByteSource;
import org.joda.time.LocalDateTime;
import play.Configuration;
import play.Logger;
import play.Play;
import play.data.Form;
import play.i18n.Messages;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.Cookie;
import play.mvc.Result;
import utils.*;
import views.html.user.*;
import javax.annotation.Nonnull;
import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.NamingException;
import java.io.IOException;
import java.util.*;
import static com.feth.play.module.mail.Mailer.getEmailName;
import static models.NotificationMail.isAllowedEmailDomains;
import static play.data.Form.form;
import static play.libs.Json.toJson;
import static utils.HtmlUtil.defaultSanitize;
public class UserApp extends Controller {
public static final String SESSION_USERID = "userId";
public static final String SESSION_LOGINID = "loginId";
public static final String SESSION_USERNAME = "userName";
public static final String SESSION_KEY = "key";
public static final String TOKEN = "yobi.token";
public static final String TOKEN_SEPARATOR = ":";
public static final int TOKEN_LENGTH = 2;
public static final int MAX_AGE = 30*24*60*60;
public static final String DEFAULT_AVATAR_URL
= routes.Assets.at("images/default-avatar-128.png").url();
private static final int AVATAR_FILE_LIMIT_SIZE = 1024*1000*1;
public static final int MAX_FETCH_USERS = 10; //Match value to Typeahead deafult value at yobi.ui.Typeaheds.js
private static final int HASH_ITERATIONS = 1024;
public static final int DAYS_AGO = 7;
public static final int UNDEFINED = 0;
public static final String DAYS_AGO_COOKIE = "daysAgo";
public static final String DEFAULT_GROUP = "own";
public static final String DEFAULT_SELECTED_TAB = "projects";
public static final String TOKEN_USER = "TOKEN_USER";
public static final String USER_TOKEN_HEADER = "Yona-Token";
public static final boolean useSocialLoginOnly = play.Configuration.root()
.getBoolean("application.use.social.login.only", false);
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
private static boolean usingEmailVerification = play.Configuration.root()
.getBoolean("application.use.email.verification", false);
@AnonymousCheck
public static Result users(String query) {
String referer = StringUtils.defaultString(request().getHeader("referer"), "");
if (!referer.endsWith("members") || !request().accepts("application/json")) {
return status(Http.Status.NOT_ACCEPTABLE);
}
if(StringUtils.isEmpty(query)){
return ok(toJson(new ArrayList<>()));
}
List<Map<String, String>> users = new ArrayList<>();
ExpressionList<User> el = User.find.select("loginId, name").where()
.ne("state", UserState.DELETED).disjunction();
el.icontains("loginId", query);
el.icontains("name", query);
el.endJunction();
int total = el.findRowCount();
if (total > MAX_FETCH_USERS) {
el.setMaxRows(MAX_FETCH_USERS);
response().setHeader("Content-Range", "items " + MAX_FETCH_USERS + "/" + total);
}
for (User user : el.findList()) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("<img class='mention_image' src='%s'>", user.avatarUrl()));
sb.append(String.format("<b class='mention_name'>%s</b>", user.name));
sb.append(String.format("<span class='mention_username'> @%s</span>", user.loginId));
Map<String, String> userMap = new HashMap<>();
userMap.put("info", sb.toString());
userMap.put("loginId", user.loginId);
users.add(userMap);
}
return ok(toJson(users));
}
public static void noCache(final Http.Response response) {
response.setHeader(Http.Response.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // HTTP 1.1
response.setHeader(Http.Response.PRAGMA, "no-cache"); // HTTP 1.0.
response.setHeader(Http.Response.EXPIRES, "0"); // Proxies.
}
public static Result loginForm() {
noCache(response());
if(!UserApp.currentUser().isAnonymous()) {
return redirect(routes.Application.index());
}
String redirectUrl = request().getQueryString("redirectUrl");
String loginFormUrl = routes.UserApp.loginForm().url();
String referer = request().getHeader("Referer");
if(StringUtils.isEmpty(redirectUrl) && !StringUtils.equals(loginFormUrl, referer)) {
redirectUrl = request().getHeader("Referer");
}
//Assume oAtuh is passed but not linked with existed account
if(PlayAuthenticate.isLoggedIn(session())){
UserApp.linkWithExistedOrCreateLocalUser();
return redirect(redirectUrl);
} else {
return ok(views.html.user.login.render("title.login", form(AuthInfo.class), redirectUrl));
}
}
public static Result logout() {
processLogout();
flash(Constants.SUCCESS, "user.logout.success");
String redirectUrl = request().getHeader("Referer");
return redirect(redirectUrl);
}
public static Result login() {
noCache(response());
if(useSocialLoginOnly){
flash(FLASH_ERROR_KEY,
Messages.get("app.warn.support.social.login.only"));
return Application.index();
}
if (HttpUtil.isJSONPreferred(request())) {
return loginByAjaxRequest();
} else {
return loginByFormRequest();
}
}
/**
* Process login in general case of request.
*
* Returns:
* - If "signup.require.confirm = true" has enabled in application.conf,
* the user in state of locked(or unconfirmed) cannot be logged in.
* and page will be redirected to login form with message "user.locked".
*
* - If "signup.require.confirm" is disabled(as default),
* the user in state of locked can be logged in. (TODO: check this in feature specification).
*
* - If failed to authentication, redirect to login form with error message.
*
* Cookie for login will be created
* if success to authenticate with request.
*
* If "rememberMe" included in request,
* Cookie for "rememberMe" (which means "Stay logged in") will be create
* separate from login cookie.
*
* @return
*/
private static Result loginByFormRequest() {
Form<AuthInfo> authInfoForm = form(AuthInfo.class).bindFromRequest();
if(authInfoForm.hasErrors()) {
flash(Constants.WARNING, "user.login.required");
return badRequest(login.render("title.login", authInfoForm, null));
}
User sourceUser = User.findByLoginKey(authInfoForm.get().loginIdOrEmail);
if (isUsingSignUpConfirm()) {
if (User.findByLoginId(sourceUser.loginId).state == UserState.LOCKED) {
flash(Constants.WARNING, "user.locked");
return redirect(getLoginFormURLWithRedirectURL());
}
}
if (User.findByLoginId(sourceUser.loginId).state == UserState.DELETED) {
flash(Constants.WARNING, "user.deleted");
return redirect(getLoginFormURLWithRedirectURL());
}
User authenticate = User.anonymous;
if (LdapService.useLdap) {
authenticate = authenticateWithLdap(authInfoForm.get().loginIdOrEmail, authInfoForm.get().password);
} else {
authenticate = authenticateWithPlainPassword(sourceUser.loginId, authInfoForm.get().password);
}
if(authenticate.isLocked()){
flash(Constants.WARNING, "user.locked");
return logout();
}
if (!authenticate.isAnonymous()) {
addUserInfoToSession(authenticate);
if (authInfoForm.get().rememberMe) {
setupRememberMe(authenticate);
}
authenticate.lang = play.mvc.Http.Context.current().lang().code();
authenticate.update();
String redirectUrl = getRedirectURLFromParams();
if(StringUtils.isEmpty(redirectUrl)){
return redirect(routes.Application.index());
} else {
return redirect(encodedPath(redirectUrl));
}
}
flash(Constants.WARNING, "user.login.invalid");
return redirect(routes.UserApp.loginForm());
}
private static String encodedPath(String path){
String[] paths = path.split("/");
if(paths.length == 0){
return "/";
}
String[] encodedPaths = new String[paths.length];
for (int i=0; i< paths.length; i++) {
encodedPaths[i] = HttpUtil.encodeUrlString(paths[i]);
}
return String.join("/", encodedPaths);
}
/**
* Process login request by AJAX
*
* Almost same with loginByFormRequest
* except part of handle with "redirectUrl" has excluded.
*
* Returns:
* - In case of success: empty JSON string {}
* - In case of failed: error message as JSON string in form of {"message":"cause"}.
*
* @return
*/
private static Result loginByAjaxRequest() {
Form<AuthInfo> authInfoForm = form(AuthInfo.class).bindFromRequest();
if(authInfoForm.hasErrors()) {
return badRequest(getObjectNodeWithMessage("user.login.required"));
}
User sourceUser = User.findByLoginKey(authInfoForm.get().loginIdOrEmail);
if (isUsingSignUpConfirm()) {
if (User.findByLoginId(sourceUser.loginId).state == UserState.LOCKED) {
return forbidden(getObjectNodeWithMessage("user.locked"));
}
}
if (User.findByLoginId(sourceUser.loginId).state == UserState.DELETED) {
return notFound(getObjectNodeWithMessage("user.deleted"));
}
User user = User.anonymous;
if (LdapService.useLdap) {
user = authenticateWithLdap(authInfoForm.get().loginIdOrEmail, authInfoForm.get().password);
} else {
user = authenticateWithPlainPassword(sourceUser.loginId, authInfoForm.get().password);
}
if(user.isLocked()){
return forbidden(getObjectNodeWithMessage("user.locked"));
}
if (!user.isAnonymous()) {
if (authInfoForm.get().rememberMe) {
setupRememberMe(user);
}
user.refresh();
user.lang = play.mvc.Http.Context.current().lang().code();
user.update();
addUserInfoToSession(user);
return ok("{}");
}
return forbidden(getObjectNodeWithMessage("user.login.invalid"));
}
/**
* Get value of "redirectUrl" from query
* @return
*/
private static String getRedirectURLFromParams(){
Map<String, String[]> params = request().body().asFormUrlEncoded();
return HttpUtil.getFirstValueFromQuery(params, "redirectUrl");
}
/**
* Get login form URL string with "redirectUrl" parameter in query
* @return
*/
private static String getLoginFormURLWithRedirectURL(){
String redirectUrl = getRedirectURLFromParams();
String loginFormUrl = routes.UserApp.loginForm().url();
loginFormUrl = loginFormUrl + "?redirectUrl=" + redirectUrl;
return loginFormUrl;
}
/**
* Returns ObjectNode which has "message" node filled with {@code message}
* loginByAjaxRequest() uses this to return result as JSON string
*
* @param message
* @return
*/
private static ObjectNode getObjectNodeWithMessage(String message){
ObjectNode result = Json.newObject();
result.put("message", message);
return result;
}
public static User authenticateWithHashedPassword(String loginId, String password) {
return authenticate(loginId, password, true);
}
public static User authenticateWithPlainPassword(String loginId, String password) {
return authenticate(loginId, password, false);
}
public static Result signupForm() {
if(!UserApp.currentUser().isAnonymous()) {
return redirect(routes.Application.index());
}
return ok(signup.render("title.signup", form(User.class)));
}
@Transactional
public static Result newUser() {
Form<User> newUserForm = form(User.class).bindFromRequest();
validate(newUserForm);
if (newUserForm.hasErrors()) {
return badRequest(signup.render("title.signup", newUserForm));
}
if (!isAllowedEmailDomains(newUserForm.get().email)) {
flash(Constants.INFO, "user.unacceptable.email.domain");
play.Logger.warn("Signup rejected: " + newUserForm.get().name + " with " + newUserForm.get().email);
return badRequest(signup.render("title.signup", newUserForm));
}
User user = createNewUser(newUserForm.get());
if (isUsingEmailVerification()) {
if (isAllowedEmailDomains(user.email)) {
flash(Constants.INFO, "user.verification.mail.sent");
} else {
flash(Constants.INFO, "user.unacceptable.email.domain");
}
}
if (user.state == UserState.LOCKED && isUsingSignUpConfirm()) {
flash(Constants.INFO, "user.signup.requested");
} else {
addUserInfoToSession(user);
}
return redirect(routes.Application.index());
}
private static String newLoginIdWithoutDup(final String candidate, int num) {
String newLoginIdSuggestion = candidate + "" + num;
if(User.findByLoginId(newLoginIdSuggestion).isAnonymous()){
return newLoginIdSuggestion;
} else {
num = num + 1;
return newLoginIdWithoutDup(newLoginIdSuggestion, num);
}
}
public static User createLocalUserWithOAuth(UserCredential userCredential){
if(userCredential.email == null || "null".equalsIgnoreCase(userCredential.email)) {
flash(FLASH_ERROR_KEY,
Messages.get("app.warn.cannot.access.email.information"));
play.Logger.error("Cannot confirm email address of " + userCredential.id + ": " + userCredential.name);
userCredential.delete();
forceOAuthLogout();
return User.anonymous;
}
if (!isAllowedEmailDomains(userCredential.email)) {
flash(Constants.INFO, "user.unacceptable.email.domain");
play.Logger.warn("Signup rejected: " + userCredential.name + " with " + userCredential.email);
userCredential.delete();
forceOAuthLogout();
return User.anonymous;
}
User created = createUserDelegate(userCredential.name, userCredential.email, null);
if(isUsingEmailVerification() && created.isLocked()){
flash(Constants.INFO, "user.verification.mail.sent");
forceOAuthLogout();
} else if (created.state == UserState.LOCKED) {
flash(Constants.INFO, "user.signup.requested");
forceOAuthLogout();
}
//Also, update userCredential
userCredential.loginId = created.loginId;
userCredential.user = created;
userCredential.update();
return created;
}
private static void forceOAuthLogout() {
session().put("pa.url.orig", routes.Application.oAuthLogout().url());
}
private static User createUserDelegate(@Nonnull String name, @Nonnull String email, String password) {
String loginIdCandidate = email.substring(0, email.indexOf("@"));
User user = new User();
user.loginId = generateLoginId(user, loginIdCandidate);
user.name = name;
user.email = email;
if(StringUtils.isEmpty(password)){
user.password = (new SecureRandomNumberGenerator()).nextBytes().toBase64(); // random password because created with OAuth
} else {
user.password = password;
}
return createNewUser(user);
}
public static Result verifyUser(String loginId, String verificationCode){
if(!UserApp.currentUser().isAnonymous()) {
return redirect(routes.Application.index());
}
UserVerification uv = UserVerification.findbyLoginIdAndVerificationCode(loginId, verificationCode);
if(uv == null){
return notFound("Invalid verification");
}
if (uv.isValidDate()) {
User user = User.findByLoginId(loginId);
user.state = UserState.ACTIVE;
user.update();
uv.invalidate();
return ok(verified.render("", loginId));
}
return notFound("Invalid verification");
}
private static void sendMailAfterUserCreation(User created) {
if (!isAllowedEmailDomains(created.email)) {
flash(Constants.INFO, "user.unacceptable.email.domain");
return;
}
Mail mail = new Mail(Messages.get("user.verification.signup.confirm")
+ ": " + getServeIndexPageUrl(),
getNewAccountMailBody(created),
new String[] { getEmailName(created.email, created.name) });
Mailer mailer = Mailer.getCustomMailer(Configuration.root().getConfig("play-easymail"));
mailer.sendMail(mail);
}
private static Body getNewAccountMailBody(User user){
String passwordResetUrl = getServeIndexPageUrl() + routes.PasswordResetApp.lostPassword();
StringBuilder html = new StringBuilder();
StringBuilder plainText = new StringBuilder();
if(isUsingEmailVerification()){
setVerificationMessage(user, html, plainText);
}
setSignupInfomation(user, passwordResetUrl, html, plainText);
return new Body(plainText.toString(), html.toString());
}
private static void setSignupInfomation(User user, String passwordResetUrl, StringBuilder html, StringBuilder plainText) {
html.append("URL: <a href='").append(getServeIndexPageUrl()).append("'>")
.append(getServeIndexPageUrl()).append("</a><br/>\n")
.append("ID: ").append(user.loginId).append("<br/>\n")
.append("Email: ").append(user.email).append("<br/>\n<br/>\n")
.append("Password reset: <a href='").append(passwordResetUrl).append("' target='_blank'>")
.append(passwordResetUrl).append("</a><br/>\n");
plainText.append("URL: ").append(getServeIndexPageUrl()).append("\n")
.append("ID: ").append(user.loginId).append("\n")
.append("Email: ").append(user.email).append("\n\n")
.append("Password reset: ").append(passwordResetUrl).append("\n");
}
private static void setVerificationMessage(User user, StringBuilder html, StringBuilder plainText) {
UserVerification verification = UserVerification.findbyUser(user);
if(verification == null){
verification = UserVerification.newVerification(user);
}
String verificationUrl = getServeIndexPageUrl()
+ routes.UserApp.verifyUser(user.loginId, verification.verificationCode).toString();
html.append("<h1>").append(Messages.get("user.verification")).append("</h1>\n");
html.append("<hr />\n");
html.append("<p><a href='").append(verificationUrl).append("'>")
.append(Messages.get("user.verification.link.click")).append("</a></p>\n");
html.append("<br />\n");
html.append("<br />\n");
plainText.append(Messages.get("user.verification")).append("\n");
plainText.append("
plainText.append(verificationUrl).append("\n");
plainText.append("\n");
plainText.append("\n");
}
private static String getServeIndexPageUrl(){
StringBuilder url = new StringBuilder();
if(request().secure()){
url.append("https:
} else {
url.append("http:
}
url.append(request().host());
return url.toString();
}
private static String generateLoginId(User user, String loginIdCandidate) {
User sameLoginIdUser = User.findByLoginId(loginIdCandidate);
if (sameLoginIdUser.isAnonymous()) {
return loginIdCandidate;
} else {
sameLoginIdUser = User.findByLoginId(loginIdCandidate + "-yona");
if (sameLoginIdUser.isAnonymous()) {
return loginIdCandidate + "-yona"; // first dup, then use suffix "-yona"
} else {
return newLoginIdWithoutDup(loginIdCandidate, 2);
}
}
}
@Transactional
public static Result resetUserPassword() {
Form<User> userForm = form(User.class).bindFromRequest();
if(userForm.hasErrors()) {
return badRequest(ErrorViews.BadRequest.render("error.badrequest"));
}
User currentUser = currentUser();
User user = userForm.get();
if(!isValidPassword(currentUser, user.oldPassword)) {
Form<User> currentUserForm = new Form<>(User.class);
currentUserForm = currentUserForm.fill(currentUser);
flash(Constants.WARNING, "user.wrongPassword.alert");
return badRequest(edit.render(currentUserForm, currentUser));
}
resetPassword(currentUser, user.password);
//go to login page
processLogout();
flash(Constants.WARNING, "user.loginWithNewPassword");
return redirect(routes.UserApp.loginForm());
}
public static Result resetUserVisitedList() {
RecentProject.deleteAll(currentUser());
flash(Constants.INFO, "userinfo.reset.visited.project.list.done");
return redirect(routes.UserApp.editUserInfoForm());
}
public static boolean isValidPassword(User currentUser, String password) {
String hashedOldPassword = hashedPassword(password, currentUser.passwordSalt);
return currentUser.password.equals(hashedOldPassword);
}
@Transactional
public static void resetPassword(User user, String newPassword) {
user.password = hashedPassword(newPassword, user.passwordSalt);
user.save();
}
@Transactional
public static User currentUser() {
User user = getUserFromSession();
if (!user.isAnonymous()) {
return user;
} else {
user = User.findUserIfTokenExist(user);
}
if(!user.isAnonymous()) {
return user;
}
return getUserFromContext();
}
private static User getUserFromSession() {
String userId = session().get(SESSION_USERID);
String userKey = session().get(SESSION_KEY);
if (userId == null) {
return User.anonymous;
}
if (!StringUtils.isNumeric(userId)) {
return invalidSession();
}
User user = null;
if ((userKey != null && Long.valueOf(userId) != null)){
user = CacheStore.yonaUsers.getIfPresent(Long.valueOf(userId));
}
if (user == null) {
return invalidSession();
}
return user;
}
private static User getUserFromContext() {
Object cached = Http.Context.current().args.get(TOKEN_USER);
if (cached instanceof User) {
return (User) cached;
}
initTokenUser();
return (User) Http.Context.current().args.get(TOKEN_USER);
}
public static void initTokenUser() {
User user = getUserFromToken();
Http.Context.current().args.put(TOKEN_USER, user);
if (!user.isAnonymous() && getUserFromSession().isAnonymous()) {
addUserInfoToSession(user);
}
}
private static User getUserFromToken() {
Cookie cookie = request().cookies().get(TOKEN);
if (cookie == null) {
return User.anonymous;
}
String[] subject = StringUtils.split(cookie.value(), TOKEN_SEPARATOR);
if (ArrayUtils.getLength(subject) != TOKEN_LENGTH) {
return invalidToken();
}
User user = authenticateWithHashedPassword(subject[0], subject[1]);
if (user.isAnonymous()) {
return invalidToken();
}
return user;
}
private static User invalidSession() {
session().clear();
return User.anonymous;
}
private static User invalidToken() {
response().discardCookie(TOKEN);
return User.anonymous;
}
@AnonymousCheck
public static Result userFiles(){
final int USER_FILES_COUNT_PER_PAGE = 50;
String pageNumString = request().getQueryString("pageNum");
String filter = request().getQueryString("filter");
int pageNum = 1;
if (StringUtils.isNotEmpty(pageNumString)){
pageNum = Integer.parseInt(pageNumString);
}
Page<Attachment> page = Attachment.findByUser(currentUser(), USER_FILES_COUNT_PER_PAGE, pageNum, filter);
return ok(userFiles.render("User Files", page));
}
@AnonymousCheck
public static Result userInfo(String loginId, String groups, int daysAgo, String selected) {
Organization org = Organization.findByName(loginId);
if(org != null) {
return redirect(routes.OrganizationApp.organization(org.name));
}
if (daysAgo == UNDEFINED) {
Cookie cookie = request().cookie(DAYS_AGO_COOKIE);
if (cookie != null && StringUtils.isNotEmpty(cookie.value())) {
daysAgo = Integer.parseInt(cookie.value());
} else {
daysAgo = DAYS_AGO;
response().setCookie(DAYS_AGO_COOKIE, daysAgo + "");
}
} else {
if (daysAgo < 0) {
daysAgo = 1;
}
response().setCookie(DAYS_AGO_COOKIE, daysAgo + "");
}
User user = User.findByLoginId(loginId);
String[] groupNames = groups.trim().split(",");
List<Posting> postings = new ArrayList<>();
List<Issue> issues = new ArrayList<>();
List<PullRequest> pullRequests = new ArrayList<>();
List<Milestone> milestones = new ArrayList<>();
List<Project> projects = new ArrayList<>();
if(Application.HIDE_PROJECT_LISTING){
if(!UserApp.currentUser().isAnonymous() && UserApp.currentUser().loginId.equals(loginId)){
projects = collectProjects(loginId, user, groupNames);
collectDatum(projects, postings, issues, pullRequests, milestones, daysAgo);
sortDatum(postings, issues, pullRequests, milestones);
sortByLastPushedDateAndName(projects);
}
} else {
projects = collectProjects(loginId, user, groupNames);
collectDatum(projects, postings, issues, pullRequests, milestones, daysAgo);
sortDatum(postings, issues, pullRequests, milestones);
sortByLastPushedDateAndName(projects);
}
if (user.isAnonymous()) {
return notFound(ErrorViews.NotFound.render("user.notExists.name"));
}
return ok(view.render(user, groupNames, projects, postings, issues, pullRequests, milestones, daysAgo, selected));
}
private static void sortByLastPushedDateAndName(List<Project> projects) {
Collections.sort(projects, new Comparator<Project>() {
@Override
public int compare(Project p1, Project p2) {
int compareLastPushedDate;
if (p1.lastPushedDate == null && p2.lastPushedDate == null) {
return p1.name.compareTo(p2.name);
}
if (p1.lastPushedDate == null) {
return 1;
} else if (p2.lastPushedDate == null) {
return -1;
}
compareLastPushedDate = p2.lastPushedDate.compareTo(p1.lastPushedDate);
if (compareLastPushedDate == 0) {
return p1.name.compareTo(p2.name);
}
return compareLastPushedDate;
}
});
}
private static void sortDatum(List<Posting> postings, List<Issue> issues, List<PullRequest> pullRequests, List<Milestone> milestones) {
Collections.sort(issues, new Comparator<Issue>() {
@Override
public int compare(Issue i1, Issue i2) {
return i2.createdDate.compareTo(i1.createdDate);
}
});
Collections.sort(postings, new Comparator<Posting>() {
@Override
public int compare(Posting p1, Posting p2) {
return p2.createdDate.compareTo(p1.createdDate);
}
});
Collections.sort(pullRequests, new Comparator<PullRequest>() {
@Override
public int compare(PullRequest p1, PullRequest p2) {
return p2.created.compareTo(p1.created);
}
});
Collections.sort(milestones, new Comparator<Milestone>() {
@Override
public int compare(Milestone m1, Milestone m2) {
return m2.title.compareTo(m1.title);
}
});
}
private static void collectDatum(List<Project> projects, List<Posting> postings, List<Issue> issues, List<PullRequest> pullRequests, List<Milestone> milestones, int daysAgo) {
// collect all postings, issues, pullrequests and milesotnes that are contained in the projects.
for (Project project : projects) {
if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
postings.addAll(Posting.findRecentlyCreatedByDaysAgo(project, daysAgo));
issues.addAll(Issue.findRecentlyOpendIssuesByDaysAgo(project, daysAgo));
pullRequests.addAll(PullRequest.findOpendPullRequestsByDaysAgo(project, daysAgo));
milestones.addAll(Milestone.findOpenMilestones(project.id));
}
}
}
private static List<Project> collectProjects(String loginId, User user, String[] groupNames) {
List<Project> projectCollection = new ArrayList<>();
// collect all projects that are included in the project groups.
for (String group : groupNames) {
switch (group) {
case "own":
addProjectNotDupped(projectCollection, Project.findProjectsCreatedByUser(loginId, null));
break;
case "member":
addProjectNotDupped(projectCollection, Project.findProjectsJustMemberAndNotOwner(user));
break;
case "watching":
addProjectNotDupped(projectCollection, user.getWatchingProjects());
break;
}
}
return projectCollection;
}
private static void addProjectNotDupped(List<Project> target, List<Project> foundProjects) {
for (Project project : foundProjects) {
if( !target.contains(project) &&
AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
target.add(project);
}
}
}
@AnonymousCheck(requiresLogin = true, displaysFlashMessage = true)
public static Result editUserInfoForm() {
User user = UserApp.currentUser();
Form<User> userForm = new Form<>(User.class);
userForm = userForm.fill(user);
return ok(edit.render(userForm, user));
}
@AnonymousCheck(requiresLogin = true, displaysFlashMessage = true)
public static Result editUserInfoByTabForm(String tabId) {
User user = UserApp.currentUser();
Form<User> userForm = new Form<>(User.class);
userForm = userForm.fill(user);
switch(UserInfoFormTabType.fromString(tabId)){
case PASSWORD:
return ok(edit_password.render(userForm, user));
case NOTIFICATIONS:
return ok(edit_notifications.render(userForm, user));
case EMAILS:
return ok(edit_emails.render(userForm, user));
case TOKEN_RESET:
user.token = null;
case TOKEN:
if( StringUtils.isEmpty(user.token)){
user.token = new Sha256Hash(LocalDateTime.now().toString()).toBase64();
user.save();
}
return ok(edit_token.render(userForm, user));
case PROFILE:
return ok(edit.render(userForm, user));
default:
return ok(edit.render(userForm, user));
}
}
private static boolean isUsingEmailVerification() {
return usingEmailVerification;
}
private enum UserInfoFormTabType {
PROFILE("profile"),
PASSWORD("password"),
NOTIFICATIONS("notifications"),
EMAILS("emails"),
TOKEN("token"),
TOKEN_RESET("token_reset");
private String tabId;
UserInfoFormTabType(String tabId) {
this.tabId = tabId;
}
public String value(){
return tabId;
}
public static UserInfoFormTabType fromString(String text)
throws IllegalArgumentException {
for(UserInfoFormTabType tab : UserInfoFormTabType.values()){
if (tab.value().equalsIgnoreCase(text)) {
return tab;
}
}
throw new IllegalArgumentException("Invalid tabId");
}
}
@AnonymousCheck(requiresLogin = true, displaysFlashMessage = true)
@Transactional
public static Result editUserInfo() {
Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email");
String newEmail = userForm.data().get("email");
String newName = defaultSanitize(userForm.data().get("name"));
User user = UserApp.currentUser();
if (StringUtils.isEmpty(newEmail)) {
userForm.reject("email", "user.wrongEmail.alert");
} else {
if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) {
userForm.reject("email", "user.email.duplicate");
}
}
if (userForm.error("email") != null) {
flash(Constants.WARNING, userForm.error("email").message());
return badRequest(edit.render(userForm, user));
}
user.email = newEmail;
user.name = HtmlUtil.defaultSanitize(newName);
try {
Long avatarId = Long.valueOf(userForm.data().get("avatarId"));
if (avatarId != null) {
Attachment attachment = Attachment.find.byId(avatarId);
String primary = attachment.mimeType.split("/")[0].toLowerCase();
if (attachment.size > AVATAR_FILE_LIMIT_SIZE){
userForm.reject("avatarId", "user.avatar.fileSizeAlert");
}
if (primary.equals("image")) {
Attachment.deleteAll(currentUser().avatarAsResource());
attachment.moveTo(currentUser().avatarAsResource());
}
}
} catch (NumberFormatException ignored) {
}
Email.deleteOtherInvalidEmails(user.email);
user.update();
CacheStore.yonaUsers.put(user.id, user);
return redirect(routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB));
}
@Transactional
public static Result leave(String userName, String projectName) {
ProjectApp.deleteMember(userName, projectName, UserApp.currentUser().id);
return redirect(routes.UserApp.userInfo(UserApp.currentUser().loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB));
}
/**
* check the given {@code loginId} is being used by someone else's logindId or group name,
* and whether {@code loginId} is a reserved word or not.
*
* @param name
* @return
* @see User#isLoginIdExist(String)
* @see Organization#isNameExist(String)
* @see ReservedWordsValidator#isReserved(String)
*/
public static Result isUsed(String name) {
ObjectNode result = Json.newObject();
result.put("isExist", User.isLoginIdExist(name) || Organization.isNameExist(name));
result.put("isReserved", ReservedWordsValidator.isReserved(name));
return ok(result);
}
@BodyParser.Of(BodyParser.Json.class)
public static Result isEmailExist(String email) {
ObjectNode result = Json.newObject();
result.put("isExist", User.isEmailExist(email));
return ok(result);
}
/**
* @param plainTextPassword plain text
* @param passwordSalt hash salt
* @return hashed password
*/
public static String hashedPassword(String plainTextPassword, String passwordSalt) {
if (plainTextPassword == null || passwordSalt == null) {
throw new IllegalArgumentException("Bad password or passwordSalt!");
}
return new Sha256Hash(plainTextPassword, ByteSource.Util.bytes(passwordSalt), HASH_ITERATIONS).toBase64();
}
@Transactional
public static Result addEmail() {
Form<Email> emailForm = form(Email.class).bindFromRequest();
String newEmail = emailForm.data().get("email");
if(emailForm.hasErrors()) {
flash(Constants.WARNING, emailForm.error("email").message());
return redirect(routes.UserApp.editUserInfoForm());
}
User currentUser = currentUser();
if(currentUser == null || currentUser.isAnonymous()) {
return forbidden(ErrorViews.NotFound.render());
}
if(User.isEmailExist(newEmail) || Email.exists(newEmail, true) || currentUser.has(newEmail)) {
flash(Constants.WARNING, Messages.get("user.email.duplicate"));
return redirect(routes.UserApp.editUserInfoForm());
}
Email email = new Email();
User user = currentUser();
email.user = user;
email.email = newEmail;
email.valid = false;
user.addEmail(email);
return redirect(routes.UserApp.editUserInfoForm());
}
@Transactional
public static Result deleteEmail(Long id) {
User currentUser = currentUser();
Email email = Email.find.byId(id);
if(currentUser == null || currentUser.isAnonymous() || email == null) {
return forbidden(ErrorViews.NotFound.render());
}
if(!AccessControl.isAllowed(currentUser, email.user.asResource(), Operation.DELETE)) {
return forbidden(ErrorViews.Forbidden.render(Messages.get("error.forbidden")));
}
email.delete();
return redirect(routes.UserApp.editUserInfoForm());
}
@Transactional
public static Result sendValidationEmail(Long id) {
User currentUser = currentUser();
Email email = Email.find.byId(id);
if(currentUser == null || currentUser.isAnonymous() || email == null) {
return forbidden(ErrorViews.NotFound.render());
}
if(!AccessControl.isAllowed(currentUser, email.user.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render(Messages.get("error.forbidden")));
}
email.sendValidationEmail();
flash(Constants.WARNING, " .");
return redirect(routes.UserApp.editUserInfoForm());
}
@Transactional
public static Result confirmEmail(Long id, String token) {
Email email = Email.find.byId(id);
if(email == null) {
return forbidden(ErrorViews.NotFound.render());
}
if(email.validate(token)) {
addUserInfoToSession(email.user);
return redirect(routes.UserApp.editUserInfoForm());
} else {
return forbidden(ErrorViews.NotFound.render());
}
}
@Transactional
public static Result setAsMainEmail(Long id) {
User currentUser = currentUser();
Email email = Email.find.byId(id);
if(currentUser == null || currentUser.isAnonymous() || email == null) {
return forbidden(ErrorViews.NotFound.render());
}
if(!AccessControl.isAllowed(currentUser, email.user.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render(Messages.get("error.forbidden")));
}
String oldMainEmail = currentUser.email;
currentUser.email = email.email;
currentUser.removeEmail(email);
currentUser.update();
Email newSubEmail = new Email();
newSubEmail.valid = true;
newSubEmail.email = oldMainEmail;
newSubEmail.user = currentUser;
currentUser.addEmail(newSubEmail);
return redirect(routes.UserApp.editUserInfoForm());
}
private static User authenticate(String loginId, String password, boolean hashed) {
User user = User.findByLoginId(loginId);
if (user.isAnonymous()) {
return user;
}
String hashedPassword = hashed ? password : hashedPassword(password, user.passwordSalt);
if (StringUtils.equals(user.password, hashedPassword)) {
return user;
}
return User.anonymous;
}
public static User authenticateWithLdap(String loginIdOrEmail, String password) {
LdapService ldapService = new LdapService();
try {
LdapUser ldapUser = ldapService.authenticate(loginIdOrEmail, password);
User localUserFoundByLdapLogin = User.findByEmail(ldapUser.getEmail());
if (localUserFoundByLdapLogin.isAnonymous()) {
User created = createUserDelegate(ldapUser.getDisplayName(), ldapUser.getEmail(), password);
if (created.state == UserState.LOCKED) {
flash(Constants.INFO, "user.signup.requested");
return User.anonymous;
}
return created;
} else {
if(!localUserFoundByLdapLogin.isSamePassword(password)) {
User.resetPassword(localUserFoundByLdapLogin.loginId, password);
}
return localUserFoundByLdapLogin;
}
} catch (CommunicationException e) {
play.Logger.error("Cannot connect to ldap server \n" + e.getMessage());
e.printStackTrace();
return User.anonymous;
} catch (AuthenticationException e) {
flash(Constants.WARNING, Messages.get("user.login.invalid"));
play.Logger.warn("login failed \n" + e.getMessage());
return User.anonymous;
} catch (NamingException e) {
play.Logger.error("Cannot connect to ldap server \n" + e.getMessage());
e.printStackTrace();
return User.anonymous;
}
}
public static boolean isUsingSignUpConfirm(){
Configuration config = play.Play.application().configuration();
Boolean useSignUpConfirm = config.getBoolean("signup.require.admin.confirm");
if(useSignUpConfirm == null) {
useSignUpConfirm = config.getBoolean("signup.require.confirm", false); // for compatibility under v1.1
}
return useSignUpConfirm;
}
public static void setupRememberMe(User user) {
response().setCookie(TOKEN, user.loginId + ":" + user.password, MAX_AGE);
Logger.debug("remember me enabled");
}
private static void processLogout() {
session().clear();
response().discardCookie(TOKEN);
}
private static void validate(Form<User> newUserForm) {
if (newUserForm.field("loginId").value().trim().isEmpty()) {
newUserForm.reject("loginId", "user.wrongloginId.alert");
}
if (newUserForm.field("loginId").value().contains(" ")) {
newUserForm.reject("loginId", "user.wrongloginId.alert");
}
if (newUserForm.field("password").value().trim().isEmpty()) {
newUserForm.reject("password", "user.wrongPassword.alert");
}
if (User.isLoginIdExist(newUserForm.field("loginId").value())
|| Organization.isNameExist(newUserForm.field("loginId").value())) {
newUserForm.reject("loginId", "user.loginId.duplicate");
}
if (User.isEmailExist(newUserForm.field("email").value())) {
newUserForm.reject("email", "user.email.duplicate");
}
}
private static User createNewUser(User user) {
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
user.passwordSalt = rng.nextBytes().toBase64();
user.password = hashedPassword(user.password, user.passwordSalt);
if (isUsingSignUpConfirm() || isUsingEmailVerification()) {
user.state = UserState.LOCKED;
} else {
user.state = UserState.ACTIVE;
}
User.create(user);
Email.deleteOtherInvalidEmails(user.email);
if (isUsingEmailVerification()) {
UserVerification.newVerification(user);
sendMailAfterUserCreation(user);
}
return user;
}
public static void addUserInfoToSession(User user) {
if(user.isLocked()){
return;
}
String key = new Sha256Hash(new Date().toString(), ByteSource.Util.bytes(user.passwordSalt), 1024)
.toBase64();
CacheStore.yonaUsers.put(user.id, user);
session(SESSION_USERID, String.valueOf(user.id));
session(SESSION_LOGINID, user.loginId);
session(SESSION_USERNAME, user.name);
session(SESSION_KEY, key);
}
public static boolean linkWithExistedOrCreateLocalUser() {
final UserCredential oAuthUser = UserCredential.findByAuthUserIdentity(PlayAuthenticate
.getUser(Http.Context.current().session()));
User user = null;
if (oAuthUser.loginId == null) {
user = User.findByEmail(oAuthUser.email);
} else {
user = User.findByLoginId(oAuthUser.loginId);
}
if(PlayAuthenticate.isLoggedIn(session()) && user.isAnonymous()){
return !createLocalUserWithOAuth(oAuthUser).isAnonymous();
} else {
if (oAuthUser.loginId == null) {
oAuthUser.loginId = user.loginId;
oAuthUser.user = user;
oAuthUser.update();
}
UserApp.addUserInfoToSession(user);
}
return true;
}
public static void updatePreferredLanguage() {
Http.Request request = Http.Context.current().request();
User user = UserApp.currentUser();
if (user.isAnonymous()) {
return;
}
if (request.acceptLanguages().isEmpty() &&
request.cookie(Play.langCookieName()) == null) {
return;
}
String code = StringUtils.left(Http.Context.current().lang().code(), 255);
if (!code.equals(user.lang)) {
synchronized (user) {
user.refresh();
user.lang = code;
user.update();
}
}
}
public static Result resetUserPasswordBySiteManager(String loginId){
if (!request().getQueryString("action").equals("resetPassword")) {
ObjectNode json = Json.newObject();
json.put("isSuccess", false);
json.put("reason", "BAD_REQUEST");
return badRequest(json);
}
String newPassword = PasswordReset.generateResetHash(loginId).substring(0,6);
User targetUser = User.findByLoginId(loginId);
if(!targetUser.isAnonymous() && UserApp.currentUser().isSiteManager()){
User.resetPassword(loginId, newPassword);
ObjectNode json = Json.newObject();
json.put("loginId", targetUser.loginId);
json.put("name", targetUser.name);
json.put("newPassword", newPassword);
json.put("isSuccess", true);
return ok(json);
} else {
ObjectNode json = Json.newObject();
json.put("isSuccess", false);
json.put("reason", "FORBIDDEN");
return forbidden(json);
}
}
public static boolean isSiteAdminLoggedInSession(){
if(SiteAdmin.SITEADMIN_DEFAULT_LOGINID.equals(session().get(SESSION_LOGINID))){
return true;
} else {
return false;
}
}
@AnonymousCheck
public static Result setDefaultLoginPage() throws IOException, WriteException {
UserSetting userSetting = UserSetting.findByUser(UserApp.currentUser().id);
userSetting.loginDefaultPage = request().getQueryString("path");
userSetting.save();
ObjectNode json = Json.newObject();
json.put("defaultLoginPage", userSetting.loginDefaultPage);
return ok(json);
}
public static Result usermenuTabContentList(){
return ok(views.html.common.usermenu_tab_content_list.render());
}
} |
package com.parc.ccn.data.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import com.parc.ccn.data.CompleteName;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.query.Interest;
/**
* Table of Interests, holding an arbitrary value for any
* Interest or ContentName. This is conceptually like a Map<Interest, V> except it supports
* duplicate entries and has operations for access based on CCN
* matching. An InterestTable may be used to hold real Interests, or merely
* ContentNames only, though mixing the two in the same instance of InterestTable
* is not recommended.
* @author jthornto
*
*/
public class InterestTable<V> {
public interface Entry<T> {
/**
* Get the ContentName of this entry. All table entries have non-null
* ContentName.
* @return
*/
public ContentName name();
/**
* Get the Interest of this entry. If a name is entered in the table
* then the Interest will be null.
* @return Interest if present, null otherwise
*/
public Interest interest();
/**
* Get the value of this entry. A value may be null.
* @return
*/
public T value();
}
protected SortedMap<ContentName,List<Holder<V>>> _contents = new TreeMap<ContentName,List<Holder<V>>>();
protected abstract class Holder<T> implements Entry<T> {
protected T value;
public Holder(T v) {
value= v;
}
public T value() {
return value;
}
}
protected class NameHolder<T> extends Holder<T> {
protected ContentName name;
public NameHolder(ContentName n, T v) {
super(v);
name = n;
}
public ContentName name() {
return name;
}
public Interest interest() {
return null;
}
}
protected class InterestHolder<T> extends Holder<T> {
protected Interest interest;
public InterestHolder(Interest i, T v) {
super(v);
interest = i;
}
public ContentName name() {
return interest.name();
}
public Interest interest() {
return interest;
}
}
public void add(Interest interest, V value) {
if (null == interest) {
throw new NullPointerException("InterestTable may not contain null Interest");
}
if (null == interest.name()) {
throw new NullPointerException("InterestTable may not contain Interest with null name");
}
Holder<V> holder = new InterestHolder<V>(interest, value);
add(holder);
}
public void add(ContentName name, V value) {
if (null == name) {
throw new NullPointerException("InterestTable may not contain null name");
}
Holder<V> holder = new NameHolder<V>(name, value);
add(holder);
}
protected void add(Holder<V> holder) {
if (_contents.containsKey(holder.name())) {
_contents.get(holder.name()).add(holder);
} else {
ArrayList<Holder<V>> list = new ArrayList<Holder<V>>(1);
list.add(holder);
_contents.put(holder.name(), list);
}
}
protected Holder<V> getMatchByName(ContentName name, CompleteName target) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
return holder;
}
}
}
}
return null;
}
// Internal: return all the entries having exactly the specified name,
// useful once you have found the matching names to collect entries from them
protected List<Holder<V>> getAllMatchByName(ContentName name, CompleteName target) {
List<Holder<V>> matches = new ArrayList<Holder<V>>();
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
matches.add(holder);
}
}
}
}
return matches;
}
protected Holder<V> removeMatchByName(ContentName name, CompleteName target) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
holdIt.remove();
if (list.size() == 0) {
_contents.remove(name);
}
return holder;
}
}
}
}
return null;
}
/**
* Remove first exact match entry (both name and value match).
* @param name
* @param value
* @return
*/
public Entry<V> remove(ContentName name, V value) {
Holder<V> result = null;
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null == holder.value()) {
if (null == value) {
holdIt.remove();
result = holder;
}
} else {
if (holder.value().equals(value)) {
holdIt.remove();
result = holder;
}
}
}
}
return result;
}
/**
* Remove first exact match entry (both interest and value match)
* @param interest
* @param value
* @return
*/
public Entry<V> remove(Interest interest, V value) {
Holder<V> result = null;
List<Holder<V>> list = _contents.get(interest.name());
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (interest.equals(holder.interest())) {
if (null == holder.value()) {
if (null == value) {
holdIt.remove();
result = holder;
}
} else {
if (holder.value().equals(value)) {
holdIt.remove();
result = holder;
}
}
}
}
}
return result;
}
protected List<Holder<V>> removeAllMatchByName(ContentName name, CompleteName target) {
List<Holder<V>> matches = new ArrayList<Holder<V>>();
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
holdIt.remove();
matches.add(holder);
}
}
}
if (list.size() == 0) {
_contents.remove(name);
}
}
return matches;
}
/**
* Get value of longest matching Interest for a CompleteName, where longest is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation. If there are multiple matches, first is returned.
* @param target - desired CompleteName
* @return Entry of longest match if any, null if no match
*/
public V getValue(ContentObject target) {
Entry<V> match = getMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Get longest matching Interest for a CompleteName. This is the same as
* getValue() except that the Entry is returned so the matching item
* may be retrieved and null value may be detected. The Entry returned will have a
* non-null interest because this method matches only Interests in the table.
* @param target - desired CompleteName
* @return Entry of longest match if any, null if no match
*
* Comment by Paul Rasmussen - these used to try to use headMap as an optimization but
* that won't work because without examining the interest we can't know what subset of
* _contents might contain a matching interest. Also since headMap requires a bunch of
* compares I'm not so sure how much of an optimization it is anyway...
*/
public Entry<V> getMatch(ContentObject target) {
Entry<V> match = null;
for (ContentName name : _contents.keySet()) {
if (name.isPrefixOf(target)) {
// Name match - is there an interest match here?
Entry<V> found = getMatchByName(name, target.completeName());
if (null != found) {
match = getMatchByName(name, target.completeName());
}
}
}
return match;
}
/**
* Get values of all matching Interests for a ContentObject.
* Any ContentName entries in the table will be
* ignored by this operation and any null values will be ignored.
*/
public List<V> getValues(ContentObject target) {
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = getMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Get all matching Interests for a CompleteName.
* Any ContentName entries in the table will be
* ignored by this operation, so every Entry returned will have a
* non-null interest. This is the same as getValues() except that
* Entry objects are returned.
* @param target - desired CompleteName
* @return List of matches, empty if no match
*/
public List<Entry<V>> getMatches(ContentObject target) {
List<Entry<V>> matches = new ArrayList<Entry<V>>();
if (null != target) {
for (ContentName name : _contents.keySet()) {
if (name.isPrefixOf(target)) {
// Name match - is there an interest match here?
matches.addAll(getAllMatchByName(name, target.completeName()));
}
}
Collections.reverse(matches);
}
return matches;
}
/**
* Get value of longest matching Interest for a ContentName, where longest is defined
* as longest ContentName. If there are multiple matches, first is returned.
* This will return a mix of ContentName and Interest entries if they exist
* (and match) in the table, i.e. the Interest of an Entry may be null in some cases.
* @param target desired ContentName
* @return Entry of longest match if any, null if no match
*/
public V getValue(ContentName target) {
Entry<V> match = getMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Get longest matching Interest. This method is the same as getValue()
* except that the Entry is returned so the matching item may be retrieved
* and null value may be detected.
* @param target
* @return
*/
public Entry<V> getMatch(ContentName target) {
Entry<V> match = null;
ContentName headname = new ContentName(target, new byte[] {0} ); // need to include equal item in headMap
for (Iterator<ContentName> nameIt = _contents.headMap(headname).keySet().iterator(); nameIt.hasNext();) {
ContentName name = nameIt.next();
if (name.isPrefixOf(target)) {
match = _contents.get(name).get(0);
}
}
return match;
}
public List<V> getValues(ContentName target) {
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = getMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Get all matching entries for a ContentName.
* This will return a mix of ContentName and Interest entries if they exist
* (and match) in the table, i.e. the Interest of an Entry may be null in some cases.
* @param target desired ContentName
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<Entry<V>> getMatches(ContentName target) {
List<Entry<V>> matches = new ArrayList<Entry<V>>();
for (ContentName name : _contents.keySet()) {
if (name.isPrefixOf(target)) {
matches.addAll(_contents.get(name));
}
}
Collections.reverse(matches);
return matches;
}
/**
* Get all entries. This will return a mix of ContentName and Interest entries
* if they exist in the table, i.e. the Interest of an Entry may be null in some cases.
* @return Collection of entries in arbitrary order
*/
public Collection<Entry<V>> values() {
List<Entry<V>> results = new ArrayList<Entry<V>>();
for (Iterator<ContentName> keyIt = _contents.keySet().iterator(); keyIt.hasNext();) {
ContentName name = (ContentName) keyIt.next();
List<Holder<V>> list = _contents.get(name);
results.addAll(list);
}
return results;
}
/**
* Remove and return value of the longest matching Interest for a CompleteName, where best is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation, as will null values.
* @param target - desired CompleteName
* @return value of longest match if any, null if no match
*/
public V removeValue(CompleteName target) {
Entry<V> match = removeMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Remove and return the longest matching Interest for a CompleteName, where best is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation, so the Entry returned will have a
* non-null interest.
* @param target - desired CompleteName
* @return Entry of longest match if any, null if no match
*/
public Entry<V> removeMatch(CompleteName target) {
Entry<V> match = null;
if (null != target) {
ContentName matchName = null;
ContentName headname = new ContentName(target.name(), new byte[] {0} ); // need to include equal item in headMap
for (Iterator<ContentName> nameIt = _contents.headMap(headname).keySet().iterator(); nameIt.hasNext();) {
ContentName name = nameIt.next();
if (name.isPrefixOf(target.name())) {
// Name match - is there an interest match here?
Entry<V> found = getMatchByName(name, target);
if (null != found) {
match = found;
matchName = name;
}
// Do not remove here -- need to find best match and avoid disturbing iterator
}
}
if (null != match) {
return removeMatchByName(matchName, target);
}
}
return match;
}
/**
* Remove and return values for all matching Interests for a CompleteName.
* Any ContentName entries in the table will be
* ignored by this operation. Null values will not be represented in returned
* list though their Interests will have been removed if any.
* @param target - desired CompleteName
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<V> removeValues(CompleteName target) {
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = removeMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Remove and return all matching Interests for a CompleteName.
* Any ContentName entries in the table will be
* ignored by this operation, so every Entry returned will have a
* non-null interest.
* @param target - desired CompleteName
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<Entry<V>> removeMatches(CompleteName target) {
List<Entry<V>> matches = new ArrayList<Entry<V>>();
List<ContentName> names = new ArrayList<ContentName>();
ContentName headname = new ContentName(target.name(), new byte[] {0} ); // need to include equal item in headMap
for (Iterator<ContentName> nameIt = _contents.headMap(headname).keySet().iterator(); nameIt.hasNext();) {
ContentName name = nameIt.next();
if (name.isPrefixOf(target.name())) {
// Name match - is there an interest match here?
matches.addAll(getAllMatchByName(name, target));
names.add(name);
}
}
if (matches.size() != 0) {
for (ContentName contentName : names) {
removeAllMatchByName(contentName, target);
}
}
Collections.reverse(matches);
return matches;
}
/**
* Get the number of distinct entries in the table. Note that duplicate entries
* are fully supported, so the number of entries may be much larger than the
* number of ContentNames (sizeNames()).
* @return
*/
public int size() {
int result = 0;
for (Iterator<ContentName> nameIt = _contents.keySet().iterator(); nameIt.hasNext();) {
ContentName name = nameIt.next();
List<Holder<V>> list = _contents.get(name);
result += list.size();
}
return result;
}
/**
* Get the number of distinct ContentNames in the table. Note that duplicate
* entries are fully supported, so the number of ContentNames may be much smaller
* than the number of entries (size()).
* @return
*/
public int sizeNames() {
return _contents.size();
}
} |
package blogr.vpm.fr.blogr.activity;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.ActionMode;
import blogr.vpm.fr.blogr.R;
import blogr.vpm.fr.blogr.bean.Post;
public class PostActivity extends Activity implements PostSelectionListener{
private PostEditionFragment postEditionFragment;
private Fragment postListFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
postEditionFragment = (PostEditionFragment) getFragmentManager().findFragmentById(R.id.postEditionFragment);
postListFragment = getFragmentManager().findFragmentById(R.id.postListFragment);
FragmentTransaction displayPostList = getFragmentManager().beginTransaction();
displayPostList.hide(postEditionFragment);
displayPostList.commit();
setTitle("");
}
@Override
public void onPostSelection(Post post) {
postEditionFragment.editPost(post);
displayPostEdition();
}
@Override
public void onActionModeFinished(ActionMode mode) {
postListFragment.onResume();
}
/**
* Displays the fragment to edit a post and hides the fragment with the list of posts
*/
private void displayPostEdition() {
FragmentTransaction displayPostEdition = getFragmentManager().beginTransaction();
displayPostEdition.hide(postListFragment);
displayPostEdition.show(postEditionFragment);
displayPostEdition.addToBackStack("displayPostEdition");
displayPostEdition.commit();
}
} |
package com.parc.ccn.security.access;
import java.security.InvalidKeyException;
import java.sql.Timestamp;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.library.profiles.AccessControlProfile;
import com.parc.ccn.library.profiles.VersionMissingException;
import com.parc.ccn.library.profiles.VersioningProfile;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.crypto.KeyDerivationFunction;
public class NodeKey {
/**
* The node this key is associated with, with _access_ information stripped.
*/
private ContentName _nodeName;
/**
* The full name of the stored node key that is either this key itself,
* or the ancestor node key this is derived from, including its version information.
*/
private ContentName _storedNodeKeyName;
private byte [] _storedNodeKeyID;
/**
* The unwrapped node key
*/
private byte [] _nodeKey;
public NodeKey(ContentName nodeKeyName, byte [] unwrappedNodeKey) {
if ((null == nodeKeyName) || (null == unwrappedNodeKey)) {
throw new IllegalArgumentException("NodeKey: key name and key cannot be null!");
}
_storedNodeKeyName = nodeKeyName;
_storedNodeKeyID = generateKeyID(unwrappedNodeKey);
_nodeKey = unwrappedNodeKey;
_nodeName = AccessControlProfile.accessRoot(nodeKeyName);
if ((null == _nodeName) || (!AccessControlProfile.isNodeKeyName(nodeKeyName))) {
throw new IllegalArgumentException("NodeKey: key name " + nodeKeyName + " is not a valid node key name.");
}
}
protected NodeKey(ContentName nodeName, byte [] derivedNodeKey,
ContentName ancestorNodeKeyName, byte [] ancestorNodeKeyID) {
_storedNodeKeyName = ancestorNodeKeyName;
_storedNodeKeyID = ancestorNodeKeyID;
_nodeName = nodeName;
_nodeKey = derivedNodeKey;
}
public NodeKey computeDescendantNodeKey(ContentName descendantNodeName, String keyLabel) throws InvalidKeyException, XMLStreamException {
if (!nodeName().isPrefixOf(descendantNodeName)) {
throw new IllegalArgumentException("Node " + descendantNodeName + " is not a child of this node " + nodeName());
}
byte [] derivedKey = KeyDerivationFunction.DeriveKeyForNode(nodeName(), nodeKey(), keyLabel, descendantNodeName);
return new NodeKey(descendantNodeName, derivedKey, storedNodeKeyName(), storedNodeKeyID());
}
public ContentName nodeName() { return _nodeName; }
public ContentName storedNodeKeyName() { return _storedNodeKeyName; }
public byte [] storedNodeKeyID() { return _storedNodeKeyID; }
public byte [] nodeKey() { return _nodeKey; }
public boolean isDerivedNodeKey() {
return (!nodeName().isPrefixOf(storedNodeKeyName()));
}
public Timestamp nodeKeyVersion() throws VersionMissingException {
return VersioningProfile.getVersionAsTimestamp(storedNodeKeyName());
}
public static byte [] generateKeyID(byte [] key) {
return CCNDigestHelper.digest(key);
}
} |
package cav.pdst.ui.fragments;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.spans.DotSpan;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import cav.pdst.R;
import cav.pdst.data.managers.DataManager;
import cav.pdst.data.models.TrainingModel;
import cav.pdst.ui.adapters.SpTrainingAdapter;
public class SpTrainingFragment extends Fragment {
private static final String SPORTSMAN_ID = "SP_ID";
private int sp_id;
private ListView mListView;
private SpTrainingAdapter mAdapter;
private DataManager mDataManager;
private MaterialCalendarView calendarView;
private Date selectedDate;
private Collection<CalendarDay> mCalendarDays;
public static SpTrainingFragment newInstanse(int sp_id){
Bundle args = new Bundle();
args.putSerializable(SPORTSMAN_ID,sp_id);
SpTrainingFragment fragment = new SpTrainingFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDataManager = DataManager.getInstance();
this.sp_id = getArguments().getInt(SPORTSMAN_ID);
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sp_training, container, false);
selectedDate = new Date();
Calendar newYear = Calendar.getInstance();
newYear.add(Calendar.YEAR, 1);
calendarView = (MaterialCalendarView) rootView.findViewById(R.id.calendarView);
calendarView.state().edit()
.setFirstDayOfWeek(Calendar.MONDAY)
.setMinimumDate(CalendarDay.from(2016,12,31))
.setMaximumDate(newYear)
.commit();
/*
mCalendarDays = new ArrayList<>();
for (Date l : mDataManager.getTrainingDay(sp_id)) {
mCalendarDays.add(CalendarDay.from(l));
}
calendarView.addDecorator(new StartDayViewDecorator(mCalendarDays));
*/
new LoadUseDay().execute();
calendarView.setOnDateChangedListener(mDateSelectedListener);
calendarView.setCurrentDate(new Date());
calendarView.setDateSelected(new Date(),true);
mListView = (ListView) rootView.findViewById(R.id.sp_info_list_view);
updateUI();
return rootView;
// return super.onCreateView(inflater, container, savedInstanceState);
}
OnDateSelectedListener mDateSelectedListener = new OnDateSelectedListener() {
@Override
public void onDateSelected(MaterialCalendarView widget,CalendarDay date, boolean selected) {
selectedDate = date.getDate();
updateUI();
}
};
private void updateUI() {
ArrayList<TrainingModel> model = mDataManager.getTraining(sp_id,selectedDate);
if (mAdapter == null){
mAdapter = new SpTrainingAdapter(this.getContext(),R.layout.sp_training_item,model);
mListView.setAdapter(mAdapter);
}else {
mAdapter.setData(model);
mAdapter.notifyDataSetChanged();
}
}
private class StartDayViewDecorator implements DayViewDecorator {
private final HashSet<CalendarDay> dates;
private final int color;
public StartDayViewDecorator(Collection<CalendarDay> dates){
this.color = Color.GREEN;
this.dates = new HashSet<>(dates);
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return dates.contains(day);
}
@Override
public void decorate(DayViewFacade view) {
view.addSpan(new ForegroundColorSpan(ContextCompat.getColor(getActivity(),R.color.app_green_dark)));
//view.addSpan(new DotSpan(5, color));
//view.addSpan(new ForegroundColorSpan(Color.WHITE));
view.setBackgroundDrawable(ContextCompat.getDrawable(getContext(),R.drawable.custom_select_green_background));
}
}
private class LoadUseDay extends AsyncTask<Void,Void,Void> {
@Override
protected Void doInBackground(Void... voids) {
mCalendarDays = new ArrayList<>();
for (Date l : mDataManager.getTrainingDay(sp_id)) {
mCalendarDays.add(CalendarDay.from(l));
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
calendarView.addDecorator(new StartDayViewDecorator(mCalendarDays));
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.