answer
stringlengths 17
10.2M
|
|---|
package net.wolfesoftware.jax.test;
import java.io.*;
import java.util.ArrayList;
/**
* Set CLEAN to false to see the intermediate .class files generated by tests.
* Turn RUN off and CLEAN on to just clean and not run the tests.
*/
public class TestMain
{
private static final boolean RUN = true;
private static final boolean CLEAN = true;
private static final boolean VERBOSE = false;
private static ArrayList<TestCase> getTests()
{
ArrayList<TestCase> tests = new ArrayList<TestCase>();
addAll(tests, JaxcOptionsTests.getTests());
addAll(tests, CallTests.getTests());
addAll(tests, MiscTests.getTests());
return tests;
}
private static void addAll(ArrayList<TestCase> tests, TestCase[] testCases)
{
for (TestCase test : testCases)
tests.add(test);
}
public static void main(String args[])
{
ArrayList<TestCase> tests = getTests();
PrintStream verboseStream = VERBOSE ? System.out : new PrintStream(new ByteArrayOutputStream());
PrintStream stderrStream = System.err;
int failcount = 0;
if (RUN) {
for (TestCase test : tests) {
String status;
if (test.run(verboseStream, stderrStream)) {
status = "+++ PASS ";
} else {
status = " *** FAIL ";
failcount++;
}
System.out.println(status + test.getName());
}
}
if (CLEAN)
for (TestCase test : tests)
test.clean();
if (!RUN)
System.out.println("done");
else if (failcount == 0)
System.out.println("+++ ALL PASS");
else
System.out.println(" *** " + failcount + " failed out of " + tests.size());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.renderer;
import org.broad.igv.util.StringUtils;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* @author jrobinso
*/
public class GraphicUtils {
public static void drawCenteredChar(Graphics g, char[] chars, int x, int y,
int w, int h) {
// Get measures needed to center the message
FontMetrics fm = g.getFontMetrics();
// How many pixels wide is the string
int msg_width = fm.charsWidth(chars, 0, 1);
// How far above the baseline can the font go?
int ascent = fm.getMaxAscent();
// How far below the baseline?
int descent = fm.getMaxDescent();
// Use the string width to find the starting point
int msgX = x + w / 2 - msg_width / 2;
// Use the vertical height of this font to find
// the vertical starting coordinate
int msgY = y + h / 2 - descent / 2 + ascent / 2;
g.drawChars(chars, 0, 1, msgX, msgY);
}
/**
* Draw a block of text centered in or over the rectangle
*
* @param text
* @param rect
* @param g
*/
public static void drawCenteredText(String text, Rectangle rect, Graphics g) {
drawCenteredText(text, rect.x, rect.y, rect.width, rect.height, g);
}
public static void drawCenteredText(String text, int x, int y, int w, int h, Graphics g) {
drawCenteredText(text, x, y, w, h, g, null);
}
public static void drawCenteredText(String text, int x, int y, int w, int h, Graphics g, Color backgroundColor) {
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle2D textBounds = fontMetrics.getStringBounds(text, g);
int xOffset = (int) ((w - textBounds.getWidth()) / 2);
int yOffset = (int) ((h - textBounds.getHeight()) / 2);
int xs = x + xOffset;
int ys = y + h - yOffset - (int) (textBounds.getHeight() / 4);
if(backgroundColor != null){
Graphics gb = g.create();
gb.setColor(backgroundColor);
int th = (int) textBounds.getHeight();
gb.fillRect(xs, ys - 3*th/4, (int) textBounds.getWidth(), th);
}
g.drawString(text, xs, ys);
}
public static void drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify) {
drawVerticallyCenteredText(text, margin, rect, g2D, rightJustify, false);
}
/**
* Draw a block of text centered verticallyin the rectangle
*
* @param text
* @param rect
* @param g2D
*/
public static void drawVerticallyCenteredText
(String text,
int margin,
Rectangle rect,
Graphics g2D,
boolean rightJustify,
boolean clear) {
FontMetrics fontMetrics = g2D.getFontMetrics();
Rectangle2D textBounds = fontMetrics.getStringBounds(text, g2D);
int yOffset = (int) ((rect.getHeight() - textBounds.getHeight()) / 2);
int yPos = (rect.y + rect.height) - yOffset - (int) (textBounds.getHeight() / 4);
if (clear) {
int h = 2 * (int) textBounds.getHeight();
//Color c = g2D.getColor();
//Globals.isHeadless();
//g2D.setColor(Globals.VERY_LIGHT_GREY);
int y = Math.max(rect.y, yPos - h);
int h2 = Math.min(rect.height, 2 * h);
g2D.clearRect(rect.x, y, rect.width, h2);
}
if (rightJustify) {
drawRightJustifiedText(text, rect.x + rect.width - margin, yPos, g2D);
} else {
g2D.drawString(text, margin, yPos);
}
}
/**
* Draw a block of text right justified to the given location
*
* @param text
* @param right
* @param y
* @param g
*/
public static void drawRightJustifiedText(String text, int right, int y,
Graphics g) {
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle2D textBounds = fontMetrics.getStringBounds(text, g);
int x = right - (int) textBounds.getWidth();
g.drawString(text, x, y);
}
public static void drawDottedDashLine(Graphics2D g, int x1, int y1, int x2,
int y2) {
Stroke thindashed = new BasicStroke(1.0f, // line width
BasicStroke.CAP_BUTT, // cap style
BasicStroke.JOIN_BEVEL, 1.0f, // join style, miter limit
new float[]{8.0f, 3.0f, 2.0f, 3.0f}, // the dash pattern : on 8, off 3, on 2, off 3
0.0f); // the dash phase
drawDashedLine(g, thindashed, x1, y1, x2, y2);
}
public static void drawDashedLine(Graphics2D g, int x1, int y1, int x2,
int y2) {
Stroke thindashed = new BasicStroke(1.0f, // line width
BasicStroke.CAP_BUTT, // cap style
BasicStroke.JOIN_BEVEL, 1.0f, // join style, miter limit
new float[]{3.0f, 3.0f}, // the dash pattern : on 8, off 3, on 2, off 3
0.0f); // the dash phase
drawDashedLine(g, thindashed, x1, y1, x2, y2);
}
public static void drawWrappedText(String string, Rectangle rect, Graphics2D g2D, boolean clear) {
FontMetrics fontMetrics = g2D.getFontMetrics();
Rectangle2D stringBounds = fontMetrics.getStringBounds(string, g2D);
final int margin = 5;
int textHeight = (int) stringBounds.getHeight() + margin;
double textWidth = stringBounds.getWidth() + 10;
if (textWidth < rect.width) {
GraphicUtils.drawVerticallyCenteredText(string, margin, rect, g2D, false, clear);
} else {
int charWidth = (int) (stringBounds.getWidth() / string.length());
int charsPerLine = rect.width / charWidth;
int nStrings = (string.length() / charsPerLine) + 1;
if (nStrings * textHeight > rect.height) {
// Shorten string to fit in space. Try a max of 5 times, progressivley shortening string
int nChars = (rect.width - 2 * margin) / charWidth + 1;
int nTries = 0;
String shortString;
double w;
do {
shortString = StringUtils.checkLength(string, nChars);
w = fontMetrics.getStringBounds(shortString, g2D).getWidth() + 2 * margin;
nTries++;
nChars
} while (w > rect.width && nTries <= 5 && nChars > 1);
GraphicUtils.drawVerticallyCenteredText(shortString, margin, rect, g2D, false, clear);
} else {
int breakPoint = 0;
Rectangle tmp = new Rectangle(rect);
tmp.y -= ((nStrings - 1) * textHeight) / 2;
while (breakPoint < string.length()) {
int end = Math.min(string.length(), breakPoint + charsPerLine);
GraphicUtils.drawVerticallyCenteredText(string.substring(breakPoint, end), margin, tmp, g2D, false);
breakPoint += charsPerLine;
tmp.y += textHeight;
}
}
}
}
/**
* Method description
* Stroke thindashed = new BasicStroke(thickness, // line width
* BasicStroke.CAP_BUTT, // cap style
* BasicStroke.JOIN_BEVEL, 1.0f, // join style, miter limit
* dashPattern, // the dash pattern : on 8, off 3, on 2, off 3
* phase); // the dash phase
*
* @param g
*/
public static void drawDashedLine(Graphics2D g, Stroke stroke,
int x1, int y1, int x2, int y2) {
Stroke currentStroke = g.getStroke();
g.setStroke(stroke);
g.drawLine(x1, y1, x2, y2);
g.setStroke(currentStroke);
}
public static void drawHorizontalArrow(Graphics g, Rectangle r, boolean direction) {
int[] x;
int[] y;
int dy = r.height / 3;
int y0 = r.y;
int y1 = y0 + dy;
int y3 = y0 + r.height;
int y2 = y3 - dy;
int yc = (y1 + y2) / 2;
int dx = yc - y0;
if (direction) {
int x1 = r.x;
int x3 = x1 + r.width;
int x2 = x3 - dx;
x = new int[]{x1, x2, x2, x3, x2, x2, x1};
y = new int[]{y1, y1, y0, yc, y3, y2, y2};
} else {
int x1 = r.x;
int x3 = x1 + r.width;
int x2 = x1 + dx;
x = new int[]{x1, x2, x2, x3, x3, x2, x2};
y = new int[]{yc, y0, y1, y1, y2, y2, y3};
}
g.fillPolygon(x, y, x.length);
}
public static void drawCenteredText(char[] chars, int x, int y, int w, int h, Graphics2D g) {
// Get measures needed to center the message
FontMetrics fm = g.getFontMetrics();
// How many pixels wide is the string
int msg_width = fm.charsWidth(chars, 0, 1);
// How far above the baseline can the font go?
int ascent = fm.getMaxAscent();
// How far below the baseline?
int descent = fm.getMaxDescent();
// Use the string width to find the starting point
int msgX = x + w / 2 - msg_width / 2;
// Use the vertical height of this font to find
// the vertical starting coordinate
int msgY = y + h / 2 - descent / 2 + ascent / 2;
g.drawChars(chars, 0, 1, msgX, msgY);
}
}
|
package org.broad.igv.ui.panel;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.Chromosome;
import org.broad.igv.feature.FeatureDB;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.NamedFeature;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.lists.GeneList;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.MessageUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author jrobinso
* @date Sep 10, 2010
*/
public class FrameManager {
private static List<ReferenceFrame> frames = new ArrayList();
private static ReferenceFrame defaultFrame;
static {
defaultFrame = new ReferenceFrame("genome");
frames.add(defaultFrame);
}
public static ReferenceFrame getDefaultFrame() {
return defaultFrame;
}
public static List<ReferenceFrame> getFrames() {
return frames;
}
public static void setFrames(List<ReferenceFrame> f) {
frames = f;
}
public static boolean isGeneListMode() {
return frames.size() > 1;
}
public static void setToDefaultFrame(String searchString) {
frames.clear();
if (searchString != null) {
Locus locus = getLocus(searchString, 0);
if (locus != null) {
defaultFrame.setInterval(locus);
}
}
frames.add(defaultFrame);
defaultFrame.recordHistory();
}
public static void resetFrames(GeneList gl) {
frames.clear();
if (gl == null) {
frames.add(defaultFrame);
} else {
int flankingRegion = PreferenceManager.getInstance().getAsInt(PreferenceManager.FLANKING_REGION);
List<String> lociNotFound = new ArrayList();
for (String searchString : gl.getLoci()) {
Locus locus = getLocus(searchString, flankingRegion);
if (locus == null) {
lociNotFound.add(searchString);
} else {
ReferenceFrame referenceFrame = new ReferenceFrame(searchString);
referenceFrame.setInterval(locus);
frames.add(referenceFrame);
}
}
if (lociNotFound.size() > 1) {
StringBuffer message = new StringBuffer();
message.append("<html>The following loci could not be found in the currently loaded annotation sets: <br>");
for (String s : lociNotFound) {
message.append(s + " ");
}
MessageUtils.showMessage(message.toString());
}
}
}
/**
* @return The minimum scale among all active frames
* TODO -- track this with "rescale" events, rather than compute on the fly
*/
public static double getMinimumScale() {
double minScale = Double.MAX_VALUE;
for (ReferenceFrame frame : frames) {
minScale = Math.min(minScale, frame.getScale());
}
return minScale;
}
public static Locus getLocus(String name) {
int flankingRegion = PreferenceManager.getInstance().getAsInt(PreferenceManager.FLANKING_REGION);
return getLocus(name, flankingRegion);
}
public static Locus getLocus(String searchString, int flankingRegion) {
Locus locus = null;
NamedFeature feature = FeatureDB.getFeature(searchString.toUpperCase().trim());
if (feature != null) {
locus = new Locus(
feature.getChr(),
feature.getStart() - flankingRegion,
feature.getEnd() + flankingRegion);
} else {
locus = new Locus(searchString);
String chr = locus.getChr();
if (chr != null) {
return locus;
} else {
if (IGV.hasInstance()) {
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
if (genome != null) {
Chromosome chromsome = genome.getChromosome(searchString);
locus = new Locus(chromsome.getName(), 0, chromsome.getLength());
}
}
}
}
return locus;
}
public static void removeFrame(ReferenceFrame frame) {
frames.remove(frame);
}
public static void reset(String chr) {
setToDefaultFrame(null);
getDefaultFrame().setChrName(chr);
getDefaultFrame().computeMaxZoom();
getDefaultFrame().invalidateLocationScale();
}
}
|
package gui;
import gui.dialog.InputStringDialogHelper;
import gui.dialog.settings.ProjectSettingsDialog;
import model.Project;
import model.Route;
import plugin.OperationNameIcon;
import plugin.PluginClassLoader;
import plugin.editor.DiderotProjectEditor;
import plugin.exporter.DefaultDiderotDocumentationExporter;
import plugin.exporter.DefaultDiderotProjectExporter;
import plugin.exporter.DiderotProjectExporter;
import plugin.importer.DefaultDiderotProjectImporter;
import plugin.importer.DiderotProjectImporter;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.jar.JarFile;
import static model.Route.getAbsoluteNodePath;
public class MainWindow extends JFrame implements TreeSelectionListener
{
private final static String NO_ROUTE_SELECTED = "nrs";
private final static String ROUTE_SELECTED = "rs";
private Route rootRoutes;
private RoutesTreePanel routesTreePanel;
private AbstractAction addRouteAction, delRouteAction, moveRouteAction, focusOnRouteAction;
private JButton addRouteBtn = new JButton(),
delRouteBtn = new JButton(),
moveRouteBtn = new JButton(),
confBtn = new JButton();
private JTextField currentRouteLbl = new JTextField();
private JMenu methodMenu;
private JMenu importMenu;
private JMenu exportMenu;
private JMenu editMenu;
private MethodsManagementPanel methodsManagementPanel = new MethodsManagementPanel();
private JPanel routeMethodPanel;
private TreeMap<String, DiderotProjectImporter> importPlugins = new TreeMap<>();
private TreeMap<String, DiderotProjectExporter> exportPlugins = new TreeMap<>();
private TreeMap<String, DiderotProjectEditor> editPlugins = new TreeMap<>();
public MainWindow()
{
super();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
rootRoutes = new Route(Project.getActiveProject().getDomain());
buildUI();
setPreferredSize(new Dimension(900, 800));
pack();
setLocationRelativeTo(null);
loadPlugins();
DiderotProjectImporter importer = importPlugins.get(DefaultDiderotProjectImporter.class.getName());
DefaultDiderotProjectImporter defaultImporter = (DefaultDiderotProjectImporter) importer;
defaultImporter.setDiderotData(rootRoutes, Project.getActiveProject());
defaultImporter.createProject();
routesTreePanel.updateModel();
setTitle("Diderot - " + Project.getActiveProject().getName());
setIconImage(ImageIconProxy.getIcon("icon").getImage());
setVisible(true);
//getWindowListeners()[0].windowClosing(null);
}
private void createSampleRoute()
{
//rootRoutes.addRoute("index");
//rootRoutes.addRoute("index");
rootRoutes.addRoute("home");
rootRoutes.addRoute("home/page1");
/*rootRoutes.addRoute("home/page2");
rootRoutes.addRoute("data/type/subtype1");
rootRoutes.addRoute("data/type/subtype2");
rootRoutes.addRoute("bidule/truc");
rootRoutes.addRoute("data/type2");
rootRoutes.addRoute("home/page2");
rootRoutes.addRoute("home/page2");*/
Project project = Project.getActiveProject();
project.addUserRouteProperty("Controller", "myController");
project.addUserRouteProperty("View", "myView");
project.addUserRouteProperty("View template", "myViewTemplate");
project.addUserRouteProperty("test delete", "test del");
project.addUserRouteProperty("test rename", "old val");
for(String prop : project.getUserRoutesPropertiesNames())
{
rootRoutes.addUserProperty(prop, project.getUserRouteProperty(prop).getDefaultValue());
}
project.removeUserRouteProperty("test delete");
rootRoutes.removeUserProperty("test delete");
rootRoutes.changeUserPropertyValue("test rename", "old val", "new val");
rootRoutes.changeUserPropertyValue("View", "old val", "new val");
}
private void buildUI()
{
//button for route management
Box btnPanel = Box.createVerticalBox();
btnPanel.add(addRouteBtn);
btnPanel.add(moveRouteBtn);
btnPanel.add(delRouteBtn);
btnPanel.add(confBtn);
btnPanel.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
addRouteBtn.setAlignmentX(CENTER_ALIGNMENT);
delRouteBtn.setAlignmentX(CENTER_ALIGNMENT);
moveRouteBtn.setAlignmentX(CENTER_ALIGNMENT);
confBtn.setAlignmentX(CENTER_ALIGNMENT);
addRouteBtn.setMaximumSize(new Dimension(208,34));
delRouteBtn.setMaximumSize(new Dimension(208,34));
moveRouteBtn.setMaximumSize(new Dimension(208,34));
confBtn.setMaximumSize(new Dimension(208,34));
//confBtn.doClick();
/*DefaultDiderotProjectImporter defaultDiderotProjectImporter = new DefaultDiderotProjectImporter();
defaultDiderotProjectImporter.setDiderotData(rootRoutes, Project.getActiveProject());
defaultDiderotProjectImporter.importProject();*/
//System.exit(0);
//route tree
routesTreePanel = new RoutesTreePanel(rootRoutes);
//panel containing routes tree and associated buttons
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add(new JScrollPane(routesTreePanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
leftPanel.add(btnPanel, BorderLayout.SOUTH);
//full route path display
currentRouteLbl.setOpaque(true);
currentRouteLbl.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(currentRouteLbl.getBackground().darker(), 3),
BorderFactory.createEmptyBorder(2,2,2,2)));
currentRouteLbl.setBackground(currentRouteLbl.getBackground());
currentRouteLbl.setVisible(false);
currentRouteLbl.setEditable(false);
currentRouteLbl.setBackground(null);
currentRouteLbl.setBackground(null);
//display of route characteristics
CardLayout cardLayout = new CardLayout();
routeMethodPanel = new JPanel(cardLayout);
JLabel noRouteSelectedLabel = new JLabel("Select an existing route or create one.");
noRouteSelectedLabel.setHorizontalAlignment(SwingConstants.CENTER);
routeMethodPanel.add(noRouteSelectedLabel, NO_ROUTE_SELECTED);
methodsManagementPanel.setBorder(BorderFactory.createEmptyBorder(7, 2, 0, 0));
routeMethodPanel.add(methodsManagementPanel, ROUTE_SELECTED);
cardLayout.show(routeMethodPanel, NO_ROUTE_SELECTED);
//display of full route path and route characteristics
JPanel rightPanel = new JPanel(new BorderLayout());
rightPanel.add(currentRouteLbl, BorderLayout.NORTH);
rightPanel.add(routeMethodPanel, BorderLayout.CENTER);
leftPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 1));
JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, leftPanel, rightPanel);
mainPanel.setBorder(BorderFactory.createLineBorder(mainPanel.getBackground(), 5));
mainPanel.setResizeWeight(0.2);
add(mainPanel);
addListeners();
buildMenuBar();
enableButton(false);
}
private void addListeners()
{
JFrame that = this;
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
//Todo: add confirmation dialog
/*DefaultDiderotProjectExporter diderotProjectExporter = new DefaultDiderotProjectExporter();
diderotProjectExporter.setDiderotData(rootRoutes, Project.getActiveProject());
diderotProjectExporter.exportProject();
DefaultDiderotDocumentationExporter defaultDiderotDocumentationExporter = new DefaultDiderotDocumentationExporter();
defaultDiderotDocumentationExporter.setDiderotData(rootRoutes, Project.getActiveProject());
defaultDiderotDocumentationExporter.generateHtmlDocumentation();*/
that.dispose();
}
});
focusOnRouteAction = new AbstractAction("Set focus on route panel")
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
routesTreePanel.requestFocusInWindow();
}
};
addRouteAction = new AbstractAction("Add new route", ImageIconProxy.getIcon("add"))
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
actionAddRoute();
}
};
delRouteAction = new AbstractAction("Delete route", ImageIconProxy.getIcon("del"))
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
actionRemoveRoute();
}
};
moveRouteAction = new AbstractAction("Move route", ImageIconProxy.getIcon("edit"))
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
actionMoveRoute();
}
};
addRouteBtn.setAction(addRouteAction);
delRouteBtn.setAction(delRouteAction);
moveRouteBtn.setAction(moveRouteAction);
final JFrame parent = this;
confBtn.setAction(new AbstractAction("Project settings", ImageIconProxy.getIcon("conf"))
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
ProjectSettingsDialog projectSettingsDialog = new ProjectSettingsDialog(parent, rootRoutes, importPlugins, exportPlugins, editPlugins);
projectSettingsDialog.display();
TreePath selectedElement = routesTreePanel.getSelectionPath();
methodsManagementPanel.saveDisplayStatus();
routesTreePanel.updateModel();
routesTreePanel.setSelectionPath(selectedElement);
methodsManagementPanel.restoreDisplayStatus();
}
});
routesTreePanel.addTreeSelectionListener(this);
routesTreePanel.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e )
{
if(e.isPopupTrigger())
{
TreePath treePath = routesTreePanel.getPathForLocation(e.getX(), e.getY());
if(treePath != null)
{
routesTreePanel.setSelectionPath(treePath);
showRoutePopUpMenu(e.getX(), e.getY());
}
}
}
});
routesTreePanel.addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_CONTEXT_MENU)
{
TreePath treePath = routesTreePanel.getSelectionPath();
if(treePath != null)
{
Rectangle bounds = routesTreePanel.getPathBounds(treePath);
showRoutePopUpMenu(bounds.x + 30, bounds.y + bounds.height);
}
}
}
});
}
private void showRoutePopUpMenu(int x, int y)
{
JPopupMenu jPopupMenu = new JPopupMenu();
jPopupMenu.add(new JMenuItem(addRouteAction));
jPopupMenu.add(new JMenuItem(moveRouteAction));
jPopupMenu.add(new JMenuItem(delRouteAction));
jPopupMenu.show(routesTreePanel, x, y);
}
public void loadPlugins()
{
Vector<String> availableImporters = new Vector<>();
availableImporters.add(DefaultDiderotProjectImporter.class.getName());
Vector<String> availableExporters = new Vector<>();
availableExporters.add(DefaultDiderotProjectExporter.class.getName());
availableExporters.add(DefaultDiderotDocumentationExporter.class.getName());
Vector<String> availableEditors = new Vector<>();
File[] jarFiles = new File("plugins").listFiles();
if(jarFiles != null)
{
for(File file : jarFiles)
{
if(file.isDirectory())
{
continue;
}
try
{
JarFile jar = new JarFile(file);
PluginClassLoader.getInstance().addURL(file.toURI().toURL());
Enumeration jarEntries = jar.entries();
while(jarEntries.hasMoreElements())
{
String entryName = jarEntries.nextElement().toString();
if(entryName.endsWith(".class"))
{
String className = entryName.substring(0, entryName.length() - 6).replaceAll("/", ".");
Class pluginClass = Class.forName(className, true, PluginClassLoader.getInstance());
Class[] interfaces = pluginClass.getInterfaces();
for(Class implementedInterface : interfaces)
{
if(implementedInterface.equals(DiderotProjectImporter.class))
{
availableImporters.add(className);
}
else if(implementedInterface.equals(DiderotProjectExporter.class))
{
availableExporters.add(className);
}
else if(implementedInterface.equals(DiderotProjectEditor.class))
{
availableEditors.add(className);
}
}
}
}
}
catch(IOException e)
{
System.out.println("Cannot load \"" + file.getName() + "\".");
//e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
setUpImportPlugins(availableImporters);
setUpExportPlugins(availableExporters);
setUpEditPlugins(availableEditors);
}
private void setUpImportPlugins(Vector<String> availableImporters)
{
importPlugins.clear();
importMenu.removeAll();
for(String importerName : availableImporters)
{
Class importer = null;
try
{
importer = Class.forName(importerName, true, PluginClassLoader.getInstance());
DiderotProjectImporter importerInstance = (DiderotProjectImporter) importer.newInstance();
importPlugins.put(importerName, importerInstance);
JMenu actionMenu = new JMenu(importerInstance.getPluginName());
HashMap<String, OperationNameIcon> importingOperations = importerInstance.getAvailableImportingOperations();
JFrame parent = this;
for(String actionName : importingOperations.keySet())
{
final Class finalImporter = importer;
JMenuItem actionMenuItem = new JMenuItem(new AbstractAction(actionName, importingOperations.get(actionName).operationIcon)
{
@Override
public void actionPerformed(ActionEvent e)
{
if(Project.getActiveProject().isOpened() && JOptionPane.YES_OPTION !=
JOptionPane.showConfirmDialog(parent, "Project \"" + Project.getActiveProject().getName() + "\" is currently opened.\nUnsaved modifications may be lost.\nDo you want to continue?", "Project already opened", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE))
{
return;
}
importerInstance.setDiderotData(rootRoutes, Project.getActiveProject());
importerInstance.setParentFrame(parent);
try
{
Method method = finalImporter.getMethod(importerInstance.getAvailableImportingOperations().get(actionName).methodName);
method.invoke(importerInstance);
setTitle("Diderot - " + Project.getActiveProject().getName());
routesTreePanel.updateModel();
enableButton(false);
}
catch(NoSuchMethodException e1)
{
e1.printStackTrace();
}
catch(InvocationTargetException e1)
{
e1.printStackTrace();
}
catch(IllegalAccessException e1)
{
e1.printStackTrace();
}
}
});
if("plugin.importer.DefaultDiderotProjectImporter".equals(importerName))
{
if("createProject".equals(importerInstance.getAvailableImportingOperations().get(actionName).methodName))
{
actionMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));
}
else if("importProject".equals(importerInstance.getAvailableImportingOperations().get(actionName).methodName))
{
actionMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
}
}
actionMenu.add(actionMenuItem);
}
importMenu.add(actionMenu);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
continue;
}
catch(InstantiationException e)
{
e.printStackTrace();
continue;
}
catch(IllegalAccessException e)
{
e.printStackTrace();
continue;
}
}
}
private void setUpExportPlugins(Vector<String> availableExporters)
{
exportPlugins.clear();
exportMenu.removeAll();
for(String exporterName : availableExporters)
{
Class exporter = null;
try
{
exporter = Class.forName(exporterName, true, PluginClassLoader.getInstance());
DiderotProjectExporter exporterInstance = (DiderotProjectExporter) exporter.newInstance();
exportPlugins.put(exporterName, exporterInstance);
JMenu actionMenu = new JMenu(exporterInstance.getPluginName());
HashMap<String, OperationNameIcon> exportingOperations = exporterInstance.getAvailableExportingOperations();
JFrame parent = this;
for(String actionName : exportingOperations.keySet())
{
final Class finalExporter = exporter;
JMenuItem actionMenuItem = new JMenuItem(new AbstractAction(actionName, exportingOperations.get(actionName).operationIcon)
{
@Override
public void actionPerformed(ActionEvent e)
{
exporterInstance.setDiderotData(rootRoutes, Project.getActiveProject());
exporterInstance.setParentFrame(parent);
try
{
Method method = finalExporter.getMethod(exporterInstance.getAvailableExportingOperations().get(actionName).methodName);
method.invoke(exporterInstance);
}
catch(NoSuchMethodException e1)
{
e1.printStackTrace();
}
catch(InvocationTargetException e1)
{
e1.printStackTrace();
}
catch(IllegalAccessException e1)
{
e1.printStackTrace();
}
}
});
if("plugin.exporter.DefaultDiderotProjectExporter".equals(exporterName))
{
if("exportProject".equals(exporterInstance.getAvailableExportingOperations().get(actionName).methodName))
{
actionMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
}
else if("exportProjectAs".equals(exporterInstance.getAvailableExportingOperations().get(actionName).methodName))
{
actionMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK));
}
}
else if("plugin.exporter.DefaultDiderotDocumentationExporter".equals(exporterName))
{
actionMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK));
}
actionMenu.add(actionMenuItem);
}
exportMenu.add(actionMenu);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
continue;
}
catch(InstantiationException e)
{
e.printStackTrace();
continue;
}
catch(IllegalAccessException e)
{
e.printStackTrace();
continue;
}
}
}
private void setUpEditPlugins(Vector<String> availableEditors)
{
editPlugins.clear();
editMenu.removeAll();
for(String editorName : availableEditors)
{
Class editor = null;
try
{
editor = Class.forName(editorName, true, PluginClassLoader.getInstance());
DiderotProjectEditor editorInstance = (DiderotProjectEditor) editor.newInstance();
editPlugins.put(editorName, editorInstance);
JMenu actionMenu = new JMenu(editorInstance.getPluginName());
HashMap<String, OperationNameIcon> editingOperations = editorInstance.getAvailableEditingOperations();
JFrame parent = this;
for(String actionName : editingOperations.keySet())
{
final Class finalEditor = editor;
JMenuItem actionMenuItem = new JMenuItem(new AbstractAction(actionName, editingOperations.get(actionName).operationIcon)
{
@Override
public void actionPerformed(ActionEvent e)
{
editorInstance.setDiderotData(rootRoutes, Project.getActiveProject());
editorInstance.setParentFrame(parent);
try
{
Method method = finalEditor.getMethod(editorInstance.getAvailableEditingOperations().get(actionName).methodName);
method.invoke(editorInstance);
}
catch(NoSuchMethodException e1)
{
e1.printStackTrace();
}
catch(InvocationTargetException e1)
{
e1.printStackTrace();
}
catch(IllegalAccessException e1)
{
e1.printStackTrace();
}
}
});
actionMenu.add(actionMenuItem);
}
editMenu.add(actionMenu);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
continue;
}
catch(InstantiationException e)
{
e.printStackTrace();
continue;
}
catch(IllegalAccessException e)
{
e.printStackTrace();
continue;
}
}
}
private void buildMenuBar()
{
JMenuBar menuBar = new JMenuBar();
importMenu = new JMenu("Import");
importMenu.setMnemonic('I');
menuBar.add(importMenu);
exportMenu = new JMenu("Export");
exportMenu.setMnemonic('E');
menuBar.add(exportMenu);
editMenu = new JMenu("Edit");
editMenu.setMnemonic('U');
menuBar.add(editMenu);
JMenu routeMenu = new JMenu("Route");
routeMenu.setMnemonic('R');
JMenuItem addRouteMenuItem = new JMenuItem(addRouteAction);
addRouteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));
routeMenu.add(addRouteMenuItem);
JMenuItem moveRouteMenuItem = new JMenuItem(moveRouteAction);
moveRouteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_DOWN_MASK));
routeMenu.add(moveRouteMenuItem);
JMenuItem delRouteMenuItem = new JMenuItem(delRouteAction);
delRouteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK));
routeMenu.add(delRouteMenuItem);
JMenuItem focusRouteMenuItem = new JMenuItem(focusOnRouteAction);
focusRouteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK));
routeMenu.add(focusRouteMenuItem);
menuBar.add(routeMenu);
methodMenu = methodsManagementPanel.getMethodMenu();
methodMenu.setMnemonic('M');
methodMenu.setEnabled(false);
menuBar.add(methodMenu);
setJMenuBar(menuBar);
}
private void enableButton(boolean enabled)
{
moveRouteAction.setEnabled(enabled);
delRouteAction.setEnabled(enabled);
}
@Override
public void valueChanged(TreeSelectionEvent e)
{
String absPath = getAbsoluteNodePath(e.getPath(), false);
currentRouteLbl.setText(absPath);
currentRouteLbl.setVisible(true);
if(routesTreePanel.getLastSelectedPathComponent() != null)
{
Route lastRoute = rootRoutes.getLastRoute(getAbsoluteNodePath(e.getPath(), true));
methodsManagementPanel.setRoute(lastRoute);
CardLayout cl = (CardLayout) routeMethodPanel.getLayout();
cl.show(routeMethodPanel, ROUTE_SELECTED);
methodMenu.setEnabled(true);
enableButton(true);
}
else
{
CardLayout cl = (CardLayout) routeMethodPanel.getLayout();
cl.show(routeMethodPanel, NO_ROUTE_SELECTED);
methodMenu.setEnabled(false);
}
}
private void actionAddRoute()
{
String defaultRoute = "";
TreePath treePath = routesTreePanel.getSelectionPath();
if(treePath != null)
{
defaultRoute = getAbsoluteNodePath(treePath, true);
}
String routeToAdd = InputStringDialogHelper.showInputNoSpacesDialog(this,
"Enter route path:", "Add new route", JOptionPane.PLAIN_MESSAGE, defaultRoute + "/");
if(routeToAdd != null)
{
if(!rootRoutes.addRoute(routeToAdd))
{
JOptionPane.showMessageDialog(this, "This route already exists, or contains multiple occurrence of '/' without character between them.", "Cannot add route", JOptionPane.ERROR_MESSAGE);
return;
}
routesTreePanel.updateModel();
routesTreePanel.setSelectionPath(new TreePath(rootRoutes.getPathToRoute(routeToAdd)));
}
}
private void actionRemoveRoute()
{
TreePath treePath = routesTreePanel.getSelectionPath();
String routeToDelete = getAbsoluteNodePath(treePath, true);
if(routeToDelete.isEmpty())
{
JOptionPane.showMessageDialog(this, "You cannot delete project's root.", "Cannot delete project root", JOptionPane.ERROR_MESSAGE);
return;
}
if(JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(this,
"Are you sure you want to delete the following route and its sub-routes?\n" + routeToDelete,
"Delete route", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE))
{
if(!rootRoutes.deleteRoute(routeToDelete))
{
JOptionPane.showMessageDialog(this, "This route does not exists.", "Cannot delete route", JOptionPane.ERROR_MESSAGE);
return;
}
routesTreePanel.updateModel(treePath, null);
currentRouteLbl.setVisible(false);
enableButton(false);
}
}
private void actionMoveRoute()
{
TreePath treePath = routesTreePanel.getSelectionPath();
String oldRoutePath = getAbsoluteNodePath(treePath, true);
if(oldRoutePath.isEmpty())
{
JOptionPane.showMessageDialog(this, "You cannot rename project's root here, check project settings to do so.", "Cannot rename project root", JOptionPane.ERROR_MESSAGE);
return;
}
String newRoutePath = InputStringDialogHelper.showInputNoSpacesDialog(this,
"Move route:\n" + oldRoutePath + "\nto:", "Move route", JOptionPane.PLAIN_MESSAGE, oldRoutePath);
if(newRoutePath != null)
{
if(!rootRoutes.moveRoute(oldRoutePath, newRoutePath))
{
JOptionPane.showMessageDialog(this, "The destination route already exists, or contains multiple occurrence of '/' without character between them.", "Cannot move route", JOptionPane.ERROR_MESSAGE);
return;
}
TreePath tp = new TreePath(rootRoutes.getPathToRoute(newRoutePath));
routesTreePanel.updateModel(treePath, tp);
routesTreePanel.setSelectionPath(tp);
}
}
}
|
package org.exist.util.serializer;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import org.exist.dom.QName;
import org.exist.util.XMLString;
import org.exist.util.serializer.encodings.CharacterSet;
/**
* Write XML to a writer. This class defines methods similar to SAX. It deals
* with opening and closing tags, writing attributes and so on.
*
* @author wolf
*/
public class XMLWriter {
protected final static Properties defaultProperties = new Properties();
static {
defaultProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
}
protected Writer writer = null;
protected CharacterSet charSet = null;
protected boolean tagIsOpen = false;
protected boolean tagIsEmpty = true;
protected boolean declarationWritten = false;
protected boolean doctypeWritten = false;
protected Properties outputProperties;
private char[] charref = new char[10];
private static boolean[] textSpecialChars;
private static boolean[] attrSpecialChars;
static {
textSpecialChars = new boolean[128];
Arrays.fill(textSpecialChars, false);
textSpecialChars['<'] = true;
textSpecialChars['>'] = true;
// textSpecialChars['\r'] = true;
textSpecialChars['&'] = true;
attrSpecialChars = new boolean[128];
Arrays.fill(attrSpecialChars, false);
attrSpecialChars['<'] = true;
attrSpecialChars['>'] = true;
attrSpecialChars['\r'] = true;
attrSpecialChars['\n'] = true;
attrSpecialChars['\t'] = true;
attrSpecialChars['&'] = true;
attrSpecialChars['"'] = true;
}
public XMLWriter() {
}
public XMLWriter(Writer writer) {
super();
this.writer = writer;
}
/**
* Set the output properties.
*
* @param outputProperties
*/
public void setOutputProperties(Properties properties) {
if (properties == null)
outputProperties = defaultProperties;
else
outputProperties = properties;
String encoding = outputProperties.getProperty(OutputKeys.ENCODING,
"UTF-8");
charSet = CharacterSet.getCharacterSet(encoding);
}
/**
* Set a new writer. Calling this method will reset the state of the object.
*
* @param writer
*/
public void setWriter(Writer writer) {
this.writer = writer;
tagIsOpen = false;
tagIsEmpty = true;
declarationWritten = false;
}
public void startDocument() throws TransformerException {
tagIsOpen = false;
tagIsEmpty = true;
declarationWritten = false;
doctypeWritten = false;
}
public void endDocument() throws TransformerException {
}
public void startElement(String qname) throws TransformerException {
if (!declarationWritten)
writeDeclaration();
if (!doctypeWritten)
writeDoctype(qname.toString());
try {
if (tagIsOpen)
closeStartTag(false);
writer.write('<');
writer.write(qname);
tagIsOpen = true;
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void startElement(QName qname) throws TransformerException {
if (!declarationWritten)
writeDeclaration();
if (!doctypeWritten)
writeDoctype(qname.toString());
try {
if (tagIsOpen)
closeStartTag(false);
writer.write('<');
if (qname.getPrefix() != null && qname.getPrefix().length() > 0) {
writer.write(qname.getPrefix());
writer.write(':');
}
writer.write(qname.getLocalName());
tagIsOpen = true;
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void endElement(String qname) throws TransformerException {
try {
if (tagIsOpen)
closeStartTag(true);
else {
writer.write("</");
writer.write(qname);
writer.write('>');
}
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void endElement(QName qname) throws TransformerException {
try {
if (tagIsOpen)
closeStartTag(true);
else {
writer.write("</");
if (qname.getPrefix() != null && qname.getPrefix().length() > 0) {
writer.write(qname.getPrefix());
writer.write(':');
}
writer.write(qname.getLocalName());
writer.write('>');
}
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void namespace(String prefix, String nsURI)
throws TransformerException {
if ((nsURI == null || nsURI.length() == 0)
&& (prefix == null || prefix.length() == 0))
return;
try {
if (!tagIsOpen)
throw new TransformerException(
"Found a namespace declaration outside an element");
writer.write(' ');
writer.write("xmlns");
if (prefix != null && prefix.length() > 0) {
writer.write(':');
writer.write(prefix);
}
writer.write("=\"");
writeChars(nsURI, true);
writer.write('"');
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void attribute(String qname, String value)
throws TransformerException {
try {
if (!tagIsOpen) {
characters(value);
return;
// throw new TransformerException("Found an attribute outside an
// element");
}
writer.write(' ');
writer.write(qname);
writer.write("=\"");
writeChars(value, true);
writer.write('"');
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void attribute(QName qname, String value)
throws TransformerException {
try {
if (!tagIsOpen) {
characters(value);
return;
// throw new TransformerException("Found an attribute outside an
// element");
}
writer.write(' ');
if (qname.getPrefix() != null && qname.getPrefix().length() > 0) {
writer.write(qname.getPrefix());
writer.write(':');
}
writer.write(qname.getLocalName());
writer.write("=\"");
writeChars(value, true);
writer.write('"');
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void characters(CharSequence chars) throws TransformerException {
if (!declarationWritten)
writeDeclaration();
try {
if (tagIsOpen)
closeStartTag(false);
writeChars(chars, false);
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void characters(char[] ch, int start, int len)
throws TransformerException {
if (!declarationWritten)
writeDeclaration();
XMLString s = new XMLString(ch, start, len);
characters(s);
s.release();
}
public void processingInstruction(String target, String data)
throws TransformerException {
if (!declarationWritten)
writeDeclaration();
try {
if (tagIsOpen)
closeStartTag(false);
writer.write("<?");
writer.write(target);
if (data != null && data.length() > 0) {
writer.write(' ');
writeChars(data, false);
}
writer.write("?>");
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void comment(CharSequence data) throws TransformerException {
if (!declarationWritten)
writeDeclaration();
try {
if (tagIsOpen)
closeStartTag(false);
writer.write("<!
writeChars(data, false);
writer.write("
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void cdataSection(char[] ch, int start, int len)
throws TransformerException {
if (tagIsOpen)
closeStartTag(false);
try {
writer.write("<![CDATA[");
writer.write(ch, start, len);
writer.write("]]>");
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
public void documentType(String name, String publicId, String systemId)
throws TransformerException {
if (!declarationWritten)
writeDeclaration();
if (publicId == null && systemId == null)
return;
try {
writer.write("<!DOCTYPE ");
writer.write(name);
if (publicId != null) {
writer.write(" PUBLIC \"" + publicId + "\"");
}
if (systemId != null) {
if (publicId == null)
writer.write(" SYSTEM");
writer.write(" \"" + systemId + "\"");
}
writer.write(">");
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
doctypeWritten = true;
}
protected void closeStartTag(boolean isEmpty) throws TransformerException {
try {
if (tagIsOpen) {
if (isEmpty)
writer.write("/>");
else
writer.write('>');
tagIsOpen = false;
}
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
protected void writeDeclaration() throws TransformerException {
if (declarationWritten)
return;
if (outputProperties == null)
outputProperties = defaultProperties;
declarationWritten = true;
String omitXmlDecl = outputProperties.getProperty(
OutputKeys.OMIT_XML_DECLARATION, "yes");
if (omitXmlDecl.equals("no")) {
String version = outputProperties.getProperty(OutputKeys.VERSION, "1.0");
String standalone = outputProperties.getProperty(OutputKeys.STANDALONE);
String encoding = outputProperties.getProperty(OutputKeys.ENCODING,
"UTF-8");
try {
writer.write("<?xml version=\"");
writer.write(version);
writer.write("\" encoding=\"");
writer.write(encoding);
writer.write('"');
if (standalone != null) {
writer.write(" standalone=\"");
writer.write(standalone);
writer.write('"');
}
writer.write("?>\n");
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
}
}
protected void writeDoctype(String rootElement) throws TransformerException {
if (doctypeWritten)
return;
String publicId = outputProperties.getProperty(OutputKeys.DOCTYPE_PUBLIC);
String systemId = outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM);
if (publicId != null || systemId != null)
documentType(rootElement, publicId, systemId);
doctypeWritten = true;
}
private final void writeChars(CharSequence s, boolean inAttribute)
throws IOException {
boolean[] specialChars = inAttribute ? attrSpecialChars
: textSpecialChars;
char ch = 0;
final int len = s.length();
int pos = 0, i;
while (pos < len) {
i = pos;
while (i < len) {
ch = s.charAt(i);
if (ch < 128) {
if (specialChars[ch])
break;
else
i++;
} else if (!charSet.inCharacterSet(ch) || ch == 160)
break;
else
i++;
}
writeCharSeq(s, pos, i);
// writer.write(s.subSequence(pos, i).toString());
if (i >= len)
return;
switch (ch) {
case '<':
writer.write("<");
break;
case '>':
writer.write(">");
break;
case '&':
writer.write("&");
break;
case '\r':
writer.write("&
break;
case '\n':
writer.write("&
break;
case '\t':
writer.write("&
break;
case '"':
writer.write("&
break;
// non-breaking space:
case 160:
writer.write(" ");
break;
default:
writeCharacterReference(ch);
}
pos = ++i;
}
}
private void writeCharSeq(CharSequence ch, int start, int end)
throws IOException {
for (int i = start; i < end; i++) {
writer.write(ch.charAt(i));
}
}
protected void writeCharacterReference(char charval) throws IOException {
int o = 0;
charref[o++] = '&';
charref[o++] = '
charref[o++] = 'x';
String code = Integer.toHexString(charval);
int len = code.length();
for (int k = 0; k < len; k++) {
charref[o++] = code.charAt(k);
}
charref[o++] = ';';
writer.write(charref, 0, o);
}
}
|
package org.exist.xquery.test;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.exist.storage.DBBroker;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
public class DeepEqualTest extends TestCase {
private final static String URI = "xmldb:exist://" + DBBroker.ROOT_COLLECTION;
private final static String DRIVER = "org.exist.xmldb.DatabaseImpl";
private XPathQueryService query;
private Collection c;
public static void main(String[] args) {
TestRunner.run(DeepEqualTest.class);
}
public DeepEqualTest(String name) {
super(name);
}
public void testAtomic1() {
assertQuery(true, "deep-equal('hello', 'hello')");
}
public void testAtomic2() {
assertQuery(false, "deep-equal('hello', 'goodbye')");
}
public void testAtomic3() {
assertQuery(true, "deep-equal(42, 42)");
}
public void testAtomic4() {
assertQuery(false, "deep-equal(42, 17)");
}
public void testAtomic5() {
assertQuery(false, "deep-equal(42, 'hello')");
}
public void testAtomic6() {
assertQuery(true, "deep-equal( 1. , xs:integer(1) )" );
assertQuery(true, "deep-equal( xs:double(1) , xs:integer(1) )" );
}
public void testEmptySeq() {
assertQuery(true, "deep-equal((), ())");
}
public void testDiffLengthSeq1() {
assertQuery(false, "deep-equal((), 42)");
}
public void testDiffLengthSeq2() {
assertQuery(false, "deep-equal((), (42, 'hello'))");
}
public void testDiffKindNodes1() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(false, "deep-equal(/test, /test/@key)");
}
public void testDiffKindNodes2() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(false, "deep-equal(/test, /test/text())");
}
public void testDiffKindNodes3() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(false, "deep-equal(/test/@key, /test/text())");
}
public void testSameNode1() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(true, "deep-equal(/test, /test)");
}
public void testSameNode2() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(true, "deep-equal(/test/@key, /test/@key)");
}
public void testSameNode3() {
createDocument("test", "<test key='value'>hello</test>");
assertQuery(true, "deep-equal(/test/text(), /test/text())");
}
public void testDocuments1() {
createDocument("test1", "<test key='value'>hello</test>");
createDocument("test2", "<test key='value'>hello</test>");
assertQuery(true, "deep-equal(document('test1'), document('test2'))");
}
public void testDocuments2() {
createDocument("test1", "<test key='value'>hello</test>");
createDocument("test2", "<notatest/>");
assertQuery(false, "deep-equal(document('test1'), document('test2'))");
}
public void testText1() {
createDocument("test", "<test><g1><a>1</a><b>2</b></g1><g2><c>1</c><d>2</d></g2></test>");
assertQuery(true, "deep-equal(//a/text(), //c/text())");
}
public void testText2() {
createDocument("test", "<test><g1><a>1</a><b>2</b></g1><g2><c>1</c><d>2</d></g2></test>");
assertQuery(false, "deep-equal(//a/text(), //b/text())");
}
public void testText3() {
createDocument("test", "<test><g1><a>1</a><b>2</b></g1><g2><c>1</c><d>2</d></g2></test>");
assertQuery(true, "deep-equal(//g1/text(), //g2/text())");
}
public void testText4() {
createDocument("test", "<test><a>12</a><b>1<!--blah-->2</b></test>");
assertQuery(false, "deep-equal(//a/text(), //b/text())");
}
public void testAttributes1() {
createDocument("test", "<test><e1 a='1'/><e2 a='1' b='2' c='1'/><e3 a='2'/></test>");
assertQuery(true, "deep-equal(//e1/@a, //e2/@a)");
}
public void testAttributes2() {
createDocument("test", "<test><e1 a='1'/><e2 a='1' b='2' c='1'/><e3 a='2'/></test>");
assertQuery(false, "deep-equal(//e1/@a, //e2/@b)");
}
public void testAttributes3() {
createDocument("test", "<test><e1 a='1'/><e2 a='1' b='2' c='1'/><e3 a='2'/></test>");
assertQuery(false, "deep-equal(//e1/@a, //e2/@c)");
}
public void testAttributes4() {
createDocument("test", "<test><e1 a='1'/><e2 a='1' b='2' c='1'/><e3 a='2'/></test>");
assertQuery(false, "deep-equal(//e1/@a, //e3/@a)");
}
public void testNSAttributes1() {
createDocument("test", "<test xmlns:n='urn:blah' xmlns:p='urn:foo' xmlns:q='urn:blah'><e1 n:a='1'/><e2 n:a='1' p:a='1' p:b='1'/><e3 n:a='2'/><e4 q:a='1'/></test>");
assertQuery(true, "declare namespace n = 'urn:blah'; declare namespace p = 'urn:foo'; declare namespace q = 'urn:blah'; deep-equal(//e1/@n:a, //e2/@n:a)");
}
public void testNSAttributes2() {
createDocument("test", "<test xmlns:n='urn:blah' xmlns:p='urn:foo' xmlns:q='urn:blah'><e1 n:a='1'/><e2 n:a='1' p:a='1' p:b='1'/><e3 n:a='2'/><e4 q:a='1'/></test>");
assertQuery(true, "declare namespace n = 'urn:blah'; declare namespace p = 'urn:foo'; declare namespace q = 'urn:blah'; deep-equal(//e1/@q:a, //e4/@n:a)");
}
public void testNSAttributes3() {
createDocument("test", "<test xmlns:n='urn:blah' xmlns:p='urn:foo' xmlns:q='urn:blah'><e1 n:a='1'/><e2 n:a='1' p:a='1' p:b='1'/><e3 n:a='2'/><e4 q:a='1'/></test>");
assertQuery(false, "declare namespace n = 'urn:blah'; declare namespace p = 'urn:foo'; declare namespace q = 'urn:blah'; deep-equal(//e1/@n:a, //e2/@p:a)");
}
public void testNSAttributes4() {
createDocument("test", "<test xmlns:n='urn:blah' xmlns:p='urn:foo' xmlns:q='urn:blah'><e1 n:a='1'/><e2 n:a='1' p:a='1' p:b='1'/><e3 n:a='2'/><e4 q:a='1'/></test>");
assertQuery(false, "declare namespace n = 'urn:blah'; declare namespace p = 'urn:foo'; declare namespace q = 'urn:blah'; deep-equal(//e1/@n:a, //e2/@p:b)");
}
public void testNSAttributes5() {
createDocument("test", "<test xmlns:n='urn:blah' xmlns:p='urn:foo' xmlns:q='urn:blah'><e1 n:a='1'/><e2 n:a='1' p:a='1' p:b='1'/><e3 n:a='2'/><e4 q:a='1'/></test>");
assertQuery(false, "declare namespace n = 'urn:blah'; declare namespace p = 'urn:foo'; declare namespace q = 'urn:blah'; deep-equal(//e1/@n:a, //e3/@n:a)");
}
public void testElements1() {
createDocument("test", "<test><a/><a/></test>");
|
package org.jgroups.protocols.pbcast;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.annotations.GuardedBy;
import org.jgroups.stack.*;
import org.jgroups.util.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically increasing sequence number (seqno).
* Receivers deliver messages ordered according to seqno and request retransmission of missing messages.<br/>
* Retransmit requests are usually sent to the original sender of a message, but this can be changed by
* xmit_from_random_member (send to random member) or use_mcast_xmit_req (send to everyone). Responses can also be sent
* to everyone instead of the requester by setting use_mcast_xmit to true.
*
* @author Bela Ban
* @version $Id: NAKACK.java,v 1.176 2008/02/27 16:20:13 belaban Exp $
*/
public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener {
private long[] retransmit_timeouts={600, 1200, 2400, 4800}; // time(s) to wait before requesting retransmission
private boolean is_server=false;
private Address local_addr=null;
private final List<Address> members=new CopyOnWriteArrayList<Address>();
private View view;
@GuardedBy("seqno_lock")
private long seqno=0; // current message sequence number (starts with 1)
private final Lock seqno_lock=new ReentrantLock();
private int gc_lag=20; // number of msgs garbage collection lags behind
private Map<Thread,ReentrantLock> locks;
private static final long INITIAL_SEQNO=0;
/**
* Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers lost a
* message, the sender only retransmits once.
*/
private boolean use_mcast_xmit=true;
/** Use a multicast to request retransmission of missing messages. This may be costly as every member in the cluster
* will send a response
*/
private boolean use_mcast_xmit_req=false;
/**
* Ask a random member for retransmission of a missing message. If set to true, discard_delivered_msgs will be
* set to false
*/
private boolean xmit_from_random_member=false;
/** The first value (in milliseconds) to use in the exponential backoff retransmission mechanism. Only enabled
* if the value is > 0
*/
private long exponential_backoff=0;
/** If enabled, we use statistics gathered from actual retransmission times to compute the new retransmission times */
private boolean use_stats_for_retransmission=false;
/**
* Messages that have been received in order are sent up the stack (= delivered to the application). Delivered
* messages are removed from NakReceiverWindow.xmit_table and moved to NakReceiverWindow.delivered_msgs, where
* they are later garbage collected (by STABLE). Since we do retransmits only from sent messages, never
* received or delivered messages, we can turn the moving to delivered_msgs off, so we don't keep the message
* around, and don't need to wait for garbage collection to remove them.
*/
private boolean discard_delivered_msgs=false;
private boolean eager_lock_release=true;
/** If value is > 0, the retransmit buffer is bounded: only the max_xmit_buf_size latest messages are kept,
* older ones are discarded when the buffer size is exceeded. A value <= 0 means unbounded buffers
*/
private int max_xmit_buf_size=0;
/** Map to store sent and received messages (keyed by sender) */
private final ConcurrentMap<Address,NakReceiverWindow> xmit_table=new ConcurrentHashMap<Address,NakReceiverWindow>(11);
/** Map which keeps track of threads removing messages from NakReceiverWindows, so we don't wait while a thread
* is removing messages */
// private final ConcurrentMap<Address,AtomicBoolean> in_progress=new ConcurrentHashMap<Address,AtomicBoolean>();
private boolean leaving=false;
private boolean started=false;
private TimeScheduler timer=null;
private static final String name="NAKACK";
private long xmit_reqs_received;
private long xmit_reqs_sent;
private long xmit_rsps_received;
private long xmit_rsps_sent;
private long missing_msgs_received;
/** Captures stats on XMIT_REQS, XMIT_RSPS per sender */
private HashMap<Address,StatsEntry> sent=new HashMap<Address,StatsEntry>();
/** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */
private HashMap<Address,StatsEntry> received=new HashMap<Address,StatsEntry>();
private int stats_list_size=20;
/** BoundedList<MissingMessage>. Keeps track of the last stats_list_size XMIT requests */
private BoundedList<MissingMessage> receive_history;
/** BoundedList<XmitRequest>. Keeps track of the last stats_list_size missing messages received */
private BoundedList<XmitRequest> send_history;
/** Per-sender map of seqnos and timestamps, to keep track of avg times for retransmission of messages */
private final ConcurrentMap<Address,ConcurrentMap<Long,Long>> xmit_stats=new ConcurrentHashMap<Address,ConcurrentMap<Long,Long>>();
private int xmit_history_max_size=50;
/** Maintains a list of the last N retransmission times (duration it took to retransmit a message) for all members */
private final ConcurrentMap<Address,BoundedList<Long>> xmit_times_history=new ConcurrentHashMap<Address,BoundedList<Long>>();
/** Maintains a smoothed average of the retransmission times per sender, these are the actual values that are used for
* new retransmission requests */
private final Map<Address,Double> smoothed_avg_xmit_times=new HashMap<Address,Double>();
/** the weight with which we take the previous smoothed average into account, WEIGHT should be >0 and <= 1 */
private static final double WEIGHT=0.9;
private static final double INITIAL_SMOOTHED_AVG=30.0;
// private final ConcurrentMap<Address,LossRate> loss_rates=new ConcurrentHashMap<Address,LossRate>();
/**
* Maintains retransmission related data across a time. Only used if enable_xmit_time_stats is set to true.
* At program termination, accumulated data is dumped to a file named by the address of the member. Careful,
* don't enable this in production as the data in this hashmap are never reaped ! Really only meant for
* diagnostics !
*/
private ConcurrentMap<Long,XmitTimeStat> xmit_time_stats=null;
private long xmit_time_stats_start;
/** Keeps track of OOB messages sent by myself, needed by {@link #handleMessage(org.jgroups.Message, NakAckHeader)} */
private final Set<Long> oob_loopback_msgs=Collections.synchronizedSet(new HashSet<Long>());
private final Lock rebroadcast_lock=new ReentrantLock();
private final Condition rebroadcast_done=rebroadcast_lock.newCondition();
// set during processing of a rebroadcast event
private volatile boolean rebroadcasting=false;
private final Lock rebroadcast_digest_lock=new ReentrantLock();
@GuardedBy("rebroadcast_digest_lock")
private Digest rebroadcast_digest=null;
private long max_rebroadcast_timeout=2000;
private static final int NUM_REBROADCAST_MSGS=3;
/** BoundedList<Digest>, keeps the last 10 stability messages */
private final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10);
/** When not finding a message on an XMIT request, include the last N stability messages in the error message */
protected boolean print_stability_history_on_failed_xmit=false;
public NAKACK() {
}
public String getName() {
return name;
}
public long getXmitRequestsReceived() {return xmit_reqs_received;}
public long getXmitRequestsSent() {return xmit_reqs_sent;}
public long getXmitResponsesReceived() {return xmit_rsps_received;}
public long getXmitResponsesSent() {return xmit_rsps_sent;}
public long getMissingMessagesReceived() {return missing_msgs_received;}
public int getPendingRetransmissionRequests() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.getPendingXmits();
}
return num;
}
public int getXmitTableSize() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.size();
}
return num;
}
public int getReceivedTableSize() {
return getPendingRetransmissionRequests();
}
public void resetStats() {
xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0;
sent.clear();
received.clear();
if(receive_history !=null)
receive_history.clear();
if(send_history != null)
send_history.clear();
}
public void init() throws Exception {
if(stats) {
send_history=new BoundedList<XmitRequest>(stats_list_size);
receive_history=new BoundedList<MissingMessage>(stats_list_size);
}
}
public int getGcLag() {
return gc_lag;
}
public void setGcLag(int gc_lag) {
this.gc_lag=gc_lag;
}
public boolean isUseMcastXmit() {
return use_mcast_xmit;
}
public void setUseMcastXmit(boolean use_mcast_xmit) {
this.use_mcast_xmit=use_mcast_xmit;
}
public boolean isXmitFromRandomMember() {
return xmit_from_random_member;
}
public void setXmitFromRandomMember(boolean xmit_from_random_member) {
this.xmit_from_random_member=xmit_from_random_member;
}
public boolean isDiscardDeliveredMsgs() {
return discard_delivered_msgs;
}
public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) {
boolean old=this.discard_delivered_msgs;
this.discard_delivered_msgs=discard_delivered_msgs;
if(old != this.discard_delivered_msgs) {
for(NakReceiverWindow win: xmit_table.values()) {
win.setDiscardDeliveredMessages(this.discard_delivered_msgs);
}
}
}
public int getMaxXmitBufSize() {
return max_xmit_buf_size;
}
public void setMaxXmitBufSize(int max_xmit_buf_size) {
this.max_xmit_buf_size=max_xmit_buf_size;
}
/**
*
* @return
* @deprecated removed in 2.6
*/
public long getMaxXmitSize() {
return -1;
}
/**
*
* @param max_xmit_size
* @deprecated removed in 2.6
*/
public void setMaxXmitSize(long max_xmit_size) {
}
public boolean setProperties(Properties props) {
String str;
long[] tmp;
super.setProperties(props);
str=props.getProperty("retransmit_timeout");
if(str != null) {
tmp=Util.parseCommaDelimitedLongs(str);
props.remove("retransmit_timeout");
if(tmp != null && tmp.length > 0) {
retransmit_timeouts=tmp;
}
}
str=props.getProperty("gc_lag");
if(str != null) {
gc_lag=Integer.parseInt(str);
if(gc_lag < 0) {
log.error("gc_lag cannot be negative, setting it to 0");
}
props.remove("gc_lag");
}
str=props.getProperty("max_xmit_size");
if(str != null) {
if(log.isWarnEnabled())
log.warn("max_xmit_size was deprecated in 2.6 and will be ignored");
props.remove("max_xmit_size");
}
str=props.getProperty("use_mcast_xmit");
if(str != null) {
use_mcast_xmit=Boolean.valueOf(str).booleanValue();
props.remove("use_mcast_xmit");
}
str=props.getProperty("use_mcast_xmit_req");
if(str != null) {
use_mcast_xmit_req=Boolean.valueOf(str).booleanValue();
props.remove("use_mcast_xmit_req");
}
str=props.getProperty("exponential_backoff");
if(str != null) {
exponential_backoff=Long.parseLong(str);
props.remove("exponential_backoff");
}
str=props.getProperty("use_stats_for_retransmission");
if(str != null) {
use_stats_for_retransmission=Boolean.valueOf(str);
props.remove("use_stats_for_retransmission");
}
str=props.getProperty("discard_delivered_msgs");
if(str != null) {
discard_delivered_msgs=Boolean.valueOf(str);
props.remove("discard_delivered_msgs");
}
str=props.getProperty("xmit_from_random_member");
if(str != null) {
xmit_from_random_member=Boolean.valueOf(str);
props.remove("xmit_from_random_member");
}
str=props.getProperty("max_xmit_buf_size");
if(str != null) {
max_xmit_buf_size=Integer.parseInt(str);
props.remove("max_xmit_buf_size");
}
str=props.getProperty("stats_list_size");
if(str != null) {
stats_list_size=Integer.parseInt(str);
props.remove("stats_list_size");
}
str=props.getProperty("xmit_history_max_size");
if(str != null) {
xmit_history_max_size=Integer.parseInt(str);
props.remove("xmit_history_max_size");
}
str=props.getProperty("enable_xmit_time_stats");
if(str != null) {
boolean enable_xmit_time_stats=Boolean.valueOf(str);
props.remove("enable_xmit_time_stats");
if(enable_xmit_time_stats) {
if(log.isWarnEnabled())
log.warn("enable_xmit_time_stats is experimental, and may be removed in any release");
xmit_time_stats=new ConcurrentHashMap<Long,XmitTimeStat>();
xmit_time_stats_start=System.currentTimeMillis();
}
}
str=props.getProperty("max_rebroadcast_timeout");
if(str != null) {
max_rebroadcast_timeout=Long.parseLong(str);
props.remove("max_rebroadcast_timeout");
}
str=props.getProperty("eager_lock_release");
if(str != null) {
eager_lock_release=Boolean.valueOf(str).booleanValue();
props.remove("eager_lock_release");
}
if(xmit_from_random_member) {
if(discard_delivered_msgs) {
discard_delivered_msgs=false;
log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false");
}
}
str=props.getProperty("print_stability_history_on_failed_xmit");
if(str != null) {
print_stability_history_on_failed_xmit=Boolean.valueOf(str).booleanValue();
props.remove("print_stability_history_on_failed_xmit");
}
if(!props.isEmpty()) {
log.error("these properties are not recognized: " + props);
return false;
}
return true;
}
public Map<String,Object> dumpStats() {
Map<String,Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String,Object>();
retval.put("xmit_reqs_received", new Long(xmit_reqs_received));
retval.put("xmit_reqs_sent", new Long(xmit_reqs_sent));
retval.put("xmit_rsps_received", new Long(xmit_rsps_received));
retval.put("xmit_rsps_sent", new Long(xmit_rsps_sent));
retval.put("missing_msgs_received", new Long(missing_msgs_received));
retval.put("msgs", printMessages());
return retval;
}
public String printStats() {
Map.Entry entry;
Object key, val;
StringBuilder sb=new StringBuilder();
sb.append("sent:\n");
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
if(key == null) key="<mcast dest>";
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nreceived:\n");
for(Iterator it=received.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nXMIT_REQS sent:\n");
for(XmitRequest tmp: send_history) {
sb.append(tmp).append("\n");
}
sb.append("\nMissing messages received\n");
for(MissingMessage missing: receive_history) {
sb.append(missing).append("\n");
}
sb.append("\nStability messages received\n");
sb.append(printStabilityMessages()).append("\n");
return sb.toString();
}
public String printStabilityMessages() {
StringBuilder sb=new StringBuilder();
sb.append(Util.printListWithDelimiter(stability_msgs, "\n"));
return sb.toString();
}
public String printStabilityHistory() {
StringBuilder sb=new StringBuilder();
int i=1;
for(Digest digest: stability_msgs) {
sb.append(i++).append(": ").append(digest).append("\n");
}
return sb.toString();
}
public String printLossRates() {
StringBuilder sb=new StringBuilder();
NakReceiverWindow win;
for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) {
win=entry.getValue();
sb.append(entry.getKey()).append(": ").append(win.printLossRate()).append("\n");
}
return sb.toString();
}
public double getAverageLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getLossRate();
count++;
}
return retval / (double)count;
}
public double getAverageSmoothedLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getSmoothedLossRate();
count++;
}
return retval / (double)count;
}
public Vector<Integer> providedUpServices() {
Vector<Integer> retval=new Vector<Integer>(5);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.MERGE_DIGEST));
return retval;
}
public void start() throws Exception {
timer=stack != null ? stack.timer : null;
if(timer == null)
throw new Exception("timer is null");
locks=stack.getLocks();
started=true;
if(xmit_time_stats != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
String filename="xmit-stats-" + local_addr + ".log";
System.out.println("-- dumping runtime xmit stats to " + filename);
try {
dumpXmitStats(filename);
}
catch(IOException e) {
e.printStackTrace();
}
}
});
}
}
public void stop() {
started=false;
reset(); // clears sent_msgs and destroys all NakReceiverWindows
oob_loopback_msgs.clear();
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this
* method as the event is passed down by default by the superclass after this method returns !</b>
*/
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) {
break; // unicast address: not null and not mcast, pass down unchanged
}
send(evt, msg);
return null; // don't pass down the stack
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass down further (Bela Aug 7 2001)
case Event.GET_DIGEST:
return getDigest();
case Event.SET_DIGEST:
setDigest((Digest)evt.getArg());
return null;
case Event.MERGE_DIGEST:
mergeDigest((Digest)evt.getArg());
return null;
case Event.TMP_VIEW:
View tmp_view=(View)evt.getArg();
Vector<Address> mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
// adjustReceivers(false);
break;
case Event.VIEW_CHANGE:
tmp_view=(View)evt.getArg();
mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
adjustReceivers(members);
is_server=true; // check vids from now on
Set<Address> tmp=new LinkedHashSet<Address>(members);
tmp.add(null); // for null destination (= mcast)
sent.keySet().retainAll(tmp);
received.keySet().retainAll(tmp);
view=tmp_view;
xmit_stats.keySet().retainAll(tmp);
// in_progress.keySet().retainAll(mbrs); // remove elements which are not in the membership
break;
case Event.BECOME_SERVER:
is_server=true;
break;
case Event.DISCONNECT:
leaving=true;
reset();
break;
case Event.REBROADCAST:
rebroadcasting=true;
rebroadcast_digest=(Digest)evt.getArg();
try {
rebroadcastMessages();
}
finally {
rebroadcasting=false;
rebroadcast_digest_lock.lock();
try {
rebroadcast_digest=null;
}
finally {
rebroadcast_digest_lock.unlock();
}
}
return null;
}
return down_prot.down(evt);
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this
* method as the event is passed up by default by the superclass after this method returns !</b>
*/
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
NakAckHeader hdr=(NakAckHeader)msg.getHeader(name);
if(hdr == null)
break; // pass up (e.g. unicast msg)
// discard messages while not yet server (i.e., until JOIN has returned)
if(!is_server) {
if(log.isTraceEnabled())
log.trace("message was discarded (not yet server)");
return null;
}
// Changed by bela Jan 29 2003: we must not remove the header, otherwise
// further xmit requests will fail !
//hdr=(NakAckHeader)msg.removeHeader(getName());
switch(hdr.type) {
case NakAckHeader.MSG:
handleMessage(msg, hdr);
return null; // transmitter passes message up for us !
case NakAckHeader.XMIT_REQ:
if(hdr.range == null) {
if(log.isErrorEnabled()) {
log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc());
}
return null;
}
handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender);
return null;
case NakAckHeader.XMIT_RSP:
if(log.isTraceEnabled())
log.trace("received missing message " + msg.getSrc() + ":" + hdr.seqno);
handleXmitRsp(msg);
return null;
default:
if(log.isErrorEnabled()) {
log.error("NakAck header type " + hdr.type + " not known !");
}
return null;
}
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass up further (Bela Aug 7 2001)
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
case Event.SUSPECT:
// release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new
// flush round anyway
if(rebroadcasting) {
cancelRebroadcasting();
}
break;
}
return up_prot.up(evt);
}
private void send(Event evt, Message msg) {
if(msg == null)
throw new NullPointerException("msg is null; event is " + evt);
if(!started) {
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] discarded message as start() has not been called, message: " + msg);
return;
}
long msg_id;
NakReceiverWindow win=xmit_table.get(local_addr);
msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr
seqno_lock.lock();
try {
try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic
msg_id=seqno +1;
msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id));
win.add(msg_id, msg);
seqno=msg_id;
}
catch(Throwable t) {
throw new RuntimeException("failure adding msg " + msg + " to the retransmit table for " + local_addr, t);
}
}
finally {
seqno_lock.unlock();
}
try {
if(msg.isFlagSet(Message.OOB))
oob_loopback_msgs.add(msg_id);
if(log.isTraceEnabled())
log.trace("sending " + local_addr + "#" + msg_id);
down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted
}
catch(Throwable t) { // eat the exception, don't pass it up the stack
if(log.isWarnEnabled()) {
log.warn("failure passing message down", t);
}
}
}
/**
* Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many
* messages as possible from the NRW and passes them up the stack. Discards messages from non-members.
*/
private void handleMessage(Message msg, NakAckHeader hdr) {
Address sender=msg.getSrc();
if(sender == null) {
if(log.isErrorEnabled())
log.error("sender of message is null");
return;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder().append('[').append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno));
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) { // discard message if there is no entry for sender
if(leaving)
return;
if(log.isWarnEnabled())
log.warn(local_addr + "] discarded message from non-member " + sender + ", my view is " + view);
return;
}
boolean loopback=local_addr.equals(sender);
boolean added=loopback || win.add(hdr.seqno, msg);
// message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering !
if(msg.isFlagSet(Message.OOB) && added) {
if(!loopback || oob_loopback_msgs.remove(hdr.seqno)) {
up_prot.up(new Event(Event.MSG, msg));
}
}
//AtomicBoolean busy=in_progress.get(sender);
//if(busy == null) {
// in_progress.putIfAbsent(sender, busy=new AtomicBoolean(false));
// check whether a thread is already active for the same sender, if so, terminate. This prevents lots of
// threads blocking on the same lock and then - when that lock is released - from terminating anyway, because
// if(busy.compareAndSet(false, true)) {
// try {
// where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time
// We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in
// delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered in the
// order in which they were sent by the sender
Message msg_to_deliver;
ReentrantLock lock=win.getLock();
lock.lock();
try {
if(eager_lock_release)
locks.put(Thread.currentThread(), lock);
while((msg_to_deliver=win.remove()) != null) {
if(msg_to_deliver.isFlagSet(Message.OOB)) {
continue;
}
// Changed by bela Jan 29 2003: not needed (see above)
//msg_to_deliver.removeHeader(getName());
up_prot.up(new Event(Event.MSG, msg_to_deliver));
}
}
finally {
if(eager_lock_release)
locks.remove(Thread.currentThread());
if(lock.isHeldByCurrentThread())
lock.unlock();
}
}
/**
* Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester,
* called when XMIT_REQ is received.
* @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address
* @param first_seqno The first sequence number to be retransmitted (<= last_seqno)
* @param last_seqno The last sequence number to be retransmitted (>= first_seqno)
* @param original_sender The member who originally sent the messsage. Guaranteed to be non-null
*/
private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) {
Message msg;
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for ");
sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]");
log.trace(sb.toString());
}
if(first_seqno > last_seqno) {
if(log.isErrorEnabled())
log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit");
return;
}
if(stats) {
xmit_reqs_received+=last_seqno - first_seqno +1;
updateStats(received, xmit_requester, 1, 0, 0);
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
xmit_time_stats.putIfAbsent(key, stat);
}
stat.xmit_reqs_received.addAndGet((int)(last_seqno - first_seqno +1));
stat.xmit_rsps_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
NakReceiverWindow win=xmit_table.get(original_sender);
if(win == null) {
if(log.isErrorEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") ").append(original_sender).append(" not found in retransmission table: ").append(printMessages());
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.error(sb);
}
return;
}
for(long i=first_seqno; i <= last_seqno; i++) {
msg=win.get(i);
if(msg == null || msg == NakReceiverWindow.NULL_MSG) {
if(log.isWarnEnabled() && !local_addr.equals(xmit_requester)) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") message ").append(original_sender).append("::").append(i);
sb.append(" not found in retransmission table of ").append(original_sender).append(": ").append(win);
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.warn(sb);
}
continue;
}
sendXmitRsp(xmit_requester, msg, i);
}
}
private void cancelRebroadcasting() {
rebroadcast_lock.lock();
try {
rebroadcasting=false;
rebroadcast_done.signalAll();
}
finally {
rebroadcast_lock.unlock();
}
}
private static void updateStats(HashMap<Address,StatsEntry> map, Address key, int req, int rsp, int missing) {
StatsEntry entry=map.get(key);
if(entry == null) {
entry=new StatsEntry();
map.put(key, entry);
}
entry.xmit_reqs+=req;
entry.xmit_rsps+=rsp;
entry.missing_msgs_rcvd+=missing;
}
/**
* Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need
* to preserve the original message's properties, such as src, headers etc.
* @param dest
* @param msg
* @param seqno
*/
private void sendXmitRsp(Address dest, Message msg, long seqno) {
Buffer buf;
if(msg == null) {
if(log.isErrorEnabled())
log.error("message is null, cannot send retransmission");
return;
}
if(use_mcast_xmit)
dest=null;
if(stats) {
xmit_rsps_sent++;
updateStats(sent, dest, 0, 1, 0);
}
if(msg.getSrc() == null)
msg.setSrc(local_addr);
try {
buf=Util.messageToByteBuffer(msg);
Message xmit_msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength());
// changed Bela Jan 4 2007: we should not use OOB for retransmitted messages, otherwise we tax the OOB thread pool
// too much
// msg.setFlag(Message.OOB);
xmit_msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, seqno));
down_prot.down(new Event(Event.MSG, xmit_msg));
}
catch(IOException ex) {
log.error("failed marshalling xmit list", ex);
}
}
private void handleXmitRsp(Message msg) {
if(msg == null) {
if(log.isWarnEnabled())
log.warn("message is null");
return;
}
try {
Message wrapped_msg=Util.byteBufferToMessage(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
xmit_time_stats.putIfAbsent(key, stat);
}
stat.xmit_rsps_received.incrementAndGet();
}
if(stats) {
xmit_rsps_received++;
updateStats(received, msg.getSrc(), 0, 1, 0);
}
up(new Event(Event.MSG, wrapped_msg));
if(rebroadcasting) {
Digest tmp=getDigest();
boolean cancel_rebroadcasting;
rebroadcast_digest_lock.lock();
try {
cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest);
}
finally {
rebroadcast_digest_lock.unlock();
}
if(cancel_rebroadcasting) {
cancelRebroadcasting();
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) {
log.error("failed reading retransmitted message", ex);
}
}
}
/**
* Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages,
* then send retransmit messages for the missing messages. Return when all missing messages have been received. If
* we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set.
*/
private void rebroadcastMessages() {
Digest my_digest;
Map<Address,Digest.Entry> their_digest;
Address sender;
Digest.Entry their_entry, my_entry;
long their_high, my_high;
long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS;
long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis();
while(wait_time > 0) {
rebroadcast_digest_lock.lock();
try {
if(rebroadcast_digest == null)
break;
their_digest=rebroadcast_digest.getSenders();
}
finally {
rebroadcast_digest_lock.unlock();
}
my_digest=getDigest();
boolean xmitted=false;
for(Map.Entry<Address,Digest.Entry> entry: their_digest.entrySet()) {
sender=entry.getKey();
their_entry=entry.getValue();
my_entry=my_digest.get(sender);
if(my_entry == null)
continue;
their_high=their_entry.getHighest();
my_high=my_entry.getHighest();
if(their_high > my_high) {
if(log.isTraceEnabled())
log.trace("sending XMIT request to " + sender + " for messages " + my_high + " - " + their_high);
retransmit(my_high, their_high, sender, true); // use multicast to send retransmit request
xmitted=true;
}
}
if(!xmitted)
return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest
rebroadcast_lock.lock();
try {
try {
my_digest=getDigest();
rebroadcast_digest_lock.lock();
try {
if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest))
return;
}
finally {
rebroadcast_digest_lock.unlock();
}
rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS);
wait_time-=(System.currentTimeMillis() - start);
}
catch(InterruptedException e) {
}
}
finally {
rebroadcast_lock.unlock();
}
}
}
/**
* Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all
* entries from xmit_table that are not in <code>members</code>. This method is not called concurrently
* multiple times
*/
private void adjustReceivers(List<Address> new_members) {
NakReceiverWindow win;
// 1. Remove all senders in xmit_table that are not members anymore
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address sender=it.next();
if(!new_members.contains(sender)) {
if(local_addr != null && local_addr.equals(sender)) {
if(log.isErrorEnabled())
log.error("will not remove myself (" + sender + ") from xmit_table, received incorrect new membership of " + new_members);
continue;
}
win=xmit_table.get(sender);
win.reset();
if(log.isDebugEnabled()) {
log.debug("removing " + sender + " from xmit_table (not member anymore)");
}
it.remove();
}
}
// 2. Add newly joined members to xmit_table (starting seqno=0)
for(Address sender: new_members) {
if(!xmit_table.containsKey(sender)) {
win=createNakReceiverWindow(sender, INITIAL_SEQNO, 0);
xmit_table.put(sender, win);
}
}
}
/**
* Returns a message digest: for each member P the lowest, highest delivered and highest received seqno is added
*/
private Digest getDigest() {
Digest.Entry entry;
Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(members.size());
for(Address sender: members) {
entry=getEntry(sender);
if(entry == null) {
if(log.isErrorEnabled()) {
log.error("range is null");
}
continue;
}
map.put(sender, entry);
}
return new Digest(map);
}
/**
* Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists,
* reset it.
*/
private void setDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
if(local_addr != null && digest.contains(local_addr)) {
clear();
}
else {
// remove all but local_addr (if not null)
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address key=it.next();
if(local_addr != null && local_addr.equals(key)) {
;
}
else {
it.remove();
}
}
}
Address sender;
Digest.Entry val;
long initial_seqno;
NakReceiverWindow win;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
initial_seqno=val.getHighestDeliveredSeqno();
win=createNakReceiverWindow(sender, initial_seqno, val.getLow());
xmit_table.put(sender, win);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private void mergeDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
StringBuilder sb=null;
if(log.isDebugEnabled()) {
sb=new StringBuilder();
sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest);
}
Address sender;
Digest.Entry val;
NakReceiverWindow win;
long highest_delivered_seqno, low_seqno;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
highest_delivered_seqno=val.getHighestDeliveredSeqno();
low_seqno=val.getLow();
// except for myself
win=xmit_table.get(sender);
if(win != null) {
if(local_addr != null && local_addr.equals(sender)) {
continue;
}
else {
win.reset(); // stops retransmission
win.remove();
}
}
win=createNakReceiverWindow(sender, highest_delivered_seqno, low_seqno);
xmit_table.put(sender, win);
}
if(log.isDebugEnabled() && sb != null) {
sb.append("\n").append("resulting digest: " + getDigest());
log.debug(sb);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno, long lowest_seqno) {
NakReceiverWindow win=new NakReceiverWindow(local_addr, sender, this, initial_seqno, lowest_seqno, timer);
if(use_stats_for_retransmission) {
win.setRetransmitTimeouts(new ActualInterval(sender));
}
else if(exponential_backoff > 0) {
win.setRetransmitTimeouts(new ExponentialInterval(exponential_backoff));
}
else {
win.setRetransmitTimeouts(new StaticInterval(retransmit_timeouts));
}
win.setDiscardDeliveredMessages(discard_delivered_msgs);
win.setMaxXmitBufSize(this.max_xmit_buf_size);
if(stats)
win.setListener(this);
return win;
}
private void dumpXmitStats(String filename) throws IOException {
Writer out=new FileWriter(filename);
try {
TreeMap<Long,XmitTimeStat> map=new TreeMap<Long,XmitTimeStat>(xmit_time_stats);
StringBuilder sb;
XmitTimeStat stat;
out.write("time (secs) gaps-detected xmit-reqs-sent xmit-reqs-received xmit-rsps-sent xmit-rsps-received missing-msgs-received\n\n");
for(Map.Entry<Long,XmitTimeStat> entry: map.entrySet()) {
sb=new StringBuilder();
stat=entry.getValue();
sb.append(entry.getKey()).append(" ");
sb.append(stat.gaps_detected).append(" ");
sb.append(stat.xmit_reqs_sent).append(" ");
sb.append(stat.xmit_reqs_received).append(" ");
sb.append(stat.xmit_rsps_sent).append(" ");
sb.append(stat.xmit_rsps_received).append(" ");
sb.append(stat.missing_msgs_received).append("\n");
out.write(sb.toString());
}
}
finally {
out.close();
}
}
private Digest.Entry getEntry(Address sender) {
if(sender == null) {
if(log.isErrorEnabled()) {
log.error("sender is null");
}
return null;
}
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) {
if(log.isErrorEnabled()) {
log.error("sender " + sender + " not found in xmit_table");
}
return null;
}
long low=win.getLowestSeen(),
highest_delivered=win.getHighestDelivered(),
highest_received=win.getHighestReceived();
return new Digest.Entry(low, highest_delivered, highest_received);
}
/**
* Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest
* which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table:
* for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the
* NakReceiverWindow corresponding to P which are <= seqno at digest[P].
*/
private void stable(Digest digest) {
NakReceiverWindow recv_win;
long my_highest_rcvd; // highest seqno received in my digest for a sender P
long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P
if(members == null || local_addr == null || digest == null) {
if(log.isWarnEnabled())
log.warn("members, local_addr or digest are null !");
return;
}
if(log.isTraceEnabled()) {
log.trace("received stable digest " + digest);
}
stability_msgs.add(digest);
Address sender;
Digest.Entry val;
long high_seqno_delivered, high_seqno_received;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
if(sender == null)
continue;
val=entry.getValue();
high_seqno_delivered=val.getHighestDeliveredSeqno();
high_seqno_received=val.getHighestReceivedSeqno();
// check whether the last seqno received for a sender P in the stability vector is > last seqno
// received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic
// in DESIGN)
recv_win=xmit_table.get(sender);
if(recv_win != null) {
my_highest_rcvd=recv_win.getHighestReceived();
stability_highest_rcvd=high_seqno_received;
if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) {
if(log.isTraceEnabled()) {
log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" +
stability_highest_rcvd + "): requesting retransmission of " +
sender + '#' + stability_highest_rcvd);
}
retransmit(stability_highest_rcvd, stability_highest_rcvd, sender);
}
}
high_seqno_delivered-=gc_lag;
if(high_seqno_delivered < 0) {
continue;
}
if(log.isTraceEnabled())
log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender);
// delete *delivered* msgs that are stable
if(recv_win != null) {
recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno
}
}
}
/**
* Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected.
*/
public void retransmit(long first_seqno, long last_seqno, Address sender) {
retransmit(first_seqno, last_seqno, sender, false);
}
protected void retransmit(long first_seqno, long last_seqno, Address sender, boolean multicast_xmit_request) {
NakAckHeader hdr;
Message retransmit_msg;
Address dest=sender; // to whom do we send the XMIT request ?
if(multicast_xmit_request || this.use_mcast_xmit_req) {
dest=null;
}
else {
if(xmit_from_random_member && !local_addr.equals(sender)) {
Address random_member=(Address)Util.pickRandomElement(members);
if(random_member != null && !local_addr.equals(random_member)) {
dest=random_member;
if(log.isTraceEnabled())
log.trace("picked random member " + dest + " to send XMIT request to");
}
}
}
hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender);
retransmit_msg=new Message(dest, null, null);
retransmit_msg.setFlag(Message.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest);
retransmit_msg.putHeader(name, hdr);
ConcurrentMap<Long,Long> tmp=xmit_stats.get(sender);
if(tmp == null) {
tmp=new ConcurrentHashMap<Long,Long>();
xmit_stats.putIfAbsent(sender, tmp);
}
for(long seq=first_seqno; seq < last_seqno; seq++) {
tmp.putIfAbsent(seq, System.currentTimeMillis());
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
xmit_time_stats.putIfAbsent(key, stat);
}
stat.xmit_reqs_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
down_prot.down(new Event(Event.MSG, retransmit_msg));
if(stats) {
xmit_reqs_sent+=last_seqno - first_seqno +1;
updateStats(sent, dest, 1, 0, 0);
XmitRequest req=new XmitRequest(sender, first_seqno, last_seqno, dest);
send_history.add(req);
}
}
public void missingMessageReceived(long seqno, Address original_sender) {
ConcurrentMap<Long,Long> tmp=xmit_stats.get(original_sender);
if(tmp != null) {
Long timestamp=tmp.remove(seqno);
if(timestamp != null) {
long diff=System.currentTimeMillis() - timestamp;
BoundedList<Long> list=xmit_times_history.get(original_sender);
if(list == null) {
list=new BoundedList<Long>(xmit_history_max_size);
xmit_times_history.putIfAbsent(original_sender, list);
}
list.add(diff);
// compute the smoothed average for retransmission times for original_sender
synchronized(smoothed_avg_xmit_times) {
Double smoothed_avg=smoothed_avg_xmit_times.get(original_sender);
if(smoothed_avg == null)
smoothed_avg=INITIAL_SMOOTHED_AVG;
// the smoothed avg takes 90% of the previous value, 100% of the new value and averages them
// then, we add 10% to be on the safe side (an xmit value should rather err on the higher than lower side)
smoothed_avg=((smoothed_avg * WEIGHT) + diff) / 2;
smoothed_avg=smoothed_avg * (2 - WEIGHT);
smoothed_avg_xmit_times.put(original_sender, smoothed_avg);
}
}
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
xmit_time_stats.putIfAbsent(key, stat);
}
stat.missing_msgs_received.incrementAndGet();
}
if(stats) {
missing_msgs_received++;
updateStats(received, original_sender, 0, 0, 1);
MissingMessage missing=new MissingMessage(original_sender, seqno);
receive_history.add(missing);
}
}
/** Called when a message gap is detected */
public void messageGapDetected(long from, long to, Address src) {
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
xmit_time_stats.putIfAbsent(key, stat);
}
stat.gaps_detected.addAndGet((int)(to - from +1));
}
}
private void clear() {
// changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between
// a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might
// fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection)
// sent_msgs.clear();
for(NakReceiverWindow win: xmit_table.values()) {
win.reset();
}
xmit_table.clear();
}
private void reset() {
seqno_lock.lock();
try {
seqno=0;
}
finally {
seqno_lock.unlock();
}
for(NakReceiverWindow win: xmit_table.values()) {
win.destroy();
}
xmit_table.clear();
}
public String printMessages() {
StringBuilder ret=new StringBuilder();
Map.Entry<Address,NakReceiverWindow> entry;
Address addr;
Object w;
for(Iterator<Map.Entry<Address,NakReceiverWindow>> it=xmit_table.entrySet().iterator(); it.hasNext();) {
entry=it.next();
addr=entry.getKey();
w=entry.getValue();
ret.append(addr).append(": ").append(w.toString()).append('\n');
}
return ret.toString();
}
public String printRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
long tmp=0;
int i=0;
for(Long val: list) {
tmp+=val;
i++;
}
double avg=i > 0? tmp / i: -1;
sb.append(sender).append(": ").append(avg).append("\n");
}
return sb.toString();
}
public String printSmoothedRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,Double> entry: smoothed_avg_xmit_times.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
public String printRetransmissionTimes() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
sb.append(sender).append(": ").append(list).append("\n");
}
return sb.toString();
}
public double getTotalAverageRetransmissionTime() {
long total=0;
int i=0;
for(BoundedList<Long> list: xmit_times_history.values()) {
for(Long val: list) {
total+=val;
i++;
}
}
return i > 0? total / i: -1;
}
public double getTotalAverageSmoothedRetransmissionTime() {
double total=0.0;
int cnt=0;
synchronized(smoothed_avg_xmit_times) {
for(Double val: smoothed_avg_xmit_times.values()) {
if(val != null) {
total+=val;
cnt++;
}
}
}
return cnt > 0? total / cnt : -1;
}
/** Returns the smoothed average retransmission time for a given sender */
public double getSmoothedAverageRetransmissionTime(Address sender) {
synchronized(smoothed_avg_xmit_times) {
Double retval=smoothed_avg_xmit_times.get(sender);
if(retval == null) {
retval=INITIAL_SMOOTHED_AVG;
smoothed_avg_xmit_times.put(sender, retval);
}
return retval;
}
}
// public static final class LossRate {
// private final Set<Long> received=new HashSet<Long>();
// private final Set<Long> missing=new HashSet<Long>();
// private double smoothed_loss_rate=0.0;
// public synchronized void addReceived(long seqno) {
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addReceived(Long ... seqnos) {
// for(int i=0; i < seqnos.length; i++) {
// Long seqno=seqnos[i];
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addMissing(long from, long to) {
// for(long i=from; i <= to; i++) {
// if(!received.contains(i))
// missing.add(i);
// setSmoothedLossRate();
// public synchronized double computeLossRate() {
// int num_missing=missing.size();
// if(num_missing == 0)
// return 0.0;
// int num_received=received.size();
// int total=num_missing + num_received;
// return num_missing / (double)total;
// public synchronized double getSmoothedLossRate() {
// return smoothed_loss_rate;
// public synchronized String toString() {
// StringBuilder sb=new StringBuilder();
// int num_missing=missing.size();
// int num_received=received.size();
// int total=num_missing + num_received;
// sb.append("total=").append(total).append(" (received=").append(received.size()).append(", missing=")
// .append(missing.size()).append(", loss rate=").append(computeLossRate())
// .append(", smoothed loss rate=").append(smoothed_loss_rate).append(")");
// return sb.toString();
// /** Set the new smoothed_loss_rate value to 70% of the new value and 30% of the old value */
// private void setSmoothedLossRate() {
// double new_loss_rate=computeLossRate();
// if(smoothed_loss_rate == 0) {
// smoothed_loss_rate=new_loss_rate;
// else {
// smoothed_loss_rate=smoothed_loss_rate * .3 + new_loss_rate * .7;
private static class XmitTimeStat {
final AtomicInteger gaps_detected=new AtomicInteger(0);
final AtomicInteger xmit_reqs_sent=new AtomicInteger(0);
final AtomicInteger xmit_reqs_received=new AtomicInteger(0);
final AtomicInteger xmit_rsps_sent=new AtomicInteger(0);
final AtomicInteger xmit_rsps_received=new AtomicInteger(0);
final AtomicInteger missing_msgs_received=new AtomicInteger(0);
}
private class ActualInterval implements Interval {
private final Address sender;
public ActualInterval(Address sender) {
this.sender=sender;
}
public long next() {
return (long)getSmoothedAverageRetransmissionTime(sender);
}
public Interval copy() {
return this;
}
}
static class StatsEntry {
long xmit_reqs, xmit_rsps, missing_msgs_rcvd;
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps");
sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs");
return sb.toString();
}
}
static class XmitRequest {
Address original_sender; // original sender of message
long low, high, timestamp=System.currentTimeMillis();
Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender
XmitRequest(Address original_sender, long low, long high, Address xmit_dest) {
this.original_sender=original_sender;
this.xmit_dest=xmit_dest;
this.low=low;
this.high=high;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #[").append(low);
sb.append("-").append(high).append("]");
sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")");
return sb.toString();
}
}
static class MissingMessage {
Address original_sender;
long seq, timestamp=System.currentTimeMillis();
MissingMessage(Address original_sender, long seqno) {
this.original_sender=original_sender;
this.seq=seqno;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq);
return sb.toString();
}
}
}
|
package org.jgroups.protocols.pbcast;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.stack.NakReceiverWindow;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.Retransmitter;
import org.jgroups.util.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically increasing sequence number (seqno).
* Receivers deliver messages ordered according to seqno and request retransmission of missing messages. Retransmitted
* messages are bundled into bigger ones, e.g. when getting an xmit request for messages 1-10, instead of sending 10
* unicast messages, we bundle all 10 messages into 1 and send it. However, since this protocol typically sits below
* FRAG, we cannot count on FRAG to fragement/defragment the (possibly) large message into smaller ones. Therefore we
* only bundle messages up to max_xmit_size bytes to prevent too large messages. For example, if the bundled message
* size was a total of 34000 bytes, and max_xmit_size=16000, we'd send 3 messages: 2 16K and a 2K message. <em>Note that
* max_xmit_size should be the same value as FRAG.frag_size (or smaller).</em><br/> Retransmit requests are always sent
* to the sender. If the sender dies, and not everyone has received its messages, they will be lost. In the future, this
* may be changed to have receivers store all messages, so that retransmit requests can be answered by any member.
* Trivial to implement, but not done yet. For most apps, the default retransmit properties are sufficient, if not use
* vsync.
*
* @author Bela Ban
* @version $Id: NAKACK.java,v 1.121 2007/04/02 13:39:32 belaban Exp $
*/
public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener {
private long[] retransmit_timeout={600, 1200, 2400, 4800}; // time(s) to wait before requesting retransmission
private boolean is_server=false;
private Address local_addr=null;
private final List<Address> members=new CopyOnWriteArrayList<Address>();
private View view;
private long seqno=-1; // current message sequence number (starts with 0)
private long max_xmit_size=8192; // max size of a retransmit message (otherwise send multiple)
private int gc_lag=20; // number of msgs garbage collection lags behind
/**
* Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers lost a
* message, the sender only retransmits once.
*/
private boolean use_mcast_xmit=true;
/**
* Ask a random member for retransmission of a missing message. If set to true, discard_delivered_msgs will be
* set to false
*/
private boolean xmit_from_random_member=false;
/**
* Messages that have been received in order are sent up the stack (= delivered to the application). Delivered
* messages are removed from NakReceiverWindow.received_msgs and moved to NakReceiverWindow.delivered_msgs, where
* they are later garbage collected (by STABLE). Since we do retransmits only from sent messages, never
* received or delivered messages, we can turn the moving to delivered_msgs off, so we don't keep the message
* around, and don't need to wait for garbage collection to remove them.
*/
private boolean discard_delivered_msgs=false;
/** If value is > 0, the retransmit buffer is bounded: only the max_xmit_buf_size latest messages are kept,
* older ones are discarded when the buffer size is exceeded. A value <= 0 means unbounded buffers
*/
private int max_xmit_buf_size=0;
/**
* Hashtable<Address,NakReceiverWindow>. Stores received messages (keyed by sender). Note that this is no long term
* storage; messages are just stored until they can be delivered (ie., until the correct FIFO order is established)
*/
private final ConcurrentMap<Address,NakReceiverWindow> received_msgs=new ConcurrentHashMap<Address,NakReceiverWindow>(11);
/** TreeMap<Long,Message>. Map of messages sent by me (keyed and sorted on sequence number) */
private final TreeMap<Long,Message> sent_msgs=new TreeMap<Long,Message>();
private boolean leaving=false;
private boolean started=false;
private TimeScheduler timer=null;
private static final String name="NAKACK";
private long xmit_reqs_received;
private long xmit_reqs_sent;
private long xmit_rsps_received;
private long xmit_rsps_sent;
private long missing_msgs_received;
/** Captures stats on XMIT_REQS, XMIT_RSPS per sender */
private HashMap<Address,StatsEntry> sent=new HashMap<Address,StatsEntry>();
/** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */
private HashMap<Address,StatsEntry> received=new HashMap<Address,StatsEntry>();
private int stats_list_size=20;
/** BoundedList<XmitRequest>. Keeps track of the last stats_list_size XMIT requests */
private BoundedList receive_history;
/** BoundedList<MissingMessage>. Keeps track of the last stats_list_size missing messages received */
private BoundedList send_history;
private final Lock rebroadcast_lock=new ReentrantLock();
private final Condition rebroadcast_done=rebroadcast_lock.newCondition();
// set during processing of a rebroadcast event
private volatile boolean rebroadcasting=false;
private Digest rebroadcast_digest=null;
private long max_rebroadcast_timeout=2000;
private static final int NUM_REBROADCAST_MSGS=3;
/** BoundedList<Digest>, keeps the last 10 stability messages */
private final BoundedList stability_msgs=new BoundedList(10);
/** When not finding a message on an XMIT request, include the last N stability messages in the error message */
protected boolean print_stability_history_on_failed_xmit=false;
public NAKACK() {
}
public String getName() {
return name;
}
public long getXmitRequestsReceived() {return xmit_reqs_received;}
public long getXmitRequestsSent() {return xmit_reqs_sent;}
public long getXmitResponsesReceived() {return xmit_rsps_received;}
public long getXmitResponsesSent() {return xmit_rsps_sent;}
public long getMissingMessagesReceived() {return missing_msgs_received;}
public int getPendingRetransmissionRequests() {
int num=0;
for(NakReceiverWindow win: received_msgs.values()) {
num+=win.size();
}
return num;
}
public int getSentTableSize() {
int size;
synchronized(sent_msgs) {
size=sent_msgs.size();
}
return size;
}
public int getReceivedTableSize() {
return getPendingRetransmissionRequests();
}
public void resetStats() {
xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0;
sent.clear();
received.clear();
if(receive_history !=null)
receive_history.removeAll();
if(send_history != null)
send_history.removeAll();
}
public void init() throws Exception {
if(stats) {
send_history=new BoundedList(stats_list_size);
receive_history=new BoundedList(stats_list_size);
}
}
public int getGcLag() {
return gc_lag;
}
public void setGcLag(int gc_lag) {
this.gc_lag=gc_lag;
}
public boolean isUseMcastXmit() {
return use_mcast_xmit;
}
public void setUseMcastXmit(boolean use_mcast_xmit) {
this.use_mcast_xmit=use_mcast_xmit;
}
public boolean isXmitFromRandomMember() {
return xmit_from_random_member;
}
public void setXmitFromRandomMember(boolean xmit_from_random_member) {
this.xmit_from_random_member=xmit_from_random_member;
}
public boolean isDiscardDeliveredMsgs() {
return discard_delivered_msgs;
}
public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) {
this.discard_delivered_msgs=discard_delivered_msgs;
}
public int getMaxXmitBufSize() {
return max_xmit_buf_size;
}
public void setMaxXmitBufSize(int max_xmit_buf_size) {
this.max_xmit_buf_size=max_xmit_buf_size;
}
public long getMaxXmitSize() {
return max_xmit_size;
}
public void setMaxXmitSize(long max_xmit_size) {
this.max_xmit_size=max_xmit_size;
}
public boolean setProperties(Properties props) {
String str;
long[] tmp;
super.setProperties(props);
str=props.getProperty("retransmit_timeout");
if(str != null) {
tmp=Util.parseCommaDelimitedLongs(str);
props.remove("retransmit_timeout");
if(tmp != null && tmp.length > 0) {
retransmit_timeout=tmp;
}
}
str=props.getProperty("gc_lag");
if(str != null) {
gc_lag=Integer.parseInt(str);
if(gc_lag < 0) {
log.error("NAKACK.setProperties(): gc_lag cannot be negative, setting it to 0");
}
props.remove("gc_lag");
}
str=props.getProperty("max_xmit_size");
if(str != null) {
max_xmit_size=Long.parseLong(str);
props.remove("max_xmit_size");
}
str=props.getProperty("use_mcast_xmit");
if(str != null) {
use_mcast_xmit=Boolean.valueOf(str).booleanValue();
props.remove("use_mcast_xmit");
}
str=props.getProperty("discard_delivered_msgs");
if(str != null) {
discard_delivered_msgs=Boolean.valueOf(str).booleanValue();
props.remove("discard_delivered_msgs");
}
str=props.getProperty("xmit_from_random_member");
if(str != null) {
xmit_from_random_member=Boolean.valueOf(str).booleanValue();
props.remove("xmit_from_random_member");
}
str=props.getProperty("max_xmit_buf_size");
if(str != null) {
max_xmit_buf_size=Integer.parseInt(str);
props.remove("max_xmit_buf_size");
}
str=props.getProperty("stats_list_size");
if(str != null) {
stats_list_size=Integer.parseInt(str);
props.remove("stats_list_size");
}
str=props.getProperty("max_rebroadcast_timeout");
if(str != null) {
max_rebroadcast_timeout=Long.parseLong(str);
props.remove("max_rebroadcast_timeout");
}
if(xmit_from_random_member) {
if(discard_delivered_msgs) {
discard_delivered_msgs=false;
log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false");
}
}
str=props.getProperty("print_stability_history_on_failed_xmit");
if(str != null) {
print_stability_history_on_failed_xmit=Boolean.valueOf(str).booleanValue();
props.remove("print_stability_history_on_failed_xmit");
}
if(!props.isEmpty()) {
log.error("these properties are not recognized: " + props);
return false;
}
return true;
}
public Map<String,Object> dumpStats() {
Map<String,Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String,Object>();
retval.put("xmit_reqs_received", new Long(xmit_reqs_received));
retval.put("xmit_reqs_sent", new Long(xmit_reqs_sent));
retval.put("xmit_rsps_received", new Long(xmit_rsps_received));
retval.put("xmit_rsps_sent", new Long(xmit_rsps_sent));
retval.put("missing_msgs_received", new Long(missing_msgs_received));
retval.put("sent_msgs", printSentMsgs());
StringBuilder sb=new StringBuilder();
Address addr;
Object w;
for(Map.Entry<Address,NakReceiverWindow> entry: received_msgs.entrySet()) {
addr=entry.getKey();
w=entry.getValue();
sb.append(addr).append(": ").append(w.toString()).append('\n');
}
retval.put("received_msgs", sb.toString());
return retval;
}
public String printStats() {
Map.Entry entry;
Object key, val;
StringBuilder sb=new StringBuilder();
sb.append("sent:\n");
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
if(key == null) key="<mcast dest>";
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nreceived:\n");
for(Iterator it=received.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nXMIT_REQS sent:\n");
XmitRequest tmp;
for(Enumeration en=send_history.elements(); en.hasMoreElements();) {
tmp=(XmitRequest)en.nextElement();
sb.append(tmp).append("\n");
}
sb.append("\nMissing messages received\n");
MissingMessage missing;
for(Enumeration en=receive_history.elements(); en.hasMoreElements();) {
missing=(MissingMessage)en.nextElement();
sb.append(missing).append("\n");
}
sb.append("\nStability messages received\n");
sb.append(printStabilityMessages()).append("\n");
return sb.toString();
}
public String printStabilityMessages() {
StringBuilder sb=new StringBuilder();
sb.append(stability_msgs.toStringWithDelimiter("\n"));
return sb.toString();
}
public String printStabilityHistory() {
StringBuilder sb=new StringBuilder();
int i=1;
Digest digest;
for(Enumeration en=stability_msgs.elements(); en.hasMoreElements();) {
digest=(Digest)en.nextElement();
sb.append(i).append(": ").append(digest).append("\n");
}
return sb.toString();
}
public Vector<Integer> providedUpServices() {
Vector<Integer> retval=new Vector<Integer>(5);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.GET_DIGEST_STABLE));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.MERGE_DIGEST));
return retval;
}
public void start() throws Exception {
timer=stack != null ? stack.timer : null;
if(timer == null)
throw new Exception("timer is null");
started=true;
}
public void stop() {
started=false;
reset(); // clears sent_msgs and destroys all NakReceiverWindows
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this
* method as the event is passed down by default by the superclass after this method returns !</b>
*/
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) {
break; // unicast address: not null and not mcast, pass down unchanged
}
send(evt, msg);
return null; // don't pass down the stack
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass down further (Bela Aug 7 2001)
case Event.GET_DIGEST:
return getDigest();
case Event.GET_DIGEST_STABLE:
return getDigestHighestDeliveredMsgs();
case Event.SET_DIGEST:
setDigest((Digest)evt.getArg());
return null;
case Event.MERGE_DIGEST:
mergeDigest((Digest)evt.getArg());
return null;
case Event.CONFIG:
Object retval=down_prot.down(evt);
if(log.isDebugEnabled())
log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return retval;
case Event.TMP_VIEW:
View tmp_view=(View)evt.getArg();
Vector<Address> mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
adjustReceivers(false);
break;
case Event.VIEW_CHANGE:
tmp_view=(View)evt.getArg();
mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
adjustReceivers(true);
is_server=true; // check vids from now on
Set<Address> tmp=new LinkedHashSet<Address>(members);
tmp.add(null); // for null destination (= mcast)
sent.keySet().retainAll(tmp);
received.keySet().retainAll(tmp);
view=tmp_view;
break;
case Event.BECOME_SERVER:
is_server=true;
break;
case Event.DISCONNECT:
leaving=true;
reset();
break;
case Event.REBROADCAST:
rebroadcasting=true;
rebroadcast_digest=(Digest)evt.getArg();
try {
rebroadcastMessages();
}
finally {
rebroadcasting=false;
rebroadcast_digest=null;
}
return null;
}
return down_prot.down(evt);
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this
* method as the event is passed up by default by the superclass after this method returns !</b>
*/
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
NakAckHeader hdr=(NakAckHeader)msg.getHeader(name);
if(hdr == null)
break; // pass up (e.g. unicast msg)
// discard messages while not yet server (i.e., until JOIN has returned)
if(!is_server) {
if(trace)
log.trace("message was discarded (not yet server)");
return null;
}
// Changed by bela Jan 29 2003: we must not remove the header, otherwise
// further xmit requests will fail !
//hdr=(NakAckHeader)msg.removeHeader(getName());
switch(hdr.type) {
case NakAckHeader.MSG:
handleMessage(msg, hdr);
return null; // transmitter passes message up for us !
case NakAckHeader.XMIT_REQ:
if(hdr.range == null) {
if(log.isErrorEnabled()) {
log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc());
}
return null;
}
handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender);
return null;
case NakAckHeader.XMIT_RSP:
if(trace)
log.trace("received missing messages " + hdr.range);
handleXmitRsp(msg);
return null;
default:
if(log.isErrorEnabled()) {
log.error("NakAck header type " + hdr.type + " not known !");
}
return null;
}
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass up further (Bela Aug 7 2001)
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
case Event.SUSPECT:
// release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new
// flush round anyway
if(rebroadcasting) {
cancelRebroadcasting();
}
break;
case Event.CONFIG:
up_prot.up(evt);
if(log.isDebugEnabled()) {
log.debug("received CONFIG event: " + evt.getArg());
}
handleConfigEvent((HashMap)evt.getArg());
return null;
}
return up_prot.up(evt);
}
private void send(Event evt, Message msg) {
if(msg == null)
throw new NullPointerException("msg is null; event is " + evt);
if(!started) {
if(trace)
log.trace("[" + local_addr + "] discarded message as start() has not been called, message: " + msg);
return;
}
long msg_id;
synchronized(sent_msgs) {
try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic
msg_id=seqno +1;
msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id));
sent_msgs.put(new Long(msg_id), msg);
seqno=msg_id;
}
catch(Throwable t) {
throw new RuntimeException("failure adding msg " + msg + " to the retransmit table", t);
}
}
try {
if(trace)
log.trace("sending " + local_addr + "#" + msg_id);
down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted
}
catch(Throwable t) { // eat the exception, don't pass it up the stack
if(warn) {
log.warn("failure passing message down", t);
}
}
}
/**
* Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many
* messages as possible from the NRW and passes them up the stack. Discards messages from non-members.
*/
private void handleMessage(Message msg, NakAckHeader hdr) {
NakReceiverWindow win;
Message msg_to_deliver;
Address sender=msg.getSrc();
if(sender == null) {
if(log.isErrorEnabled())
log.error("sender of message is null");
return;
}
if(trace) {
StringBuilder sb=new StringBuilder('[');
sb.append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno);
log.trace(sb.toString());
}
// msg is potentially re-sent later as result of XMIT_REQ reception; that's why hdr is added !
// Changed by bela Jan 29 2003: we currently don't resend from received msgs, just from sent_msgs !
// msg.putHeader(getName(), hdr);
win=received_msgs.get(sender);
if(win == null) { // discard message if there is no entry for sender
if(leaving)
return;
if(warn) {
StringBuffer sb=new StringBuffer('[');
sb.append(local_addr).append("] discarded message from non-member ")
.append(sender).append(", my view is " ).append(this.view);
log.warn(sb);
}
return;
}
boolean added=win.add(hdr.seqno, msg); // add in order, then remove and pass up as many msgs as possible
// message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering !
if(msg.isFlagSet(Message.OOB) && added) {
up_prot.up(new Event(Event.MSG, msg));
}
// where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time
// We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in
// delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered in the
// order in which they were sent by the sender
synchronized(win) {
while((msg_to_deliver=win.remove()) != null) {
if(msg_to_deliver.isFlagSet(Message.OOB)) {
continue;
}
// Changed by bela Jan 29 2003: not needed (see above)
//msg_to_deliver.removeHeader(getName());
up_prot.up(new Event(Event.MSG, msg_to_deliver));
}
}
}
/**
* Retransmit from sent-table, called when XMIT_REQ is received. Bundles all messages to be xmitted into one large
* message and sends them back with an XMIT_RSP header. Note that since we cannot count on a fragmentation layer
* below us, we have to make sure the message doesn't exceed max_xmit_size bytes. If this is the case, we split the
* message into multiple, smaller-chunked messages. But in most cases this still yields fewer messages than if each
* requested message was retransmitted separately.
*
* @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address
* @param first_seqno The first sequence number to be retransmitted (<= last_seqno)
* @param last_seqno The last sequence number to be retransmitted (>= first_seqno)
* @param original_sender The member who originally sent the messsage. Guaranteed to be non-null
*/
private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) {
Message m, tmp;
LinkedList<Message> list;
long size=0, marker=first_seqno, len;
NakReceiverWindow win=null;
boolean amISender; // am I the original sender ?
if(trace) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for ");
sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]");
log.trace(sb.toString());
}
if(first_seqno > last_seqno) {
if(log.isErrorEnabled())
log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit");
return;
}
if(stats) {
xmit_reqs_received+=last_seqno - first_seqno +1;
updateStats(received, xmit_requester, 1, 0, 0);
}
amISender=local_addr.equals(original_sender);
if(!amISender)
win=received_msgs.get(original_sender);
list=new LinkedList<Message>();
for(long i=first_seqno; i <= last_seqno; i++) {
if(amISender) {
m=sent_msgs.get(new Long(i)); // no need to synchronize
}
else {
m=win != null? win.get(i) : null;
}
if(m == null) {
if(log.isErrorEnabled()) {
StringBuffer sb=new StringBuffer();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") message ").append(original_sender).append("::").append(i);
sb.append(" not found in ").append((amISender? "sent" : "received")).append(" msgs ");
if(win != null) {
sb.append("from ").append(original_sender).append(": ").append(win.toString());
}
else {
sb.append(printSentMsgs());
}
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.error(sb);
}
continue;
}
len=m.size();
size+=len;
if(size > max_xmit_size && !list.isEmpty()) { // changed from >= to > (yaron-r, bug #943709)
// yaronr: added &&listSize()>0 since protocols between FRAG and NAKACK add headers, and message exceeds size.
// size has reached max_xmit_size. go ahead and send message (excluding the current message)
if(trace)
log.trace("xmitting msgs [" + marker + '-' + (i - 1) + "] to " + xmit_requester);
sendXmitRsp(xmit_requester, (LinkedList)list.clone(), marker, i - 1);
marker=i;
list.clear();
// fixed Dec 15 2003 (bela, patch from Joel Dice (dicej)), see explanantion under
// bug report #854887
size=len;
}
tmp=m;
// tmp.setDest(xmit_requester);
// tmp.setSrc(local_addr);
if(tmp.getSrc() == null)
tmp.setSrc(local_addr);
list.add(tmp);
}
if(!list.isEmpty()) {
if(trace)
log.trace("xmitting msgs [" + marker + '-' + last_seqno + "] to " + xmit_requester);
sendXmitRsp(xmit_requester, (LinkedList)list.clone(), marker, last_seqno);
list.clear();
}
}
private void cancelRebroadcasting() {
rebroadcast_lock.lock();
try {
rebroadcasting=false;
rebroadcast_done.signalAll();
}
finally {
rebroadcast_lock.unlock();
}
}
private static void updateStats(HashMap<Address,StatsEntry> map, Address key, int req, int rsp, int missing) {
StatsEntry entry=map.get(key);
if(entry == null) {
entry=new StatsEntry();
map.put(key, entry);
}
entry.xmit_reqs+=req;
entry.xmit_rsps+=rsp;
entry.missing_msgs_rcvd+=missing;
}
private void sendXmitRsp(Address dest, LinkedList xmit_list, long first_seqno, long last_seqno) {
Buffer buf;
if(xmit_list == null || xmit_list.isEmpty()) {
if(log.isErrorEnabled())
log.error("xmit_list is empty");
return;
}
if(use_mcast_xmit)
dest=null;
if(stats) {
xmit_rsps_sent+=xmit_list.size();
updateStats(sent, dest, 0, 1, 0);
}
try {
buf=Util.msgListToByteBuffer(xmit_list);
Message msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength());
// changed Bela Jan 4 2007: we should use OOB for retransmitted messages, otherwise we tax the OOB thread pool
// too much
// msg.setFlag(Message.OOB);
msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, first_seqno, last_seqno));
down_prot.down(new Event(Event.MSG, msg));
}
catch(IOException ex) {
log.error("failed marshalling xmit list", ex);
}
}
private void handleXmitRsp(Message msg) {
LinkedList list;
Message m;
if(msg == null) {
if(warn)
log.warn("message is null");
return;
}
try {
list=Util.byteBufferToMessageList(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
if(list != null) {
if(stats) {
xmit_rsps_received+=list.size();
updateStats(received, msg.getSrc(), 0, 1, 0);
}
int count=0;
for(Iterator it=list.iterator(); it.hasNext();) {
m=(Message)it.next();
if(rebroadcasting)
count++;
up(new Event(Event.MSG, m));
}
if(rebroadcasting && count > 0) {
Digest tmp=getDigest();
if(tmp.isGreaterThanOrEqual(rebroadcast_digest)) {
cancelRebroadcasting();
}
}
list.clear();
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) {
log.error("failed reading list of retransmitted messages", ex);
}
}
}
/**
* Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages,
* then send retransmit messages for the missing messages. Return when all missing messages have been received. If
* we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set.
*/
private void rebroadcastMessages() {
Digest my_digest;
Map<Address,Digest.Entry> their_digest;
Address sender;
Digest.Entry their_entry, my_entry;
long their_high, my_high;
long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS;
long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis();
while(rebroadcast_digest != null && wait_time > 0) {
my_digest=getDigest();
their_digest=rebroadcast_digest.getSenders();
boolean xmitted=false;
for(Map.Entry<Address,Digest.Entry> entry: their_digest.entrySet()) {
sender=entry.getKey();
their_entry=entry.getValue();
my_entry=my_digest.get(sender);
if(my_entry == null)
continue;
their_high=their_entry.getHighest();
my_high=my_entry.getHighest();
if(their_high > my_high) {
if(trace)
log.trace("sending XMIT request to " + sender + " for messages " + my_high + " - " + their_high);
retransmit(my_high, their_high, sender);
xmitted=true;
}
}
if(!xmitted)
return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest
rebroadcast_lock.lock();
try {
try {
my_digest=getDigest();
if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest)) {
return;
}
rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS);
wait_time-=(System.currentTimeMillis() - start);
}
catch(InterruptedException e) {
}
}
finally {
rebroadcast_lock.unlock();
}
}
}
/**
* Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all
* entries from received_msgs that are not in <code>members</code>. This method is not called concurrently
* multiple times
*/
private void adjustReceivers(boolean remove) {
NakReceiverWindow win;
if(remove) {
// 1. Remove all senders in received_msgs that are not members anymore
for(Iterator it=received_msgs.keySet().iterator(); it.hasNext();) {
Address sender=(Address)it.next();
if(!members.contains(sender)) {
win=received_msgs.get(sender);
win.reset();
if(log.isDebugEnabled()) {
log.debug("removing " + sender + " from received_msgs (not member anymore)");
}
it.remove();
}
}
}
// 2. Add newly joined members to received_msgs (starting seqno=0)
for(Address sender: members) {
if(!received_msgs.containsKey(sender)) {
win=createNakReceiverWindow(sender, 0);
received_msgs.put(sender, win);
}
}
}
/**
* Returns a message digest: for each member P the highest seqno received from P is added to the digest.
*/
private Digest getDigest() {
Range range;
Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(members.size());
for(Address sender: members) {
range=getLowestAndHighestSeqno(sender, false); // get the highest received seqno
if(range == null) {
if(log.isErrorEnabled()) {
log.error("range is null");
}
continue;
}
map.put(sender, new Digest.Entry(range.low, range.high));
}
return new Digest(map);
}
/**
* Returns a message digest: for each member P the highest seqno received from P <em>without a gap</em> is added to
* the digest. E.g. if the seqnos received from P are [+3 +4 +5 -6 +7 +8], then 5 will be returned. Also, the
* highest seqno <em>seen</em> is added. The max of all highest seqnos seen will be used (in STABLE) to determine
* whether the last seqno from a sender was received (see "Last Message Dropped" topic in DESIGN).
*/
private Digest getDigestHighestDeliveredMsgs() {
Range range;
long high_seqno_seen;
Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(members.size());
for(Address sender: members) {
range=getLowestAndHighestSeqno(sender, true); // get the highest deliverable seqno
if(range == null) {
if(log.isErrorEnabled()) {
log.error("range is null");
}
continue;
}
high_seqno_seen=getHighSeqnoSeen(sender);
map.put(sender, new Digest.Entry(range.low, range.high, high_seqno_seen));
}
return new Digest(map);
}
/**
* Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists,
* reset it.
*/
private void setDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
clear();
Map.Entry entry;
Address sender;
org.jgroups.protocols.pbcast.Digest.Entry val;
long initial_seqno;
NakReceiverWindow win;
for(Iterator it=digest.getSenders().entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
sender=(Address)entry.getKey();
val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue();
if(sender == null || val == null) {
if(warn) {
log.warn("sender or value is null");
}
continue;
}
initial_seqno=val.getHigh();
win=createNakReceiverWindow(sender, initial_seqno);
received_msgs.put(sender, win);
}
}
/**
* For all members of the digest, adjust the NakReceiverWindows in the received_msgs hashtable. If the member
* already exists, sets its seqno to be the max of the seqno and the seqno of the member in the digest. If no entry
* exists, create one with the initial seqno set to the seqno of the member in the digest.
*/
private void mergeDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
Map.Entry entry;
Address sender;
org.jgroups.protocols.pbcast.Digest.Entry val;
NakReceiverWindow win;
long initial_seqno;
for(Iterator it=digest.getSenders().entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
sender=(Address)entry.getKey();
val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue();
if(sender == null || val == null) {
if(warn) {
log.warn("sender or value is null");
}
continue;
}
initial_seqno=val.getHigh();
win=received_msgs.get(sender);
if(win == null) {
win=createNakReceiverWindow(sender, initial_seqno);
received_msgs.putIfAbsent(sender, win);
}
else {
if(win.getHighestReceived() < initial_seqno) {
win.reset();
received_msgs.remove(sender);
win=createNakReceiverWindow(sender, initial_seqno);
received_msgs.put(sender, win);
}
}
}
}
private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno) {
NakReceiverWindow win=new NakReceiverWindow(sender, this, initial_seqno, timer);
win.setRetransmitTimeouts(retransmit_timeout);
win.setDiscardDeliveredMessages(discard_delivered_msgs);
win.setMaxXmitBufSize(this.max_xmit_buf_size);
if(stats)
win.setListener(this);
return win;
}
/**
* Returns the lowest seqno still in cache (so it can be retransmitted) and the highest seqno received so far.
*
* @param sender The address for which the highest and lowest seqnos are to be retrieved
* @param stop_at_gaps If true, the highest seqno *deliverable* will be returned. If false, the highest seqno
* *received* will be returned. E.g. for [+3 +4 +5 -6 +7 +8], the highest_seqno_received is 8,
* whereas the higheset_seqno_seen (deliverable) is 5.
*/
private Range getLowestAndHighestSeqno(Address sender, boolean stop_at_gaps) {
Range r=null;
NakReceiverWindow win;
if(sender == null) {
if(log.isErrorEnabled()) {
log.error("sender is null");
}
return r;
}
win=received_msgs.get(sender);
if(win == null) {
if(log.isErrorEnabled()) {
log.error("sender " + sender + " not found in received_msgs");
}
return r;
}
if(stop_at_gaps) {
r=new Range(win.getLowestSeen(), win.getHighestSeen()); // deliverable messages (no gaps)
}
else {
r=new Range(win.getLowestSeen(), win.getHighestReceived() + 1); // received messages
}
return r;
}
/**
* Returns the highest seqno seen from sender. E.g. if we received 1, 2, 4, 5 from P, then 5 will be returned
* (doesn't take gaps into account). If we are the sender, we will return the highest seqno <em>sent</em> rather
* then <em>received</em>
*/
private long getHighSeqnoSeen(Address sender) {
NakReceiverWindow win;
long ret=0;
if(sender == null) {
if(log.isErrorEnabled()) {
log.error("sender is null");
}
return ret;
}
if(sender.equals(local_addr)) {
return seqno - 1;
}
win=received_msgs.get(sender);
if(win == null) {
if(log.isErrorEnabled()) {
log.error("sender " + sender + " not found in received_msgs");
}
return ret;
}
ret=win.getHighestReceived();
return ret;
}
/**
* Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest
* which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update received_msgs:
* for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the
* NakReceiverWindow corresponding to P which are <= seqno at digest[P].
*/
private void stable(Digest d) {
NakReceiverWindow recv_win;
long my_highest_rcvd; // highest seqno received in my digest for a sender P
long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P
if(members == null || local_addr == null || d == null) {
if(warn)
log.warn("members, local_addr or digest are null !");
return;
}
if(trace) {
log.trace("received stable digest " + d);
}
stability_msgs.add(d);
Map.Entry entry;
Address sender;
org.jgroups.protocols.pbcast.Digest.Entry val;
long high_seqno_delivered, high_seqno_received;
for(Iterator it=d.getSenders().entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
sender=(Address)entry.getKey();
if(sender == null)
continue;
val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue();
high_seqno_delivered=val.getHigh();
high_seqno_received=val.getHighSeen();
// check whether the last seqno received for a sender P in the stability vector is > last seqno
// received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic
// in DESIGN)
recv_win=received_msgs.get(sender);
if(recv_win != null) {
my_highest_rcvd=recv_win.getHighestReceived();
stability_highest_rcvd=high_seqno_received;
if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) {
if(trace) {
log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" +
stability_highest_rcvd + "): requesting retransmission of " +
sender + '#' + stability_highest_rcvd);
}
retransmit(stability_highest_rcvd, stability_highest_rcvd, sender);
}
}
high_seqno_delivered-=gc_lag;
if(high_seqno_delivered < 0) {
continue;
}
if(trace)
log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender);
// garbage collect from sent_msgs if sender was myself
if(sender.equals(local_addr)) {
synchronized(sent_msgs) {
// gets us a subset from [lowest seqno - seqno]
SortedMap stable_keys=sent_msgs.headMap(new Long(high_seqno_delivered));
if(stable_keys != null) {
stable_keys.clear(); // this will modify sent_msgs directly
}
}
}
// delete *delivered* msgs that are stable
// recv_win=(NakReceiverWindow)received_msgs.get(sender);
if(recv_win != null)
recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno
}
}
/**
* Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected.
*/
public void retransmit(long first_seqno, long last_seqno, Address sender) {
NakAckHeader hdr;
Message retransmit_msg;
Address dest=sender; // to whom do we send the XMIT request ?
if(xmit_from_random_member && !local_addr.equals(sender)) {
Address random_member=(Address)Util.pickRandomElement(members);
if(random_member != null && !local_addr.equals(random_member)) {
dest=random_member;
if(trace)
log.trace("picked random member " + dest + " to send XMIT request to");
}
}
hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender);
retransmit_msg=new Message(dest, null, null);
retransmit_msg.setFlag(Message.OOB);
if(trace)
log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest);
retransmit_msg.putHeader(name, hdr);
down_prot.down(new Event(Event.MSG, retransmit_msg));
if(stats) {
xmit_reqs_sent+=last_seqno - first_seqno +1;
updateStats(sent, dest, 1, 0, 0);
for(long i=first_seqno; i <= last_seqno; i++) {
XmitRequest req=new XmitRequest(sender, i, dest);
send_history.add(req);
}
}
}
public void missingMessageReceived(long seqno, Message msg) {
if(stats) {
missing_msgs_received++;
updateStats(received, msg.getSrc(), 0, 0, 1);
MissingMessage missing=new MissingMessage(msg.getSrc(), seqno);
receive_history.add(missing);
}
}
private void clear() {
NakReceiverWindow win;
// changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between
// a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might
// fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection)
// sent_msgs.clear();
for(Iterator it=received_msgs.values().iterator(); it.hasNext();) {
win=(NakReceiverWindow)it.next();
win.reset();
}
received_msgs.clear();
}
private void reset() {
NakReceiverWindow win;
synchronized(sent_msgs) {
sent_msgs.clear();
seqno=-1;
}
for(Iterator it=received_msgs.values().iterator(); it.hasNext();) {
win=(NakReceiverWindow)it.next();
win.destroy();
}
received_msgs.clear();
}
public String printMessages() {
StringBuilder ret=new StringBuilder();
Map.Entry entry;
Address addr;
Object w;
ret.append("\nsent_msgs: ").append(printSentMsgs());
ret.append("\nreceived_msgs:\n");
for(Iterator it=received_msgs.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
addr=(Address)entry.getKey();
w=entry.getValue();
ret.append(addr).append(": ").append(w.toString()).append('\n');
}
return ret.toString();
}
public String printSentMsgs() {
StringBuilder sb=new StringBuilder();
Long min_seqno, max_seqno;
synchronized(sent_msgs) {
min_seqno=!sent_msgs.isEmpty()? sent_msgs.firstKey() : new Long(0);
max_seqno=!sent_msgs.isEmpty()? sent_msgs.lastKey() : new Long(0);
}
sb.append('[').append(min_seqno).append(" - ").append(max_seqno).append("] (").append(sent_msgs.size()).append(")");
return sb.toString();
}
private void handleConfigEvent(HashMap map) {
if(map == null) {
return;
}
if(map.containsKey("frag_size")) {
max_xmit_size=((Integer)map.get("frag_size")).intValue();
if(log.isInfoEnabled()) {
log.info("max_xmit_size=" + max_xmit_size);
}
}
}
static class StatsEntry {
long xmit_reqs, xmit_rsps, missing_msgs_rcvd;
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps");
sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs");
return sb.toString();
}
}
static class XmitRequest {
Address original_sender; // original sender of message
long seq, timestamp=System.currentTimeMillis();
Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender
XmitRequest(Address original_sender, long seqno, Address xmit_dest) {
this.original_sender=original_sender;
this.xmit_dest=xmit_dest;
this.seq=seqno;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq);
sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")");
return sb.toString();
}
}
static class MissingMessage {
Address original_sender;
long seq, timestamp=System.currentTimeMillis();
MissingMessage(Address original_sender, long seqno) {
this.original_sender=original_sender;
this.seq=seqno;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq);
return sb.toString();
}
}
}
|
// $Id: STABLE.java,v 1.21 2005/06/13 07:49:20 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Promise;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import org.jgroups.util.Streamable;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
/**
* Computes the broadcast messages that are stable, i.e. have been received by all members. Sends
* STABLE events up the stack when this is the case. This allows NAKACK to garbage collect messages that
* have been seen by all members.<p>
* Works as follows: periodically we mcast our highest seqnos (seen for each member) to the group.
* A stability vector, which maintains the highest seqno for each member and initially contains no data,
* is updated when such a message is received. The entry for a member P is computed set to
* min(entry[P], digest[P]). When messages from all members have been received, a stability
* message is mcast, which causes all members to send a STABLE event up the stack (triggering garbage collection
* in the NAKACK layer).<p>
* The stable task now terminates after max_num_gossips if no messages or view changes have been sent or received
* in the meantime. It will resume when messages are received. This effectively suspends sending superfluous
* STABLE messages in the face of no activity.<br/>
* New: when <code>max_bytes</code> is exceeded (unless disabled by setting it to 0),
* a STABLE task will be started (unless it is already running).
* @author Bela Ban
*/
public class STABLE extends Protocol {
Address local_addr=null;
final Vector mbrs=new Vector();
final Digest digest=new Digest(); // keeps track of the highest seqnos from all members
final Promise digest_promise=new Promise(); // for fetching digest (from NAKACK layer)
final Vector heard_from=new Vector(); // keeps track of who we already heard from (STABLE_GOSSIP msgs)
long digest_timeout=60000; // time to wait until digest is received (from NAKACK)
/** Sends a STABLE gossip every 20 seconds on average. 0 disables gossipping of STABLE messages */
long desired_avg_gossip=20000;
/** delay before we send STABILITY msg (give others a change to send first). This should be set to a very
* small number (> 0 !) if <code>max_bytes</code> is used */
long stability_delay=6000;
StabilitySendTask stability_task=null;
final Object stability_mutex=new Object(); // to synchronize on stability_task
StableTask stable_task=null; // bcasts periodic STABLE message (added to timer below)
final Object stable_task_mutex=new Object(); // to sync on stable_task
TimeScheduler timer=null; // to send periodic STABLE msgs (and STABILITY messages)
int max_gossip_runs=3; // max. number of times the StableTask runs before terminating
int num_gossip_runs=max_gossip_runs; // this number is decremented (max_gossip_runs doesn't change)
static final String name="STABLE";
/** Total amount of bytes from incoming messages (default = 0 = disabled). When exceeded, a STABLE
* message will be broadcast and <code>num_bytes_received</code> reset to 0 . If this is > 0, then ideally
* <code>stability_delay</code> should be set to a low number as well */
long max_bytes=0;
/** The total number of bytes received from unicast and multicast messages */
long num_bytes_received=0;
/** When true, don't take part in garbage collection protocol: neither send STABLE messages nor
* handle STABILITY messages */
boolean suspended=false;
/** Max time we should hold off on message garbage collection. This is a second line of defense in case
* we get a SUSPEND_STABLE, but forget to send a corresponding RESUME_STABLE (which should never happen !)
* The consequence of a missing RESUME_STABLE would be that the group doesn't garbage collect stable
* messages anymore, eventually, with a lot of traffic, every member would accumulate messages and run
* out of memory !
*/
// long max_suspend_time=600000;
ResumeTask resume_task=null;
final Object resume_task_mutex=new Object();
public String getName() {
return name;
}
public long getDesiredAverageGossip() {
return desired_avg_gossip;
}
public void setDesiredAverageGossip(long gossip_interval) {
desired_avg_gossip=gossip_interval;
}
public long getMaxBytes() {
return max_bytes;
}
public void setMaxBytes(long max_bytes) {
this.max_bytes=max_bytes;
}
public Vector requiredDownServices() {
Vector retval=new Vector();
retval.addElement(new Integer(Event.GET_DIGEST_STABLE)); // NAKACK layer
return retval;
}
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("digest_timeout");
if(str != null) {
digest_timeout=Long.parseLong(str);
props.remove("digest_timeout");
}
str=props.getProperty("desired_avg_gossip");
if(str != null) {
desired_avg_gossip=Long.parseLong(str);
props.remove("desired_avg_gossip");
}
str=props.getProperty("stability_delay");
if(str != null) {
stability_delay=Long.parseLong(str);
props.remove("stability_delay");
}
str=props.getProperty("max_gossip_runs");
if(str != null) {
max_gossip_runs=Integer.parseInt(str);
num_gossip_runs=max_gossip_runs;
props.remove("max_gossip_runs");
}
str=props.getProperty("max_bytes");
if(str != null) {
max_bytes=Long.parseLong(str);
props.remove("max_bytes");
}
str=props.getProperty("max_suspend_time");
if(str != null) {
log.error("max_suspend_time is not supported any longer; please remove it (ignoring it)");
props.remove("max_suspend_time");
}
if(props.size() > 0) {
log.error("STABLE.setProperties(): these properties are not recognized: " + props);
return false;
}
return true;
}
void suspend(long timeout) {
if(!suspended) {
suspended=true;
if(log.isDebugEnabled())
log.debug("suspending message garbage collection");
}
startResumeTask(timeout); // will not start task if already running
}
void resume() {
suspended=false;
if(log.isDebugEnabled())
log.debug("resuming message garbage collection");
stopResumeTask();
}
public void start() throws Exception {
if(stack != null && stack.timer != null)
timer=stack.timer;
else
throw new Exception("STABLE.up(): timer cannot be retrieved from protocol stack");
}
public void stop() {
stopStableTask();
}
public void up(Event evt) {
Message msg;
StableHeader hdr;
Header obj;
int type=evt.getType();
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
if(max_bytes > 0) { // message counting is enabled
long size=Math.max(msg.getLength(), 24);
num_bytes_received+=size;
if(num_bytes_received >= max_bytes) {
if(log.isTraceEnabled()) {
StringBuffer sb=new StringBuffer("max_bytes has been exceeded (max_bytes=");
sb.append(max_bytes).append(", number of bytes received=");
sb.append(num_bytes_received).append("): sending STABLE message");
log.trace(sb.toString());
}
new Thread() {
public void run() {
initialize();
sendStableMessage();
}
}.start();
num_bytes_received=0;
}
}
obj=msg.getHeader(name);
if(obj == null || !(obj instanceof StableHeader))
break;
hdr=(StableHeader)msg.removeHeader(name);
switch(hdr.type) {
case StableHeader.STABLE_GOSSIP:
handleStableGossip(msg.getSrc(), hdr.stableDigest);
break;
case StableHeader.STABILITY:
handleStabilityMessage(hdr.stableDigest);
break;
default:
if(log.isErrorEnabled()) log.error("StableHeader type " + hdr.type + " not known");
}
return; // don't pass STABLE or STABILITY messages up the stack
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
}
passUp(evt);
if(desired_avg_gossip > 0) {
if(type == Event.VIEW_CHANGE || type == Event.MSG)
startStableTask(); // only starts task if not yet running
}
}
/**
* We need to receive this event out-of-band, otherwise we would block. The use case is
* <ol>
* <li>To send a STABLE_GOSSIP message we need the digest (from NAKACK below)
* <li>We send a GET_DIGEST_STABLE event down <em>from the up() method</em>
* <li>NAKACK sends the GET_DIGEST_STABLE_OK backup. <em>However, we may have other messages in the
* up queue ahead of this event !</em> Therefore the event cannot be processed until all messages ahead of
* the event have been processed. These can't be processed, however, because the up() call waits for
* GET_DIGEST_STABLE_OK ! The up() call would always run into the timeout.<be/>
* Having out-of-band reception of just this one event eliminates the problem.
* </ol>
* @param evt
*/
protected void receiveUpEvent(Event evt) {
if(evt.getType() == Event.GET_DIGEST_STABLE_OK) {
digest_promise.setResult(evt.getArg());
return;
}
super.receiveUpEvent(evt);
}
public void down(Event evt) {
int type=evt.getType();
switch(evt.getType()) {
case Event.VIEW_CHANGE:
View v=(View)evt.getArg();
Vector tmp=v.getMembers();
mbrs.removeAllElements();
mbrs.addAll(tmp);
heard_from.retainAll(tmp); // removes all elements from heard_from that are not in new view
stopStableTask();
break;
case Event.SUSPEND_STABLE:
long timeout=0;
Object t=evt.getArg();
if(t != null && t instanceof Long)
timeout=((Long)t).longValue();
stopStableTask();
suspend(timeout);
break;
case Event.RESUME_STABLE:
resume();
break;
}
if(desired_avg_gossip > 0) {
if(type == Event.VIEW_CHANGE || type == Event.MSG)
startStableTask(); // only starts task if not yet running
}
passDown(evt);
}
public void runMessageGarbageCollection() {
sendStableMessage();
}
void initialize() {
synchronized(digest) {
digest.reset(mbrs.size());
for(int i=0; i < mbrs.size(); i++)
digest.add((Address)mbrs.elementAt(i), -1, -1);
heard_from.removeAllElements();
heard_from.addAll(mbrs);
}
}
void startStableTask() {
num_gossip_runs=max_gossip_runs;
// Here, double-checked locking works: we don't want to synchronize if the task already runs (which is the case
// 99% of the time). If stable_task gets nulled after the condition check, we return anyways, but just miss
// 1 cycle: on the next message or view, we will start the task
if(stable_task != null)
return;
synchronized(stable_task_mutex) {
if(stable_task != null && stable_task.running()) {
return; // already running
}
stable_task=new StableTask();
timer.add(stable_task, true); // fixed-rate scheduling
}
if(log.isTraceEnabled())
log.trace("stable task started; num_gossip_runs=" + num_gossip_runs + ", max_gossip_runs=" + max_gossip_runs);
}
void stopStableTask() {
// contrary to startStableTask(), we don't need double-checked locking here because this method is not
// called frequently
synchronized(stable_task_mutex) {
if(stable_task != null) {
stable_task.stop();
stable_task=null;
}
}
}
void startResumeTask(long max_suspend_time) {
max_suspend_time=(long)(max_suspend_time * 1.1); // little slack
synchronized(resume_task_mutex) {
if(resume_task != null && resume_task.running()) {
return; // already running
}
else {
resume_task=new ResumeTask(max_suspend_time);
timer.add(resume_task, true); // fixed-rate scheduling
}
}
if(log.isDebugEnabled())
log.debug("resume task started, max_suspend_time=" + max_suspend_time);
}
void stopResumeTask() {
synchronized(resume_task_mutex) {
if(resume_task != null) {
resume_task.stop();
resume_task=null;
}
}
}
void startStabilityTask(Digest d, long delay) {
synchronized(stability_mutex) {
if(stability_task != null && stability_task.running()) {
return; // already running
}
else {
stability_task=new StabilitySendTask(d, delay);
timer.add(stability_task, true); // fixed-rate scheduling
}
}
}
void stopStabilityTask() {
synchronized(stability_mutex) {
if(stability_task != null) {
stability_task.stop();
stability_task=null;
}
}
}
/**
Digest d contains (a) the highest seqnos <em>deliverable</em> for each sender and (b) the highest seqnos
<em>seen</em> for each member. (Difference: with 1,2,4,5, the highest seqno seen is 5, whereas the highest
seqno deliverable is 2). The minimum of all highest seqnos deliverable will be taken to send a stability
message, which results in garbage collection of messages lower than the ones in the stability vector. The
maximum of all seqnos will be taken to trigger possible retransmission of last missing seqno (see DESIGN
for details).
*/
void handleStableGossip(Address sender, Digest d) {
Address mbr;
long highest_seqno, my_highest_seqno;
long highest_seen_seqno, my_highest_seen_seqno;
if(d == null || sender == null) {
if(log.isErrorEnabled()) log.error("digest or sender is null");
return;
}
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("STABLE message will not be handled as suspended=" + suspended);
}
return;
}
if(log.isDebugEnabled()) log.debug("received digest " + printStabilityDigest(d) + " from " + sender);
if(!heard_from.contains(sender)) { // already received gossip from sender; discard it
if(log.isDebugEnabled()) log.debug("already received gossip from " + sender);
return;
}
// we won't handle the gossip d, if d's members don't match the membership in my own digest,
// this is part of the fix for the NAKACK problem (bugs #943480 and #938584)
if(!this.digest.sameSenders(d)) {
if(log.isDebugEnabled()) {
log.debug("received digest from " + sender + " (digest=" + d + ") which does not match my own digest ("+
this.digest + "): ignoring digest and re-initializing own digest");
}
initialize();
return;
}
for(int i=0; i < d.size(); i++) {
mbr=d.senderAt(i);
highest_seqno=d.highSeqnoAt(i);
highest_seen_seqno=d.highSeqnoSeenAt(i);
if(digest.getIndex(mbr) == -1) {
if(log.isDebugEnabled()) log.debug("sender " + mbr + " not found in stability vector");
continue;
}
// compute the minimum of the highest seqnos deliverable (for garbage collection)
my_highest_seqno=digest.highSeqnoAt(mbr);
if(my_highest_seqno < 0) {
if(highest_seqno >= 0)
digest.setHighSeqnoAt(mbr, highest_seqno);
}
else {
digest.setHighSeqnoAt(mbr, Math.min(my_highest_seqno, highest_seqno));
}
// compute the maximum of the highest seqnos seen (for retransmission of last missing message)
my_highest_seen_seqno=digest.highSeqnoSeenAt(mbr);
if(my_highest_seen_seqno < 0) {
if(highest_seen_seqno >= 0)
digest.setHighSeqnoSeenAt(mbr, highest_seen_seqno);
}
else {
digest.setHighSeqnoSeenAt(mbr, Math.max(my_highest_seen_seqno, highest_seen_seqno));
}
}
heard_from.removeElement(sender);
if(heard_from.size() == 0) {
if(log.isDebugEnabled()) log.debug("sending stability msg " + printStabilityDigest(digest));
sendStabilityMessage(digest.copy());
initialize();
}
}
/**
* Bcasts a STABLE message to all group members. Message contains highest seqnos of all members
* seen by this member. Highest seqnos are retrieved from the NAKACK layer above.
*/
void sendStableMessage() {
Digest d=null;
Message msg=new Message(); // mcast message
StableHeader hdr;
if(suspended) {
if(log.isTraceEnabled())
log.trace("will not send STABLE message as suspended=" + suspended);
return;
}
d=getDigest();
if(d != null && d.size() > 0) {
if(log.isTraceEnabled())
log.trace("mcasting STABLE msg, digest=" + d +
" (num_gossip_runs=" + num_gossip_runs + ", max_gossip_runs=" + max_gossip_runs + ')');
hdr=new StableHeader(StableHeader.STABLE_GOSSIP, d);
msg.putHeader(name, hdr);
passDown(new Event(Event.MSG, msg));
}
}
Digest getDigest() {
Digest ret=null;
passDown(new Event(Event.GET_DIGEST_STABLE));
ret=(Digest)digest_promise.getResult(digest_timeout);
if(ret == null) {
if(log.isErrorEnabled())
log.error("digest could not be fetched from below " + "(timeout was " + digest_timeout + " msecs)");
}
return ret;
}
/**
Schedules a stability message to be mcast after a random number of milliseconds (range 1-5 secs).
The reason for waiting a random amount of time is that, in the worst case, all members receive a
STABLE_GOSSIP message from the last outstanding member at the same time and would therefore mcast the
STABILITY message at the same time too. To avoid this, each member waits random N msecs. If, before N
elapses, some other member sent the STABILITY message, we just cancel our own message. If, during
waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just
discard S2.
@param tmp A copy of te stability digest, so we don't need to copy it again
*/
void sendStabilityMessage(Digest tmp) {
long delay;
if(timer == null) {
if(log.isErrorEnabled())
log.error("timer is null, cannot schedule stability message to be sent");
timer=stack != null ? stack.timer : null;
return;
}
// give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of
// our random sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a
// STABILITY msg at the same time
delay=Util.random(stability_delay);
startStabilityTask(tmp, delay);
}
void handleStabilityMessage(Digest d) {
if(d == null) {
if(log.isErrorEnabled()) log.error("stability vector is null");
return;
}
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("STABILITY message will not be handled as suspened=" + suspended);
}
return;
}
if(log.isDebugEnabled()) log.debug("stability vector is " + d.printHighSeqnos());
stopStabilityTask();
// we won't handle the gossip d, if d's members don't match the membership in my own digest,
// this is part of the fix for the NAKACK problem (bugs #943480 and #938584)
if(!this.digest.sameSenders(d)) {
if(log.isDebugEnabled()) {
log.debug("received digest (digest=" + d + ") which does not match my own digest ("+
this.digest + "): ignoring digest and re-initializing own digest");
}
initialize();
return;
}
// pass STABLE event down the stack, so NAKACK can garbage collect old messages
passDown(new Event(Event.STABLE, d));
}
String printStabilityDigest(Digest d) {
StringBuffer sb=new StringBuffer();
boolean first=true;
if(d != null) {
for(int i=0; i < d.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
sb.append(d.senderAt(i) + "#" + d.highSeqnoAt(i) + " (" + d.highSeqnoSeenAt(i) + ')');
}
}
return sb.toString();
}
public static class StableHeader extends Header implements Streamable {
static final int STABLE_GOSSIP=1;
static final int STABILITY=2;
int type=0;
// Digest digest=new Digest(); // used for both STABLE_GOSSIP and STABILITY message
Digest stableDigest=null; // changed by Bela April 4 2004
public StableHeader() {
} // used for externalizable
StableHeader(int type, Digest digest) {
this.type=type;
this.stableDigest=digest;
}
static String type2String(int t) {
switch(t) {
case STABLE_GOSSIP:
return "STABLE_GOSSIP";
case STABILITY:
return "STABILITY";
default:
return "<unknown>";
}
}
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append('[');
sb.append(type2String(type));
sb.append("]: digest is ");
sb.append(stableDigest);
return sb.toString();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(type);
if(stableDigest == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
stableDigest.writeExternal(out);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readInt();
boolean digest_not_null=in.readBoolean();
if(digest_not_null) {
stableDigest=new Digest();
stableDigest.readExternal(in);
}
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeInt(type);
Util.writeStreamable(stableDigest, out);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readInt();
stableDigest=(Digest)Util.readStreamable(Digest.class, in);
}
}
/**
Mcast periodic STABLE message. Interval between sends varies. Terminates after num_gossip_runs is 0.
However, UP or DOWN messages will reset num_gossip_runs to max_gossip_runs. This has the effect that the
stable_send task terminates only after a period of time within which no messages were either sent
or received
*/
private class StableTask implements TimeScheduler.Task {
boolean stopped=false;
public void stop() {
stopped=true;
}
public boolean running() { // syntactic sugar
return !stopped;
}
public boolean cancelled() {
return stopped;
}
public long nextInterval() {
long interval=computeSleepTime();
if(interval <= 0)
return 10000;
else
return interval;
}
public void run() {
if(suspended) {
if(log.isTraceEnabled())
log.trace("stable task will not run as suspended=" + suspended);
stopStableTask();
return;
}
initialize();
sendStableMessage();
num_gossip_runs
if(num_gossip_runs <= 0) {
if(log.isTraceEnabled())
log.trace("stable task terminating (num_gossip_runs=" +
num_gossip_runs + ", max_gossip_runs=" + max_gossip_runs + ')');
stopStableTask();
}
}
long computeSleepTime() {
return getRandom((mbrs.size() * desired_avg_gossip * 2));
}
long getRandom(long range) {
return (long)((Math.random() * range) % range);
}
}
/**
* Multicasts a STABILITY message.
*/
private class StabilitySendTask implements TimeScheduler.Task {
Digest d=null;
boolean stopped=false;
long delay=2000;
public StabilitySendTask(Digest d, long delay) {
this.d=d;
this.delay=delay;
}
public boolean running() {
return !stopped;
}
public void stop() {
stopped=true;
}
public boolean cancelled() {
return stopped;
}
/** wait a random number of msecs (to give other a chance to send the STABILITY msg first) */
public long nextInterval() {
return delay;
}
public void run() {
Message msg;
StableHeader hdr;
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("STABILITY message will not be sent as suspended=" + suspended);
}
stopped=true;
return;
}
if(d != null && !stopped) {
msg=new Message();
hdr=new StableHeader(StableHeader.STABILITY, d);
msg.putHeader(STABLE.name, hdr);
passDown(new Event(Event.MSG, msg));
d=null;
}
stopped=true; // run only once
}
}
private class ResumeTask implements TimeScheduler.Task {
boolean running=true;
long max_suspend_time=0;
ResumeTask(long max_suspend_time) {
this.max_suspend_time=max_suspend_time;
}
void stop() {
running=false;
}
public boolean running() {
return running;
}
public boolean cancelled() {
return running == false;
}
public long nextInterval() {
return max_suspend_time;
}
public void run() {
if(suspended)
log.warn("ResumeTask resumed message garbage collection - this should be done by a RESUME_STABLE event; " +
"check why this event was not received (or increase max_suspend_time for large state transfers)");
resume();
}
}
}
|
// $Id: AckReceiverWindow.java,v 1.9 2005/01/28 09:53:08 belaban Exp $
package org.jgroups.stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Message;
import java.util.HashMap;
/**
* Counterpart of AckSenderWindow. Simple FIFO buffer.
* Every message received is ACK'ed (even duplicates) and added to a hashmap
* keyed by seqno. The next seqno to be received is stored in <code>next_to_remove</code>. When a message with
* a seqno less than next_to_remove is received, it will be discarded. The <code>remove()</code> method removes
* and returns a message whose seqno is equal to next_to_remove, or null if not found.<br>
* Change May 28 2002 (bela): replaced TreeSet with HashMap. Keys do not need to be sorted, and adding a key to
* a sorted set incurs overhead.
*
* @author Bela Ban
*/
public class AckReceiverWindow {
final long initial_seqno;
long next_to_remove=0;
final HashMap msgs=new HashMap(); // keys: seqnos (Long), values: Messages
static final Log log=LogFactory.getLog(AckReceiverWindow.class);
public AckReceiverWindow(long initial_seqno) {
this.initial_seqno=initial_seqno;
next_to_remove=initial_seqno;
}
public void add(long seqno, Message msg) {
if(seqno < next_to_remove) {
if(log.isTraceEnabled())
log.trace("discarded msg with seqno=" + seqno + " (next msg to receive is " + next_to_remove + ')');
return;
}
msgs.put(new Long(seqno), msg);
}
/**
* Removes a message whose seqno is equal to <code>next_to_remove</code>, increments the latter.
* Returns message that was removed, or null, if no message can be removed. Messages are thus
* removed in order.
*/
public Message remove() {
Message retval=(Message)msgs.remove(new Long(next_to_remove));
if(retval != null)
next_to_remove++;
return retval;
}
public void reset() {
msgs.clear();
next_to_remove=initial_seqno;
}
public int size() {
return msgs.size();
}
public String toString() {
return msgs.keySet().toString();
}
}
|
package org.jgroups.stack;
import org.jgroups.Address;
import org.jgroups.PhysicalAddress;
import org.jgroups.annotations.GuardedBy;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Manages a list of RouterStubs (e.g. health checking, reconnecting etc.
* @author Vladimir Blagojevic
* @author Bela Ban
*/
public class RouterStubManager implements Runnable, RouterStub.CloseListener {
@GuardedBy("reconnectorLock")
protected final ConcurrentMap<RouterStub,Future<?>> futures=new ConcurrentHashMap<>();
// List of currently connected RouterStubs
protected volatile List<RouterStub> stubs;
// List of destinations that the reconnect task needs to create and connect
protected volatile Set<Target> reconnect_list;
protected final Protocol owner;
protected final TimeScheduler timer;
protected final String cluster_name;
protected final Address local_addr;
protected final String logical_name;
protected final PhysicalAddress phys_addr;
protected final long interval; // reconnect interval (ms)
protected boolean use_nio=true; // whether to use RouterStubTcp or RouterStubNio
protected Future<?> reconnector_task;
protected final Log log;
public RouterStubManager(Protocol owner, String cluster_name, Address local_addr,
String logical_name, PhysicalAddress phys_addr, long interval) {
this.owner = owner;
this.stubs = new ArrayList<>();
this.reconnect_list=new HashSet<>();
this.log = LogFactory.getLog(owner.getClass());
this.timer = owner.getTransport().getTimer();
this.cluster_name=cluster_name;
this.local_addr=local_addr;
this.logical_name=logical_name;
this.phys_addr=phys_addr;
this.interval = interval;
}
public static RouterStubManager emptyGossipClientStubManager(Protocol p) {
return new RouterStubManager(p,null,null,null, null,0L);
}
public RouterStubManager useNio(boolean flag) {use_nio=flag; return this;}
/**
* Applies action to all RouterStubs that are connected
* @param action
*/
public void forEach(Consumer<RouterStub> action) {
stubs.stream().filter(RouterStub::isConnected).forEach(action::accept);
}
/**
* Applies action to a randomly picked RouterStub that's connected
* @param action
*/
public void forAny(Consumer<RouterStub> action) {
while(!stubs.isEmpty()) {
RouterStub stub=Util.pickRandomElement(stubs);
if(stub != null && stub.isConnected()) {
action.accept(stub);
return;
}
}
}
public RouterStub createAndRegisterStub(IpAddress local, IpAddress router_addr) {
RouterStub stub=new RouterStub(local, router_addr, use_nio, this);
RouterStub old_stub=unregisterStub(router_addr);
if(old_stub != null)
old_stub.destroy();
add(stub);
return stub;
}
public RouterStub unregisterStub(IpAddress router_addr) {
RouterStub stub=find(router_addr);
if(stub != null)
remove(stub);
return stub;
}
public void connectStubs() {
for(RouterStub stub : stubs) {
try {
if(!stub.isConnected())
stub.connect(cluster_name, local_addr, logical_name, phys_addr);
}
catch (Throwable e) {
moveStubToReconnects(stub);
}
}
}
public void disconnectStubs() {
stopReconnector();
for(RouterStub stub : stubs) {
try {
stub.disconnect(cluster_name, local_addr);
}
catch (Throwable e) {
}
}
}
public void destroyStubs() {
stopReconnector();
stubs.forEach(RouterStub::destroy);
stubs.clear();
}
public String printStubs() {
return Util.printListWithDelimiter(stubs, ", ");
}
public String printReconnectList() {
return Util.printListWithDelimiter(reconnect_list, ", ");
}
public String print() {
return String.format("Stubs: %s\nReconnect list: %s", printStubs(), printReconnectList());
}
public void run() {
if(reconnect_list.removeIf(this::reconnect) && reconnect_list.isEmpty())
stopReconnector();
}
@Override
public void closed(RouterStub stub) {
moveStubToReconnects(stub);
}
protected boolean reconnect(Target target) {
RouterStub stub=new RouterStub(target.bind_addr, target.router_addr, this.use_nio, this).receiver(target.receiver);
if(!add(stub))
return false;
try {
stub.connect(this.cluster_name, this.local_addr, this.logical_name, this.phys_addr);
log.debug("re-established connection to %s successfully for group=%s and address=%s", stub.remote(), this.cluster_name, this.local_addr);
return true;
}
catch(Throwable t) {
remove(stub);
return false;
}
}
protected void moveStubToReconnects(RouterStub stub) {
if(stub == null) return;
remove(stub);
if(add(new Target(stub.local(), stub.remote(), stub.receiver()))) {
log.debug("connection to %s closed, trying to re-establish connection", stub.remote());
startReconnector();
}
}
protected boolean add(RouterStub stub) {
if(stub == null) return false;
List<RouterStub> new_stubs=new ArrayList<>(stubs);
boolean retval=!new_stubs.contains(stub) && new_stubs.add(stub);
this.stubs=new_stubs;
return retval;
}
protected boolean add(Target target) {
if(target == null) return false;
Set<Target> new_set=new HashSet<>(reconnect_list);
if(new_set.add(target)) {
this.reconnect_list=new_set;
return true;
}
return false;
}
protected boolean remove(RouterStub stub) {
if(stub == null) return false;
stub.destroy();
List<RouterStub> new_stubs=new ArrayList<>(stubs);
boolean retval=new_stubs.remove(stub);
this.stubs=new_stubs;
return retval;
}
protected boolean remove(Target target) {
if(target == null) return false;
Set<Target> new_set=new HashSet<>(reconnect_list);
if(new_set.remove(target)) {
this.reconnect_list=new_set;
return true;
}
return false;
}
protected RouterStub find(IpAddress router_addr) {
for(RouterStub stub: stubs) {
IpAddress addr=stub.gossipRouterAddress();
if(Objects.equals(addr, router_addr))
return stub;
}
return null;
}
protected synchronized void startReconnector() {
if(reconnector_task == null || reconnector_task.isDone())
reconnector_task=timer.scheduleWithFixedDelay(this, interval, interval, TimeUnit.MILLISECONDS);
}
protected synchronized void stopReconnector() {
if(reconnector_task != null)
reconnector_task.cancel(true);
}
protected static class Target implements Comparator<Target>, Serializable {
private static final long serialVersionUID = 1L;
protected final IpAddress bind_addr, router_addr;
protected final RouterStub.StubReceiver receiver;
public Target(IpAddress bind_addr, IpAddress router_addr, RouterStub.StubReceiver receiver) {
this.bind_addr=bind_addr;
this.router_addr=router_addr;
this.receiver=receiver;
}
@Override
public int compare(Target o1, Target o2) {
return o1.router_addr.compareTo(o2.router_addr);
}
public int hashCode() {
return router_addr.hashCode();
}
public boolean equals(Object obj) {
return compare(this, (Target)obj) == 0;
}
public String toString() {
return String.format("%s -> %s", bind_addr, router_addr);
}
}
}
|
package org.lambda.sequence.util;
import java.util.Calendar;
public class CallerInfo extends SecurityManager
{
private static CallerInfo caller = new CallerInfo();
public static long getCallDate()
{
return Calendar.getInstance().getTimeInMillis();
}
public static String getCallerClassName()
{
Class<?>[] context = caller.getClassContext();
if(context.length>2)
return context[2].getName();
return null;
}
public static String getCallerName()
{
String r = "";
StackTraceElement[] s = new Throwable().getStackTrace();
//for(StackTraceElement e : s)
// System.out.println("--> "+e);
if(s.length<3)
r += s[s.length-1];
else
r += s[2];
return r;
}
}
|
/*
* $Id: IdentityManager.java,v 1.25 2003-04-05 00:57:15 tal Exp $
*/
package org.lockss.protocol;
import java.io.*;
import java.net.*;
import java.util.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.poller.Vote;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.*;
public class IdentityManager extends BaseLockssManager {
protected static Logger log = Logger.getLogger("IDMgr");
static final String PARAM_LOCAL_IP = Configuration.PREFIX + "localIPAddress";
static final String PREFIX = Configuration.PREFIX + "id.";
static final String PARAM_MAX_DELTA = PREFIX + "maxReputationDelta";
static final String PARAM_AGREE_DELTA = PREFIX + "agreeDelta";
static final String PARAM_DISAGREE_DELTA = PREFIX + "disagreeDelta";
static final String PARAM_CALL_INTERNAL = PREFIX + "callInternalDelta";
static final String PARAM_SPOOF_DETECTED = PREFIX + "spoofDetected";
static final String PARAM_REPLAY_DETECTED = PREFIX + "replayDetected";
static final String PARAM_ATTACK_DETECTED = PREFIX + "attackDetected";
static final String PARAM_VOTE_NOTVERIFIED = PREFIX + "voteNotVerified ";
static final String PARAM_VOTE_VERIFIED = PREFIX + "voteVerified";
static final String PARAM_VOTE_DISOWNED = PREFIX + "voteDisowned";
static final String PARAM_IDDB_DIR = PREFIX + "database.dir";
static final String IDDB_FILENAME = "iddb.xml";
static final String IDDB_MAP_FILENAME = "idmapping.xml";
/* Reputation constants */
public static final int MAX_DELTA = 0;
public static final int AGREE_VOTE = 1;
public static final int DISAGREE_VOTE = 2;
public static final int CALL_INTERNAL = 3;
public static final int SPOOF_DETECTED = 4;
public static final int REPLAY_DETECTED = 5;
public static final int ATTACK_DETECTED = 6;
public static final int VOTE_NOTVERIFIED = 7;
public static final int VOTE_VERIFIED = 8;
public static final int VOTE_DISOWNED = 9;
static final int INITIAL_REPUTATION = 500;
static final int REPUTATION_NUMERATOR = 1000;
static Logger theLog = Logger.getLogger("IdentityManager");
static Random theRandom = new Random();
static String localIdentityStr = null;
int[] reputationDeltas = new int[10];
LcapIdentity theLocalIdentity = null;
Mapping mapping = null;
HashMap theIdentities = new HashMap(); // all known identities
public IdentityManager() { }
/**
* start the identity manager.
* @see org.lockss.app.LockssManager#startService()
*/
public void startService() {
super.startService();
reloadIdentities();
log.info("Local identity: " + getLocalIdentity());
getDaemon().getStatusService().registerStatusAccessor("Identities",
new Status());
}
/**
* stop the plugin manager
* @see org.lockss.app.LockssManager#stopService()
*/
public void stopService() {
try {
storeIdentities();
}
catch (ProtocolException ex) {
}
super.stopService();
}
/**
* public constructor for the creation of an Identity object
* from an address.
* @param addr the InetAddress
* @return a newly constructed Identity
*/
public LcapIdentity findIdentity(InetAddress addr) {
LcapIdentity ret;
if(addr == null) {
ret = getLocalIdentity();
}
else {
ret = getIdentity(LcapIdentity.makeIdKey(addr));
if(ret == null) {
ret = new LcapIdentity(addr);
theIdentities.put(ret.getIdKey(), ret);
}
}
return ret;
}
/**
* get and return an already created identity
* @param idKey the key for the identity we want to find
* @return the LcapIdentity or null
*/
public LcapIdentity getIdentity(Object idKey) {
return (LcapIdentity)theIdentities.get(idKey);
}
/**
* Get the Identity of the local host
* @return newly constructed <code>Identity<\code>
*/
public LcapIdentity getLocalIdentity() {
if (theLocalIdentity == null) {
try {
InetAddress addr = InetAddress.getByName(getLocalHostName());
theLocalIdentity = new LcapIdentity(addr);
} catch (UnknownHostException uhe) {
theLog.error("Could not resolve: "+localIdentityStr, uhe);
}
}
return theLocalIdentity;
}
/**
* Get the local host name
* @return hostname as a String
*/
public static String getLocalHostName() {
if (localIdentityStr == null) {
localIdentityStr = Configuration.getParam(PARAM_LOCAL_IP);
}
return localIdentityStr;
}
/**
* return true if this Identity is the same as the local host
* @param id the LcapIdentity
* @return boolean true if is the local identity, false otherwise
*/
public boolean isLocalIdentity(LcapIdentity id) {
if (theLocalIdentity == null) {
getLocalIdentity();
}
return id.isEqual(theLocalIdentity);
}
/**
* returns true if the InetAddress is the same as the InetAddress for our
* local host
* @param addr the address to check
* @return boolean true if the this is InetAddress is considered local
*/
public boolean isLocalIdentity(InetAddress addr) {
if (theLocalIdentity == null) {
getLocalIdentity();
}
return theLocalIdentity.m_address.equals(addr);
}
/**
* return the max value of an Identity's reputation
* @return the int value of max reputation
*/
public int getMaxReputaion() {
return REPUTATION_NUMERATOR;
}
public void changeReputation(LcapIdentity id, int changeKind) {
int delta = reputationDeltas[changeKind];
int max_delta = reputationDeltas[MAX_DELTA];
int reputation = id.getReputation();
if (id == theLocalIdentity) {
theLog.debug(id.getIdKey() + " ignoring reputation delta " + delta);
return;
}
delta = (int) (((float) delta) * theRandom.nextFloat());
if (delta > 0) {
if (delta > max_delta) {
delta = max_delta;
}
if (delta > (REPUTATION_NUMERATOR - reputation)) {
delta = (REPUTATION_NUMERATOR - reputation);
}
}
else if (delta < 0) {
if (delta < (-max_delta)) {
delta = -max_delta;
}
if ((reputation + delta) < 0) {
delta = -reputation;
}
}
if (delta != 0)
theLog.debug(id.getIdKey() +" change reputation from " + reputation +
" to " + (reputation + delta));
id.changeReputation(delta);
}
void reloadIdentities() {
try {
String iddbDir = Configuration.getParam(PARAM_IDDB_DIR);
if (iddbDir==null) {
theLog.warning("No value found for config parameter '" +
PARAM_IDDB_DIR+"'");
return;
}
String fn = iddbDir + File.separator + IDDB_FILENAME;
File iddbFile = new File(fn);
if((iddbFile != null) && iddbFile.canRead()) {
Unmarshaller unmarshaller = new Unmarshaller(IdentityListBean.class);
unmarshaller.setMapping(getMapping());
IdentityListBean idlb = (IdentityListBean)unmarshaller.unmarshal(
new FileReader(iddbFile));
setIdentities(idlb.getIdBeans());
}
else {
theLog.warning("Unable to read Identity file:" + fn);
}
} catch (Exception e) {
theLog.warning("Couldn't load identity database: " + e.getMessage());
}
}
void storeIdentities() throws ProtocolException {
try {
String fn = Configuration.getParam(PARAM_IDDB_DIR);
if (fn==null) {
theLog.warning("No value found for config parameter '" +
PARAM_IDDB_DIR+"'");
return;
}
File iddbDir = new File(fn);
if (!iddbDir.exists()) {
iddbDir.mkdirs();
}
File iddbFile = new File(iddbDir, IDDB_FILENAME);
if(!iddbFile.exists()) {
iddbFile.createNewFile();
}
if((iddbFile != null) && iddbFile.canWrite()) {
IdentityListBean idlb = getIdentityListBean();
Marshaller marshaller = new Marshaller(new FileWriter(iddbFile));
marshaller.setMapping(getMapping());
marshaller.marshal(idlb);
}
else {
throw new ProtocolException("Unable to store identity database.");
}
} catch (Exception e) {
theLog.error("Couldn't store identity database: ", e);
throw new ProtocolException("Unable to store identity database.");
}
}
IdentityListBean getIdentityListBean() {
synchronized(theIdentities) {
List beanList = new ArrayList(theIdentities.size());
Iterator mapIter = theIdentities.values().iterator();
while(mapIter.hasNext()) {
LcapIdentity id = (LcapIdentity) mapIter.next();
IdentityBean bean = new IdentityBean(id.getIdKey(),id.getReputation());
beanList.add(bean);
}
IdentityListBean listBean = new IdentityListBean(beanList);
return listBean;
}
}
void setIdentities(Collection idList) {
Iterator beanIter = idList.iterator();
synchronized(theIdentities) {
while (beanIter.hasNext()) {
IdentityBean bean = (IdentityBean)beanIter.next();
try {
LcapIdentity id = new LcapIdentity(bean.getKey(), bean.getReputation());
theIdentities.put(id.getIdKey(), id);
}
catch (UnknownHostException ex) {
theLog.warning("Error reloading identity-Unknown Host: " +
bean.getKey());
}
}
}
}
Mapping getMapping() {
if (mapping==null) {
URL mappingLoc = this.getClass().getResource(IDDB_MAP_FILENAME);
if (mappingLoc == null) {
theLog.error("Unable to find resource '"+IDDB_MAP_FILENAME+"'");
return null;
}
Mapping map = new Mapping();
try {
map.loadMapping(mappingLoc);
mapping = map;
} catch (Exception ex) {
theLog.error("Loading of mapfile failed:" + mappingLoc);
}
}
return mapping;
}
protected void setConfig(Configuration config, Configuration oldConfig,
Set changedKeys) {
reputationDeltas[MAX_DELTA] =
config.getInt(PARAM_MAX_DELTA, 100);
reputationDeltas[AGREE_VOTE] =
config.getInt(PARAM_AGREE_DELTA, 100);
reputationDeltas[DISAGREE_VOTE] =
config.getInt(PARAM_DISAGREE_DELTA, -150);
reputationDeltas[CALL_INTERNAL] =
config.getInt(PARAM_CALL_INTERNAL, 100);
reputationDeltas[SPOOF_DETECTED] =
config.getInt(PARAM_SPOOF_DETECTED, -30);
reputationDeltas[REPLAY_DETECTED] =
config.getInt(PARAM_REPLAY_DETECTED, -20);
reputationDeltas[ATTACK_DETECTED] =
config.getInt(PARAM_ATTACK_DETECTED, -500);
reputationDeltas[VOTE_NOTVERIFIED] =
config.getInt(PARAM_VOTE_NOTVERIFIED, -30);
reputationDeltas[VOTE_VERIFIED] =
config.getInt(PARAM_VOTE_VERIFIED, 40);
reputationDeltas[VOTE_DISOWNED] =
config.getInt(PARAM_VOTE_DISOWNED, -400);
}
private static final List statusSortRules =
ListUtil.list(new StatusTable.SortRule("ip", true));
private static final List statusColDescs =
ListUtil.list(
new ColumnDescriptor("ip", "IP",
ColumnDescriptor.TYPE_IP_ADDRESS),
new ColumnDescriptor("lastPkt", "Last Pkt",
ColumnDescriptor.TYPE_DATE,
"Last time a packet that originated " +
"at IP was received"),
new ColumnDescriptor("lastOp", "Last Op",
ColumnDescriptor.TYPE_DATE,
"Last time a non-NoOp packet that " +
"originated at IP was received"),
new ColumnDescriptor("origTot", "Orig Tot",
ColumnDescriptor.TYPE_INT,
"Total packets received that " +
"originated at IP."),
new ColumnDescriptor("origOp", "Orig Op",
ColumnDescriptor.TYPE_INT,
"Total non-noop packets received that "+
"originated at IP."),
new ColumnDescriptor("sendOrig", "1 Hop",
ColumnDescriptor.TYPE_INT,
"Packets arriving from originator " +
"in one hop."),
new ColumnDescriptor("sendFwd", "Fwd",
ColumnDescriptor.TYPE_INT,
"Packets forwarded by IP to us."),
new ColumnDescriptor("reputation", "Reputation",
ColumnDescriptor.TYPE_INT)
);
private class Status implements StatusAccessor {
public void populateTable(StatusTable table) {
String key = table.getKey();
table.setTitle("Cache Identities");
table.setColumnDescriptors(statusColDescs);
table.setDefaultSortRules(statusSortRules);
table.setRows(getRows(key));
// table.setSummaryInfo(getSummaryInfo(key));
}
public boolean requiresKey() {
return false;
}
private List getRows(String key) {
List table = new ArrayList();
for (Iterator iter = theIdentities.values().iterator();
iter.hasNext();) {
table.add(makeRow((LcapIdentity)iter.next()));
}
return table;
}
private Map makeRow(LcapIdentity id) {
Map row = new HashMap();
InetAddress ip = id.getAddress();
Object obj = ip;
if (isLocalIdentity(ip)) {
StatusTable.DisplayedValue val =
new StatusTable.DisplayedValue(ip);
val.setBold(true);
obj = val;
}
row.put("ip", obj);
row.put("lastPkt", new Long(id.getLastActiveTime()));
row.put("lastOp", new Long(id.getLastOpTime()));
row.put("origTot", new Long(id.getEventCount(LcapIdentity.EVENT_ORIG)));
row.put("origOp",
new Long(id.getEventCount(LcapIdentity.EVENT_ORIG_OP)));
row.put("sendOrig",
new Long(id.getEventCount(LcapIdentity.EVENT_SEND_ORIG)));
row.put("sendFwd",
new Long(id.getEventCount(LcapIdentity.EVENT_SEND_FWD)));
// row.put("dupl", new Long(id.getEventCount(LcapIdentity.EVENT_DUPL)));
row.put("reputation", new Long(id.getReputation()));
return row;
}
private List getSummaryInfo(String key) {
List res = new ArrayList();
// res.add(new StatusTable.SummaryInfo("Total bytes hashed",
// ColumnDescriptor.TYPE_INT,
// new Integer(0)));
return res;
}
}
}
|
package org.opencms.i18n;
import java.util.Locale;
/**
* Convenience base class to access the localized messages of an OpenCms package.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
* @since 5.7.3
*/
public abstract class A_CmsMessageBundle implements I_CmsMessageBundle {
/**
* Returns an array of all messages bundles used by the OpenCms core.<p>
*
* @return an array of all messages bundles used by the OpenCms core
*/
public static I_CmsMessageBundle[] getOpenCmsMessageBundles() {
return new I_CmsMessageBundle[] {
org.opencms.cache.Messages.get(),
org.opencms.configuration.Messages.get(),
org.opencms.db.Messages.get(),
org.opencms.file.collectors.Messages.get(),
org.opencms.flex.Messages.get(),
org.opencms.importexport.Messages.get(),
org.opencms.jsp.Messages.get(),
org.opencms.jsp.layout.Messages.get(),
org.opencms.loader.Messages.get(),
org.opencms.lock.Messages.get(),
org.opencms.mail.Messages.get(),
org.opencms.main.Messages.get(),
org.opencms.module.Messages.get(),
org.opencms.monitor.Messages.get(),
org.opencms.scheduler.Messages.get(),
org.opencms.search.Messages.get(),
org.opencms.search.documents.Messages.get(),
org.opencms.security.Messages.get(),
org.opencms.setup.Messages.get(),
org.opencms.site.Messages.get(),
org.opencms.staticexport.Messages.get(),
org.opencms.synchronize.Messages.get(),
org.opencms.threads.Messages.get(),
org.opencms.util.Messages.get(),
org.opencms.validation.Messages.get(),
org.opencms.workflow.Messages.get(),
org.opencms.workplace.list.Messages.get(),
org.opencms.workplace.tools.Messages.get(),
org.opencms.workplace.administration.Messages.get(),
org.opencms.xml.Messages.get()};
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#container(java.lang.String)
*/
public CmsMessageContainer container(String key) {
return container(key, null);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#container(java.lang.String, java.lang.Object)
*/
public CmsMessageContainer container(String key, Object arg0) {
return container(key, new Object[] {arg0});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#container(java.lang.String, java.lang.Object, java.lang.Object)
*/
public CmsMessageContainer container(String key, Object arg0, Object arg1) {
return container(key, new Object[] {arg0, arg1});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#container(java.lang.String, java.lang.Object, java.lang.Object, java.lang.Object)
*/
public CmsMessageContainer container(String key, Object arg0, Object arg1, Object arg2) {
return container(key, new Object[] {arg0, arg1, arg2});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#container(java.lang.String, java.lang.Object[])
*/
public CmsMessageContainer container(String message, Object[] args) {
return new CmsMessageContainer(this, message, args);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#getBundle()
*/
public CmsMessages getBundle() {
Locale locale = CmsLocaleManager.getDefaultLocale();
if (locale == null) {
locale = Locale.getDefault();
}
return getBundle(locale);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#getBundle(java.util.Locale)
*/
public CmsMessages getBundle(Locale locale) {
return new CmsMessages(getBundleName(), locale);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.util.Locale, java.lang.String, java.lang.Object[])
*/
public String key(Locale locale, String key, Object[] args) {
return getBundle(locale).key(key, args);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.lang.String)
*/
public String key(String key) {
return key(key, null);
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.lang.String, java.lang.Object)
*/
public String key(String key, Object arg0) {
return key(key, new Object[] {arg0});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.lang.String, java.lang.Object, java.lang.Object)
*/
public String key(String key, Object arg0, Object arg1) {
return key(key, new Object[] {arg0, arg1});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.lang.String, java.lang.Object, java.lang.Object, java.lang.Object)
*/
public String key(String key, Object arg0, Object arg1, Object arg2) {
return key(key, new Object[] {arg0, arg1, arg2});
}
/**
* @see org.opencms.i18n.I_CmsMessageBundle#key(java.lang.String, java.lang.Object[])
*/
public String key(String key, Object[] args) {
return getBundle().key(key, args);
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer result = new StringBuffer();
result.append('[');
result.append(this.getClass().getName());
result.append(", bundle: ");
result.append(getBundle());
result.append(']');
return result.toString();
}
}
|
package org.openid4java.message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.OpenIDException;
import java.util.List;
import java.util.Arrays;
/**
* @author Marius Scurtescu, Johnny Bufu
*/
public class DirectError extends Message
{
private static Log _log = LogFactory.getLog(DirectError.class);
private static final boolean DEBUG = _log.isDebugEnabled();
protected final static List requiredFields = Arrays.asList( new String[] {
"error"
});
protected final static List optionalFields = Arrays.asList( new String[] {
"ns",
"contact",
"reference"
});
// exception that generated the error, if any
private OpenIDException _exception;
protected DirectError(String msg)
{
this(msg, false);
}
protected DirectError(String msg, boolean compatibility)
{
this(null, msg, compatibility);
}
protected DirectError(OpenIDException e, boolean compatibility)
{
this(e, e.getMessage(), compatibility);
}
protected DirectError(OpenIDException e, String msg, boolean compatibility)
{
set("error", msg);
_exception = e;
if ( ! compatibility )
set("ns", OPENID2_NS);
}
protected DirectError(ParameterList params)
{
super(params);
}
public static DirectError createDirectError(OpenIDException e)
{
return createDirectError(e, false);
}
public static DirectError createDirectError(String msg)
{
return createDirectError(null, msg, false);
}
public static DirectError createDirectError(String msg, boolean compatibility)
{
return createDirectError(null, msg, compatibility);
}
public static DirectError createDirectError(OpenIDException e, boolean compatibility)
{
return createDirectError(e, e.getMessage(), compatibility);
}
public static DirectError createDirectError(OpenIDException e, String msg, boolean compatibility)
{
DirectError err = new DirectError(e, msg, compatibility);
try
{
err.validate();
}
catch (MessageException ex)
{
_log.error("Invalid " + (compatibility? "OpenID1" : "OpenID2") +
" direct error message created for message: " + msg);
}
_log.debug("Created direct error message:\n" + err.keyValueFormEncoding());
return err;
}
public static DirectError createDirectError(ParameterList params)
{
DirectError err = new DirectError(params);
try
{
err.validate();
}
catch (MessageException e)
{
_log.error("Invalid direct error message created: "
+ err.keyValueFormEncoding() );
}
_log.debug("Created direct error message:\n" + err.keyValueFormEncoding());
return err;
}
public OpenIDException getException()
{
return _exception;
}
public void setException(OpenIDException e)
{
this._exception = e;
}
public List getRequiredFields()
{
return requiredFields;
}
public boolean isVersion2()
{
return hasParameter("ns") &&
OPENID2_NS.equals(getParameterValue("ns"));
}
public void setErrorMsg(String msg)
{
set("error", msg);
}
public String getErrorMsg()
{
return getParameterValue("error");
}
public void setContact(String contact)
{
set("contact", contact);
}
public void setReference(String reference)
{
set("reference", reference);
}
}
|
package org.pentaho.di.shared;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.cluster.ClusterSchema;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.trans.step.StepMeta;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Based on a piece of XML, this factory will give back a list of objects.
* In other words, it does XML de-serialisation
*
* @author Matt
*
*/
public class SharedObjects
{
private static final String XML_TAG = "sharedobjects";
private String filename;
private Map<SharedEntry, SharedObjectInterface> objectsMap;
private class SharedEntry
{
public String className;
public String objectName;
/**
* @param className
* @param objectName
*/
public SharedEntry(String className, String objectName)
{
this.className = className;
this.objectName = objectName;
}
public boolean equals(Object obj)
{
SharedEntry sharedEntry = (SharedEntry) obj;
return className.equals(sharedEntry.className) && objectName.equals(objectName);
}
public int hashCode()
{
return className.hashCode() ^ objectName.hashCode();
}
}
public SharedObjects(String sharedObjectsFile) throws KettleXMLException
{
try
{
this.filename = createFilename(sharedObjectsFile);
this.objectsMap = new Hashtable<SharedEntry, SharedObjectInterface>();
// Extra information
FileObject file = KettleVFS.getFileObject(filename);
// If we have a shared file, load the content, otherwise, just keep this one empty
if (file.exists())
{
LogWriter.getInstance().logDetailed(Messages.getString("SharedOjects.ReadingFile.Title"), Messages.getString("SharedOjects.ReadingFile.Message",""+file));
Document document = XMLHandler.loadXMLFile(file);
Node sharedObjectsNode = XMLHandler.getSubNode(document, XML_TAG);
if (sharedObjectsNode!=null)
{
List<SlaveServer> privateSlaveServers = new ArrayList<SlaveServer>();
List<DatabaseMeta> privateDatabases = new ArrayList<DatabaseMeta>();
NodeList childNodes = sharedObjectsNode.getChildNodes();
// First load databases & slaves
for (int i=0;i<childNodes.getLength();i++)
{
Node node = childNodes.item(i);
String nodeName = node.getNodeName();
SharedObjectInterface isShared = null;
if (nodeName.equals(DatabaseMeta.XML_TAG))
{
DatabaseMeta sharedDatabaseMeta = new DatabaseMeta(node);
isShared = sharedDatabaseMeta;
privateDatabases.add(sharedDatabaseMeta);
}
else if (nodeName.equals(SlaveServer.XML_TAG))
{
SlaveServer sharedSlaveServer = new SlaveServer(node);
isShared = sharedSlaveServer;
privateSlaveServers.add(sharedSlaveServer);
}
if (isShared!=null)
{
isShared.setShared(true);
storeObject(isShared);
}
}
// Then load the other objects that might reference databases & slaves
for (int i=0;i<childNodes.getLength();i++)
{
Node node = childNodes.item(i);
String nodeName = node.getNodeName();
SharedObjectInterface isShared = null;
if (nodeName.equals(StepMeta.XML_TAG))
{
StepMeta stepMeta = new StepMeta(node, privateDatabases, null);
stepMeta.setDraw(false); // don't draw it, keep it in the tree.
isShared = stepMeta;
}
else if (nodeName.equals(PartitionSchema.XML_TAG))
{
isShared = new PartitionSchema(node);
}
else if (nodeName.equals(ClusterSchema.XML_TAG))
{
isShared = new ClusterSchema(node, privateSlaveServers);
}
if (isShared!=null)
{
isShared.setShared(true);
storeObject(isShared);
}
}
}
}
}
catch(Exception e)
{
throw new KettleXMLException(Messages.getString("SharedOjects.Readingfile.UnexpectedError", sharedObjectsFile), e);
}
}
public static final String createFilename(String sharedObjectsFile)
{
String filename;
if (Const.isEmpty(sharedObjectsFile))
{
// First fallback is the environment/kettle variable ${KETTLE_SHARED_OBJECTS}
// This points to the file
filename = Variables.getADefaultVariableSpace().getVariable("KETTLE_SHARED_OBJECTS");
// Last line of defence...
if (Const.isEmpty(filename))
{
filename = Const.getSharedObjectsFile();
}
}
else
{
filename = sharedObjectsFile;
}
return filename;
}
public SharedObjects() throws KettleXMLException
{
this(null);
}
public Map<SharedEntry, SharedObjectInterface> getObjectsMap()
{
return objectsMap;
}
public void setObjectsMap(Map<SharedEntry, SharedObjectInterface> objects)
{
this.objectsMap = objects;
}
/**
* Store the sharedObject in the object map.
* It is possible to have 2 different types of shared object with the same name.
* They will be stored separately.
*
* @param sharedObject
*/
public void storeObject(SharedObjectInterface sharedObject)
{
SharedEntry key = new SharedEntry(sharedObject.getClass().getName(), sharedObject.getName());
objectsMap.put(key, sharedObject);
}
public void saveToFile() throws IOException
{
OutputStream outputStream = KettleVFS.getOutputStream(filename, false);
PrintStream out = new PrintStream(outputStream);
out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));
out.println("<"+XML_TAG+">");
Collection<SharedObjectInterface> collection = objectsMap.values();
for (SharedObjectInterface sharedObject : collection)
{
out.println(sharedObject.getXML());
}
out.println("</"+XML_TAG+">");
out.flush();
out.close();
outputStream.close();
}
/**
* @return the filename
*/
public String getFilename() {
return filename;
}
/**
* @param filename the filename to set
*/
public void setFilename(String filename) {
this.filename = filename;
}
}
|
package org.usfirst.frc.team166.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team166.robot.commands.Autonomous.CenterGearAutonomous;
import org.usfirst.frc.team166.robot.commands.GearManipulator.ToggleGearManip;
import org.usfirst.frc.team166.robot.commands.Shooter.RunShooter;
import org.usfirst.frc.team166.robot.subsystems.Climber;
import org.usfirst.frc.team166.robot.subsystems.Drive;
import org.usfirst.frc.team166.robot.subsystems.Elevator;
import org.usfirst.frc.team166.robot.subsystems.GearManipulator;
import org.usfirst.frc.team166.robot.subsystems.Intake;
import org.usfirst.frc.team166.robot.subsystems.Shooter;
import org.usfirst.frc.team166.robot.subsystems.Storage;
import org.usfirst.frc.team166.robot.subsystems.Vision;
import org.usfirst.frc.team166.robot.subsystems.XboxLeftTrigger;
import org.usfirst.frc.team166.robot.subsystems.XboxRightTrigger;
/**
* The VM is configured to automatically run this class, and to call the functions corresponding to each mode, as
* described in the IterativeRobot documentation. If you change the name of this class or the package after creating
* this project, you must also update the manifest file in the resource directory.
*/
public class Robot extends IterativeRobot {
public static final Drive drive = new Drive();
public static final GearManipulator gearManipulator = new GearManipulator();
public static final Intake intake = new Intake();
public static final Shooter shooter = new Shooter();
public static final Storage storage = new Storage();
public static final Climber climber = new Climber();
public static final Elevator elevator = new Elevator();
public static final Vision vision = new Vision();
public static OI oi;
private XboxLeftTrigger xboxLeftTrigger = new XboxLeftTrigger();
private XboxRightTrigger xboxRightTrigger = new XboxRightTrigger();
Command autonomousCommand;
SendableChooser<Command> chooser = new SendableChooser<>();
/**
* This function is run when the robot is first started up and should be used for any initialization code.
*/
@Override
public void robotInit() {
Robot.gearManipulator.close();
oi = new OI();
chooser.addObject("Center Gear Auto", new CenterGearAutonomous());
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto Mode", chooser);
// SmartDashboard.putData(drive);
xboxLeftTrigger.whenActive(new ToggleGearManip());
xboxRightTrigger.whenActive(new RunShooter());
}
/**
* This function is called once each time the robot enters Disabled mode. You can use it to reset any subsystem
* information you want to clear when the robot is disabled.
*/
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes using
* the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard,
* remove all of the chooser code and uncomment the getString code to get the auto name from the text box below the
* Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented
* example) or additional comparisons to the switch structure below with additional strings & commands.
*/
@Override
public void autonomousInit() {
autonomousCommand = chooser.getSelected();
/*
* String autoSelected = SmartDashboard.getString("Auto Selector", "Default"); switch(autoSelected) { case
* "My Auto": autonomousCommand = new MyAutoCommand(); break; case "Default Auto": default: autonomousCommand =
* new ExampleCommand(); break; }
*/
// schedule the autonomous command (example)
if (autonomousCommand != null)
autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
@Override
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
@Override
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null)
autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
@Override
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
@Override
public void testPeriodic() {
LiveWindow.run();
}
}
|
package picoded.junit;
// Junit includes
import static org.junit.Assert.*;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runner.notification.Failure;
/// Single JUnit test case runner
/// Processes all argument, which splits along #, for class, followed by function. This is actually used by runTest.sh
/// # Example
/// `./runTest.sh package.namespace.classname#testFunction`
public class SingleJUnitTestRunner {
/// System out print ln handling
private static void println(String in) {
// Note: this is intentionally not using logger, to ensure same output format with JUnit.
System.out.println(in);
}
/// Calls a method name in a test class
/// @param Class name to run test
/// @param Method/Function name to run test
/// @return Number of successful test cases ( 1 ) or failure ( -1 )
public static int runTestMethod(String className, String methodName) {
try {
// Note: Dynamic loading of class is intentional. Exempted from vulnerability check.
Request request = Request.method(Class.forName(className), methodName);
Result result = new JUnitCore().run(request);
// This is following the standard JUnit output format
println("Total Time: " + ((result.getRunTime()) / 1000.0F));
println("");
if (result.wasSuccessful()) {
println("OK (" + result.getRunCount() + " tests)");
println("");
return result.getRunCount();
} else {
println("FAIL (" + result.getRunCount() + " tests)");
println("");
println("There was " + result.getFailureCount() + " failure:");
Failure fail = result.getFailures().get(0);
println("1) " + fail.getTestHeader());
println(fail.getTrace());
return -result.getFailureCount();
}
} catch(ClassNotFoundException e) {
throw new IllegalArgumentException("Class not found for : "+className, e);
}
}
/// Calls a method name in a test class
/// @param ClassName#MethodName format string
/// @return Number of successful test cases ( 1 ) or failure ( -1 )
public static int runTestMethod(String classAndMethod) {
String[] formatPair = classAndMethod.split("
if(formatPair.length != 2) {
throw new IllegalArgumentException("Unknown class and method format : "+formatPair);
}
return runTestMethod(formatPair[0],formatPair[1]);
}
/// The main command line test runner, see example in class above
/// @param Arguments of class#method name pairs
public static void main(String... args) {
for(String pair : args) {
runTestMethod(pair);
}
}
/// Used internally to help provide code coverage testing of failure conditons. Do not use
/// Note: Intentionally breaking convention, to indicate with an _underscore, that this *should not be used*.
@Test
public void _thisAssertsFailure() {
assertTrue(false);
}
}
|
package pigeon.view;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import pigeon.model.ValidationException;
/**
@author pauldoo
*/
public class MultipleCheckBoxesPanel<T extends Comparable<T>> extends javax.swing.JPanel {
private static final long serialVersionUID = 4428293282361765217L;
public static interface Creator<T> {
public T createFromString(String value) throws ValidationException;
public String friendlyName();
}
private final Map<T, JCheckBox> checkBoxes;
private final Creator<T> creator;
/**
Creates new form MultiSelectionComboBoxesPanel
*/
public MultipleCheckBoxesPanel(SortedSet<T> available, Set<T> selected, Creator<T> creator) {
initComponents();
this.addButton.setText(addButton.getText() + " " + creator.friendlyName());
this.creator = creator;
checkBoxes = new HashMap<T, JCheckBox>();
for (T t: available) {
JCheckBox box = addSingleCheckBox(t);
box.setSelected(selected.contains(t));
}
}
private JCheckBox addSingleCheckBox(T t) {
JCheckBox box = new JCheckBox(t.toString());
checkBoxes.put(t, box);
checkBoxPanel.add(box);
// TODO: Repainting needed for WinXP + Java 1.7.0_05 (others too?)
checkBoxPanel.revalidate();
return box;
}
/**
This method is called from within the constructor to initialize the form.
WARNING: Do NOT modify this code. The content of this method is always
regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
addButton = new javax.swing.JButton();
checkBoxPanel = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
addButton.setText("Add");
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
add(addButton, java.awt.BorderLayout.SOUTH);
checkBoxPanel.setLayout(new javax.swing.BoxLayout(checkBoxPanel, javax.swing.BoxLayout.Y_AXIS));
add(checkBoxPanel, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
final String friendlyName = creator.friendlyName();
final String message = String.format("Name for %s", friendlyName);
final String title = String.format("Add %s", friendlyName);
String valueAsString = JOptionPane.showInputDialog(this, message, title, JOptionPane.QUESTION_MESSAGE,null,null, "").toString();
if (valueAsString != null) {
try {
T newValue = creator.createFromString(valueAsString);
if (checkBoxes.containsKey(newValue) == false) {
addSingleCheckBox(newValue);
}
checkBoxes.get(newValue).setSelected(true);
} catch (ValidationException e) {
e.displayErrorDialog(this);
}
}
}//GEN-LAST:event_addButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JPanel checkBoxPanel;
// End of variables declaration//GEN-END:variables
public Set<T> getSelected() {
Set<T> result = new HashSet<T>();
for (Map.Entry<T, JCheckBox> pair: checkBoxes.entrySet()) {
if (pair.getValue().isSelected()) {
result.add(pair.getKey());
}
}
return Collections.unmodifiableSet(result);
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello-world", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
/* Testing DB with recording of "ticks" */
get("/", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
get("/общественная-приемная", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "mp-public-reception.ftl");
}, new FreeMarkerEngine());
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> "Hello World");
get("/ucsb", (req, res) -> "Go Gauchos!");
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import static spark.Spark.*;
import static spark.Spark.get;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import com.heroku.sdk.jdbc.DatabaseUrl;
import java.util.List;
import workshop4.Controller.SizeController;
import workshop4.Model.SizeInfo;
import workshop4.Model.SizeRange;
import static spark.Spark.get;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
/**
*Calculates and Displays Size
*/
get("/calculateSize", (req, res) -> {
SizeController controller = new SizeController();
//Test Case 1
List<SizeInfo> data1;
SizeRange result1 = new SizeRange();
data1 = controller.loadClassInfo("List1.txt");
String htmlData = "Test Case # 1<br><br>"; //Title
htmlData += "<div style=\"display: inline-flex\">";
htmlData += "<table style=\"border: 1px solid; border-collapse: collapse; text-align: center\">"; //Open Table
htmlData += "<tr><th style=\"border: 1px solid; width: 150px;\">Class Name</th><th style=\"border: 1px solid; width: 60px;\">LOC</th><th style=\"border: 1px solid; width: 60px;\">Items</th></tr>"; //Header
for(SizeInfo classData : data1)
{
htmlData += String.format("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", classData.getClassName(), classData.getLoc(), classData.getNumberOfMethods());
}
htmlData += "</table><br>"; //Close Table
result1 = controller.calculateSizeRange(data1);
htmlData += String.format("<p style=\"float:left; margin-left: 20px\">Very Small = %.5g%n LOCs/Method<br>Small = %.5g%n LOCs/Method<br>Medium = %.4g%n LOCs/Method<br>Large = %.4g%n LOCs/Method<br>Very Large = %.4g%n LOCs/Method<br></p>", result1.getVerySmall(), result1.getSmall(), result1.getMedium(), result1.getLarge(), result1.getVeryLarge());
htmlData += "</div><br><br><br>";
//Test Case 2
List<SizeInfo> data2;
SizeRange result2 = new SizeRange();
data2 = controller.loadClassInfo("List2.txt");
htmlData += "Test Case # 2<br><br>"; //Title
htmlData += "<div style=\"display: inline-flex\">";
htmlData += "<table style=\"border: 1px solid; border-collapse: collapse; text-align: center\">"; //Open Table
htmlData += "<tr><th style=\"border: 1px solid; width: 120px;\">Chapter</th><th style=\"border: 1px solid; width: 60px;\">Pages</th><th style=\"border: 1px solid; width: 60px;\">Items</th></tr>"; //Header
for(SizeInfo chapterData : data2)
{
htmlData += String.format("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", chapterData.getClassName(), chapterData.getLoc(), chapterData.getNumberOfMethods());
}
htmlData += "</table><br>"; //Close Table
result2 = controller.calculateSizeRange(data2);
htmlData += String.format("<p style=\"float:left; margin-left: 20px\">Very Small = %.5g%n Pages/Chapter<br>Small = %.5g%n Pages/Chapter<br>Medium = %.4g%n Pages/Chapter<br>Large = %.4g%n Pages/Chapter<br>Very Large = %.4g%n Pages/Chapter<br></p>", result2.getVerySmall(), result2.getSmall(), result2.getMedium(), result2.getLarge(), result2.getVeryLarge());
htmlData += "</div><br><br>";
return htmlData;
});
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Properties;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import sun.misc.BASE64Encoder;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURI().endsWith("/proximo")) {
showProximo(req,resp);
} else if (req.getRequestURI().endsWith("/fixie")) {
showFixie(req,resp);
} else if (req.getRequestURI().endsWith("/quotaguard")) {
showFixie(req,resp);
} else {
resp.getWriter().print("<p><a href='/proximo'>Proximo</a></p>");
resp.getWriter().print("<p><a href='/fixie'>Fixie</a></p>");
resp.getWriter().print("<p><a href='/quotaguard'>QuotaGuard</a></p>");
}
}
private void showProximo(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String urlStr = "http://httpbin.org/ip";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(urlStr);
CloseableHttpResponse response = httpClient.execute(request);
try {
resp.getWriter().print("Hello from Java! " + handleResponse(response));
} catch (Exception e) {
resp.getWriter().print(e.getMessage());
}
}
private void showFixie(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
URL proximo = new URL(System.getenv("FIXIE_URL"));
String userInfo = proximo.getUserInfo();
String user = userInfo.substring(0, userInfo.indexOf(':'));
String password = userInfo.substring(userInfo.indexOf(':') + 1);
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// HttpHost proxy = new HttpHost(System.getenv("FIXIE_URL"), 80, "http");
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proximo.getHost(), 80),
new UsernamePasswordCredentials(user, password));
HttpHost proxy = new HttpHost(proximo.getHost(), 80);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
String encodedAuth = new BASE64Encoder().encode(userInfo).getBytes());
HttpHost target = new HttpHost(proximo.getHost(), 80, "http");
HttpGet req = new HttpGet("/ip");
req.setHeader("Host", "httpbin.org");
req.setHeader("Proxy-Authorization", "Basic " + encodedAuth);
System.out.println("executing request to " + target + " via "
+ proxy);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
resp.getWriter().print("Hello from Java! ");
}
private static String handleResponse(CloseableHttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
return readStream(entity.getContent());
}
private static String readStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String output = "";
String tmp = reader.readLine();
while (tmp != null) {
output += tmp;
tmp = reader.readLine();
}
return output;
}
public static void main(String[] args) throws Exception{
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Goodbye world");
try {
// mainThread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// URL proximo = new URL(System.getenv("FIXIE_URL"));
// String userInfo = proximo.getUserInfo();
// String user = userInfo.substring(0, userInfo.indexOf(':'));
// String password = userInfo.substring(userInfo.indexOf(':') + 1);
// System.setProperty("socksProxyHost", proximo.getHost());
// Authenticator.setDefault(new ProxyAuthenticator(user, password));
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
import java.util.List;
import java.util.ArrayList;
import org.sql2o.*;
public class User {
private int id;
private String user_name;
private int score = 0;
//CONSTRUCTOR//
public User(String user_name) {
this.user_name = user_name;
}
//GETTERS//
public String getUserName() {
return user_name;
}
public int getId() {
return id;
}
// public Timestamp getRightNow() {
// Date date = new Date();
// long time = date.getTime();
// Timestamp right_now = new Timestamp(time);
// return right_now;
@Override
public boolean equals(Object otherUser){
if (!(otherUser instanceof User)) {
return false;
} else {
User newUser = (User) otherUser;
return this.getUserName().equals(newUser.getUserName());
}
}
//CREATE//
public void save() {
try(Connection con = DB.sql2o.open()) {
String sql = "INSERT INTO users(user_name) VALUES (:user_name)";
this.id = (int) con.createQuery(sql,true)
.addParameter("user_name", this.user_name)
.executeUpdate()
.getKey();
}
}
//READ//
public static List<User> all() {
String sql = "SELECT id, user_name FROM users";
try(Connection con = DB.sql2o.open()) {
return con.createQuery(sql)
.executeAndFetch(User.class);
}
}
public static User find(int id) {
try(Connection con = DB.sql2o.open()) {
String sql = "SELECT * FROM Users where id=:id";
User user = con.createQuery(sql)
.addParameter("id", id)
.executeAndFetchFirst(User.class);
return user;
}
}
public List<Restaurant> getRestaurants() {
String sql = "SELECT restaurants.* FROM users JOIN check_ins ON (users.id = check_ins.user_id) JOIN restaurants ON (check_ins.restaurant_id = restaurants.id) WHERE users.id = :user_id";
try(Connection con = DB.sql2o.open()) {
return con.createQuery(sql)
.addParameter("user_id", id)
.executeAndFetch(Restaurant.class);
}
}
//UPDATE//
public void update(String newUserName) {
this.user_name = newUserName;
String sql = "UPDATE users SET user_name = :newUserName WHERE id=:id";
try(Connection con = DB.sql2o.open()) {
con.createQuery(sql)
.addParameter("newUserName", newUserName)
.addParameter("id", this.id)
.executeUpdate();
}
}
public void addRestaurant(Restaurant restaurant) {
try(Connection con = DB.sql2o.open()) {
String sql = "INSERT INTO check_ins (restaurant_id, user_id) VALUES (:restaurant_id, :user_id)";
con.createQuery(sql)
.addParameter("restaurant_id", restaurant.getId())
.addParameter("user_id", this.getId())
.executeUpdate();
}
}
public void assignRestaurant(int restaurant_id) {
restaurant_id = restaurant_id;
String sql = "UPDATE check_ins SET restaurant_id = :restaurant_id WHERE user_id=:user_id";
try(Connection con = DB.sql2o.open()) {
con.createQuery(sql)
.addParameter("restaurant_id", restaurant_id)
.addParameter("id", this.id)
.executeUpdate();
}
}
//DESTROY//
public void delete() {
try(Connection con = DB.sql2o.open()) {
String sql = "DELETE FROM users WHERE id = :id;";
con.createQuery(sql)
.addParameter("id", id)
.executeUpdate();
String check_insQuery = "DELETE FROM check_ins WHERE user_id = :userId";
con.createQuery(check_insQuery)
.addParameter("userId", this.getId())
.executeUpdate();
}
}
}
|
package controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import models.World;
import play.jobs.Job;
import play.mvc.Controller;
public class Application extends Controller {
private static final int TEST_DATABASE_ROWS = 10000;
// FIXME: should this test be consistent - ie set seed or not?
private static Random random = new Random();
public static void index() {
render();
}
public static void json() {
Map<String, String> result = new HashMap<String, String>();
result.put("message", "Hello, World!");
renderJSON(result);
}
public static void setup() {
//JPAPlugin plugin = play.Play.plugin(JPAPlugin.class);
//plugin.startTx(true);
World w = new World() ;
w.getPersistenceManager().beginTransaction();
// clean out the old
World.deleteAll();
System.out.println("DELETED");
// in with the new
List<World> worlds = new ArrayList<World>() ;
for (long i = 0; i <= TEST_DATABASE_ROWS; i++) {
int randomNumber = random.nextInt(TEST_DATABASE_ROWS) + 1;
worlds.add(new World(i, randomNumber));
if (i % 100 == 0) {
World.batch().insert(worlds) ;
System.out.println("FLUSHED : " + i + "/" + TEST_DATABASE_ROWS);
worlds.clear() ;
}
}
System.out.println("ADDED");
//plugin.closeTx(false);
w.getPersistenceManager().commitTransaction();
}
public static void db(int queries) throws InterruptedException,
ExecutionException {
if (queries == 0)
queries = 1;
final int queryCount = queries;
final List<World> worlds = new ArrayList<World>();
Job<List<World>> job = new Job<List<World>>() {
public java.util.List<World> doJobWithResult() throws Exception {
for (int i = 0; i < queryCount; ++i) {
Long id = Long
.valueOf(random.nextInt(TEST_DATABASE_ROWS) + 1);
World result = World.findById(id);
worlds.add(result);
}
return worlds;
};
};
List<World> result = job.now().get();
renderJSON(result);
}
public static void dbSync(int queries) {
if (queries == 0)
queries = 1;
final List<World> worlds = new ArrayList<World>();
for (int i = 0; i < queries; ++i) {
Long id = Long.valueOf(random.nextInt(TEST_DATABASE_ROWS) + 1);
World result = World.findById(id);
worlds.add(result);
}
renderJSON(worlds);
}
}
|
package net.commotionwireless.olsrinfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.commotionwireless.olsrinfo.datatypes.Config;
import net.commotionwireless.olsrinfo.datatypes.Gateway;
import net.commotionwireless.olsrinfo.datatypes.HNA;
import net.commotionwireless.olsrinfo.datatypes.Interface;
import net.commotionwireless.olsrinfo.datatypes.Link;
import net.commotionwireless.olsrinfo.datatypes.MID;
import net.commotionwireless.olsrinfo.datatypes.Neighbor;
import net.commotionwireless.olsrinfo.datatypes.Node;
import net.commotionwireless.olsrinfo.datatypes.OlsrDataDump;
import net.commotionwireless.olsrinfo.datatypes.Plugin;
import net.commotionwireless.olsrinfo.datatypes.Route;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonInfo {
String host = "127.0.0.1";
int port = 9090;
ObjectMapper mapper = null;
public JsonInfo() {
}
public JsonInfo(String sethost) {
host = sethost;
}
public JsonInfo(String sethost, int setport) {
host = sethost;
port = setport;
}
/**
* Request a reply from the jsoninfo plugin via a network socket.
*
* @param The command to query jsoninfo with
* @return A String array of the result, line-by-line
* @throws IOException when it cannot get a result.
*/
String[] request(String req) throws IOException {
Socket sock = null;
BufferedReader in = null;
PrintWriter out = null;
List<String> retlist = new ArrayList<String>();
try {
sock = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()), 8192);
out = new PrintWriter(sock.getOutputStream(), true);
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + host);
return new String[0];
} catch (IOException e) {
System.err.println("Couldn't get I/O for socket to " + host + ":"
+ Integer.toString(port));
return new String[0];
}
out.println(req);
String line;
while ((line = in.readLine()) != null) {
if (!line.equals(""))
retlist.add(line);
}
// the jsoninfo plugin drops the connection once it outputs
out.close();
in.close();
sock.close();
return retlist.toArray(new String[retlist.size()]);
}
/**
* Send a command to the jsoninfo plugin.
*
* @param The command to query jsoninfo with
* @return The complete JSON from jsoninfo as single String
*/
String command(String cmd) {
String[] data = null;
String ret = "";
final Set<String> supportedCommands = new HashSet<String>(
Arrays.asList(new String[] {
// combined reports
"/all", // all of the JSON info
"/runtime", // all of the runtime status reports
"/startup", // all of the startup config reports
// individual runtime reports
"/gateways", // gateways
"/hna", // Host and Network Association
"/interfaces", // network interfaces
"/links", // links
"/mid", // MID
"/neighbors", // neighbors
"/routes", // routes
"/topology", // mesh network topology
"/runtime", // all of the runtime info in a single
// report
// the following don't change during runtime, so they
// are separate
"/config", // the current running config info
"/plugins", // loaded plugins and their config
// the only non-JSON output, and can't be combined with
// the others
"/olsrd.conf", // current config info in olsrd.conf file
// format
}));
if (!supportedCommands.contains(cmd))
System.out.println("Unsupported command: " + cmd);
try {
data = request(cmd);
} catch (IOException e) {
System.err.println("Couldn't get I/O for socket to " + host + ":"
+ Integer.toString(port));
}
for (String s : data) {
ret += s + "\n";
}
return ret;
}
/**
* Query the jsoninfo plugin over a network socket and return the results
* parsed into Java objects.
*
* @param The command to query jsoninfo with
* @return The complete JSON reply parsed into Java objects.
*/
public OlsrDataDump parseCommand(String cmd) {
if (mapper == null)
mapper = new ObjectMapper();
OlsrDataDump ret = new OlsrDataDump();
try {
String dump = command(cmd);
if (! dump.contentEquals(""))
ret = mapper.readValue(dump, OlsrDataDump.class);
ret.setRaw(dump);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// change nulls to blank objects so you can use this result in a for()
if (ret.config == null)
ret.config = new Config();
if (ret.gateways == null)
ret.gateways = Collections.emptyList();
if (ret.hna == null)
ret.hna = Collections.emptyList();
if (ret.interfaces == null)
ret.interfaces = Collections.emptyList();
if (ret.links == null)
ret.links = Collections.emptyList();
if (ret.mid == null)
ret.mid = Collections.emptyList();
if (ret.neighbors == null)
ret.neighbors = Collections.emptyList();
if (ret.topology == null)
ret.topology = Collections.emptyList();
if (ret.plugins == null)
ret.plugins = Collections.emptyList();
if (ret.routes == null)
ret.routes = Collections.emptyList();
return ret;
}
/**
* all of the runtime and startup status information in a single report
*
* @return array of per-IP arrays of IP address, SYM, MPR, MPRS,
* Willingness, and 2 Hop Neighbors
*/
public OlsrDataDump all() {
return parseCommand("/all");
}
/**
* all of the runtime status information in a single report
*
* @return array of per-IP arrays of IP address, SYM, MPR, MPRS,
* Willingness, and 2 Hop Neighbors
*/
public OlsrDataDump runtime() {
return parseCommand("/interfaces");
}
/**
* all of the startup config information in a single report
*
* @return array of per-IP arrays of IP address, SYM, MPR, MPRS,
* Willingness, and 2 Hop Neighbors
*/
public OlsrDataDump startup() {
return parseCommand("/interfaces");
}
/**
* immediate neighbors on the mesh
*
* @return array of per-IP arrays of IP address, SYM, MPR, MPRS,
* Willingness, and 2 Hop Neighbors
*/
public Collection<Neighbor> neighbors() {
return parseCommand("/neighbors").neighbors;
}
/**
* direct connections on the mesh, i.e. nodes with direct IP connectivity
* via Ad-hoc
*
* @return array of per-IP arrays of Local IP, Remote IP, Hysteresis, LQ,
* NLQ, and Cost
*/
public Collection<Link> links() {
return parseCommand("/links").links;
}
/**
* IP routes to nodes on the mesh
*
* @return array of per-IP arrays of Destination, Gateway IP, Metric, ETX,
* and Interface
*/
public Collection<Route> routes() {
return parseCommand("/routes").routes;
}
/**
* Host and Network Association (for supporting dynamic internet gateways)
*
* @return array of per-IP arrays of Destination and Gateway
*/
public Collection<HNA> hna() {
return parseCommand("/hna").hna;
}
/**
* Multiple Interface Declaration
*
* @return array of per-IP arrays of IP address and Aliases
*/
public Collection<MID> mid() {
return parseCommand("/mid").mid;
}
/**
* topology of the whole mesh
*
* @return array of per-IP arrays of Destination IP, Last hop IP, LQ, NLQ,
* and Cost
*/
public Collection<Node> topology() {
return parseCommand("/topology").topology;
}
/**
* the network interfaces that olsrd is aware of
*
* @return array of per-IP arrays of Destination IP, Last hop IP, LQ, NLQ,
* and Cost
*/
public Collection<Interface> interfaces() {
return parseCommand("/interfaces").interfaces;
}
/**
* the gateways to other networks that this node knows about
*
* @return array of per-IP arrays of Status, Gateway IP, ETX, Hopcount,
* Uplink, Downlink, IPv4, IPv6, Prefix
*/
public Collection<Gateway> gateways() {
return parseCommand("/gateways").gateways;
}
/**
* The parsed configuration of olsrd in its current state
*/
public Config config() {
return parseCommand("/config").config;
}
/**
* The parsed configuration of plugins in their current state
*/
public Collection<Plugin> plugins() {
return parseCommand("/plugins").plugins;
}
/**
* The current olsrd configuration in the olsrd.conf format, NOT json
*/
public String olsrdconf() {
return command("/olsrd.conf");
}
/**
* for testing from the command line
*/
public static void main(String[] args) throws IOException {
JsonInfo jsoninfo = new JsonInfo();
OlsrDataDump dump = jsoninfo.all();
System.out.println("gateways:");
for (Gateway g : dump.gateways)
System.out.println("\t" + g.ipAddress);
System.out.println("hna:");
for (HNA h : dump.hna)
System.out.println("\t" + h.destination);
System.out.println("Interfaces:");
for (Interface i : dump.interfaces)
System.out.println("\t" + i.name);
System.out.println("Links:");
for (Link l : dump.links)
System.out.println("\t" + l.localIP + " <--> " + l.remoteIP);
System.out.println("MID:");
for (MID m : dump.mid)
System.out.println("\t" + m.ipAddress);
System.out.println("Neighbors:");
for (Neighbor n : dump.neighbors)
System.out.println("\t" + n.ipv4Address);
System.out.println("Plugins:");
for (Plugin p : dump.plugins)
System.out.println("\t" + p.plugin);
System.out.println("Routes:");
for (Route r : dump.routes)
System.out.println("\t" + r.destination);
System.out.println("Topology:");
for (Node node : dump.topology)
System.out.println("\t" + node.destinationIP);
}
}
|
package nl.mpi.arbil.templates;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.LinorgWindowManager;
import nl.mpi.arbil.clarin.CmdiProfileReader;
public class TemplateDialogue extends javax.swing.JPanel implements ActionListener {
/** Creates new form TemplateDialogue */
public TemplateDialogue() {
initComponents();
populateLists();
jProgressBar1.setVisible(false);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jButton3 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
templatesPanel = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
jScrollPane1 = new javax.swing.JScrollPane();
clarinPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridLayout(1, 0));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Internal Templates"));
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel6.setLayout(new javax.swing.BoxLayout(jPanel6, javax.swing.BoxLayout.LINE_AXIS));
jButton3.setText("New Template");
jButton3.setToolTipText("Create a new editable template");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel6.add(jButton3);
jPanel2.add(jPanel6, java.awt.BorderLayout.PAGE_END);
org.jdesktop.layout.GroupLayout templatesPanelLayout = new org.jdesktop.layout.GroupLayout(templatesPanel);
templatesPanel.setLayout(templatesPanelLayout);
templatesPanelLayout.setHorizontalGroup(
templatesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 342, Short.MAX_VALUE)
);
templatesPanelLayout.setVerticalGroup(
templatesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 288, Short.MAX_VALUE)
);
jScrollPane2.setViewportView(templatesPanel);
jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);
add(jPanel2);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Clarin Profiles"));
jPanel3.setLayout(new java.awt.BorderLayout());
jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));
jButton1.setText("Reload Clarin Profiles");
jButton1.setToolTipText("Download the latest clarin profiles");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel4.add(jButton1);
jPanel4.add(jProgressBar1);
jPanel3.add(jPanel4, java.awt.BorderLayout.PAGE_END);
org.jdesktop.layout.GroupLayout clarinPanelLayout = new org.jdesktop.layout.GroupLayout(clarinPanel);
clarinPanel.setLayout(clarinPanelLayout);
clarinPanelLayout.setHorizontalGroup(
clarinPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 342, Short.MAX_VALUE)
);
clarinPanelLayout.setVerticalGroup(
clarinPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 288, Short.MAX_VALUE)
);
jScrollPane1.setViewportView(clarinPanel);
jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
add(jPanel3);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
jButton1.setVisible(false);
jProgressBar1.setVisible(true);
this.doLayout();
new Thread() {
@Override
public void run() {
CmdiProfileReader cmdiProfileReader = new CmdiProfileReader();
cmdiProfileReader.refreshProfiles(jProgressBar1);
jProgressBar1.setVisible(false);
jButton1.setVisible(true);
doLayout();
}
}.start();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
try {
String newDirectoryName = JOptionPane.showInputDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "Enter the name for the new template", LinorgWindowManager.getSingleInstance().linorgFrame.getTitle(), JOptionPane.PLAIN_MESSAGE, null, null, null).toString();
// if the user cancels the directory string will be a empty string.
if (ArbilTemplateManager.getSingleInstance().getTemplateFile(newDirectoryName).exists()) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The template \"" + newDirectoryName + "\" already exists.", "Templates");
}
File freshTemplateFile = ArbilTemplateManager.getSingleInstance().createTemplate(newDirectoryName);
if (freshTemplateFile != null) {
GuiHelper.getSingleInstance().openFileInExternalApplication(freshTemplateFile.toURI());
GuiHelper.getSingleInstance().openFileInExternalApplication(freshTemplateFile.getParentFile().toURI());
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The template \"" + newDirectoryName + "\" could not be created.", "Templates");
}
// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("This action is not yet available.", "Templates");
//GuiHelper.linorgWindowManager.openUrlWindow(evt.getActionCommand() + templateList.get(evt.getActionCommand()).toString(), new File(templateList.get(evt.getActionCommand()).toString()).toURL());
// System.out.println("setting template: " + evt.getActionCommand());
// ArbilTemplateManager.getSingleInstance().setCurrentTemplate(evt.getActionCommand());
} catch (Exception e) {
GuiHelper.linorgBugCatcher.logError(e);
}
populateLists();
}//GEN-LAST:event_jButton3ActionPerformed
private void populateLists() {
templatesPanel.removeAll();
templatesPanel.setLayout(new javax.swing.BoxLayout(templatesPanel, javax.swing.BoxLayout.PAGE_AXIS));
// add built in types
for (String currentTemplateName : ArbilTemplateManager.getSingleInstance().builtInTemplates) {
JCheckBox templateCheckBox;
templateCheckBox = new JCheckBox();
templateCheckBox.setText(currentTemplateName);
templateCheckBox.setName(currentTemplateName);
templateCheckBox.setActionCommand("builtin:" + currentTemplateName);
templateCheckBox.setToolTipText(currentTemplateName);
templateCheckBox.addActionListener(this);
templatesPanel.add(templateCheckBox);
}
// add custom templates
todo: sort these entries
for (String currentTemplateName : ArbilTemplateManager.getSingleInstance().getAvailableTemplates()) {
JCheckBox templateCheckBox;
templateCheckBox = new JCheckBox();
templateCheckBox.setText(currentTemplateName);
templateCheckBox.setName(currentTemplateName);
templateCheckBox.setActionCommand("template:" + currentTemplateName);
templateCheckBox.setToolTipText(currentTemplateName);
templateCheckBox.addActionListener(this);
templatesPanel.add(templateCheckBox);
}
templatesPanel.doLayout();
// add clarin types
todo: sort these entries
clarinPanel.removeAll();
clarinPanel.setLayout(new javax.swing.BoxLayout(clarinPanel, javax.swing.BoxLayout.PAGE_AXIS));
CmdiProfileReader cmdiProfileReader = new CmdiProfileReader();
for (CmdiProfileReader.CmdiProfile currentCmdiProfile : cmdiProfileReader.cmdiProfileArray) {
JCheckBox clarinProfileCheckBox;
clarinProfileCheckBox = new JCheckBox();
clarinProfileCheckBox.setText(currentCmdiProfile.name);
clarinProfileCheckBox.setName(currentCmdiProfile.name);
clarinProfileCheckBox.setActionCommand("clarin:" + currentCmdiProfile.getXsdHref());
clarinProfileCheckBox.setToolTipText(currentCmdiProfile.description);
clarinProfileCheckBox.addActionListener(this);
clarinPanel.add(clarinProfileCheckBox);
}
clarinPanel.doLayout();
}
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
ArbilTemplateManager.getSingleInstance().addSelectedTemplates(e.getActionCommand());
} else {
ArbilTemplateManager.getSingleInstance().removeSelectedTemplates(e.getActionCommand());
}
}
public void showTemplatesDialogue() {
JDialog dialog = new JDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "Available Templates & Profiles", true);
dialog.setContentPane(new TemplateDialogue());
dialog.pack();
dialog.setVisible(true);
// JFrame testFrame = new JFrame("Available Templates & Profiles");
// testFrame.getContentPane().add(new TemplateDialogue());
// testFrame.doLayout();
// testFrame.pack();
// testFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
// testFrame.setVisible(true);
}
public static void main(String[] args) {
JFrame testFrame = new JFrame();
testFrame.getContentPane().add(new TemplateDialogue());
testFrame.doLayout();
testFrame.pack();
testFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
testFrame.setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel clarinPanel;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel6;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel templatesPanel;
// End of variables declaration//GEN-END:variables
}
|
package org.apache.xerces.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Stack;
import java.util.Vector;
import org.apache.xerces.impl.io.ASCIIReader;
import org.apache.xerces.impl.io.UCSReader;
import org.apache.xerces.impl.io.UTF8Reader;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.util.EncodingMap;
import org.apache.xerces.util.SecurityManager;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
public class XMLEntityManager
implements XMLComponent, XMLEntityResolver {
// Constants
/** Default buffer size (2048). */
public static final int DEFAULT_BUFFER_SIZE = 2048;
/** Default buffer size before we've finished with the XMLDecl: */
public static final int DEFAULT_XMLDECL_BUFFER_SIZE = 64;
/** Default internal entity buffer size (1024). */
public static final int DEFAULT_INTERNAL_BUFFER_SIZE = 1024;
// feature identifiers
/** Feature identifier: validation. */
protected static final String VALIDATION =
Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
/** Feature identifier: external general entities. */
protected static final String EXTERNAL_GENERAL_ENTITIES =
Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE;
/** Feature identifier: external parameter entities. */
protected static final String EXTERNAL_PARAMETER_ENTITIES =
Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE;
/** Feature identifier: allow Java encodings. */
protected static final String ALLOW_JAVA_ENCODINGS =
Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE;
/** Feature identifier: warn on duplicate EntityDef */
protected static final String WARN_ON_DUPLICATE_ENTITYDEF =
Constants.XERCES_FEATURE_PREFIX +Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE;
/** Feature identifier: standard uri conformant */
protected static final String STANDARD_URI_CONFORMANT =
Constants.XERCES_FEATURE_PREFIX +Constants.STANDARD_URI_CONFORMANT_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entity resolver. */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
// property identifier: ValidationManager
protected static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
/** property identifier: buffer size. */
protected static final String BUFFER_SIZE =
Constants.XERCES_PROPERTY_PREFIX + Constants.BUFFER_SIZE_PROPERTY;
/** property identifier: security manager. */
protected static final String SECURITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
// recognized features and properties
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
VALIDATION,
EXTERNAL_GENERAL_ENTITIES,
EXTERNAL_PARAMETER_ENTITIES,
ALLOW_JAVA_ENCODINGS,
WARN_ON_DUPLICATE_ENTITYDEF,
STANDARD_URI_CONFORMANT
};
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = {
null,
Boolean.TRUE,
Boolean.TRUE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE
};
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
ENTITY_RESOLVER,
VALIDATION_MANAGER,
BUFFER_SIZE,
SECURITY_MANAGER,
};
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = {
null,
null,
null,
null,
new Integer(DEFAULT_BUFFER_SIZE),
null,
};
private static final String XMLEntity = "[xml]".intern();
private static final String DTDEntity = "[dtd]".intern();
// debugging
/**
* Debug printing of buffer. This debugging flag works best when you
* resize the DEFAULT_BUFFER_SIZE down to something reasonable like
* 64 characters.
*/
private static final boolean DEBUG_BUFFER = false;
/** Debug some basic entities. */
private static final boolean DEBUG_ENTITIES = false;
/** Debug switching readers for encodings. */
private static final boolean DEBUG_ENCODINGS = false;
// should be diplayed trace resolving messages
private static final boolean DEBUG_RESOLVER = false;
// Data
// features
protected boolean fValidation;
protected boolean fExternalGeneralEntities = true;
protected boolean fExternalParameterEntities = true;
protected boolean fAllowJavaEncodings;
protected boolean fWarnDuplicateEntityDef;
protected boolean fStrictURI;
// properties
protected SymbolTable fSymbolTable;
protected XMLErrorReporter fErrorReporter;
protected XMLEntityResolver fEntityResolver;
protected ValidationManager fValidationManager;
// settings
/**
* Buffer size. We get this value from a property. The default size
* is used if the input buffer size property is not specified.
* REVISIT: do we need a property for internal entity buffer size?
*/
protected int fBufferSize = DEFAULT_BUFFER_SIZE;
// stores defaults for entity expansion limit if it has
// been set on the configuration.
protected SecurityManager fSecurityManager = null;
/**
* True if the document entity is standalone. This should really
* only be set by the document source (e.g. XMLDocumentScanner).
*/
protected boolean fStandalone;
// are the entities being parsed in the external subset?
// NOTE: this *is not* the same as whether they're external entities!
protected boolean fInExternalSubset = false;
// handlers
/** Entity handler. */
protected XMLEntityHandler fEntityHandler;
// scanner
/** Current entity scanner. */
protected XMLEntityScanner fEntityScanner;
/** XML 1.0 entity scanner. */
protected XMLEntityScanner fXML10EntityScanner;
/** XML 1.1 entity scanner. */
protected XMLEntityScanner fXML11EntityScanner;
// entity expansion limit (contains useful data if and only if
// fSecurityManager is non-null)
protected int fEntityExpansionLimit = 0;
// entity currently being expanded:
protected int fEntityExpansionCount = 0;
// entities
/** Entities. */
protected Hashtable fEntities = new Hashtable();
/** Entity stack. */
protected Stack fEntityStack = new Stack();
/** Current entity. */
protected ScannedEntity fCurrentEntity;
// shared context
/** Shared declared entities. */
protected Hashtable fDeclaredEntities;
// temp vars
/** Resource identifer. */
private final XMLResourceIdentifierImpl fResourceIdentifier = new XMLResourceIdentifierImpl();
// Constructors
/** Default constructor. */
public XMLEntityManager() {
this(null);
} // <init>()
/**
* Constructs an entity manager that shares the specified entity
* declarations during each parse.
* <p>
* <strong>REVISIT:</strong> We might want to think about the "right"
* way to expose the list of declared entities. For now, the knowledge
* how to access the entity declarations is implicit.
*/
public XMLEntityManager(XMLEntityManager entityManager) {
// save shared entity declarations
fDeclaredEntities = entityManager != null
? entityManager.getDeclaredEntities() : null;
setScannerVersion(Constants.XML_VERSION_1_0);
} // <init>(XMLEntityManager)
// Public methods
/**
* Sets whether the document entity is standalone.
*
* @param standalone True if document entity is standalone.
*/
public void setStandalone(boolean standalone) {
fStandalone = standalone;
} // setStandalone(boolean)
/** Returns true if the document entity is standalone. */
public boolean isStandalone() {
return fStandalone;
} // isStandalone():boolean
/**
* Sets the entity handler. When an entity starts and ends, the
* entity handler is notified of the change.
*
* @param entityHandler The new entity handler.
*/
public void setEntityHandler(XMLEntityHandler entityHandler) {
fEntityHandler = entityHandler;
} // setEntityHandler(XMLEntityHandler)
// this simply returns the fResourceIdentifier object;
// this should only be used with caution by callers that
// carefully manage the entity manager's behaviour, so that
// this doesn't returning meaningless or misleading data.
// @return a reference to the current fResourceIdentifier object
public XMLResourceIdentifier getCurrentResourceIdentifier() {
return fResourceIdentifier;
}
// this simply returns the fCurrentEntity object;
// this should only be used with caution by callers that
// carefully manage the entity manager's behaviour, so that
// this doesn't returning meaningless or misleading data.
// @return a reference to the current fCurrentEntity object
public ScannedEntity getCurrentEntity() {
return fCurrentEntity;
}
/**
* Adds an internal entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param text The text of the entity.
*
* @see SymbolTable
*/
public void addInternalEntity(String name, String text) {
if (!fEntities.containsKey(name)) {
Entity entity = new InternalEntity(name, text, fInExternalSubset);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addInternalEntity(String,String)
/**
* Adds an external entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity.
* @param literalSystemId The system identifier of the entity.
* @param baseSystemId The base system identifier of the entity.
* This is the system identifier of the entity
* where <em>the entity being added</em> and
* is used to expand the system identifier when
* the system identifier is a relative URI.
* When null the system identifier of the first
* external entity on the stack is used instead.
*
* @see SymbolTable
*/
public void addExternalEntity(String name,
String publicId, String literalSystemId,
String baseSystemId) throws IOException {
if (!fEntities.containsKey(name)) {
if (baseSystemId == null) {
// search for the first external entity on the stack
int size = fEntityStack.size();
if (size == 0 && fCurrentEntity != null && fCurrentEntity.entityLocation != null) {
baseSystemId = fCurrentEntity.entityLocation.getExpandedSystemId();
}
for (int i = size - 1; i >= 0 ; i
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null && externalEntity.entityLocation.getExpandedSystemId() != null) {
baseSystemId = externalEntity.entityLocation.getExpandedSystemId();
break;
}
}
}
Entity entity = new ExternalEntity(name,
new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandSystemId(literalSystemId, baseSystemId, false)), null, fInExternalSubset);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addExternalEntity(String,String,String,String)
/**
* Checks whether an entity given by name is external.
*
* @param entityName The name of the entity to check.
* @return True if the entity is external, false otherwise
* (including when the entity is not declared).
*/
public boolean isExternalEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
return false;
}
return entity.isExternal();
}
/**
* Checks whether the declaration of an entity given by name is
// in the external subset.
*
* @param entityName The name of the entity to check.
* @return True if the entity was declared in the external subset, false otherwise
* (including when the entity is not declared).
*/
public boolean isEntityDeclInExternalSubset(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
return false;
}
return entity.isEntityDeclInExternalSubset();
}
/**
* Adds an unparsed entity declaration.
* <p>
* <strong>Note:</strong> This method ignores subsequent entity
* declarations.
* <p>
* <strong>Note:</strong> The name should be a unique symbol. The
* SymbolTable can be used for this purpose.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity.
* @param systemId The system identifier of the entity.
* @param notation The name of the notation.
*
* @see SymbolTable
*/
public void addUnparsedEntity(String name,
String publicId, String systemId,
String baseSystemId, String notation) {
if (!fEntities.containsKey(name)) {
Entity entity = new ExternalEntity(name, new XMLResourceIdentifierImpl(publicId, systemId, baseSystemId, null), notation, fInExternalSubset);
fEntities.put(name, entity);
}
else{
if(fWarnDuplicateEntityDef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ENTITY_DEFINITION",
new Object[]{ name },
XMLErrorReporter.SEVERITY_WARNING );
}
}
} // addUnparsedEntity(String,String,String,String)
/**
* Checks whether an entity given by name is unparsed.
*
* @param entityName The name of the entity to check.
* @return True if the entity is unparsed, false otherwise
* (including when the entity is not declared).
*/
public boolean isUnparsedEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
return false;
}
return entity.isUnparsed();
}
/**
* Checks whether an entity given by name is declared.
*
* @param entityName The name of the entity to check.
* @return True if the entity is declared, false otherwise.
*/
public boolean isDeclaredEntity(String entityName) {
Entity entity = (Entity)fEntities.get(entityName);
return entity != null;
}
/**
* Resolves the specified public and system identifiers. This
* method first attempts to resolve the entity based on the
* EntityResolver registered by the application. If no entity
* resolver is registered or if the registered entity handler
* is unable to resolve the entity, then default entity
* resolution will occur.
*
* @param publicId The public identifier of the entity.
* @param systemId The system identifier of the entity.
* @param baseSystemId The base system identifier of the entity.
* This is the system identifier of the current
* entity and is used to expand the system
* identifier when the system identifier is a
* relative URI.
*
* @return Returns an input source that wraps the resolved entity.
* This method will never return null.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity resolver to signal an error.
*/
public XMLInputSource resolveEntity(XMLResourceIdentifier resourceIdentifier)
throws IOException, XNIException {
if(resourceIdentifier == null ) return null;
String publicId = resourceIdentifier.getPublicId();
String literalSystemId = resourceIdentifier.getLiteralSystemId();
String baseSystemId = resourceIdentifier.getBaseSystemId();
String expandedSystemId = resourceIdentifier.getExpandedSystemId();
// if no base systemId given, assume that it's relative
// to the systemId of the current scanned entity
// Sometimes the system id is not (properly) expanded.
// We need to expand the system id if:
// a. the expanded one was null; or
// b. the base system id was null, but becomes non-null from the current entity.
boolean needExpand = (expandedSystemId == null);
// REVISIT: why would the baseSystemId ever be null? if we
// didn't have to make this check we wouldn't have to reuse the
// fXMLResourceIdentifier object...
if (baseSystemId == null && fCurrentEntity != null && fCurrentEntity.entityLocation != null) {
baseSystemId = fCurrentEntity.entityLocation.getExpandedSystemId();
if (baseSystemId != null)
needExpand = true;
}
if (needExpand)
expandedSystemId = expandSystemId(literalSystemId, baseSystemId, false);
// give the entity resolver a chance
XMLInputSource xmlInputSource = null;
if (fEntityResolver != null) {
resourceIdentifier.setBaseSystemId(baseSystemId);
resourceIdentifier.setExpandedSystemId(expandedSystemId);
xmlInputSource = fEntityResolver.resolveEntity(resourceIdentifier);
}
// do default resolution
// REVISIT: what's the correct behavior if the user provided an entity
// resolver (fEntityResolver != null), but resolveEntity doesn't return
// an input source (xmlInputSource == null)?
// do we do default resolution, or do we just return null? -SG
if (xmlInputSource == null) {
// REVISIT: when systemId is null, I think we should return null.
// is this the right solution? -SG
//if (systemId != null)
xmlInputSource = new XMLInputSource(publicId, literalSystemId, baseSystemId);
}
if (DEBUG_RESOLVER) {
System.err.println("XMLEntityManager.resolveEntity(" + publicId + ")");
System.err.println(" = " + xmlInputSource);
}
return xmlInputSource;
} // resolveEntity(XMLResourceIdentifier):XMLInputSource
/**
* Starts a named entity.
*
* @param entityName The name of the entity to start.
* @param literal True if this entity is started within a literal
* value.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startEntity(String entityName, boolean literal)
throws IOException, XNIException {
// was entity declared?
Entity entity = (Entity)fEntities.get(entityName);
if (entity == null) {
if (fEntityHandler != null) {
String encoding = null;
fResourceIdentifier.clear();
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
// should we skip external entities?
boolean external = entity.isExternal();
if (external && (fValidationManager == null || !fValidationManager.isCachedDTD())) {
boolean unparsed = entity.isUnparsed();
boolean parameter = entityName.startsWith("%");
boolean general = !parameter;
if (unparsed || (general && !fExternalGeneralEntities) ||
(parameter && !fExternalParameterEntities)) {
if (fEntityHandler != null) {
fResourceIdentifier.clear();
final String encoding = null;
ExternalEntity externalEntity = (ExternalEntity)entity;
//REVISIT: since we're storing expandedSystemId in the
// externalEntity, how could this have got here if it wasn't already
// expanded??? - neilg
String extLitSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getLiteralSystemId() : null);
String extBaseSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getBaseSystemId() : null);
String expandedSystemId = expandSystemId(extLitSysId, extBaseSysId, false);
fResourceIdentifier.setValues(
(externalEntity.entityLocation != null ? externalEntity.entityLocation.getPublicId() : null),
extLitSysId, extBaseSysId, expandedSystemId);
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
}
// is entity recursive?
int size = fEntityStack.size();
for (int i = size; i >= 0; i
Entity activeEntity = i == size
? fCurrentEntity
: (Entity)fEntityStack.elementAt(i);
if (activeEntity.name == entityName) {
String path = entityName;
for (int j = i + 1; j < size; j++) {
activeEntity = (Entity)fEntityStack.elementAt(j);
path = path + " -> " + activeEntity.name;
}
path = path + " -> " + fCurrentEntity.name;
path = path + " -> " + entityName;
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"RecursiveReference",
new Object[] { entityName, path },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
if (fEntityHandler != null) {
fResourceIdentifier.clear();
final String encoding = null;
if (external) {
ExternalEntity externalEntity = (ExternalEntity)entity;
// REVISIT: for the same reason above...
String extLitSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getLiteralSystemId() : null);
String extBaseSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getBaseSystemId() : null);
String expandedSystemId = expandSystemId(extLitSysId, extBaseSysId, false);
fResourceIdentifier.setValues(
(externalEntity.entityLocation != null ? externalEntity.entityLocation.getPublicId() : null),
extLitSysId, extBaseSysId, expandedSystemId);
}
fEntityHandler.startEntity(entityName, fResourceIdentifier, encoding);
fEntityHandler.endEntity(entityName);
}
return;
}
}
// resolve external entity
XMLInputSource xmlInputSource = null;
if (external) {
ExternalEntity externalEntity = (ExternalEntity)entity;
xmlInputSource = resolveEntity(externalEntity.entityLocation);
}
// wrap internal entity
else {
InternalEntity internalEntity = (InternalEntity)entity;
Reader reader = new StringReader(internalEntity.text);
xmlInputSource = new XMLInputSource(null, null, null, reader, null);
}
// start the entity
startEntity(entityName, xmlInputSource, literal, external);
} // startEntity(String,boolean)
/**
* Starts the document entity. The document entity has the "[xml]"
* pseudo-name.
*
* @param xmlInputSource The input source of the document entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startDocumentEntity(XMLInputSource xmlInputSource)
throws IOException, XNIException {
startEntity(XMLEntity, xmlInputSource, false, true);
} // startDocumentEntity(XMLInputSource)
/**
* Starts the DTD entity. The DTD entity has the "[dtd]"
* pseudo-name.
*
* @param xmlInputSource The input source of the DTD entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startDTDEntity(XMLInputSource xmlInputSource)
throws IOException, XNIException {
startEntity(DTDEntity, xmlInputSource, false, true);
} // startDTDEntity(XMLInputSource)
// indicate start of external subset so that
// location of entity decls can be tracked
public void startExternalSubset() {
fInExternalSubset = true;
}
public void endExternalSubset() {
fInExternalSubset = false;
}
/**
* Starts an entity.
* <p>
* This method can be used to insert an application defined XML
* entity stream into the parsing stream.
*
* @param name The name of the entity.
* @param xmlInputSource The input source of the entity.
* @param literal True if this entity is started within a
* literal value.
* @param isExternal whether this entity should be treated as an internal or external entity.
*
* @throws IOException Thrown on i/o error.
* @throws XNIException Thrown by entity handler to signal an error.
*/
public void startEntity(String name,
XMLInputSource xmlInputSource,
boolean literal, boolean isExternal)
throws IOException, XNIException {
String encoding = setupCurrentEntity(name, xmlInputSource, literal, isExternal);
//when entity expansion limit is set by the Application, we need to
//check for the entity expansion limit set by the parser, if number of entity
//expansions exceeds the entity expansion limit, parser will throw fatal error.
// Note that this is intentionally unbalanced; it counts
// the number of expansions *per document*.
if( fSecurityManager != null && fEntityExpansionCount++ > fEntityExpansionLimit ){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EntityExpansionLimitExceeded",
new Object[]{new Integer(fEntityExpansionLimit) },
XMLErrorReporter.SEVERITY_FATAL_ERROR );
// is there anything better to do than reset the counter?
// at least one can envision debugging applications where this might
// be useful...
fEntityExpansionCount = 0;
}
// call handler
if (fEntityHandler != null) {
fEntityHandler.startEntity(name, fResourceIdentifier, encoding);
}
} // startEntity(String,XMLInputSource)
/**
* This method uses the passed-in XMLInputSource to make
* fCurrentEntity usable for reading.
* @param name name of the entity (XML is it's the document entity)
* @param xmlInputSource the input source, with sufficient information
* to begin scanning characters.
* @param literal True if this entity is started within a
* literal value.
* @param isExternal whether this entity should be treated as an internal or external entity.
* @throws IOException if anything can't be read
* XNIException If any parser-specific goes wrong.
* @return the encoding of the new entity or null if a character stream was employed
*/
public String setupCurrentEntity(String name, XMLInputSource xmlInputSource,
boolean literal, boolean isExternal)
throws IOException, XNIException {
// get information
final String publicId = xmlInputSource.getPublicId();
String literalSystemId = xmlInputSource.getSystemId();
String baseSystemId = xmlInputSource.getBaseSystemId();
String encoding = xmlInputSource.getEncoding();
Boolean isBigEndian = null;
// create reader
InputStream stream = null;
Reader reader = xmlInputSource.getCharacterStream();
// First chance checking strict URI
String expandedSystemId = expandSystemId(literalSystemId, baseSystemId, fStrictURI);
if (baseSystemId == null) {
baseSystemId = expandedSystemId;
}
if (reader == null) {
stream = xmlInputSource.getByteStream();
if (stream == null) {
URL location = new URL(expandedSystemId);
URLConnection connect = location.openConnection();
stream = connect.getInputStream();
// REVISIT: If the URLConnection has external encoding
// information, we should be reading it here. It's located
// in the charset parameter of Content-Type. -- mrglavas
if (connect instanceof HttpURLConnection) {
String redirect = connect.getURL().toString();
// E43: Check if the URL was redirected, and then
// update literal and expanded system IDs if needed.
if (!redirect.equals(expandedSystemId)) {
literalSystemId = redirect;
expandedSystemId = redirect;
}
}
}
// wrap this stream in RewindableInputStream
stream = new RewindableInputStream(stream);
// perform auto-detect of encoding if necessary
if (encoding == null) {
// read first four bytes and determine encoding
final byte[] b4 = new byte[4];
int count = 0;
for (; count<4; count++ ) {
b4[count] = (byte)stream.read();
}
if (count == 4) {
Object [] encodingDesc = getEncodingName(b4, count);
encoding = (String)(encodingDesc[0]);
isBigEndian = (Boolean)(encodingDesc[1]);
stream.reset();
int offset = 0;
// tools. It's more efficient to consume the BOM than make
// the reader perform extra checks. -Ac
if (count > 2 && encoding.equals("UTF-8")) {
int b0 = b4[0] & 0xFF;
int b1 = b4[1] & 0xFF;
int b2 = b4[2] & 0xFF;
if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
// ignore first three bytes...
stream.skip(3);
}
}
reader = createReader(stream, encoding, isBigEndian);
}
else {
reader = createReader(stream, encoding, isBigEndian);
}
}
// use specified encoding
else {
encoding = encoding.toUpperCase(Locale.ENGLISH);
// If encoding is UTF-8, consume BOM if one is present.
if (encoding.equals("UTF-8")) {
final int[] b3 = new int[3];
int count = 0;
for (; count < 3; ++count) {
b3[count] = stream.read();
if (b3[count] == -1)
break;
}
if (count == 3) {
if (b3[0] != 0xEF || b3[1] != 0xBB || b3[2] != 0xBF) {
// First three bytes are not BOM, so reset.
stream.reset();
}
}
else {
stream.reset();
}
}
// If encoding is UCS-4, we still need to read the first four bytes
// in order to discover the byte order.
else if (encoding.equals("ISO-10646-UCS-4")) {
final int[] b4 = new int[4];
int count = 0;
for (; count < 4; ++count) {
b4[count] = stream.read();
if (b4[count] == -1)
break;
}
stream.reset();
// Ignore unusual octet order for now.
if (count == 4) {
// UCS-4, big endian (1234)
if (b4[0] == 0x00 && b4[1] == 0x00 && b4[2] == 0x00 && b4[3] == 0x3C) {
isBigEndian = Boolean.TRUE;
}
// UCS-4, little endian (1234)
else if (b4[0] == 0x3C && b4[1] == 0x00 && b4[2] == 0x00 && b4[3] == 0x00) {
isBigEndian = Boolean.FALSE;
}
}
}
// If encoding is UCS-2, we still need to read the first four bytes
// in order to discover the byte order.
else if (encoding.equals("ISO-10646-UCS-2")) {
final int[] b4 = new int[4];
int count = 0;
for (; count < 4; ++count) {
b4[count] = stream.read();
if (b4[count] == -1)
break;
}
stream.reset();
if (count == 4) {
// UCS-2, big endian
if (b4[0] == 0x00 && b4[1] == 0x3C && b4[2] == 0x00 && b4[3] == 0x3F) {
isBigEndian = Boolean.TRUE;
}
// UCS-2, little endian
else if (b4[0] == 0x3C && b4[1] == 0x00 && b4[2] == 0x3F && b4[3] == 0x00) {
isBigEndian = Boolean.FALSE;
}
}
}
reader = createReader(stream, encoding, isBigEndian);
}
// read one character at a time so we don't jump too far
// ahead, converting characters from the byte stream in
// the wrong encoding
if (DEBUG_ENCODINGS) {
System.out.println("$$$ no longer wrapping reader in OneCharReader");
}
//reader = new OneCharReader(reader);
}
// we've seen a new Reader. put it in a list, so that
// we can close it later.
fOwnReaders.addElement(reader);
// push entity on stack
if (fCurrentEntity != null) {
fEntityStack.push(fCurrentEntity);
}
// create entity
fCurrentEntity = new ScannedEntity(name,
new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandedSystemId),
stream, reader, encoding, literal, false, isExternal);
fEntityScanner.setCurrentEntity(fCurrentEntity);
fResourceIdentifier.setValues(publicId, literalSystemId, baseSystemId, expandedSystemId);
return encoding;
} //setupCurrentEntity(String, XMLInputSource, boolean, boolean): String
// set version of scanner to use
public void setScannerVersion(short version) {
if(version == Constants.XML_VERSION_1_0) {
if(fXML10EntityScanner == null) {
fXML10EntityScanner = new XMLEntityScanner();
fXML10EntityScanner.reset(fSymbolTable, this, fErrorReporter);
}
fEntityScanner = fXML10EntityScanner;
fEntityScanner.setCurrentEntity(fCurrentEntity);
} else {
if(fXML11EntityScanner == null) {
fXML11EntityScanner = new XML11EntityScanner();
fXML11EntityScanner.reset(fSymbolTable, this, fErrorReporter);
}
fEntityScanner = fXML11EntityScanner;
fEntityScanner.setCurrentEntity(fCurrentEntity);
}
} // setScannerVersion(short)
/** Returns the entity scanner. */
public XMLEntityScanner getEntityScanner() {
if(fEntityScanner == null) {
// default to 1.0
if(fXML10EntityScanner == null) {
fXML10EntityScanner = new XMLEntityScanner();
}
fXML10EntityScanner.reset(fSymbolTable, this, fErrorReporter);
fEntityScanner = fXML10EntityScanner;
}
return fEntityScanner;
} // getEntityScanner():XMLEntityScanner
// a list of Readers ever seen
protected Vector fOwnReaders = new Vector();
/**
* Close all opened InputStreams and Readers opened by this parser.
*/
public void closeReaders() {
// close all readers
for (int i = fOwnReaders.size()-1; i >= 0; i
try {
((Reader)fOwnReaders.elementAt(i)).close();
} catch (IOException e) {
// ignore
}
}
// and clear the list
fOwnReaders.removeAllElements();
}
// XMLComponent methods
/**
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on initialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
// sax features
try {
fValidation = componentManager.getFeature(VALIDATION);
}
catch (XMLConfigurationException e) {
fValidation = false;
}
try {
fExternalGeneralEntities = componentManager.getFeature(EXTERNAL_GENERAL_ENTITIES);
}
catch (XMLConfigurationException e) {
fExternalGeneralEntities = true;
}
try {
fExternalParameterEntities = componentManager.getFeature(EXTERNAL_PARAMETER_ENTITIES);
}
catch (XMLConfigurationException e) {
fExternalParameterEntities = true;
}
// xerces features
try {
fAllowJavaEncodings = componentManager.getFeature(ALLOW_JAVA_ENCODINGS);
}
catch (XMLConfigurationException e) {
fAllowJavaEncodings = false;
}
try {
fWarnDuplicateEntityDef = componentManager.getFeature(WARN_ON_DUPLICATE_ENTITYDEF);
}
catch (XMLConfigurationException e) {
fWarnDuplicateEntityDef = false;
}
try {
fStrictURI = componentManager.getFeature(STANDARD_URI_CONFORMANT);
}
catch (XMLConfigurationException e) {
fStrictURI = false;
}
// xerces properties
fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
try {
fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_RESOLVER);
}
catch (XMLConfigurationException e) {
fEntityResolver = null;
}
try {
fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER);
}
catch (XMLConfigurationException e) {
fValidationManager = null;
}
try {
fSecurityManager = (SecurityManager)componentManager.getProperty(SECURITY_MANAGER);
}
catch (XMLConfigurationException e) {
fSecurityManager = null;
}
// reset general state
reset();
} // reset(XMLComponentManager)
// reset general state. Should not be called other than by
// a class acting as a component manager but not
// implementing that interface for whatever reason.
public void reset() {
fEntityExpansionLimit = (fSecurityManager != null)?fSecurityManager.getEntityExpansionLimit():0;
// initialize state
fStandalone = false;
fEntities.clear();
fEntityStack.removeAllElements();
fEntityExpansionCount = 0;
fCurrentEntity = null;
// reset scanner
if(fXML10EntityScanner != null){
fXML10EntityScanner.reset(fSymbolTable, this, fErrorReporter);
}
if(fXML11EntityScanner != null) {
fXML11EntityScanner.reset(fSymbolTable, this, fErrorReporter);
}
// DEBUG
if (DEBUG_ENTITIES) {
addInternalEntity("text", "Hello, World.");
addInternalEntity("empty-element", "<foo/>");
addInternalEntity("balanced-element", "<foo></foo>");
addInternalEntity("balanced-element-with-text", "<foo>Hello, World</foo>");
addInternalEntity("balanced-element-with-entity", "<foo>&text;</foo>");
addInternalEntity("unbalanced-entity", "<foo>");
addInternalEntity("recursive-entity", "<foo>&recursive-entity2;</foo>");
addInternalEntity("recursive-entity2", "<bar>&recursive-entity3;</bar>");
addInternalEntity("recursive-entity3", "<baz>&recursive-entity;</baz>");
try {
addExternalEntity("external-text", null, "external-text.ent", "test/external-text.xml");
addExternalEntity("external-balanced-element", null, "external-balanced-element.ent", "test/external-balanced-element.xml");
addExternalEntity("one", null, "ent/one.ent", "test/external-entity.xml");
addExternalEntity("two", null, "ent/two.ent", "test/ent/one.xml");
}
catch (IOException ex) {
// should never happen
}
}
// copy declared entities
if (fDeclaredEntities != null) {
java.util.Enumeration keys = fDeclaredEntities.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = fDeclaredEntities.get(key);
fEntities.put(key, value);
}
}
fEntityHandler = null;
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone());
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
// xerces features
if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) {
String feature = featureId.substring(Constants.XERCES_FEATURE_PREFIX.length());
if (feature.equals(Constants.ALLOW_JAVA_ENCODINGS_FEATURE)) {
fAllowJavaEncodings = state;
}
}
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone());
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
// Xerces properties
if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) {
String property = propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length());
if (property.equals(Constants.SYMBOL_TABLE_PROPERTY)) {
fSymbolTable = (SymbolTable)value;
return;
}
if (property.equals(Constants.ERROR_REPORTER_PROPERTY)) {
fErrorReporter = (XMLErrorReporter)value;
return;
}
if (property.equals(Constants.ENTITY_RESOLVER_PROPERTY)) {
fEntityResolver = (XMLEntityResolver)value;
return;
}
if (property.equals(Constants.BUFFER_SIZE_PROPERTY)) {
Integer bufferSize = (Integer)value;
if (bufferSize != null &&
bufferSize.intValue() > DEFAULT_XMLDECL_BUFFER_SIZE) {
fBufferSize = bufferSize.intValue();
fEntityScanner.setBufferSize(fBufferSize);
}
}
if (property.equals(Constants.SECURITY_MANAGER_PROPERTY)) {
fSecurityManager = (SecurityManager)value;
fEntityExpansionLimit = (fSecurityManager != null)?fSecurityManager.getEntityExpansionLimit():0;
}
}
} // setProperty(String,Object)
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*
* @param featureId The feature identifier.
*
* @since Xerces 2.2.0
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*
* @param propertyId The property identifier.
*
* @since Xerces 2.2.0
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
// Public static methods
// current value of the "user.dir" property
private static String gUserDir;
// escaped value of the current "user.dir" property
private static String gEscapedUserDir;
// which ASCII characters need to be escaped
private static boolean gNeedEscaping[] = new boolean[128];
// the first hex character if a character needs to be escaped
private static char gAfterEscaping1[] = new char[128];
// the second hex character if a character needs to be escaped
private static char gAfterEscaping2[] = new char[128];
private static char[] gHexChs = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
// initialize the above 3 arrays
static {
for (int i = 0; i <= 0x1f; i++) {
gNeedEscaping[i] = true;
gAfterEscaping1[i] = gHexChs[i >> 4];
gAfterEscaping2[i] = gHexChs[i & 0xf];
}
gNeedEscaping[0x7f] = true;
gAfterEscaping1[0x7f] = '7';
gAfterEscaping2[0x7f] = 'F';
char[] escChs = {' ', '<', '>', '
'|', '\\', '^', '~', '[', ']', '`'};
int len = escChs.length;
char ch;
for (int i = 0; i < len; i++) {
ch = escChs[i];
gNeedEscaping[ch] = true;
gAfterEscaping1[ch] = gHexChs[ch >> 4];
gAfterEscaping2[ch] = gHexChs[ch & 0xf];
}
}
// To escape the "user.dir" system property, by using %HH to represent
// special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', '
// and '"'. It's a static method, so needs to be synchronized.
// this method looks heavy, but since the system property isn't expected
// to change often, so in most cases, we only need to return the string
// that was escaped before.
// According to the URI spec, non-ASCII characters (whose value >= 128)
// need to be escaped too.
// REVISIT: don't know how to escape non-ASCII characters, especially
// which encoding to use. Leave them for now.
private static synchronized String getUserDir() {
// get the user.dir property
String userDir = "";
try {
userDir = System.getProperty("user.dir");
}
catch (SecurityException se) {
}
// return empty string if property value is empty string.
if (userDir.length() == 0)
return "";
// compute the new escaped value if the new property value doesn't
// match the previous one
if (userDir.equals(gUserDir)) {
return gEscapedUserDir;
}
// record the new value as the global property value
gUserDir = userDir;
char separator = java.io.File.separatorChar;
userDir = userDir.replace(separator, '/');
int len = userDir.length(), ch;
StringBuffer buffer = new StringBuffer(len*3);
// change C:/blah to /C:/blah
if (len >= 2 && userDir.charAt(1) == ':') {
ch = Character.toUpperCase(userDir.charAt(0));
if (ch >= 'A' && ch <= 'Z') {
buffer.append('/');
}
}
// for each character in the path
int i = 0;
for (; i < len; i++) {
ch = userDir.charAt(i);
// if it's not an ASCII character, break here, and use UTF-8 encoding
if (ch >= 128)
break;
if (gNeedEscaping[ch]) {
buffer.append('%');
buffer.append(gAfterEscaping1[ch]);
buffer.append(gAfterEscaping2[ch]);
// record the fact that it's escaped
}
else {
buffer.append((char)ch);
}
}
// we saw some non-ascii character
if (i < len) {
// get UTF-8 bytes for the remaining sub-string
byte[] bytes = null;
byte b;
try {
bytes = userDir.substring(i).getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
// should never happen
return userDir;
}
len = bytes.length;
// for each byte
for (i = 0; i < len; i++) {
b = bytes[i];
// for non-ascii character: make it positive, then escape
if (b < 0) {
ch = b + 256;
buffer.append('%');
buffer.append(gHexChs[ch >> 4]);
buffer.append(gHexChs[ch & 0xf]);
}
else if (gNeedEscaping[b]) {
buffer.append('%');
buffer.append(gAfterEscaping1[b]);
buffer.append(gAfterEscaping2[b]);
}
else {
buffer.append((char)b);
}
}
}
// change blah/blah to blah/blah/
if (!userDir.endsWith("/"))
buffer.append('/');
gEscapedUserDir = buffer.toString();
return gEscapedUserDir;
}
/**
* Expands a system id and returns the system id as a URI, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URI string representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
public static String expandSystemId(String systemId, String baseSystemId,
boolean strict)
throws URI.MalformedURIException {
// system id has to be a valid URI
if (strict) {
try {
// if it's already an absolute one, return it
URI uri = new URI(systemId);
return systemId;
}
catch (URI.MalformedURIException ex) {
}
URI base = null;
// if there isn't a base uri, use the working directory
if (baseSystemId == null || baseSystemId.length() == 0) {
base = new URI("file", "", getUserDir(), null, null);
}
// otherwise, use the base uri
else {
try {
base = new URI(baseSystemId);
}
catch (URI.MalformedURIException e) {
// assume "base" is also a relative uri
String dir = getUserDir();
dir = dir + baseSystemId;
base = new URI("file", "", dir, null, null);
}
}
// absolutize the system id using the base
URI uri = new URI(base, systemId);
// return the string rep of the new uri (an absolute one)
return uri.toString();
// if any exception is thrown, it'll get thrown to the caller.
}
// check for bad parameters id
if (systemId == null || systemId.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URI uri = new URI(systemId);
if (uri != null) {
return systemId;
}
}
catch (URI.MalformedURIException e) {
// continue on...
}
// normalize id
String id = fixURI(systemId);
// normalize base
URI base = null;
URI uri = null;
try {
if (baseSystemId == null || baseSystemId.length() == 0 ||
baseSystemId.equals(systemId)) {
String dir = getUserDir();
base = new URI("file", "", dir, null, null);
}
else {
try {
base = new URI(fixURI(baseSystemId));
}
catch (URI.MalformedURIException e) {
if (baseSystemId.indexOf(':') != -1) {
// for xml schemas we might have baseURI with
// a specified drive
base = new URI("file", "", fixURI(baseSystemId), null, null);
}
else {
String dir = getUserDir();
dir = dir + fixURI(baseSystemId);
base = new URI("file", "", dir, null, null);
}
}
}
// expand id
uri = new URI(base, id);
}
catch (Exception e) {
// let it go through
}
if (uri == null) {
return systemId;
}
return uri.toString();
} // expandSystemId(String,String):String
// Protected methods
/**
* Ends an entity.
*
* @throws XNIException Thrown by entity handler to signal an error.
*/
void endEntity() throws XNIException {
// call handler
if (DEBUG_BUFFER) {
System.out.print("(endEntity: ");
print(fCurrentEntity);
System.out.println();
}
if (fEntityHandler != null) {
fEntityHandler.endEntity(fCurrentEntity.name);
}
// pop stack
// REVISIT: we are done with the current entity, should close
// the associated reader
//fCurrentEntity.reader.close();
// Now we close all readers after we finish parsing
fCurrentEntity = fEntityStack.size() > 0
? (ScannedEntity)fEntityStack.pop() : null;
fEntityScanner.setCurrentEntity(fCurrentEntity);
if (DEBUG_BUFFER) {
System.out.print(")endEntity: ");
print(fCurrentEntity);
System.out.println();
}
} // endEntity()
/**
* Returns the IANA encoding name that is auto-detected from
* the bytes specified, with the endian-ness of that encoding where appropriate.
*
* @param b4 The first four bytes of the input.
* @param count The number of bytes actually read.
* @return a 2-element array: the first element, an IANA-encoding string,
* the second element a Boolean which is true iff the document is big endian, false
* if it's little-endian, and null if the distinction isn't relevant.
*/
protected Object[] getEncodingName(byte[] b4, int count) {
if (count < 2) {
return new Object[]{"UTF-8", null};
}
// UTF-16, with BOM
int b0 = b4[0] & 0xFF;
int b1 = b4[1] & 0xFF;
if (b0 == 0xFE && b1 == 0xFF) {
// UTF-16, big-endian
return new Object [] {"UTF-16BE", new Boolean(true)};
}
if (b0 == 0xFF && b1 == 0xFE) {
// UTF-16, little-endian
return new Object [] {"UTF-16LE", new Boolean(false)};
}
// default to UTF-8 if we don't have enough bytes to make a
// good determination of the encoding
if (count < 3) {
return new Object [] {"UTF-8", null};
}
// UTF-8 with a BOM
int b2 = b4[2] & 0xFF;
if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
return new Object [] {"UTF-8", null};
}
// default to UTF-8 if we don't have enough bytes to make a
// good determination of the encoding
if (count < 4) {
return new Object [] {"UTF-8", null};
}
// other encodings
int b3 = b4[3] & 0xFF;
if (b0 == 0x00 && b1 == 0x00 && b2 == 0x00 && b3 == 0x3C) {
// UCS-4, big endian (1234)
return new Object [] {"ISO-10646-UCS-4", new Boolean(true)};
}
if (b0 == 0x3C && b1 == 0x00 && b2 == 0x00 && b3 == 0x00) {
// UCS-4, little endian (4321)
return new Object [] {"ISO-10646-UCS-4", new Boolean(false)};
}
if (b0 == 0x00 && b1 == 0x00 && b2 == 0x3C && b3 == 0x00) {
// UCS-4, unusual octet order (2143)
// REVISIT: What should this be?
return new Object [] {"ISO-10646-UCS-4", null};
}
if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x00) {
// UCS-4, unusual octect order (3412)
// REVISIT: What should this be?
return new Object [] {"ISO-10646-UCS-4", null};
}
if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F) {
// UTF-16, big-endian, no BOM
// (or could turn out to be UCS-2...
// REVISIT: What should this be?
return new Object [] {"UTF-16BE", new Boolean(true)};
}
if (b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00) {
// UTF-16, little-endian, no BOM
// (or could turn out to be UCS-2...
return new Object [] {"UTF-16LE", new Boolean(false)};
}
if (b0 == 0x4C && b1 == 0x6F && b2 == 0xA7 && b3 == 0x94) {
// EBCDIC
// a la xerces1, return CP037 instead of EBCDIC here
return new Object [] {"CP037", null};
}
// default encoding
return new Object [] {"UTF-8", null};
} // getEncodingName(byte[],int):Object[]
/**
* Creates a reader capable of reading the given input stream in
* the specified encoding.
*
* @param inputStream The input stream.
* @param encoding The encoding name that the input stream is
* encoded using. If the user has specified that
* Java encoding names are allowed, then the
* encoding name may be a Java encoding name;
* otherwise, it is an ianaEncoding name.
* @param isBigEndian For encodings (like uCS-4), whose names cannot
* specify a byte order, this tells whether the order is bigEndian. null menas
* unknown or not relevant.
*
* @return Returns a reader.
*/
protected Reader createReader(InputStream inputStream, String encoding, Boolean isBigEndian)
throws IOException {
// normalize encoding name
if (encoding == null) {
encoding = "UTF-8";
}
// try to use an optimized reader
String ENCODING = encoding.toUpperCase(Locale.ENGLISH);
if (ENCODING.equals("UTF-8")) {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating UTF8Reader");
}
return new UTF8Reader(inputStream, fBufferSize, fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN), fErrorReporter.getLocale() );
}
if (ENCODING.equals("US-ASCII")) {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating ASCIIReader");
}
return new ASCIIReader(inputStream, fBufferSize, fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN), fErrorReporter.getLocale());
}
if(ENCODING.equals("ISO-10646-UCS-4")) {
if(isBigEndian != null) {
boolean isBE = isBigEndian.booleanValue();
if(isBE) {
return new UCSReader(inputStream, UCSReader.UCS4BE);
} else {
return new UCSReader(inputStream, UCSReader.UCS4LE);
}
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingByteOrderUnsupported",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
if(ENCODING.equals("ISO-10646-UCS-2")) {
if(isBigEndian != null) { // sould never happen with this encoding...
boolean isBE = isBigEndian.booleanValue();
if(isBE) {
return new UCSReader(inputStream, UCSReader.UCS2BE);
} else {
return new UCSReader(inputStream, UCSReader.UCS2LE);
}
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingByteOrderUnsupported",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
// check for valid name
boolean validIANA = XMLChar.isValidIANAEncoding(encoding);
boolean validJava = XMLChar.isValidJavaEncoding(encoding);
if (!validIANA || (fAllowJavaEncodings && !validJava)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingDeclInvalid",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
// NOTE: AndyH suggested that, on failure, we use ISO Latin 1
// because every byte is a valid ISO Latin 1 character.
// It may not translate correctly but if we failed on
// the encoding anyway, then we're expecting the content
// of the document to be bad. This will just prevent an
// invalid UTF-8 sequence to be detected. This is only
// important when continue-after-fatal-error is turned
// on. -Ac
encoding = "ISO-8859-1";
}
// try to use a Java reader
String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING);
if (javaEncoding == null) {
if(fAllowJavaEncodings) {
javaEncoding = encoding;
} else {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"EncodingDeclInvalid",
new Object[] { encoding },
XMLErrorReporter.SEVERITY_FATAL_ERROR);
// see comment above.
javaEncoding = "ISO8859_1";
}
}
if (DEBUG_ENCODINGS) {
System.out.print("$$$ creating Java InputStreamReader: encoding="+javaEncoding);
if (javaEncoding == encoding) {
System.out.print(" (IANA encoding)");
}
System.out.println();
}
return new InputStreamReader(inputStream, javaEncoding);
} // createReader(InputStream,String, Boolean): Reader
// Protected static methods
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
protected static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
StringBuffer sb = null;
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
// change "C:blah" to "/C:blah"
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
sb = new StringBuffer(str.length());
sb.append('/');
}
}
// change "//blah" to "file://blah"
else if (ch1 == '/' && str.charAt(0) == '/') {
sb = new StringBuffer(str.length());
sb.append("file:");
}
}
int pos = str.indexOf(' ');
// there is no space in the string
// we just append "str" to the end of sb
if (pos < 0) {
if (sb != null) {
sb.append(str);
str = sb.toString();
}
}
// otherwise, convert all ' ' to "%20".
// Note: the following algorithm might not be very performant,
// but people who want to use invalid URI's have to pay the price.
else {
if (sb == null)
sb = new StringBuffer(str.length());
// put characters before ' ' into the string buffer
for (int i = 0; i < pos; i++)
sb.append(str.charAt(i));
// and %20 for the space
sb.append("%20");
// for the remamining part, also convert ' ' to "%20".
for (int i = pos+1; i < str.length(); i++) {
if (str.charAt(i) == ' ')
sb.append("%20");
else
sb.append(str.charAt(i));
}
str = sb.toString();
}
// done
return str;
} // fixURI(String):String
// Package visible methods
/**
* Returns the hashtable of declared entities.
* <p>
* <strong>REVISIT:</strong>
* This should be done the "right" way by designing a better way to
* enumerate the declared entities. For now, this method is needed
* by the constructor that takes an XMLEntityManager parameter.
*/
Hashtable getDeclaredEntities() {
return fEntities;
} // getDeclaredEntities():Hashtable
/** Prints the contents of the buffer. */
static final void print(ScannedEntity currentEntity) {
if (DEBUG_BUFFER) {
if (currentEntity != null) {
System.out.print('[');
System.out.print(currentEntity.count);
System.out.print(' ');
System.out.print(currentEntity.position);
if (currentEntity.count > 0) {
System.out.print(" \"");
for (int i = 0; i < currentEntity.count; i++) {
if (i == currentEntity.position) {
System.out.print('^');
}
char c = currentEntity.ch[i];
switch (c) {
case '\n': {
System.out.print("\\n");
break;
}
case '\r': {
System.out.print("\\r");
break;
}
case '\t': {
System.out.print("\\t");
break;
}
case '\\': {
System.out.print("\\\\");
break;
}
default: {
System.out.print(c);
}
}
}
if (currentEntity.position == currentEntity.count) {
System.out.print('^');
}
System.out.print('"');
}
System.out.print(']');
System.out.print(" @ ");
System.out.print(currentEntity.lineNumber);
System.out.print(',');
System.out.print(currentEntity.columnNumber);
}
else {
System.out.print("*NO CURRENT ENTITY*");
}
}
} // print(ScannedEntity)
// Classes
/**
* Entity information.
*
* @author Andy Clark, IBM
*/
public static abstract class Entity {
// Data
/** Entity name. */
public String name;
// whether this entity's declaration was found in the internal
// or external subset
public boolean inExternalSubset;
// Constructors
/** Default constructor. */
public Entity() {
clear();
} // <init>()
/** Constructs an entity. */
public Entity(String name, boolean inExternalSubset) {
this.name = name;
this.inExternalSubset = inExternalSubset;
} // <init>(String)
// Public methods
/** Returns true if this entity was declared in the external subset. */
public boolean isEntityDeclInExternalSubset () {
return inExternalSubset;
}
/** Returns true if this is an external entity. */
public abstract boolean isExternal();
/** Returns true if this is an unparsed entity. */
public abstract boolean isUnparsed();
/** Clears the entity. */
public void clear() {
name = null;
inExternalSubset = false;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
name = entity.name;
inExternalSubset = entity.inExternalSubset;
} // setValues(Entity)
} // class Entity
/**
* Internal entity.
*
* @author Andy Clark, IBM
*/
protected static class InternalEntity
extends Entity {
// Data
/** Text value of entity. */
public String text;
// Constructors
/** Default constructor. */
public InternalEntity() {
clear();
} // <init>()
/** Constructs an internal entity. */
public InternalEntity(String name, String text, boolean inExternalSubset) {
super(name,inExternalSubset);
this.text = text;
} // <init>(String,String)
// Entity methods
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return false;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return false;
} // isUnparsed():boolean
/** Clears the entity. */
public void clear() {
super.clear();
text = null;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
super.setValues(entity);
text = null;
} // setValues(Entity)
/** Sets the values of the entity. */
public void setValues(InternalEntity entity) {
super.setValues(entity);
text = entity.text;
} // setValues(InternalEntity)
} // class InternalEntity
/**
* External entity.
*
* @author Andy Clark, IBM
*/
protected static class ExternalEntity
extends Entity {
// Data
/** container for all relevant entity location information. */
public XMLResourceIdentifier entityLocation;
/** Notation name for unparsed entity. */
public String notation;
// Constructors
/** Default constructor. */
public ExternalEntity() {
clear();
} // <init>()
/** Constructs an internal entity. */
public ExternalEntity(String name, XMLResourceIdentifier entityLocation,
String notation, boolean inExternalSubset) {
super(name,inExternalSubset);
this.entityLocation = entityLocation;
this.notation = notation;
} // <init>(String,XMLResourceIdentifier, String)
// Entity methods
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return true;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return notation != null;
} // isUnparsed():boolean
/** Clears the entity. */
public void clear() {
super.clear();
entityLocation = null;
notation = null;
} // clear()
/** Sets the values of the entity. */
public void setValues(Entity entity) {
super.setValues(entity);
entityLocation = null;
notation = null;
} // setValues(Entity)
/** Sets the values of the entity. */
public void setValues(ExternalEntity entity) {
super.setValues(entity);
entityLocation = entity.entityLocation;
notation = entity.notation;
} // setValues(ExternalEntity)
} // class ExternalEntity
/**
* Entity state.
*
* @author Andy Clark, IBM
*/
public class ScannedEntity
extends Entity {
// Data
/** Input stream. */
public InputStream stream;
/** Reader. */
public Reader reader;
// locator information
/** entity location information */
public XMLResourceIdentifier entityLocation;
/** Line number. */
public int lineNumber = 1;
/** Column number. */
public int columnNumber = 1;
// encoding
/** Auto-detected encoding. */
public String encoding;
// status
/** True if in a literal. */
public boolean literal;
// whether this is an external or internal scanned entity
public boolean isExternal;
// buffer
/** Character buffer. */
public char[] ch = null;
/** Position in character buffer. */
public int position;
/** Count of characters in buffer. */
public int count;
// to allow the reader/inputStream to behave efficiently:
public boolean mayReadChunks;
// Constructors
/** Constructs a scanned entity. */
public ScannedEntity(String name,
XMLResourceIdentifier entityLocation,
InputStream stream, Reader reader,
String encoding, boolean literal, boolean mayReadChunks, boolean isExternal) {
super(name,XMLEntityManager.this.fInExternalSubset);
this.entityLocation = entityLocation;
this.stream = stream;
this.reader = reader;
this.encoding = encoding;
this.literal = literal;
this.mayReadChunks = mayReadChunks;
this.isExternal = isExternal;
this.ch = new char[isExternal ? fBufferSize : DEFAULT_INTERNAL_BUFFER_SIZE];
} // <init>(StringXMLResourceIdentifier,InputStream,Reader,String,boolean, boolean)
// Entity methods
/** Returns true if this is an external entity. */
public final boolean isExternal() {
return isExternal;
} // isExternal():boolean
/** Returns true if this is an unparsed entity. */
public final boolean isUnparsed() {
return false;
} // isUnparsed():boolean
public void setReader(InputStream stream, String encoding, Boolean isBigEndian) throws IOException {
reader = createReader(stream, encoding, isBigEndian);
}
// return the expanded system ID of the
// first external entity on the stack, null
// otherwise.
public String getExpandedSystemId() {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i = size - 1; i >= 0 ; i
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null &&
externalEntity.entityLocation.getExpandedSystemId() != null) {
return externalEntity.entityLocation.getExpandedSystemId();
}
}
return null;
}
// return literal systemId of
// nearest external entity
public String getLiteralSystemId() {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i = size - 1; i >= 0 ; i
ScannedEntity externalEntity =
(ScannedEntity)fEntityStack.elementAt(i);
if (externalEntity.entityLocation != null &&
externalEntity.entityLocation.getLiteralSystemId() != null) {
return externalEntity.entityLocation.getLiteralSystemId();
}
}
return null;
}
// return line number of position in most
// recent external entity
public int getLineNumber() {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i=size-1; i>0 ; i
ScannedEntity firstExternalEntity = (ScannedEntity)fEntityStack.elementAt(i);
if (firstExternalEntity.isExternal()) {
return firstExternalEntity.lineNumber;
}
}
return -1;
}
// return column number of position in most
// recent external entity
public int getColumnNumber() {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i=size-1; i>0 ; i
ScannedEntity firstExternalEntity = (ScannedEntity)fEntityStack.elementAt(i);
if (firstExternalEntity.isExternal()) {
return firstExternalEntity.columnNumber;
}
}
return -1;
}
// return encoding of most recent external entity
public String getEncoding() {
// search for the first external entity on the stack
int size = fEntityStack.size();
for (int i=size-1; i>0 ; i
ScannedEntity firstExternalEntity = (ScannedEntity)fEntityStack.elementAt(i);
if (firstExternalEntity.isExternal()) {
return firstExternalEntity.encoding;
}
}
return null;
}
// Object methods
/** Returns a string representation of this object. */
public String toString() {
StringBuffer str = new StringBuffer();
str.append("name=\""+name+'"');
str.append(",ch="+ch);
str.append(",position="+position);
str.append(",count="+count);
return str.toString();
} // toString():String
} // class ScannedEntity
// This class wraps the byte inputstreams we're presented with.
// We need it because java.io.InputStreams don't provide
// functionality to reread processed bytes, and they have a habit
// of reading more than one character when you call their read()
// methods. This means that, once we discover the true (declared)
// encoding of a document, we can neither backtrack to read the
// whole doc again nor start reading where we are with a new
// reader.
// This class allows rewinding an inputStream by allowing a mark
// to be set, and the stream reset to that position. <strong>The
// class assumes that it needs to read one character per
// invocation when it's read() method is inovked, but uses the
// underlying InputStream's read(char[], offset length) method--it
// won't buffer data read this way!</strong>
// @author Neil Graham, IBM
// @author Glenn Marcy, IBM
protected final class RewindableInputStream extends InputStream {
private InputStream fInputStream;
private byte[] fData;
private int fStartOffset;
private int fEndOffset;
private int fOffset;
private int fLength;
private int fMark;
public RewindableInputStream(InputStream is) {
fData = new byte[DEFAULT_XMLDECL_BUFFER_SIZE];
fInputStream = is;
fStartOffset = 0;
fEndOffset = -1;
fOffset = 0;
fLength = 0;
fMark = 0;
}
public void setStartOffset(int offset) {
fStartOffset = offset;
}
public void rewind() {
fOffset = fStartOffset;
}
public int read() throws IOException {
int b = 0;
if (fOffset < fLength) {
return fData[fOffset++] & 0xff;
}
if (fOffset == fEndOffset) {
return -1;
}
if (fOffset == fData.length) {
byte[] newData = new byte[fOffset << 1];
System.arraycopy(fData, 0, newData, 0, fOffset);
fData = newData;
}
b = fInputStream.read();
if (b == -1) {
fEndOffset = fOffset;
return -1;
}
fData[fLength++] = (byte)b;
fOffset++;
return b & 0xff;
}
public int read(byte[] b, int off, int len) throws IOException {
int bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return -1;
}
// better get some more for the voracious reader...
if(fCurrentEntity.mayReadChunks) {
return fInputStream.read(b, off, len);
}
int returnedVal = read();
if(returnedVal == -1) {
fEndOffset = fOffset;
return -1;
}
b[off] = (byte)returnedVal;
return 1;
}
if (len < bytesLeft) {
if (len <= 0) {
return 0;
}
}
else {
len = bytesLeft;
}
if (b != null) {
System.arraycopy(fData, fOffset, b, off, len);
}
fOffset += len;
return len;
}
public long skip(long n)
throws IOException
{
int bytesLeft;
if (n <= 0) {
return 0;
}
bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return 0;
}
return fInputStream.skip(n);
}
if (n <= bytesLeft) {
fOffset += n;
return n;
}
fOffset += bytesLeft;
if (fOffset == fEndOffset) {
return bytesLeft;
}
n -= bytesLeft;
/*
* In a manner of speaking, when this class isn't permitting more
* than one byte at a time to be read, it is "blocking". The
* available() method should indicate how much can be read without
* blocking, so while we're in this mode, it should only indicate
* that bytes in its buffer are available; otherwise, the result of
* available() on the underlying InputStream is appropriate.
*/
return fInputStream.skip(n) + bytesLeft;
}
public int available() throws IOException {
int bytesLeft = fLength - fOffset;
if (bytesLeft == 0) {
if (fOffset == fEndOffset) {
return -1;
}
return fCurrentEntity.mayReadChunks ? fInputStream.available()
: 0;
}
return bytesLeft;
}
public void mark(int howMuch) {
fMark = fOffset;
}
public void reset() {
fOffset = fMark;
}
public boolean markSupported() {
return true;
}
public void close() throws IOException {
if (fInputStream != null) {
fInputStream.close();
fInputStream = null;
}
}
} // end of RewindableInputStream class
} // class XMLEntityManager
|
package org.biojava.bio.dist;
import java.util.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A simple implementation of a distribution, which works with any finite alphabet.
*
* @author Matthew Pocock
* @author Thomas Down
* @author Mark Schreiber
*/
public class SimpleDistribution
extends AbstractDistribution
implements Serializable {
private transient AlphabetIndex indexer;
private double[] weights = null;
private Distribution nullModel;
private FiniteAlphabet alpha;
/**
* This method is needed so that indexer is rebuilt when this object is deserialized
*/
private void readObject(ObjectInputStream stream) throws IOException,ClassNotFoundException{
stream.defaultReadObject();
this.indexer = AlphabetManager.getAlphabetIndex(alpha);
indexer.addChangeListener(
new ChangeAdapter() {
public void preChange(ChangeEvent ce) throws ChangeVetoException {
if(hasWeights()) {
throw new ChangeVetoException(
ce,
"Can't allow the index to change as we have probabilities."
);
}
}
},
AlphabetIndex.INDEX
);
}
public Alphabet getAlphabet() {
return indexer.getAlphabet();
}
public Distribution getNullModel() {
return this.nullModel;
}
protected void setNullModelImpl(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException {
this.nullModel = nullModel;
}
protected boolean hasWeights() {
return weights != null;
}
protected double[] getWeights() {
if(weights == null) {
weights = new double[indexer.getAlphabet().size()];
for(int i = 0; i < weights.length; i++) {
weights[i] = Double.NaN;
}
}
return weights;
}
public double getWeightImpl(AtomicSymbol s)
throws IllegalSymbolException {
if(!hasWeights()) {
return Double.NaN;
} else {
return weights[indexer.indexForSymbol(s)];
}
}
protected void setWeightImpl(AtomicSymbol s, double w)
throws IllegalSymbolException, ChangeVetoException {
double[] weights = getWeights();
if(w < 0.0) {
throw new IllegalArgumentException(
"Can't set weight to negative score: " +
s.getName() + " -> " + w
);
}
weights[indexer.indexForSymbol(s)] = w;
}
public SimpleDistribution(FiniteAlphabet alphabet) {
this.alpha = alphabet;
this.indexer = AlphabetManager.getAlphabetIndex(alphabet);
indexer.addChangeListener(
new ChangeAdapter() {
public void preChange(ChangeEvent ce) throws ChangeVetoException {
if(hasWeights()) {
throw new ChangeVetoException(
ce,
"Can't allow the index to change as we have probabilities."
);
}
}
},
AlphabetIndex.INDEX
);
try {
setNullModel(new UniformDistribution(alphabet));
} catch (Exception e) {
throw new BioError(e, "This should never fail. Something is screwed!");
}
}
/**
* Register a simple trainer for this distribution.
*/
public void registerWithTrainer(DistributionTrainerContext dtc) {
dtc.registerTrainer(this, new Trainer());
}
protected class Trainer implements DistributionTrainer {
private final Count counts;
public Trainer() {
counts = new IndexedCount(indexer);
}
public void addCount(DistributionTrainerContext dtc, AtomicSymbol sym, double times)
throws IllegalSymbolException {
try {
counts.increaseCount(sym, times);
} catch (ChangeVetoException cve) {
throw new BioError(
cve, "Assertion Failure: Change to Count object vetoed"
);
}
}
public double getCount(DistributionTrainerContext dtc, AtomicSymbol sym)
throws IllegalSymbolException {
return counts.getCount(sym);
}
public void clearCounts(DistributionTrainerContext dtc) {
try {
int size = ((FiniteAlphabet) counts.getAlphabet()).size();
for(int i = 0; i < size; i++) {
counts.zeroCounts();
}
} catch (ChangeVetoException cve) {
throw new BioError(
cve, "Assertion Failure: Change to Count object vetoed"
);
}
}
public void train(DistributionTrainerContext dtc, double weight)
throws ChangeVetoException {
if(changeSupport == null) {
trainImpl(dtc, weight);
} else {
synchronized(changeSupport) {
ChangeEvent ce = new ChangeEvent(
SimpleDistribution.this,
Distribution.WEIGHTS
);
changeSupport.firePreChangeEvent(ce);
trainImpl(dtc, weight);
changeSupport.firePostChangeEvent(ce);
}
}
}
protected void trainImpl(DistributionTrainerContext dtc, double weight) {
try {
Distribution nullModel = getNullModel();
double[] weights = getWeights();
double []total = new double[weights.length];
double sum = 0.0;
for(int i = 0; i < total.length; i++) {
AtomicSymbol s = (AtomicSymbol) indexer.symbolForIndex(i);
sum += total[i] =
getCount(dtc, s) +
nullModel.getWeight(s) * weight;
}
double sum_inv = 1.0 / sum;
for(int i = 0; i < total.length; i++) {
weights[i] = total[i] * sum_inv;
}
} catch (IllegalSymbolException ise) {
throw new BioError(ise,
"Assertion Failure: Should be impossible to mess up the symbols."
);
}
}
}
}
|
package org.concord.datagraph.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.text.NumberFormat;
import javax.swing.JMenuItem;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.framework.data.stream.DataChannelDescription;
import org.concord.framework.data.stream.DataStoreEvent;
import org.concord.framework.data.stream.DataStoreListener;
import org.concord.graph.engine.CoordinateSystem;
import org.concord.graph.engine.GraphableList;
import org.concord.graph.util.ui.PointTextLabel;
/**
* DataPointLabel
* Class name and description
*
* Date created: Mar 1, 2005
*
* @author imoncada<p>
*
*/
public class DataPointLabel extends PointTextLabel
implements DataStoreListener, DataAnnotation
{
//Variables to watch the graphables that it's mousing over
protected GraphableList objList;
protected int indexPointOver = -1;
protected DataGraphable graphableOver = null;
//Actual graphable that the label is linked to
//(this is temporary because it should be a data point)
protected DataGraphable dataGraphable;
protected float fx = Float.NaN;
protected float fy = Float.NaN;
private DashedDataLine verticalDDL = new DashedDataLine(DashedDataLine.VERTICAL_LINE);
private DashedDataLine horizontalDDL = new DashedDataLine(DashedDataLine.HORIZONTAL_LINE);
//Labels and Units
protected String xLabel = null;
protected String xUnits = null;
protected String yLabel = null;
protected String yUnits = null;
protected int xPrecision = 2;
protected int yPrecision = 2;
protected String pointLabel = null; // format: (x, y)
protected String pointInfoLabel = null; //format: xlabel: x unit ylabel: y unit
private boolean showCoordinates = true;
public DataPointLabel()
{
this("Message");
}
public DataPointLabel(boolean newNote)
{
this();
this.newNote = newNote;
}
public DataPointLabel(String msg)
{
super(msg);
}
/**
* @param gList The GraphableList to set.
*/
public void setGraphableList(GraphableList gList)
{
this.objList = gList;
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#populatePopUpMenu()
*/
protected void populatePopUpMenu()
{
super.populatePopUpMenu();
JMenuItem disconnectItem = new JMenuItem("Disconnect");
popUpMenu.add(disconnectItem);
disconnectItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setDataPoint(null);
setDataGraphable(null);
}
});
}
/**
* This method is used to see whether this label should be listening
* to mouse actions. In this case, we want the label to only listen to mouse
* actions if the mouse is directly over a data line.
*/
public boolean isPointInProximity(Point location)
{
findAvailablePointOver(location);
return (indexPointOver > -1);
}
/**
* @see org.concord.graph.engine.MouseMotionReceiver#mouseMoved(java.awt.Point)
*/
public boolean mouseMoved(Point p)
{
if (newNote){
findAvailablePointOver(p);
}
return super.mouseMoved(p);
}
private void findAvailablePointOver(Point p)
{
if (objList != null){
//Look for a point in one of the graphables in the list
int index = -1;
DataGraphable dg = null;
for (int i=0; i<objList.size(); i++){
Object obj = objList.elementAt(i);
if (obj instanceof DataGraphable){
dg = (DataGraphable)obj;
if(dg.isVisible()) {
index = dg.getIndexValueAtDisplay(p, 10);
}
if (index != -1) break;
}
}
if(index == -1) {
if (index != indexPointOver || graphableOver != null){
indexPointOver = index;
graphableOver = null;
}
} else {
//Found a point!
if (index != indexPointOver || dg != graphableOver){
indexPointOver = index;
graphableOver = dg;
foreColor = dg.getColor();
}
}
notifyChange();
}
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseDragged(java.awt.Point)
*/
public boolean mouseDragged(Point p)
{
if (mouseInsideDataPoint || newEndPoint){
findAvailablePointOver(p);
notifyChange();
}
return super.mouseDragged(p);
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseReleased(java.awt.Point)
*/
public boolean mouseReleased(Point p)
{
if (dragEnabled){
if (indexPointOver != -1 && graphableOver != null){
Point2D pW = getPointDataGraphable(graphableOver, indexPointOver);
setDataPoint(pW);
}
else{
restoreOriginalDataPoint();
}
}
indexPointOver = -1;
graphableOver = null;
findAvailablePointOver(p);
if (indexPointOver != -1 && graphableOver != null){
float f1 = Float.NaN;
float f2 = Float.NaN;
Point2D p2 = getPointDataGraphable(graphableOver, indexPointOver);
setDataPoint(p2);
newEndPoint = false;
}
return super.mouseReleased(p);
}
private void restoreOriginalDataPoint()
{
if (dataPoint != null){
setDataPoint(originalDataPoint);
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#addAtPoint(java.awt.Point)
*/
public boolean addAtPoint(Point2D pD, Point2D pW)
{
if (indexPointOver != -1 && graphableOver != null){
setDataGraphable(graphableOver);
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
return super.addAtPoint(null, p);
}
else{
//super.addAtPoint(pD, pW);
setDataGraphable(null);
return false;
}
}
/**
* @param graphableOver2
* @param indexPointOver2
* @return
*/
protected static Point2D getPointDataGraphable(DataGraphable dg, int index)
{
Object objVal;
double x,y;
objVal = dg.getValueAt(index, 0);
if (!(objVal instanceof Float)) return null;
x = ((Float)objVal).floatValue();
objVal = dg.getValueAt(index, 1);
if (!(objVal instanceof Float)) return null;
y = ((Float)objVal).floatValue();
return new Point2D.Double(x, y);
}
/**
* @see org.concord.graph.engine.Drawable#draw(java.awt.Graphics2D)
*/
public void draw(Graphics2D g)
{
if (newNote || mouseInsideDataPoint || newEndPoint){
if (indexPointOver != -1 && graphableOver != null){
float f1 = Float.NaN;
float f2 = Float.NaN;
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
CoordinateSystem cs = graphArea.getCoordinateSystem();
Point2D pD = cs.transformToDisplay(p);
if (p != null){
f1 = (float)(p.getX());
f2 = (float)(p.getY());
fx = f1;
fy = f2;
g.drawOval((int)pD.getX() - 7, (int)pD.getY() - 7, 13, 13);
drawDashedLines(g, fx, fy);
updateDataPointLabels(p);
}
}
}
if(isSelected()) {
int pointInfoLabelLeft = graphArea.getInsets().left + 20;
int pointInfoLabelTop = Math.max(graphArea.getInsets().top, 20);
g.setColor(foreColor);
if(pointInfoLabel != null)
g.drawString(pointInfoLabel, pointInfoLabelLeft, pointInfoLabelTop);
}
// If the graphable is null we draw ourselves no matter what
// if the graphable is not null then we draw ourselves only if it's visible
if(dataGraphable == null || dataGraphable.isVisible()) {
super.draw(g);
}
}
/**
* @return Returns the dataGraphable.
*/
public DataGraphable getDataGraphable()
{
return dataGraphable;
}
/**
* @param dataGraphable The dataGraphable to set.
*/
public void setDataGraphable(DataGraphable dataGraphable)
{
if (this.dataGraphable == dataGraphable) return;
if (this.dataGraphable != null){
this.dataGraphable.removeDataStoreListener(this);
}
this.dataGraphable = dataGraphable;
if (this.dataGraphable != null){
this.dataGraphable.addDataStoreListener(this);
int numberOfChannels = dataGraphable.getTotalNumChannels();
if(numberOfChannels < 2) return;
DataChannelDescription dcd1 = dataGraphable.getDataChannelDescription(0);
DataChannelDescription dcd2 = dataGraphable.getDataChannelDescription(1);
if(dcd1 == null) return;
if(dcd2 == null) return;
xLabel = dcd1.getName();
if(xLabel == null || xLabel.length() == 0) xLabel = "";
else xLabel = xLabel +": ";
if(dcd1.getUnit() != null) xUnits = dcd1.getUnit().getDimension();
else xUnits = "";
if(dcd1.isUsePrecision()) xPrecision = dcd1.getPrecision() + 1;
else xPrecision = 2;
yLabel = dcd2.getName();
if(yLabel == null || yLabel.length() == 0) yLabel = "";
else yLabel = yLabel + ": ";
if(dcd2.getUnit() != null) yUnits = dcd2.getUnit().getDimension();
else yUnits = "";
if(dcd2.isUsePrecision()) yPrecision = dcd2.getPrecision() + 1;
else yPrecision = 2;
Point2D point = getDataPoint();
if(point != null) {
updateDataPointLabels();
}
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#doRemove()
*/
protected void doRemove()
{
setDataGraphable(null);
super.doRemove();
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataAdded(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataAdded(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChanged(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataRemoved(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataRemoved(DataStoreEvent evt)
{
//FIXME See if the point is still in the DataGraphable?
//For now, I'll check if the graphable is empty
if(this.dataGraphable == null) return;
if (this.dataGraphable.getTotalNumSamples() == 0){
remove();
}
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChannelDescChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChannelDescChanged(DataStoreEvent evt)
{
}
protected void drawDashedLines(Graphics2D g, float d1, float d2) {
setDashedLines(d1, d2);
verticalDDL.draw(g);
horizontalDDL.draw(g);
}
protected void setDashedLines(float d1, float d2) {
Point2D pVO = new Point2D.Double(d1,0);
Point2D pD = new Point2D.Double(d1,d2);
Point2D pHO = new Point2D.Double(0, d2);
verticalDDL.setDataPrecision(xPrecision);
horizontalDDL.setDataPrecision(yPrecision);
verticalDDL.setPoints(pVO, pD);
horizontalDDL.setPoints(pHO, pD);
DashedDataLine.setGraphArea(graphArea);
}
protected void updateDataPointLabels(Point2D p)
{
float f1 = (float)p.getX();
float f2 = (float)p.getY();
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(xPrecision);
pointInfoLabel = ((xLabel== null)?"":xLabel) + nf.format(f1) + ((xUnits== null)?"":xUnits) + " ";
pointLabel = "(" + nf.format(f1) + ((xUnits== null)?"":xUnits) + ", ";
nf.setMaximumFractionDigits(yPrecision);
pointInfoLabel += ((yLabel== null)?"":yLabel) + nf.format(f2) + ((yUnits== null)?"":yUnits);
pointLabel += nf.format(f2) + ((yUnits== null)?"":yUnits) + ")";
}
protected void updateDataPointLabels()
{
Point2D p = getDataPoint();
if (p == null){
pointLabel = "";
return;
}
updateDataPointLabels(p);
}
public void setDataPoint(Point2D p) {
super.setDataPoint(p);
updateDataPointLabels();
}
protected void drawMessage(Graphics2D g, boolean bDraw)
{
String words[];
String word;
double xIni = displayPositionIni.getX() + 3;
double yIni = displayPositionIni.getY() + 12;
double x = xIni;
double y = yIni;
double ww, w = 0, h;
FontMetrics fontM;
if (message == null) return;
fontM = g.getFontMetrics();
h = fontM.getHeight() - 2;
g.setColor(foreColor);
g.setFont(font);
words = message.split(" ");
for (int i=0; i < words.length; i++){
word = words[i] + " ";
//System.out.println("\""+word+"\"");
w = fontM.stringWidth(word);
if (x + w - xIni > maxWidth){
y += h;
x = xIni;
}
if (bDraw){
g.drawString(word, (int)x, (int)y);
}
x += w;
}
//// Draw uneditable coordinate values
double labelWidth = Double.NaN;
if(pointLabel != null && pointLabel.length() > 0 && getShowCoordinates()) {
y+= h;
Color oldColor = g.getColor();
Color backColor = g.getBackground();
Color newColor = new Color(255-backColor.getRed(), 255-backColor.getGreen(), 255-backColor.getBlue());
g.setColor(newColor);
g.drawString(pointLabel, (int)xIni, (int)y);
labelWidth = fontM.stringWidth(pointLabel);
g.setColor(oldColor);
msgChanged = true;
}
if (msgChanged){
msgChanged = false;
if(labelWidth != Double.NaN) ww = Math.max(maxWidth, labelWidth);
else ww = maxWidth;
if (y == yIni && !message.equals("")){
ww = x - xIni;
}
y += h;
Dimension d = new Dimension((int)(ww), (int)(y - yIni + 6));
setSize(d);
}
}
public void setShowCoordinates(boolean showCoordinates)
{
this.showCoordinates = showCoordinates;
}
public boolean getShowCoordinates()
{
return showCoordinates;
}
public void setCoordinateDecimalPlaces(int coordinateDecimalPlaces)
{
this.xPrecision = coordinateDecimalPlaces;
this.yPrecision = coordinateDecimalPlaces;
updateDataPointLabels();
}
}
|
package org.exist.http.servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
/**
* @author Wolfgang Meier (wolfgang@exist-db.org)
*/
public interface ResponseWrapper {
/**
* @param name Name of the Cookie
* @param value Value of the Cookie
*/
public void addCookie(String name, String value);
/**
* @param arg0
* @param arg1
*/
public void addDateHeader(String arg0, long arg1);
/**
* @param arg0
* @param arg1
*/
public void addHeader(String arg0, String arg1);
/**
* @param arg0
* @param arg1
*/
public void addIntHeader(String arg0, int arg1);
/**
* @param arg0 The name of the header.
* @return A boolean value indicating whether it contains the header name.
*/
public boolean containsHeader(String arg0);
/**
* @param arg0
* @return The encoded value
*/
public String encodeURL(String arg0);
/**
* @return Returns the default character encoding
*/
public String getCharacterEncoding();
/**
* @return Returns the default locale
*/
public Locale getLocale();
/**
* @param arg0
* @param arg1
*/
public void setDateHeader(String arg0, long arg1);
/**
* @param arg0
* @param arg1
*/
public void setHeader(String arg0, String arg1);
/**
* @param arg0
* @param arg1
*/
public void setIntHeader(String arg0, int arg1);
/**
* @param arg0
*/
public void setLocale(Locale arg0);
public void sendRedirect(String arg0) throws IOException;
/** @return the value of Date Header corresponding to given name,
* 0 if none has been set. */
public long getDateHeader(String name);
public OutputStream getOutputStream() throws IOException;
}
|
package org.irmacard.cardemu.selfenrol;
import android.app.*;
import android.content.*;
import android.content.res.Resources;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.*;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import net.sf.scuba.smartcards.*;
import org.irmacard.cardemu.*;
import org.irmacard.cardemu.BuildConfig;
import org.irmacard.credentials.Attributes;
import org.irmacard.credentials.CredentialsException;
import org.irmacard.credentials.idemix.IdemixCredentials;
import org.irmacard.credentials.idemix.descriptions.IdemixVerificationDescription;
import org.irmacard.credentials.idemix.smartcard.IRMACard;
import org.irmacard.credentials.idemix.smartcard.SmartCardEmulatorService;
import org.irmacard.credentials.info.CredentialDescription;
import org.irmacard.credentials.info.InfoException;
import org.irmacard.idemix.IdemixService;
import org.irmacard.idemix.IdemixSmartcard;
import org.irmacard.mno.common.BasicClientMessage;
import org.irmacard.mno.common.EnrollmentStartMessage;
import org.irmacard.mno.common.RequestFinishIssuanceMessage;
import org.irmacard.mno.common.RequestStartIssuanceMessage;
import org.jmrtd.BACKey;
import org.jmrtd.PassportService;
import java.io.*;
import java.lang.reflect.Type;
import java.net.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import com.google.gson.GsonBuilder;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class Passport extends Activity {
private NfcAdapter nfcA;
private PendingIntent mPendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private String TAG = "cardemu.Passport";
// PIN handling
private int tries = -1;
// State variables
private IRMACard card = null;
private IdemixService is = null;
private int screen;
private static final int SCREEN_START = 1;
private static final int SCREEN_BAC = 2;
private static final int SCREEN_PASSPORT = 3;
private static final int SCREEN_ISSUE = 4;
private static final int SCREEN_ERROR = 5;
private String imsi;
private final String CARD_STORAGE = "card";
private final String SETTINGS = "cardemu";
private AlertDialog urldialog = null;
private String enrollServerUrl;
private SharedPreferences settings;
private SimpleDateFormat bacDateFormat = new SimpleDateFormat("yyMMdd");
private DateFormat hrDateFormat = DateFormat.getDateInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Disable screenshots in release builds
if (!BuildConfig.DEBUG) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}
// NFC stuff
nfcA = NfcAdapter.getDefaultAdapter(getApplicationContext());
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Setup an intent filter for all TECH based dispatches
IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
mFilters = new IntentFilter[] { tech };
// Setup a tech list for all IsoDep cards
mTechLists = new String[][] { new String[] { IsoDep.class.getName() } };
// Attempt to get the enroll server URL from the settings. If none is there,
// use the default value (from res/values/strings.xml)
settings = getSharedPreferences(SETTINGS, 0);
enrollServerUrl = settings.getString("enroll_server_url", "");
if (enrollServerUrl.length() == 0)
enrollServerUrl = getString(R.string.enroll_default_url);
client = new HttpClient(gson, getSocketFactory());
if(getIntent() != null) {
onNewIntent(getIntent());
}
setContentView(R.layout.enroll_activity_start);
updateHelpText();
setTitle(R.string.app_name_enroll);
TextView descriptionTextView = (TextView)findViewById(R.id.se_feedback_text);
descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());
descriptionTextView.setLinksClickable(true);
screen = SCREEN_START;
enableContinueButton();
if (nfcA == null)
showErrorScreen(R.string.error_nfc_notsupported);
if (!nfcA.isEnabled())
showErrorScreen(R.string.error_nfc_disabled);
}
private void updateHelpText() {
String helpHtml = String.format(getString(R.string.se_connect_mno), enrollServerUrl);
TextView helpTextView = (TextView)findViewById(R.id.se_feedback_text);
helpTextView.setText(Html.fromHtml(helpHtml));
}
private void enableForegroundDispatch() {
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
Intent intent = new Intent(getApplicationContext(), this.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String[][] filter = new String[][] { new String[] { "android.nfc.tech.IsoDep" } };
adapter.enableForegroundDispatch(this, pendingIntent, null, filter);
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
if (nfcA != null) {
nfcA.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
}
Intent intent = getIntent();
Log.i(TAG, "Action: " + intent.getAction());
if (intent.hasExtra("card_json")) {
loadCard();
Log.d(TAG,"loaded card");
try {
is.open ();
} catch (CardServiceException e) {
e.printStackTrace();
}
}
Context context = getApplicationContext ();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
imsi = telephonyManager.getSubscriberId();
if (imsi == null)
imsi = "FAKE_IMSI_" + Settings.Secure.getString(
context.getContentResolver(), Settings.Secure.ANDROID_ID);
if (screen == SCREEN_START) {
((TextView) findViewById(R.id.IMSI)).setText("IMSI: " + imsi);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
//TODO: move all card functionality to a specific class, so we don't need this ugly code duplication and can do explicit card state checks there.
protected void logCard(){
Log.d(TAG, "Current card contents");
// Retrieve list of credentials from the card
IdemixCredentials ic = new IdemixCredentials(is);
List<CredentialDescription> credentialDescriptions = new ArrayList<CredentialDescription>();
// HashMap<CredentialDescription,Attributes> credentialAttributes = new HashMap<CredentialDescription,Attributes>();
try {
ic.connect();
is.sendCardPin("000000".getBytes());
credentialDescriptions = ic.getCredentials();
for(CredentialDescription cd : credentialDescriptions) {
Log.d(TAG,cd.getName());
}
} catch (CardServiceException|InfoException|CredentialsException e) {
e.printStackTrace();
}
}
private void storeCard() {
Log.d(TAG, "Storing card");
SharedPreferences.Editor editor = settings.edit();
Gson gson = new Gson();
editor.putString(CARD_STORAGE, gson.toJson(card));
editor.commit();
}
private void loadCard() {
String card_json = settings.getString(CARD_STORAGE, "");
Gson gson = new Gson();
card = gson.fromJson(card_json, IRMACard.class);
is = new IdemixService(new SmartCardEmulatorService(card));
}
@Override
public void onPause() {
super.onPause();
if (nfcA != null) {
nfcA.disableForegroundDispatch(this);
}
}
public void processIntent(Intent intent) {
// Only handle this event if we expect it
if (screen != SCREEN_PASSPORT)
return;
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
assert (tagFromIntent != null);
IsoDep tag = IsoDep.get(tagFromIntent);
CardService cs = new IsoDepCardService(tag);
PassportService passportService = null;
// Spongycastle provides the MAC ISO9797Alg3Mac, which JMRTD uses
// in the doBAC method below (at DESedeSecureMessagingWrapper.java,
// line 115)
// TODO examine if Android's BouncyCastle version causes other problems;
// perhaps we should use SpongyCastle over all projects.
Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
try {
cs.open();
passportService = new PassportService(cs);
passportService.sendSelectApplet(false);
} catch (CardServiceException e) {
// TODO under what circumstances does this happen? Maybe handle it more intelligently?
showErrorScreen(R.string.error_enroll_passporterror, e);
return;
}
try {
passportService.doBAC(getBACKey());
// TODO Active Authentication
advanceScreen();
} catch (CardServiceException e) {
showErrorScreen(R.string.error_enroll_bacfailed, e);
} catch (IOException e) {
showErrorScreen(R.string.error_enroll_nobacdata, e);
}
}
private void enableContinueButton(){
final Button button = (Button) findViewById(R.id.se_button_continue);
button.setVisibility(View.VISIBLE);
button.setEnabled(true);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "continue button pressed");
advanceScreen();
}
});
}
private void updateProgressCounter() {
Resources r = getResources();
switch (screen) {
case SCREEN_ISSUE:
((TextView)findViewById(R.id.step3_text)).setTextColor(r.getColor(R.color.irmadarkblue));
case SCREEN_PASSPORT:
((TextView)findViewById(R.id.step2_text)).setTextColor(r.getColor(R.color.irmadarkblue));
case SCREEN_BAC:
((TextView)findViewById(R.id.step1_text)).setTextColor(r.getColor(R.color.irmadarkblue));
((TextView)findViewById(R.id.step_text)).setTextColor(r.getColor(R.color.irmadarkblue));
}
}
private void showErrorScreen(int errormsgId) {
showErrorScreen(getString(errormsgId), null);
}
private void showErrorScreen(String errormsg) {
showErrorScreen(errormsg, null);
}
private void showErrorScreen(Exception e) {
showErrorScreen(e.getMessage(), e);
}
private void showErrorScreen(int errormsgId, Exception e) {
showErrorScreen(getString(errormsgId), e);
}
private void showErrorScreen(String errormsg, Exception e) {
prepareErrowScreen();
TextView view = (TextView)findViewById(R.id.enroll_error_msg);
TextView stacktraceView = (TextView)findViewById(R.id.error_stacktrace);
Button button = (Button)findViewById(R.id.se_button_continue);
view.setText(errormsg);
if (e != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
stacktraceView.setText(stacktrace);
}
else
stacktraceView.setText("");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
screen = SCREEN_START;
finish();
}
});
}
private void prepareErrowScreen() {
setContentView(R.layout.enroll_activity_error);
Resources r = getResources();
switch (screen) {
case SCREEN_ISSUE:
((TextView)findViewById(R.id.step3_text)).setTextColor(r.getColor(R.color.irmared));
case SCREEN_PASSPORT:
((TextView)findViewById(R.id.step2_text)).setTextColor(r.getColor(R.color.irmared));
case SCREEN_BAC:
((TextView)findViewById(R.id.step1_text)).setTextColor(r.getColor(R.color.irmared));
case SCREEN_START:
((TextView)findViewById(R.id.step_text)).setTextColor(r.getColor(R.color.irmared));
}
}
private void advanceScreen() {
switch (screen) {
case SCREEN_START:
setContentView(R.layout.enroll_activity_bac);
screen = SCREEN_BAC;
updateProgressCounter();
enableContinueButton();
// Restore the BAC input fields from the settings, if present
long bacDob = settings.getLong("enroll_bac_dob", 0);
long bacDoe = settings.getLong("enroll_bac_doe", 0);
String docnr = settings.getString("enroll_bac_docnr", "");
EditText docnrEditText = (EditText) findViewById(R.id.doc_nr_edittext);
EditText dobEditText = (EditText) findViewById(R.id.dob_edittext);
EditText doeEditText = (EditText) findViewById(R.id.doe_edittext);
Calendar c = Calendar.getInstance();
if (bacDob != 0) {
c.setTimeInMillis(bacDob);
setDateEditText(dobEditText, c);
}
if (bacDoe != 0) {
c.setTimeInMillis(bacDoe);
setDateEditText(doeEditText, c);
}
if (docnr.length() != 0)
docnrEditText.setText(docnr);
break;
case SCREEN_BAC:
// Store the entered document number and dates in the settings.
docnrEditText = (EditText) findViewById(R.id.doc_nr_edittext);
dobEditText = (EditText) findViewById(R.id.dob_edittext);
doeEditText = (EditText) findViewById(R.id.doe_edittext);
bacDob = 0;
bacDoe = 0;
try {
String dobString = dobEditText.getText().toString();
String doeString = doeEditText.getText().toString();
if (dobString.length() != 0)
bacDob = hrDateFormat.parse(dobString).getTime();
if (doeString.length() != 0)
bacDoe = hrDateFormat.parse(doeString).getTime();
} catch (ParseException e) {
// Should not happen: the DOB and DOE EditTexts are set only by the DatePicker's,
// OnDateSetListener, which should always set a properly formatted string.
e.printStackTrace();
}
settings.edit()
.putLong("enroll_bac_dob", bacDob)
.putLong("enroll_bac_doe", bacDoe)
.putString("enroll_bac_docnr", docnrEditText.getText().toString())
.apply();
// Get the BasicClientMessage containing our nonce to send to the passport.
getEnrollmentSession(new Handler() {
@Override
public void handleMessage(Message msg) {
EnrollmentStartResult result = (EnrollmentStartResult) msg.obj;
if (result.exception != null) { // Something went wrong
showErrorScreen(result.errorId, result.exception);
}
else {
enrollSession = result.msg;
}
}
});
// Update the UI
screen = SCREEN_PASSPORT;
setContentView(R.layout.enroll_activity_passport);
invalidateOptionsMenu();
updateProgressCounter();
break;
case SCREEN_PASSPORT:
setContentView(R.layout.enroll_activity_issue);
screen = SCREEN_ISSUE;
updateProgressCounter();
// Do it!
// POSSIBLE CAVEAT: If we are here, then it is because the passport-present-intent called advanceFunction().
// In principle, this can happen as soon as the app advances from SCREEN_BAC to SCREEN_PASSPORT - that is,
// when the code from the case above this one runs. In that case statement, we fetch an enrollment session
// asynchroneously. This means that the enroll() method (which assumes an enrollment session has been
// set in the member enrollSession) could conceivably be invoked before this member is set.
// However, assuming the server responds to our get-session-request at normal speeds, the user would have
// to put his phone on the passport absurdly fast to achieve this, so for now we simply assume this does
// not happen. TODO prevent this from going wrong, perhaps using some timer
enroll(new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.obj == null) {
enableContinueButton();
((TextView) findViewById(R.id.se_done_text)).setVisibility(View.VISIBLE);
} else {
String errormsg;
if (msg.what != 0)
showErrorScreen(msg.what, (Exception) msg.obj);
else
showErrorScreen((Exception) msg.obj);
}
}
});
break;
case SCREEN_ISSUE:
case SCREEN_ERROR:
screen = SCREEN_START;
finish();
break;
default:
Log.e(TAG, "Error, screen switch fall through");
break;
}
}
@Override
public void finish() {
// Prepare data intent
if (is != null) {
is.close();
}
Intent data = new Intent();
Log.d(TAG,"Storing card");
storeCard();
setResult(RESULT_OK, data);
super.finish();
}
public void onDateTouch(View v) {
final EditText dateView = (EditText) v;
final String name = v.getId() == R.id.dob_edittext ? "dob" : "doe";
Long current = settings.getLong("enroll_bac_" + name, 0);
final Calendar c = Calendar.getInstance();
if (current != 0)
c.setTimeInMillis(current);
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar date = new GregorianCalendar(year, monthOfYear, dayOfMonth);
setDateEditText(dateView, date);
}
}, currentYear, currentMonth, currentDay);
dpd.show();
}
private void setDateEditText(EditText dateView, Calendar c) {
dateView.setText(hrDateFormat.format(c.getTime()));
}
private BACKey getBACKey() throws IOException {
long dob = settings.getLong("enroll_bac_dob", 0);
long doe = settings.getLong("enroll_bac_doe", 0);
String docnr = settings.getString("enroll_bac_docnr", "");
if (dob == 0 || doe == 0 || docnr.length() == 0)
throw new IOException("BAC fields have not been set");
String dobString = bacDateFormat.format(new Date(dob));
String doeString = bacDateFormat.format(new Date(doe));
return new BACKey(docnr, dobString, doeString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (screen == SCREEN_START) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.enroll_activity_start, menu);
return true;
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "enroll menu press registered");
// Handle item selection
switch (item.getItemId()) {
case R.id.set_enroll_url:
Log.d(TAG, "set_enroll_url pressed");
// Create the dialog only once
if (urldialog == null)
urldialog = getUrlDialog();
// Show the dialog
urldialog.show();
// Pop up the keyboard
urldialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Helper function to build the URL dialog and set the listeners.
private AlertDialog getUrlDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Simple view containing the actual input field
View v = this.getLayoutInflater().inflate(R.layout.enroll_url_dialog, null);
// Set the URL field to the appropriate value
final EditText urlfield = (EditText)v.findViewById(R.id.enroll_url_field);
urlfield.setText(enrollServerUrl);
// Build the dialog
builder.setTitle(R.string.enroll_url_dialog_title)
.setView(v)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
enrollServerUrl = urlfield.getText().toString();
settings.edit().putString("enroll_server_url", enrollServerUrl).apply();
updateHelpText();
Log.d("Passport", enrollServerUrl);
}
}).setNeutralButton(R.string.default_string, null)
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Reset the URL field to the last known valid value
urlfield.setText(enrollServerUrl);
}
});
final AlertDialog urldialog = builder.create();
urldialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
// By overriding the neutral button's onClick event in this onShow listener,
// we prevent the dialog from closing when the default button is pressed.
Button defaultbutton = urldialog.getButton(DialogInterface.BUTTON_NEUTRAL);
defaultbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enrollServerUrl = getString(R.string.enroll_default_url);
urlfield.setText(enrollServerUrl);
settings.edit().putString("enroll_server_url", enrollServerUrl).apply();
// Move cursor to end of field
urlfield.setSelection(urlfield.getText().length());
updateHelpText();
}
});
// Move cursor to end of field
urlfield.setSelection(urlfield.getText().length());
}
});
// If the text from the input field changes to something that we do not consider valid
// (i.e., it is not a valid IP or domain name), we disable the OK button
urlfield.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) {
}
@Override
public void afterTextChanged(Editable s) {
Button okbutton = urldialog.getButton(DialogInterface.BUTTON_POSITIVE);
okbutton.setEnabled(isValidURL(s.toString()));
}
});
return urldialog;
}
//region Network and issuing
/**
* Check if an IP address is valid.
*
* @param url The IP to check
* @return True if valid, false otherwise.
*/
private static Boolean isValidIPAddress(String url) {
Pattern IP_ADDRESS = Pattern.compile(
"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
+ "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
+ "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
+ "|[1-9][0-9]|[0-9]))");
return IP_ADDRESS.matcher(url).matches();
}
/**
* Check if a given domain name is valid. We consider it valid if it consists of
* alphanumeric characters and dots, and if the first character is not a dot.
*
* @param url The domain to check
* @return True if valid, false otherwise
*/
private static Boolean isValidDomainName(String url) {
Pattern VALID_DOMAIN = Pattern.compile("([\\w]+[\\.\\w]*)");
return VALID_DOMAIN.matcher(url).matches();
}
/**
* Check if a given URL is valid. We consider it valid if it is either a valid
* IP address or a valid domain name, which is checked using
* using {@link #isValidDomainName(String)} Boolean} and
* {@link #isValidIPAddress(String) Boolean}.
*
* @param url The URL to check
* @return True if valid, false otherwise
*/
private static Boolean isValidURL(String url) {
String[] parts = url.split("\\.");
// If the part of the url after the rightmost dot consists
// only of numbers, it must be an IP address
if (Pattern.matches("[\\d]+", parts[parts.length-1]))
return isValidIPAddress(url);
else
return isValidDomainName(url);
}
public static String inputStreamToString(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
br.close();
is.close();
return sb.toString();
}
String serverUrl;
private SSLSocketFactory getSocketFactory() {
try {
Resources r = getResources();
// Get the certificate from the res/raw folder and parse it
InputStream ins = r.openRawResource(r.getIdentifier("ca", "raw", getPackageName()));
Certificate ca;
try {
ca = CertificateFactory.getInstance("X.509").generateCertificate(ins);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
ins.close();
}
// Put the certificate in the keystore, put that in the TrustManagerFactory,
// put that in the SSLContext, from which we get the SSLSocketFactory
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(keyStore);
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return new SecureSSLSocketFactory(context.getSocketFactory());
} catch (KeyManagementException|NoSuchAlgorithmException|KeyStoreException|CertificateException|IOException e) {
e.printStackTrace();
return null;
}
}
final Gson gson = new GsonBuilder()
.registerTypeAdapter(ProtocolCommand.class, new ProtocolCommandDeserializer())
.registerTypeAdapter(ProtocolResponse.class, new ProtocolResponseSerializer())
.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter())
.create();
HttpClient client = null;
EnrollmentStartMessage enrollSession = null;
/**
* Simple class to store the result of getEnrollmentSession
* (either an EnrollmentStartMessage or an exception plus error message id (use R.strings))
*/
private class EnrollmentStartResult {
public EnrollmentStartMessage msg = null;
public HttpClientException exception = null;
public int errorId = 0;
public EnrollmentStartResult(EnrollmentStartMessage msg) {
this(msg, null, 0);
}
public EnrollmentStartResult(HttpClientException exception) {
this(null, exception, 0);
}
public EnrollmentStartResult(HttpClientException exception, int errorId) {
this(null, exception, errorId);
}
public EnrollmentStartResult(EnrollmentStartMessage msg, HttpClientException exception, int errorId) {
this.msg = msg;
this.exception = exception;
this.errorId = errorId;
}
}
public void getEnrollmentSession(final Handler uiHandler) {
serverUrl = "http://" + enrollServerUrl + ":8080/irma_mno_server/api/v1";
AsyncTask<Void, Void, EnrollmentStartResult> task = new AsyncTask<Void, Void, EnrollmentStartResult>() {
@Override
protected EnrollmentStartResult doInBackground(Void... params) {
try {
EnrollmentStartMessage msg = client.doGet(EnrollmentStartMessage.class, serverUrl + "/start");
return new EnrollmentStartResult(msg);
} catch (HttpClientException e) { // TODO
if (e.cause instanceof JsonSyntaxException)
return new EnrollmentStartResult(e, R.string.error_enroll_invalidresponse);
else
return new EnrollmentStartResult(e, R.string.error_enroll_cantconnect);
}
}
@Override
protected void onPostExecute(EnrollmentStartResult result) {
Message msg = Message.obtain();
msg.obj = result;
uiHandler.sendMessage(msg);
}
}.execute();
}
/**
* Do the enrolling and send a message to uiHandler when done. If something
* went wrong, the .obj of the message sent to uiHandler will be an exception;
* if everything went OK the .obj will be null.
* TODO return our result properly using a class like EnrollmentStartResult above
*
* @param uiHandler The handler to message when done.
*/
public void enroll(final Handler uiHandler) {
serverUrl = "http://" + enrollServerUrl + ":8080/irma_mno_server/api/v1";
// Doing HTTP(S) stuff on the main thread is not allowed.
AsyncTask<EnrollmentStartMessage, Void, Message> task = new AsyncTask<EnrollmentStartMessage, Void, Message>() {
@Override
protected Message doInBackground(EnrollmentStartMessage... params) {
Message msg = Message.obtain();
try {
// Get a session token
EnrollmentStartMessage session = params[0];
// Get a list of credential that the client can issue
BasicClientMessage bcm = new BasicClientMessage(session.getSessionToken());
Type t = new TypeToken<HashMap<String, Map<String, String>>>() {}.getType();
HashMap<String, Map<String, String>> credentialList =
client.doPost(t, serverUrl + "/issue/credential-list", bcm);
// Get them all!
for (String credentialType : credentialList.keySet()) {
issue(credentialType, session);
}
} catch (CardServiceException // Issuing the credential to the card failed
|InfoException // VerificationDescription not found in configurarion
|CredentialsException e) { // Verification went wrong
e.printStackTrace();
msg.obj = e;
msg.what = R.string.error_enroll_issuing_failed;
} catch (HttpClientException e) {
e.printStackTrace();
msg.obj = e;
if (e.cause instanceof JsonSyntaxException)
msg.what = R.string.error_enroll_invalidresponse;
else
msg.what = R.string.error_enroll_cantconnect;
}
return msg;
}
private void issue(String credentialType, EnrollmentStartMessage session)
throws HttpClientException, CardServiceException, InfoException, CredentialsException {
// Get the first batch of commands for issuing
RequestStartIssuanceMessage startMsg = new RequestStartIssuanceMessage(
session.getSessionToken(),
is.execute(IdemixSmartcard.selectApplicationCommand).getData()
);
ProtocolCommands issueCommands = client.doPost(ProtocolCommands.class,
serverUrl + "/issue/" + credentialType + "/start", startMsg);
// Execute the retrieved commands
is.sendCardPin("0000".getBytes()); // TODO
ProtocolResponses responses = is.execute(issueCommands);
// Get the second batch of commands for issuing
RequestFinishIssuanceMessage finishMsg
= new RequestFinishIssuanceMessage(session.getSessionToken(), responses);
issueCommands = client.doPost(ProtocolCommands.class,
serverUrl + "/issue/" + credentialType + "/finish", finishMsg);
// Execute the retrieved commands
is.execute(issueCommands);
// Check if it worked
IdemixCredentials ic = new IdemixCredentials(is);
IdemixVerificationDescription ivd = new IdemixVerificationDescription(
"MijnOverheid", credentialType + "All");
Attributes attributes = ic.verify(ivd);
if (attributes != null)
Log.d(TAG, "Enrollment issuing succes!");
else
Log.d(TAG, "Enrollment issuing failed.");
}
@Override
protected void onPostExecute(Message msg) {
uiHandler.sendMessage(msg);
}
}.execute(enrollSession);
}
/**
* Exception class for HttpClient.
*/
public class HttpClientException extends Exception {
public int status;
public Throwable cause;
public HttpClientException(int status, Throwable cause) {
super(cause);
this.cause = cause;
this.status = status;
}
}
/**
* Convenience class to synchroniously do HTTP GET and PUT requests,
* and serialize the in- and output automatically using Gson. <br/>
* NOTE: the methods of this class must not be used on the main thread,
* as otherwise a NetworkOnMainThreadException will occur.
*/
public class HttpClient {
private Gson gson;
private SSLSocketFactory socketFactory;
private int timeout = 5000;
/**
* Instantiate a new HttpClient.
*
* @param gson The Gson object that will handle (de)serialization.
*/
public HttpClient(Gson gson) {
this(gson, null);
}
/**
* Instantiate a new HttpClient.
* @param gson The Gson object that will handle (de)serialization.
* @param socketFactory The SSLSocketFactory to use.
*/
public HttpClient(Gson gson, SSLSocketFactory socketFactory) {
this.gson = gson;
this.socketFactory = socketFactory;
}
/**
* Performs a GET on the specified url. See the javadoc of doPost.
*
* @param type The type to which the return value should be cast. If the casting fails
* an exception will be raised.
* @param url The url to post to.
* @param <T> The object to post. May be null, in which case we do a GET instead
* of post.
* @return The T returned by the server, if successful.
* @throws HttpClientException
*/
public <T> T doGet(final Type type, String url) throws HttpClientException {
return doPost(type, url, null);
}
public <T> T doPost(final Type type, String url, Object object) throws HttpClientException {
HttpURLConnection c = null;
String method;
if (object == null)
method = "GET";
else
method = "POST";
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
if (url.startsWith("https") && socketFactory != null)
((HttpsURLConnection) c).setSSLSocketFactory(socketFactory);
c.setRequestMethod(method);
c.setUseCaches(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
byte[] objectBytes = new byte[] {};
if (method.equals("POST")) {
objectBytes = gson.toJson(object).getBytes();
c.setDoOutput(true);
c.setFixedLengthStreamingMode(objectBytes.length);
c.setRequestProperty("Content-Type", "application/json;charset=utf-8");
}
c.connect();
if (method.equals("POST")) {
OutputStream os = new BufferedOutputStream(c.getOutputStream());
os.write(objectBytes);
os.flush();
}
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
return gson.fromJson(inputStreamToString(c.getInputStream()), type);
default:
throw new HttpClientException(status, null);
}
} catch (JsonSyntaxException|IOException e) { // IOException includes MalformedURLException
e.printStackTrace();
throw new HttpClientException(0, e);
} finally {
if (c != null) {
c.disconnect();
}
}
}
}
//endregion
}
|
package org.loklak.api.server;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.loklak.Caretaker;
import org.loklak.data.DAO;
import org.loklak.http.RemoteAccess;
import org.loklak.tools.CharacterCoding;
import org.loklak.tools.UTF8;
public class ThreaddumpServlet extends HttpServlet {
private static final long serialVersionUID = -7095346222464124198L;
private static final String multiDumpFilter = ".*((java.net.DatagramSocket.receive)|(java.lang.Thread.getAllStackTraces)|(java.net.SocketInputStream.read)|(java.net.ServerSocket.accept)|(java.net.Socket.connect)).*";
private static final Pattern multiDumpFilterPattern = Pattern.compile(multiDumpFilter);
private static ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
private static OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
RemoteAccess.Post post = RemoteAccess.evaluate(request);
String servlet = post.isLocalhostAccess() ? post.get("servlet", "") : "";
if (servlet.length() > 0) {
try {
final Class<?> servletClass = ClassLoader.getSystemClassLoader().loadClass("org.loklak.api.server." + servlet);
final Method getMethod = servletClass.getDeclaredMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
final Thread servletThread = new Thread(new Runnable() {
public void run() {
try {
getMethod.invoke(servletClass.newInstance(), request, new DummyResponse());
} catch (IllegalArgumentException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
});
servletThread.start();
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
long sleep = post.get("sleep", 0L);
if (sleep > 0) try {Thread.sleep(sleep);} catch (InterruptedException e) {}
}
int multi = post.isLocalhostAccess() ? post.get("multi", 0) : 0;
final StringBuilder buffer = new StringBuilder(1000);
// Thread dump
final Date dt = new Date();
Runtime runtime = Runtime.getRuntime();
int keylen = 30;
bufferappend(buffer, "************* Start Thread Dump " + dt + " *******************");
bufferappend(buffer, "");
bufferappend(buffer, keylen, "Assigned Memory", runtime.maxMemory());
bufferappend(buffer, keylen, "Used Memory", runtime.totalMemory() - runtime.freeMemory());
bufferappend(buffer, keylen, "Available Memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
bufferappend(buffer, keylen, "Cores", runtime.availableProcessors());
bufferappend(buffer, keylen, "Active Thread Count", Thread.activeCount());
bufferappend(buffer, keylen, "Total Started Thread Count", threadBean.getTotalStartedThreadCount());
bufferappend(buffer, keylen, "Peak Thread Count", threadBean.getPeakThreadCount());
bufferappend(buffer, keylen, "System Load Average", osBean.getSystemLoadAverage());
long runtimeseconds = (System.currentTimeMillis() - Caretaker.startupTime) / 1000;
int runtimeminutes = (int) (runtimeseconds / 60); runtimeseconds = runtimeseconds % 60;
int runtimehours = runtimeminutes / 60; runtimeminutes = runtimeminutes % 60;
bufferappend(buffer, keylen, "Runtime", runtimehours + "h " + runtimeminutes + "m " + runtimeseconds + "s");
long timetorestartseconds = (Caretaker.upgradeTime - System.currentTimeMillis()) / 1000;
int timetorestartminutes = (int) (timetorestartseconds / 60); timetorestartseconds = timetorestartseconds % 60;
int timetorestarthours = timetorestartminutes / 60; timetorestartminutes = timetorestartminutes % 60;
bufferappend(buffer, keylen, "Time To Restart", timetorestarthours + "h " + timetorestartminutes + "m " + timetorestartseconds + "s");
// print system beans
for (Method method : osBean.getClass().getDeclaredMethods()) try {
method.setAccessible(true);
if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
bufferappend(buffer, keylen, method.getName(), method.invoke(osBean));
}
} catch (Throwable e) {}
bufferappend(buffer, "");
bufferappend(buffer, "");
if (multi > 0) {
final ArrayList<Map<Thread,StackTraceElement[]>> traces = new ArrayList<Map<Thread,StackTraceElement[]>>();
for (int i = 0; i < multi; i++) {
try {
traces.add(ThreadDump.getAllStackTraces());
} catch (final OutOfMemoryError e) {
break;
}
}
appendStackTraceStats(buffer, traces);
} else {
// generate a single thread dump
final Map<Thread,StackTraceElement[]> stackTraces = ThreadDump.getAllStackTraces();
new ThreadDump(stackTraces, Thread.State.BLOCKED).appendStackTraces(buffer, Thread.State.BLOCKED);
new ThreadDump(stackTraces, Thread.State.RUNNABLE).appendStackTraces(buffer, Thread.State.RUNNABLE);
new ThreadDump(stackTraces, Thread.State.TIMED_WAITING).appendStackTraces(buffer, Thread.State.TIMED_WAITING);
new ThreadDump(stackTraces, Thread.State.WAITING).appendStackTraces(buffer, Thread.State.WAITING);
new ThreadDump(stackTraces, Thread.State.NEW).appendStackTraces(buffer, Thread.State.NEW);
new ThreadDump(stackTraces, Thread.State.TERMINATED).appendStackTraces(buffer, Thread.State.TERMINATED);
}
ThreadMXBean threadbean = ManagementFactory.getThreadMXBean();
bufferappend(buffer, "");
bufferappend(buffer, "THREAD LIST FROM ThreadMXBean, " + threadbean.getThreadCount() + " threads:");
bufferappend(buffer, "");
ThreadInfo[] threadinfo = threadbean.dumpAllThreads(true, true);
for (ThreadInfo ti: threadinfo) {
bufferappend(buffer, ti.getThreadName());
}
bufferappend(buffer, "");
bufferappend(buffer, "ELASTICSEARCH ClUSTER STATS");
bufferappend(buffer, DAO.clusterStats());
bufferappend(buffer, "");
bufferappend(buffer, "ELASTICSEARCH PENDING ClUSTER TASKS");
bufferappend(buffer, DAO.pendingClusterTasks());
if (post.isLocalhostAccess()) {
// this can reveal private data, so keep it on localhost access only
bufferappend(buffer, "");
bufferappend(buffer, "ELASTICSEARCH NODE SETTINGS");
bufferappend(buffer, DAO.nodeSettings().toString());
}
FileHandler.setCaching(response, 10);
post.setResponse(response, "text/plain");
response.getOutputStream().write(UTF8.getBytes(buffer.toString()));
post.finalize();
}
private static class StackTrace {
private String text;
private StackTrace(final String text) {
this.text = text;
}
@Override
public boolean equals(final Object a) {
return (a != null && a instanceof StackTrace && this.text.equals(((StackTrace) a).text));
}
@Override
public int hashCode() {
return this.text.hashCode();
}
@Override
public String toString() {
return this.text;
}
}
private static void appendStackTraceStats(
final StringBuilder buffer,
final List<Map<Thread, StackTraceElement[]>> stackTraces) {
// collect single dumps
final Map<String, Integer> dumps = new HashMap<String, Integer>();
ThreadDump x;
for (final Map<Thread, StackTraceElement[]> trace: stackTraces) {
x = new ThreadDump(trace, Thread.State.RUNNABLE);
for (final Map.Entry<StackTrace, List<String>> e: x.entrySet()) {
if (multiDumpFilterPattern.matcher(e.getKey().text).matches()) continue;
Integer c = dumps.get(e.getKey().text);
if (c == null) dumps.put(e.getKey().text, Integer.valueOf(1));
else {
c = Integer.valueOf(c.intValue() + 1);
dumps.put(e.getKey().text, c);
}
}
}
// write dumps
while (!dumps.isEmpty()) {
final Map.Entry<String, Integer> e = removeMax(dumps);
bufferappend(buffer, "Occurrences: " + e.getValue());
bufferappend(buffer, e.getKey());
bufferappend(buffer, "");
}
bufferappend(buffer, "");
}
private static Map.Entry<String, Integer> removeMax(final Map<String, Integer> result) {
Map.Entry<String, Integer> max = null;
for (final Map.Entry<String, Integer> e: result.entrySet()) {
if (max == null || e.getValue().intValue() > max.getValue().intValue()) {
max = e;
}
}
result.remove(max.getKey());
return max;
}
private static void bufferappend(final StringBuilder buffer, int keylen, final String key, Object value) {
if (value instanceof Double)
bufferappend(buffer, keylen, key, ((Double) value).toString());
else if (value instanceof Number)
bufferappend(buffer, keylen, key, ((Number) value).longValue());
else
bufferappend(buffer, keylen, key, value.toString());
}
private static final DecimalFormat cardinalFormatter = new DecimalFormat("
private static void bufferappend(final StringBuilder buffer, int keylen, final String key, long value) {
bufferappend(buffer, keylen, key, cardinalFormatter.format(value));
}
private static void bufferappend(final StringBuilder buffer, int keylen, final String key, String value) {
String a = key;
while (a.length() < keylen) a += " ";
a += "=";
for (int i = value.length(); i < 20; i++) a += " ";
a += value;
bufferappend(buffer, a);
}
private static void bufferappend(final StringBuilder buffer, final String a) {
buffer.append(a);
buffer.append('\n');
}
private static class ThreadDump extends HashMap<StackTrace, List<String>> implements Map<StackTrace, List<String>> {
private static final long serialVersionUID = -5587850671040354397L;
private static Map<Thread, StackTraceElement[]> getAllStackTraces() {
return Thread.getAllStackTraces();
}
private ThreadDump(
final Map<Thread, StackTraceElement[]> stackTraces,
final Thread.State stateIn) {
super();
Thread thread;
// collect single dumps
for (final Map.Entry<Thread, StackTraceElement[]> entry: stackTraces.entrySet()) {
thread = entry.getKey();
final StackTraceElement[] stackTraceElements = entry.getValue();
StackTraceElement ste;
String tracename = "";
final State threadState = thread.getState();
final ThreadInfo info = threadBean.getThreadInfo(thread.getId());
if (threadState != null && info != null && (stateIn == null || stateIn.equals(threadState)) && stackTraceElements.length > 0) {
final StringBuilder sb = new StringBuilder(3000);
final String threadtitle = tracename + "Thread= " + thread.getName() + " " + (thread.isDaemon()?"daemon":"") + " id=" + thread.getId() + " " + threadState.toString() + (info.getLockOwnerId() >= 0 ? " lock owner =" + info.getLockOwnerId() : "");
boolean cutcore = true;
for (int i = 0; i < stackTraceElements.length; i++) {
ste = stackTraceElements[i];
String className = ste.getClassName();
String classString = ste.toString();
if (cutcore && (className.startsWith("java.") || className.startsWith("sun."))) {
sb.setLength(0);
bufferappend(sb, tracename + "at " + classString);
} else {
cutcore = false;
bufferappend(sb, tracename + "at " + classString);
}
}
final String threaddump = sb.toString();
List<String> threads = get(threaddump);
if (threads == null) threads = new ArrayList<String>();
threads.add(threadtitle);
put(new StackTrace(threaddump), threads);
}
}
}
private void appendStackTraces(
final StringBuilder buffer,
final Thread.State stateIn) {
bufferappend(buffer, "THREADS WITH STATES: " + stateIn.toString());
bufferappend(buffer, "");
// write dumps
for (final Map.Entry<StackTrace, List<String>> entry: entrySet()) {
final List<String> threads = entry.getValue();
for (final String t: threads) bufferappend(buffer, t);
bufferappend(buffer, entry.getKey().text);
bufferappend(buffer, "");
}
bufferappend(buffer, "");
}
}
private static class DummyResponse implements HttpServletResponse {
@Override public void flushBuffer() throws IOException {}
@Override public int getBufferSize() {return 2048;}
@Override public String getCharacterEncoding() {return "UTF-8";}
@Override public String getContentType() {return "text/plain";}
@Override public Locale getLocale() {return Locale.ENGLISH;}
@Override public boolean isCommitted() {return true;}
@Override public void reset() {}
@Override public void resetBuffer() {}
@Override public void setBufferSize(int arg0) {}
@Override public void setCharacterEncoding(String arg0) {}
@Override public void setContentLength(int arg0) {}
@Override public void setContentLengthLong(long arg0) {}
@Override public void setContentType(String arg0) {}
@Override public void setLocale(Locale arg0) {}
@Override public void addCookie(Cookie arg0) {}
@Override public void addDateHeader(String arg0, long arg1) {}
@Override public void addHeader(String arg0, String arg1) {}
@Override public void addIntHeader(String arg0, int arg1) {}
@Override public boolean containsHeader(String arg0) {return true;}
@Override public String encodeRedirectURL(String arg0) {return arg0;}
@Override public String encodeRedirectUrl(String arg0) {return arg0;}
@Override public String encodeURL(String arg0) {return arg0;}
@Override public String encodeUrl(String arg0) {return arg0;}
@Override public String getHeader(String arg0) {return "";}
@Override public Collection<String> getHeaderNames() {return new ArrayList<String>(0);}
@Override public Collection<String> getHeaders(String arg0) {return new ArrayList<String>(0);}
@Override public int getStatus() {return 200;}
@Override public void sendError(int arg0) throws IOException {}
@Override public void sendError(int arg0, String arg1) throws IOException {}
@Override public void sendRedirect(String arg0) throws IOException {}
@Override public void setDateHeader(String arg0, long arg1) {}
@Override public void setHeader(String arg0, String arg1) {}
@Override public void setIntHeader(String arg0, int arg1) {}
@Override public void setStatus(int arg0) {}
@Override public void setStatus(int arg0, String arg1) {}
@Override public PrintWriter getWriter() throws IOException {return new PrintWriter(new OutputStreamWriter(getOutputStream(), "UTF-8"));}
@Override public ServletOutputStream getOutputStream() throws IOException {return new ServletOutputStream(){
public void write(int aByte) throws IOException {}
public boolean isReady() { return true; }
public void setWriteListener(WriteListener arg0) {}
};}
}
}
|
package org.mtransit.android.commons;
import org.mtransit.android.commons.api.SupportFactory;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public final class ToastUtils implements MTLog.Loggable {
private static final String LOG_TAG = ToastUtils.class.getSimpleName();
public static final int TOAST_MARGIN_IN_DP = 10;
public static final int NAVIGATION_HEIGHT_IN_DP = 48;
@Override
public String getLogTag() {
return LOG_TAG;
}
private ToastUtils() {
}
public static void makeTextAndShowCentered(@Nullable Context context, @StringRes int resId) {
makeTextAndShowCentered(context, resId, Toast.LENGTH_SHORT);
}
public static void makeTextAndShowCentered(@Nullable Context context, @StringRes int resId, int duration) {
if (context == null) {
return;
}
Toast toast = Toast.makeText(context, resId, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public static void makeTextAndShowCentered(@Nullable Context context, CharSequence text) {
makeTextAndShowCentered(context, text, Toast.LENGTH_SHORT);
}
public static void makeTextAndShowCentered(@Nullable Context context, CharSequence text, int duration) {
if (context == null) {
return;
}
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public static void makeTextAndShow(@Nullable Context context, @StringRes int resId) {
makeTextAndShow(context, resId, Toast.LENGTH_SHORT);
}
public static void makeTextAndShow(@Nullable Context context, @StringRes int resId, int duration) {
if (context == null) {
return;
}
Toast toast = Toast.makeText(context, resId, duration);
toast.show();
}
public static void makeTextAndShow(@NonNull Context context, CharSequence text) {
makeTextAndShow(context, text, Toast.LENGTH_SHORT);
}
public static void makeTextAndShow(@NonNull Context context, CharSequence text, int duration) {
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public static boolean showTouchableToast(@Nullable Context context, @Nullable PopupWindow touchableToast, @Nullable View parent) {
int additionalBottomMarginInDp = 90; // smart ad banner max height
return showTouchableToast(context, touchableToast, parent, additionalBottomMarginInDp);
}
public static boolean showTouchableToast(@Nullable Context context, @Nullable PopupWindow touchableToast, @Nullable View parent, int additionalBottomMarginInDp) {
return showTouchableToast(context, touchableToast, parent,
NAVIGATION_HEIGHT_IN_DP + additionalBottomMarginInDp + TOAST_MARGIN_IN_DP, // bottom
TOAST_MARGIN_IN_DP // left
);
}
public static boolean showTouchableToast(@Nullable Context context, @Nullable PopupWindow touchableToast, @Nullable View parent, int bottomMarginInDp, int leftMarginInDp) {
if (context == null || touchableToast == null || parent == null) {
return false;
}
int bottomMarginInPx = (int) ResourceUtils.convertSPtoPX(context, bottomMarginInDp);
int leftMarginInPx = (int) ResourceUtils.convertSPtoPX(context, leftMarginInDp);
touchableToast.showAtLocation(parent, Gravity.LEFT | Gravity.BOTTOM, leftMarginInPx, bottomMarginInPx);
return true;
}
@Nullable
public static PopupWindow getNewTouchableToast(@Nullable Context context, @StringRes int textResId) {
return getNewTouchableToast(context, android.R.drawable.toast_frame, textResId);
}
@Nullable
public static PopupWindow getNewTouchableToast(@Nullable Context context, @DrawableRes int toastResId, @StringRes int textResId) {
if (context == null) {
return null;
}
try {
TextView contentView = new TextView(context);
contentView.setText(textResId);
contentView.setTextColor(Color.WHITE);
PopupWindow newTouchableToast = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
newTouchableToast.setContentView(contentView);
newTouchableToast.setTouchable(true);
newTouchableToast.setBackgroundDrawable(SupportFactory.get().getResourcesDrawable(context.getResources(), toastResId, null));
return newTouchableToast;
} catch (Exception e) {
MTLog.w(LOG_TAG, e, "Error while creating touchable toast!");
return null;
}
}
}
|
package org.nextras.orm.intellij.utils;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.resolve.types.PhpType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.stream.Collectors;
public class OrmUtils
{
public enum OrmClass
{
COLLECTION("\\Nextras\\Orm\\Collection\\ICollection"),
MAPPER("\\Nextras\\Orm\\Mapper\\IMapper"),
REPOSITORY("\\Nextras\\Orm\\Repository\\IRepository"),
ENTITY("\\Nextras\\Orm\\Entity\\IEntity"),
HAS_MANY("\\Nextras\\Orm\\Relationships\\HasMany");
private String name;
OrmClass(String name)
{
this.name = name;
}
public boolean is(PhpClass cls, PhpIndex index)
{
Collection<PhpClass> classes = index.getAnyByFQN(name);
PhpClass instanceOf = classes.isEmpty() ? null : classes.iterator().next();
if (instanceOf == null) {
return false;
}
return instanceOf.getType().isConvertibleFrom(cls.getType(), index);
}
}
public static Collection<PhpClass> findRepositoryEntities(Collection<PhpClass> repositories)
{
final Collection<PhpClass> entities = new HashSet<>(1);
for (PhpClass repositoryClass : repositories) {
Method entityNamesMethod = repositoryClass.findMethodByName("getEntityClassNames");
if (entityNamesMethod == null) {
return Collections.emptyList();
}
if (!(entityNamesMethod.getLastChild() instanceof GroupStatement)) {
return Collections.emptyList();
}
if (!(((GroupStatement) entityNamesMethod.getLastChild()).getFirstPsiChild() instanceof PhpReturn)) {
return Collections.emptyList();
}
if (!(((GroupStatement) entityNamesMethod.getLastChild()).getFirstPsiChild().getFirstPsiChild() instanceof ArrayCreationExpression)) {
return Collections.emptyList();
}
ArrayCreationExpression arr = (ArrayCreationExpression) ((GroupStatement) entityNamesMethod.getLastChild()).getFirstPsiChild().getFirstPsiChild();
final PhpIndex phpIndex = PhpIndex.getInstance(repositoryClass.getProject());
for (PsiElement el : arr.getChildren()) {
if (!(el.getFirstChild() instanceof ClassConstantReference)) {
continue;
}
ClassConstantReference ref = (ClassConstantReference) el.getFirstChild();
if (!ref.getName().equals("class")) {
continue;
}
entities.addAll(PhpIndexUtils.getByType(ref.getClassReference().getType(), phpIndex));
}
}
return entities;
}
public static Collection<PhpClass> findQueriedEntities(MemberReference ref)
{
PhpExpression classReference = ref.getClassReference();
if (classReference == null) {
return Collections.emptyList();
}
Collection<PhpClass> entities = new HashSet<>();
PhpIndex phpIndex = PhpIndex.getInstance(ref.getProject());
Collection<PhpClass> classes = PhpIndexUtils.getByType(classReference.getType(), phpIndex);
Collection<PhpClass> repositories = classes.stream()
.filter(cls -> OrmClass.REPOSITORY.is(cls, phpIndex))
.collect(Collectors.toList());
if (repositories.size() > 0) {
entities.addAll(findRepositoryEntities(repositories));
}
for (String type : classReference.getType().getTypes()) {
if (!type.endsWith("[]")) {
continue;
}
PhpType typeWithoutArray = new PhpType().add(type.substring(0, type.length() - 2));
Collection<PhpClass> maybeEntities = PhpIndexUtils.getByType(typeWithoutArray, phpIndex);
entities.addAll(maybeEntities.stream().filter(cls -> OrmClass.ENTITY.is(cls, phpIndex)).collect(Collectors.toList()));
}
return entities;
}
public static Collection<PhpClass> findQueriedEntities(MethodReference reference, String[] path)
{
if (path.length == 0) {
return Collections.emptyList();
}
Collection<PhpClass> rootEntities;
if (path.length == 1 || path[0].equals("this")) {
rootEntities = findQueriedEntities(reference);
} else {
PhpIndex index = PhpIndex.getInstance(reference.getProject());
rootEntities = PhpIndexUtils.getByType(new PhpType().add(path[0]), index);
}
if (rootEntities.size() == 0) {
return Collections.emptyList();
}
if (path.length <= 1) {
return rootEntities;
}
return findTargetEntities(rootEntities, path, 1);
}
private static Collection<PhpClass> findTargetEntities(Collection<PhpClass> currentEntities, String[] path, int pos)
{
if (path.length == (pos + 1)) {
return currentEntities;
}
Collection<PhpClass> entities = new HashSet<>();
for (PhpClass cls : currentEntities) {
Field field = cls.findFieldByName(path[pos], false);
if (!(field instanceof PhpDocProperty)) {
continue;
}
addEntitiesFromField(entities, (PhpDocProperty) field);
}
return findTargetEntities(entities, path, pos + 1);
}
public static void addEntitiesFromField(Collection<PhpClass> entities, PhpDocProperty field)
{
PhpIndex index = PhpIndex.getInstance(field.getProject());
for (String type : field.getType().getTypes()) {
if (type.contains("Nextras\\Orm\\Relationship")) {
continue;
}
if (type.endsWith("[]")) {
type = type.substring(0, type.length() - 2);
}
for (PhpClass entityCls : PhpIndexUtils.getByType(new PhpType().add(type), index)) {
if (!OrmClass.ENTITY.is(entityCls, index)) {
continue;
}
entities.add(entityCls);
}
}
}
}
|
package org.nschmidt.ldparteditor.data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.helpers.composite3d.ViewIdleManager;
import org.nschmidt.ldparteditor.helpers.compositetext.SubfileCompiler;
import org.nschmidt.ldparteditor.helpers.math.HashBiMap;
import org.nschmidt.ldparteditor.helpers.math.PowerRay;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow;
import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow;
import org.nschmidt.ldparteditor.workbench.WorkbenchManager;
/**
* @author nils
*
*/
class VM00Base {
protected final ArrayList<MemorySnapshot> snapshots = new ArrayList<MemorySnapshot>();
// 1 Vertex kann an mehreren Stellen (GData2-5 + position) manifestiert sein
/**
* Subfile-Inhalte sind hierbei enthalten. Die Manifestierung gegen
* {@code lineLinkedToVertices} checken, wenn ausgeschlossen werden soll,
* dass es sich um Subfile Daten handelt
*/
protected final ThreadsafeTreeMap<Vertex, Set<VertexManifestation>> vertexLinkedToPositionInFile = new ThreadsafeTreeMap<Vertex, Set<VertexManifestation>>();
protected final ThreadsafeTreeMap<Vertex, Set<GData1>> vertexLinkedToSubfile = new ThreadsafeTreeMap<Vertex, Set<GData1>>();
// Auf Dateiebene: 1 Vertex kann an mehreren Stellen (GData1-5 + position)
// manifestiert sein, ist er auch im Subfile, so gibt VertexInfo dies an
/** Subfile-Inhalte sind hier nicht als Key refenziert!! */
protected final ThreadsafeHashMap<GData, Set<VertexInfo>> lineLinkedToVertices = new ThreadsafeHashMap<GData, Set<VertexInfo>>();
public final ThreadsafeHashMap<GData, Set<VertexInfo>> getLineLinkedToVertices() {
return lineLinkedToVertices;
}
protected final TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE = new TreeMap<Vertex, float[]>();
protected final HashMap<GData, float[]> dataLinkedToNormalCACHE = new HashMap<GData, float[]>();
protected final ThreadsafeHashMap<GData1, Integer> vertexCountInSubfile = new ThreadsafeHashMap<GData1, Integer>();
protected final ThreadsafeHashMap<GData0, Vertex[]> declaredVertices = new ThreadsafeHashMap<GData0, Vertex[]>();
protected final ThreadsafeHashMap<GData2, Vertex[]> lines = new ThreadsafeHashMap<GData2, Vertex[]>();
protected final ThreadsafeHashMap<GData3, Vertex[]> triangles = new ThreadsafeHashMap<GData3, Vertex[]>();
protected final ThreadsafeHashMap<GData4, Vertex[]> quads = new ThreadsafeHashMap<GData4, Vertex[]>();
protected final ThreadsafeHashMap<GData5, Vertex[]> condlines = new ThreadsafeHashMap<GData5, Vertex[]>();
protected final Vertex[] vArray = new Vertex[4];
protected final VertexManifestation[] vdArray = new VertexManifestation[4];
protected final Set<Vertex> selectedVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
protected final Set<GData> selectedData = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>());
protected final Set<GData1> selectedSubfiles = Collections.newSetFromMap(new ThreadsafeHashMap<GData1, Boolean>());
protected final Set<GData2> selectedLines = Collections.newSetFromMap(new ThreadsafeHashMap<GData2, Boolean>());
protected final Set<GData3> selectedTriangles = Collections.newSetFromMap(new ThreadsafeHashMap<GData3, Boolean>());
protected final Set<GData4> selectedQuads = Collections.newSetFromMap(new ThreadsafeHashMap<GData4, Boolean>());
protected final Set<GData5> selectedCondlines = Collections.newSetFromMap(new ThreadsafeHashMap<GData5, Boolean>());
protected final Set<Vertex> backupSelectedVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
protected final Set<GData> backupSelectedData = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>());
protected final Set<GData1> backupSelectedSubfiles = Collections.newSetFromMap(new ThreadsafeHashMap<GData1, Boolean>());
protected final Set<GData2> backupSelectedLines = Collections.newSetFromMap(new ThreadsafeHashMap<GData2, Boolean>());
protected final Set<GData3> backupSelectedTriangles = Collections.newSetFromMap(new ThreadsafeHashMap<GData3, Boolean>());
protected final Set<GData4> backupSelectedQuads = Collections.newSetFromMap(new ThreadsafeHashMap<GData4, Boolean>());
protected final Set<GData5> backupSelectedCondlines = Collections.newSetFromMap(new ThreadsafeHashMap<GData5, Boolean>());
protected final Set<GData> newSelectedData = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>());
protected GDataPNG selectedBgPicture = null;
protected int selectedBgPictureIndex = -1;
protected final Set<Vertex> selectedVerticesForSubfile = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
protected final Set<GData2> selectedLinesForSubfile = Collections.newSetFromMap(new ThreadsafeHashMap<GData2, Boolean>());
protected final Set<GData3> selectedTrianglesForSubfile = Collections.newSetFromMap(new ThreadsafeHashMap<GData3, Boolean>());
protected final Set<GData4> selectedQuadsForSubfile = Collections.newSetFromMap(new ThreadsafeHashMap<GData4, Boolean>());
protected final Set<GData5> selectedCondlinesForSubfile = Collections.newSetFromMap(new ThreadsafeHashMap<GData5, Boolean>());
protected final Set<GData> dataToHide = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>());
protected final PowerRay powerRay = new PowerRay();
protected final DatFile linkedDatFile;
protected Vertex vertexToReplace = null;
protected boolean modified = false;
protected boolean updated = true;
protected final AtomicBoolean skipSyncWithTextEditor = new AtomicBoolean(false);
protected int selectedItemIndex = -1;
protected GData selectedLine = null;
protected Vertex lastSelectedVertex = null;
protected final Set<Vertex> hiddenVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
protected final Set<GData> hiddenData = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>());
protected final HashMap<GData, Byte> bfcMap = new HashMap<GData, Byte>();
protected final AtomicBoolean resetTimer = new AtomicBoolean(false);
protected final AtomicInteger tid = new AtomicInteger(0);
protected final AtomicInteger openThreads = new AtomicInteger(0);
protected final Lock lock = new ReentrantLock();
protected VM00Base(DatFile linkedDatFile) {
this.linkedDatFile = linkedDatFile;
}
public final synchronized void setUpdated(boolean updated) {
this.updated = updated;
if (updated) {
ViewIdleManager.renderLDrawStandard[0].set(true);
}
}
public final synchronized void setModified_NoSync() {
this.modified = true;
setUpdated(false);
}
public final boolean isModified() {
return modified;
}
public final synchronized void setModified(boolean modified, boolean addHistory) {
if (modified) {
setUpdated(false);
syncWithTextEditors(addHistory);
}
this.modified = modified;
}
public final boolean isUpdated() {
return updated;
}
protected final String bigDecimalToString(BigDecimal bd) {
String result;
if (bd.compareTo(BigDecimal.ZERO) == 0)
return "0"; //$NON-NLS-1$
BigDecimal bd2 = bd.stripTrailingZeros();
result = bd2.toPlainString();
if (result.startsWith("-0."))return "-" + result.substring(2); //$NON-NLS-1$ //$NON-NLS-2$
if (result.startsWith("0."))return result.substring(1); //$NON-NLS-1$
return result;
}
public final void syncWithTextEditors(boolean addHistory) {
if (addHistory) linkedDatFile.addHistory();
try {
lock.lock();
if (isSkipSyncWithTextEditor() || !isSyncWithTextEditor()) {
// lock.unlock() call on finally!
return;
}
if (openThreads.get() > 10) {
resetTimer.set(true);
// lock.unlock() call on finally!
return;
}
final AtomicInteger tid2 = new AtomicInteger(tid.incrementAndGet());
final Thread syncThread = new Thread(new Runnable() {
@Override
public void run() {
openThreads.incrementAndGet();
do {
resetTimer.set(false);
for(int i = 0; i < 4; i++) {
try {
Thread.sleep(450);
} catch (InterruptedException e) {
}
if (tid2.get() != tid.get()) break;
}
} while (resetTimer.get());
openThreads.decrementAndGet();
if (tid2.get() != tid.get() || isSkipSyncWithTextEditor() || !isSyncWithTextEditor()) return;
boolean notFound = true;
boolean tryToUnlockLock2 = false;
Lock lock2 = null;
try {
lock2 = linkedDatFile.getHistory().getLock();
lock.lock();
// "lock2" will be locked, if undo/redo tries to restore the state.
// Any attempt to broke the data structure with an old synchronisation state will be
// prevented with this lock.
if (lock2.tryLock()) {
tryToUnlockLock2 = true;
try {
// A lot of stuff can throw an exception here, since the thread waits two seconds and
// the state of the program may not allow a synchronisation anymore
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null && txtDat.equals(linkedDatFile)) {
notFound = false;
final String txt;
if (isModified()) {
txt = txtDat.getText();
} else {
txt = null;
}
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
int ti = ((CompositeTab) t).getTextComposite().getTopIndex();
Point r = ((CompositeTab) t).getTextComposite().getSelectionRange();
((CompositeTab) t).getState().setSync(true);
if (isModified() && txt != null) {
((CompositeTab) t).getTextComposite().setText(txt);
}
((CompositeTab) t).getTextComposite().setTopIndex(ti);
try {
((CompositeTab) t).getTextComposite().setSelectionRange(r.x, r.y);
} catch (IllegalArgumentException consumed) {}
((CompositeTab) t).getTextComposite().redraw();
((CompositeTab) t).getControl().redraw();
((CompositeTab) t).getState().setSync(false);
setUpdated(true);
}
});
}
}
}
} catch (Exception consumed) {
// We want to know what can go wrong here
// because it SHOULD be avoided!!
NLogger.error(getClass(), "Synchronisation with the text editor failed."); //$NON-NLS-1$
NLogger.error(getClass(), consumed);
setUpdated(true);
} finally {
if (notFound) setUpdated(true);
}
if (WorkbenchManager.getUserSettingState().getSyncWithLpeInline().get()) {
while (!isUpdated() && Editor3DWindow.getAlive().get()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
SubfileCompiler.compile(linkedDatFile, true, true);
}
});
}
} else {
NLogger.debug(getClass(), "Synchronisation was skipped due to undo/redo."); //$NON-NLS-1$
}
} finally {
if (lock2 != null && tryToUnlockLock2) lock2.unlock();
lock.unlock();
}
}
});
syncThread.start();
} finally {
lock.unlock();
}
}
public final boolean isSyncWithLpeInline() {
return WorkbenchManager.getUserSettingState().getSyncWithLpeInline().get();
}
public final boolean isSyncWithTextEditor() {
return WorkbenchManager.getUserSettingState().getSyncWithTextEditor().get();
}
public final void setSyncWithTextEditor(boolean syncWithTextEditor) {
WorkbenchManager.getUserSettingState().getSyncWithTextEditor().set(syncWithTextEditor);
}
public final boolean isSkipSyncWithTextEditor() {
return skipSyncWithTextEditor.get();
}
public final void setSkipSyncWithTextEditor(boolean syncWithTextEditor) {
this.skipSyncWithTextEditor.set(syncWithTextEditor);
}
public final void updateUnsavedStatus() {
String newText = linkedDatFile.getText();
linkedDatFile.setText(newText);
if (newText.equals(linkedDatFile.getOriginalText()) && linkedDatFile.getOldName().equals(linkedDatFile.getNewName())) {
// Do not remove virtual files from the unsaved file list
// (they are virtual, because they were not saved at all!)
if (Project.getUnsavedFiles().contains(linkedDatFile) && !linkedDatFile.isVirtual()) {
Project.removeUnsavedFile(linkedDatFile);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
} else if (!Project.getUnsavedFiles().contains(linkedDatFile)) {
Project.addUnsavedFile(linkedDatFile);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
/**
* Validates the current data structure against dead references and other
* inconsistencies. All calls to this method will be "suppressed" in the release version.
* Except the correction of 'trivial' selection inconsistancies
*/
public final synchronized void validateState() {
// Validate and auto-correct selection inconsistancies
if (selectedData.size() != selectedSubfiles.size() + selectedLines.size() + selectedTriangles.size() + selectedQuads.size() + selectedCondlines.size()) {
// throw new AssertionError("The selected data is not equal to the content of single selection classes, e.g. 'selectedTriangles'."); //$NON-NLS-1$
selectedData.clear();
for (Iterator<GData1> gi = selectedSubfiles.iterator(); gi.hasNext();) {
GData g = gi.next();
if (!exist(g)) {
gi.remove();
}
}
for (Iterator<GData2> gi = selectedLines.iterator(); gi.hasNext();) {
GData g = gi.next();
if (!exist(g)) {
gi.remove();
}
}
for (Iterator<GData3> gi = selectedTriangles.iterator(); gi.hasNext();) {
GData g = gi.next();
if (!exist(g)) {
gi.remove();
}
}
for (Iterator<GData4> gi = selectedQuads.iterator(); gi.hasNext();) {
GData g = gi.next();
if (!exist(g)) {
gi.remove();
}
}
for (Iterator<GData5> gi = selectedCondlines.iterator(); gi.hasNext();) {
GData g = gi.next();
if (!exist(g)) {
gi.remove();
}
}
selectedData.addAll(selectedSubfiles);
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
}
cleanupSelection();
cleanupHiddenData();
// Do not validate more stuff on release, since it costs a lot performance.
if (!NLogger.DEBUG) return;
// TreeMap<Vertex, HashSet<VertexManifestation>>
// vertexLinkedToPositionInFile
// TreeMap<Vertex, HashSet<GData1>> vertexLinkedToSubfile
// HashMap<GData, HashSet<VertexInfo>> lineLinkedToVertices
// HashMap<GData1, Integer> vertexCountInSubfile
// HashMap<GData2, Vertex[]> lines
// HashMap<GData3, Vertex[]> triangles
// HashMap<GData4, Vertex[]> quads
// HashMap<GData5, Vertex[]> condlines
// TreeSet<Vertex> selectedVertices
Set<Vertex> vertices = vertexLinkedToPositionInFile.keySet();
Set<Vertex> verticesInUse = new TreeSet<Vertex>();
for (GData0 line : declaredVertices.keySet()) {
for (Vertex vertex : declaredVertices.get(line)) {
verticesInUse.add(vertex);
}
}
for (GData2 line : lines.keySet()) {
for (Vertex vertex : lines.get(line)) {
verticesInUse.add(vertex);
}
}
for (GData3 line : triangles.keySet()) {
for (Vertex vertex : triangles.get(line)) {
verticesInUse.add(vertex);
}
}
for (GData4 line : quads.keySet()) {
for (Vertex vertex : quads.get(line)) {
verticesInUse.add(vertex);
}
}
for (GData5 line : condlines.keySet()) {
for (Vertex vertex : condlines.get(line)) {
verticesInUse.add(vertex);
}
}
int vertexCount = vertices.size();
int vertexUseCount = verticesInUse.size();
if (vertexCount != vertexUseCount) {
throw new AssertionError("The number of used vertices is not equal to the number of all available vertices."); //$NON-NLS-1$
}
// Validate Render Chain
HashBiMap<Integer, GData> lineMap = linkedDatFile.getDrawPerLine();
verticesInUse.clear();
if (lineMap.getValue(1) == null)
throw new AssertionError("The first line can't be null."); //$NON-NLS-1$
GData previousData = lineMap.getValue(1).getBefore();
TreeSet<Integer> lineNumbers = new TreeSet<Integer>(lineMap.keySet());
boolean nullReferenceFound = false;
for (Integer lineNumber : lineNumbers) {
if (nullReferenceFound)
throw new AssertionError("The reference to the next data is null but the next data is a real instance."); //$NON-NLS-1$
GData currentData = lineMap.getValue(lineNumber);
Set<VertexInfo> vi = lineLinkedToVertices.get(currentData);
if (vi != null) {
for (VertexInfo vertexInfo : vi) {
verticesInUse.add(vertexInfo.vertex);
}
}
if (currentData.getBefore() == null)
throw new AssertionError("The reference to the data before can't be null."); //$NON-NLS-1$
if (!currentData.getBefore().equals(previousData))
throw new AssertionError("The pointer to previous data directs to the wrong object."); //$NON-NLS-1$
if (previousData.getNext() == null)
throw new AssertionError("The reference to this before can't be null."); //$NON-NLS-1$
if (!previousData.getNext().equals(currentData))
throw new AssertionError("The pointer to next data directs to the wrong object."); //$NON-NLS-1$
if (currentData.getNext() == null)
nullReferenceFound = true;
previousData = currentData;
}
if (!nullReferenceFound) {
throw new AssertionError("Last pointer is not null."); //$NON-NLS-1$
}
vertexUseCount = verticesInUse.size();
vertexUseCount = verticesInUse.size();
if (vertexCount != vertexUseCount) {
throw new AssertionError("The number of vertices displayed is not equal to the number of stored vertices."); //$NON-NLS-1$
}
}
private final void cleanupHiddenData() {
if (hiddenData.size() > 0) {
HashSet<GData> dataToHide = new HashSet<GData>();
for (Iterator<GData> hi = hiddenData.iterator(); hi.hasNext();) {
GData g = hi.next();
if (!lines.containsKey(g) || !triangles.containsKey(g) || !quads.containsKey(g) || !condlines.containsKey(g)) {
String representation = g.toString();
for (GData2 g2 : lines.keySet()) {
if (g2.toString().equals(representation)) {
dataToHide.add(g2);
g2.visible = false;
}
}
for (GData3 g2 : triangles.keySet()) {
if (g2.toString().equals(representation)) {
dataToHide.add(g2);
g2.visible = false;
}
}
for (GData4 g2 : quads.keySet()) {
if (g2.toString().equals(representation)) {
dataToHide.add(g2);
g2.visible = false;
}
}
for (GData5 g2 : condlines.keySet()) {
if (g2.toString().equals(representation)) {
dataToHide.add(g2);
g2.visible = false;
}
}
hi.remove();
}
}
hiddenData.addAll(dataToHide);
}
}
private final void cleanupSelection() {
selectedData.clear();
for (Iterator<Vertex> vi = selectedVertices.iterator(); vi.hasNext();) {
if (!vertexLinkedToPositionInFile.containsKey(vi.next())) {
vi.remove();
}
}
for (Iterator<GData1> g1i = selectedSubfiles.iterator(); g1i.hasNext();) {
GData1 g1 = g1i.next();
if (vertexCountInSubfile.keySet().contains(g1)) {
selectedData.add(g1);
} else {
g1i.remove();
}
}
for (Iterator<GData2> g2i = selectedLines.iterator(); g2i.hasNext();) {
GData2 g2 = g2i.next();
if (lines.keySet().contains(g2)) {
selectedData.add(g2);
} else {
g2i.remove();
}
}
for (Iterator<GData3> g3i = selectedTriangles.iterator(); g3i.hasNext();) {
GData3 g3 = g3i.next();
if (triangles.keySet().contains(g3)) {
selectedData.add(g3);
} else {
g3i.remove();
}
}
for (Iterator<GData4> g4i = selectedQuads.iterator(); g4i.hasNext();) {
GData4 g4 = g4i.next();
if (quads.keySet().contains(g4)) {
selectedData.add(g4);
} else {
g4i.remove();
}
}
for (Iterator<GData5> g5i = selectedCondlines.iterator(); g5i.hasNext();) {
GData5 g5 = g5i.next();
if (condlines.keySet().contains(g5)) {
selectedData.add(g5);
} else {
g5i.remove();
}
}
}
protected final boolean exist(GData g) {
return lines.containsKey(g) || triangles.containsKey(g) || quads.containsKey(g) || condlines.containsKey(g) || lineLinkedToVertices.containsKey(g);
}
/**
*
* @param gdata
* @return {@code true} if the tail was removed
*/
public final synchronized boolean remove(final GData gdata) {
if (gdata == null)
return false;
final Set<VertexInfo> lv = lineLinkedToVertices.get(gdata);
Set<VertexManifestation> vd;
switch (gdata.type()) {
case 0: // Vertex Reference
declaredVertices.remove(gdata);
lineLinkedToVertices.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
int position = vertexInfo.position;
vd = vertexLinkedToPositionInFile.get(vertex);
vd.remove(new VertexManifestation(position, gdata));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 1: // Subfile
lineLinkedToVertices.remove(gdata);
vertexCountInSubfile.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
vd = vertexLinkedToPositionInFile.get(vertex);
GData linkedData = vertexInfo.linkedData;
switch (linkedData.type()) {
case 0:
if (vd != null) {
declaredVertices.remove(linkedData);
vd.remove(new VertexManifestation(0, linkedData));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 2:
lines.remove(linkedData);
if (vd != null) {
vd.remove(new VertexManifestation(0, linkedData));
vd.remove(new VertexManifestation(1, linkedData));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 3:
triangles.remove(linkedData);
if (vd != null) {
vd.remove(new VertexManifestation(0, linkedData));
vd.remove(new VertexManifestation(1, linkedData));
vd.remove(new VertexManifestation(2, linkedData));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 4:
quads.remove(linkedData);
if (vd != null) {
vd.remove(new VertexManifestation(0, linkedData));
vd.remove(new VertexManifestation(1, linkedData));
vd.remove(new VertexManifestation(2, linkedData));
vd.remove(new VertexManifestation(3, linkedData));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 5:
condlines.remove(linkedData);
if (vd != null) {
vd.remove(new VertexManifestation(0, linkedData));
vd.remove(new VertexManifestation(1, linkedData));
vd.remove(new VertexManifestation(2, linkedData));
vd.remove(new VertexManifestation(3, linkedData));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
default:
throw new AssertionError();
}
Set<GData1> vs = vertexLinkedToSubfile.get(vertex);
if (vs != null) { // The same vertex can be used by different
// elements from the subfile
vs.remove(gdata);
if (vs.isEmpty())
vertexLinkedToSubfile.remove(vertex);
}
}
break;
case 2: // Line
lines.remove(gdata);
lineLinkedToVertices.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
int position = vertexInfo.position;
vd = vertexLinkedToPositionInFile.get(vertex);
vd.remove(new VertexManifestation(position, gdata));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 3: // Triangle
triangles.remove(gdata);
lineLinkedToVertices.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
int position = vertexInfo.position;
vd = vertexLinkedToPositionInFile.get(vertex);
vd.remove(new VertexManifestation(position, gdata));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 4: // Quad
quads.remove(gdata);
lineLinkedToVertices.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
int position = vertexInfo.position;
vd = vertexLinkedToPositionInFile.get(vertex);
vd.remove(new VertexManifestation(position, gdata));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 5: // Optional Line
condlines.remove(gdata);
lineLinkedToVertices.remove(gdata);
if (lv == null)
break;
for (VertexInfo vertexInfo : lv) {
Vertex vertex = vertexInfo.vertex;
int position = vertexInfo.position;
vd = vertexLinkedToPositionInFile.get(vertex);
vd.remove(new VertexManifestation(position, gdata));
if (vd.isEmpty())
vertexLinkedToPositionInFile.remove(vertex);
}
break;
case 10:
if (gdata.equals(selectedBgPicture)) {
selectedBgPicture = null;
if (!((GDataPNG) gdata).isGoingToBeReplaced()) Editor3DWindow.getWindow().updateBgPictureTab();
}
break;
default:
break;
}
gdata.derefer();
boolean tailRemoved = gdata.equals(linkedDatFile.getDrawChainTail());
if (tailRemoved) linkedDatFile.setDrawChainTail(null);
return tailRemoved;
}
/**
* FOR TEXT EDITOR ONLY (Performace should be improved (has currently O(n)
* runtime n=number of code lines)
*
* @param oldVertex
* @param newVertex
* @param modifyVertexMetaCommands
* @return
*/
public final synchronized boolean changeVertexDirect(Vertex oldVertex, Vertex newVertex, boolean modifyVertexMetaCommands) {
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
TreeSet<Integer> keys = new TreeSet<Integer>(drawPerLine.keySet());
HashSet<GData> dataToRemove = new HashSet<GData>();
boolean foundVertexDuplicate = false;
for (Integer key : keys) {
GData vm = linkedDatFile.getDrawPerLine().getValue(key);
switch (vm.type()) {
case 0:
Vertex[] va = declaredVertices.get(vm);
if (va != null) {
if (oldVertex.equals(va[0]))
dataToRemove.add(vm);
if (newVertex.equals(va[0])) {
if (modifyVertexMetaCommands) {
foundVertexDuplicate = true;
} else {
return false;
}
}
}
break;
case 2:
va = lines.get(vm);
if (oldVertex.equals(va[0]) || oldVertex.equals(va[1])) {
if (newVertex.equals(va[0]) || newVertex.equals(va[1]))
return false;
dataToRemove.add(vm);
}
break;
case 3:
va = triangles.get(vm);
if (oldVertex.equals(va[0]) || oldVertex.equals(va[1]) || oldVertex.equals(va[2])) {
if (newVertex.equals(va[0]) || newVertex.equals(va[1]) || newVertex.equals(va[2]))
return false;
dataToRemove.add(vm);
}
break;
case 4:
va = quads.get(vm);
if (oldVertex.equals(va[0]) || oldVertex.equals(va[1]) || oldVertex.equals(va[2]) || oldVertex.equals(va[3])) {
if (newVertex.equals(va[0]) || newVertex.equals(va[1]) || newVertex.equals(va[2]) || newVertex.equals(va[3]))
return false;
dataToRemove.add(vm);
}
break;
case 5:
va = condlines.get(vm);
if (oldVertex.equals(va[0]) || oldVertex.equals(va[1]) || oldVertex.equals(va[2]) || oldVertex.equals(va[3])) {
if (newVertex.equals(va[0]) || newVertex.equals(va[1]) || newVertex.equals(va[2]) || newVertex.equals(va[3]))
return false;
dataToRemove.add(vm);
}
break;
default:
break;
}
}
boolean updateTail = false;
for (GData gData : dataToRemove) {
Integer oldNumber = drawPerLine.getKey(gData);
switch (gData.type()) {
case 0:
if (foundVertexDuplicate)
break;
GData0 gd0 = (GData0) gData;
Vertex[] v0 = declaredVertices.get(gd0);
updateTail = remove(gData) | updateTail;
// modifiedData.remove(gData);
if (v0[0].equals(oldVertex))
v0[0] = newVertex;
GData0 newGdata0 = addVertex(newVertex);
// modifiedData.add(newGdata0);
drawPerLine.put(oldNumber, newGdata0);
break;
case 2:
GData2 gd2 = (GData2) gData;
Vertex[] v2 = lines.get(gd2);
updateTail = remove(gData) | updateTail;
// modifiedData.remove(gData);
if (v2[0].equals(oldVertex))
v2[0] = newVertex;
if (v2[1].equals(oldVertex))
v2[1] = newVertex;
GData2 newGdata2 = new GData2(gd2.colourNumber, gd2.r, gd2.g, gd2.b, gd2.a, v2[0], v2[1], View.DUMMY_REFERENCE, linkedDatFile);
// modifiedData.add(newGdata2);
drawPerLine.put(oldNumber, newGdata2);
break;
case 3:
GData3 gd3 = (GData3) gData;
Vertex[] v3 = triangles.get(gd3);
updateTail = remove(gData) | updateTail;
// modifiedData.remove(gData);
if (v3[0].equals(oldVertex))
v3[0] = newVertex;
if (v3[1].equals(oldVertex))
v3[1] = newVertex;
if (v3[2].equals(oldVertex))
v3[2] = newVertex;
GData3 newGdata3 = new GData3(gd3.colourNumber, gd3.r, gd3.g, gd3.b, gd3.a, v3[0], v3[1], v3[2], View.DUMMY_REFERENCE, linkedDatFile);
// modifiedData.add(newGdata3);
drawPerLine.put(oldNumber, newGdata3);
break;
case 4:
GData4 gd4 = (GData4) gData;
Vertex[] v4 = quads.get(gd4);
updateTail = remove(gData) | updateTail;
// modifiedData.remove(gData);
if (v4[0].equals(oldVertex))
v4[0] = newVertex;
if (v4[1].equals(oldVertex))
v4[1] = newVertex;
if (v4[2].equals(oldVertex))
v4[2] = newVertex;
if (v4[3].equals(oldVertex))
v4[3] = newVertex;
GData4 newGdata4 = new GData4(gd4.colourNumber, gd4.r, gd4.g, gd4.b, gd4.a, v4[0], v4[1], v4[2], v4[3], View.DUMMY_REFERENCE, linkedDatFile);
// modifiedData.add(newGdata4);
drawPerLine.put(oldNumber, newGdata4);
break;
case 5:
GData5 gd5 = (GData5) gData;
Vertex[] v5 = condlines.get(gd5);
updateTail = remove(gData) | updateTail;
// modifiedData.remove(gData);
if (v5[0].equals(oldVertex))
v5[0] = newVertex;
if (v5[1].equals(oldVertex))
v5[1] = newVertex;
if (v5[2].equals(oldVertex))
v5[2] = newVertex;
if (v5[3].equals(oldVertex))
v5[3] = newVertex;
GData5 newGdata5 = new GData5(gd5.colourNumber, gd5.r, gd5.g, gd5.b, gd5.a, v5[0], v5[1], v5[2], v5[3], View.DUMMY_REFERENCE, linkedDatFile);
// modifiedData.add(newGdata5);
drawPerLine.put(oldNumber, newGdata5);
break;
}
}
// Linking:
for (Integer key : keys) {
GData val = drawPerLine.getValue(key);
if (updateTail)
linkedDatFile.setDrawChainTail(val);
int k = key;
if (k < 2) {
linkedDatFile.getDrawChainStart().setNext(val);
} else {
GData val2 = drawPerLine.getValue(k - 1);
val2.setNext(val);
}
}
return true;
}
public final synchronized boolean changeVertexDirectFast(Vertex oldVertex, Vertex newVertex, boolean moveAdjacentData) {
GData tail = linkedDatFile.getDrawChainTail();
// Collect the data to modify
Set<VertexManifestation> manis2 = vertexLinkedToPositionInFile.get(oldVertex);
if (manis2 == null || manis2.isEmpty())
return false;
HashSet<VertexManifestation> manis = new HashSet<VertexManifestation>(manis2);
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
for (VertexManifestation mani : manis) {
GData oldData = mani.getGdata();
if (!lineLinkedToVertices.containsKey(oldData))
continue;
GData newData = null;
switch (oldData.type()) {
case 0:
GData0 oldVm = (GData0) oldData;
GData0 newVm = null;
Vertex[] va = declaredVertices.get(oldVm);
if (va == null) {
continue;
} else {
if (!moveAdjacentData && !selectedVertices.contains(va[0]))
continue;
if (va[0].equals(oldVertex))
va[0] = newVertex;
newVm = addVertex(va[0]);
newData = newVm;
}
break;
case 2:
GData2 oldLin = (GData2) oldData;
if (!moveAdjacentData && !selectedLines.contains(oldLin))
continue;
GData2 newLin = null;
switch (mani.getPosition()) {
case 0:
newLin = new GData2(oldLin.colourNumber, oldLin.r, oldLin.g, oldLin.b, oldLin.a, newVertex.X, newVertex.Y, newVertex.Z, oldLin.X2, oldLin.Y2, oldLin.Z2, oldLin.parent,
linkedDatFile);
break;
case 1:
newLin = new GData2(oldLin.colourNumber, oldLin.r, oldLin.g, oldLin.b, oldLin.a, oldLin.X1, oldLin.Y1, oldLin.Z1, newVertex.X, newVertex.Y, newVertex.Z, oldLin.parent,
linkedDatFile);
break;
}
newData = newLin;
if (selectedLines.contains(oldLin))
selectedLines.add(newLin);
break;
case 3:
GData3 oldTri = (GData3) oldData;
if (!moveAdjacentData && !selectedTriangles.contains(oldTri))
continue;
GData3 newTri = null;
switch (mani.getPosition()) {
case 0:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, newVertex, new Vertex(oldTri.X2, oldTri.Y2, oldTri.Z2),
new Vertex(oldTri.X3, oldTri.Y3, oldTri.Z3), oldTri.parent, linkedDatFile);
break;
case 1:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, new Vertex(oldTri.X1, oldTri.Y1, oldTri.Z1), newVertex,
new Vertex(oldTri.X3, oldTri.Y3, oldTri.Z3), oldTri.parent, linkedDatFile);
break;
case 2:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, new Vertex(oldTri.X1, oldTri.Y1, oldTri.Z1), new Vertex(oldTri.X2, oldTri.Y2, oldTri.Z2),
newVertex, oldTri.parent, linkedDatFile);
break;
}
newData = newTri;
if (selectedTriangles.contains(oldTri))
selectedTriangles.add(newTri);
break;
case 4:
GData4 oldQuad = (GData4) oldData;
if (!moveAdjacentData && !selectedQuads.contains(oldQuad))
continue;
GData4 newQuad = null;
switch (mani.getPosition()) {
case 0:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, newVertex, new Vertex(oldQuad.X2, oldQuad.Y2, oldQuad.Z2), new Vertex(oldQuad.X3,
oldQuad.Y3, oldQuad.Z3), new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 1:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), newVertex, new Vertex(oldQuad.X3,
oldQuad.Y3, oldQuad.Z3), new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 2:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), new Vertex(oldQuad.X2, oldQuad.Y2,
oldQuad.Z2), newVertex, new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 3:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), new Vertex(oldQuad.X2, oldQuad.Y2,
oldQuad.Z2), new Vertex(oldQuad.X3, oldQuad.Y3, oldQuad.Z3), newVertex, oldQuad.parent, linkedDatFile);
break;
}
newData = newQuad;
if (selectedQuads.contains(oldQuad))
selectedQuads.add(newQuad);
break;
case 5:
GData5 oldCLin = (GData5) oldData;
if (!moveAdjacentData && !selectedCondlines.contains(oldCLin))
continue;
GData5 newCLin = null;
switch (mani.getPosition()) {
case 0:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, newVertex, new Vertex(oldCLin.X2, oldCLin.Y2, oldCLin.Z2), new Vertex(oldCLin.X3,
oldCLin.Y3, oldCLin.Z3), new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 1:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), newVertex, new Vertex(oldCLin.X3,
oldCLin.Y3, oldCLin.Z3), new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 2:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), new Vertex(oldCLin.X2, oldCLin.Y2,
oldCLin.Z2), newVertex, new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 3:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), new Vertex(oldCLin.X2, oldCLin.Y2,
oldCLin.Z2), new Vertex(oldCLin.X3, oldCLin.Y3, oldCLin.Z3), newVertex, oldCLin.parent, linkedDatFile);
break;
}
newData = newCLin;
if (selectedCondlines.contains(oldCLin))
selectedCondlines.add(newCLin);
break;
}
if (selectedVertices.contains(oldVertex)) {
selectedVertices.remove(oldVertex);
selectedVertices.add(newVertex);
}
if (oldData.equals(tail))
linkedDatFile.setDrawChainTail(newData);
GData oldNext = oldData.getNext();
GData oldBefore = oldData.getBefore();
oldBefore.setNext(newData);
newData.setNext(oldNext);
Integer oldNumber = drawPerLine.getKey(oldData);
if (oldNumber != null)
drawPerLine.put(oldNumber, newData);
remove(oldData);
}
return true;
}
public final synchronized GData changeVertexDirectFast(Vertex oldVertex, Vertex newVertex, boolean moveAdjacentData, GData og) {
GData tail = linkedDatFile.getDrawChainTail();
// Collect the data to modify
Set<VertexManifestation> manis2 = vertexLinkedToPositionInFile.get(oldVertex);
if (manis2 == null || manis2.isEmpty())
return og;
HashSet<VertexManifestation> manis = new HashSet<VertexManifestation>(manis2);
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
for (VertexManifestation mani : manis) {
GData oldData = mani.getGdata();
if (!lineLinkedToVertices.containsKey(oldData))
continue;
GData newData = null;
switch (oldData.type()) {
case 0:
GData0 oldVm = (GData0) oldData;
GData0 newVm = null;
Vertex[] va = declaredVertices.get(oldVm);
if (va == null) {
continue;
} else {
if (!moveAdjacentData && !selectedVertices.contains(va[0]))
continue;
if (va[0].equals(oldVertex))
va[0] = newVertex;
newVm = addVertex(va[0]);
newData = newVm;
}
break;
case 2:
GData2 oldLin = (GData2) oldData;
if (!moveAdjacentData && !selectedLines.contains(oldLin))
continue;
GData2 newLin = null;
switch (mani.getPosition()) {
case 0:
newLin = new GData2(oldLin.colourNumber, oldLin.r, oldLin.g, oldLin.b, oldLin.a, newVertex.X, newVertex.Y, newVertex.Z, oldLin.X2, oldLin.Y2, oldLin.Z2, oldLin.parent,
linkedDatFile);
break;
case 1:
newLin = new GData2(oldLin.colourNumber, oldLin.r, oldLin.g, oldLin.b, oldLin.a, oldLin.X1, oldLin.Y1, oldLin.Z1, newVertex.X, newVertex.Y, newVertex.Z, oldLin.parent,
linkedDatFile);
break;
}
newData = newLin;
if (selectedLines.contains(oldLin))
selectedLines.add(newLin);
break;
case 3:
GData3 oldTri = (GData3) oldData;
if (!moveAdjacentData && !selectedTriangles.contains(oldTri))
continue;
GData3 newTri = null;
switch (mani.getPosition()) {
case 0:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, newVertex, new Vertex(oldTri.X2, oldTri.Y2, oldTri.Z2),
new Vertex(oldTri.X3, oldTri.Y3, oldTri.Z3), oldTri.parent, linkedDatFile);
break;
case 1:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, new Vertex(oldTri.X1, oldTri.Y1, oldTri.Z1), newVertex,
new Vertex(oldTri.X3, oldTri.Y3, oldTri.Z3), oldTri.parent, linkedDatFile);
break;
case 2:
newTri = new GData3(oldTri.colourNumber, oldTri.r, oldTri.g, oldTri.b, oldTri.a, new Vertex(oldTri.X1, oldTri.Y1, oldTri.Z1), new Vertex(oldTri.X2, oldTri.Y2, oldTri.Z2),
newVertex, oldTri.parent, linkedDatFile);
break;
}
newData = newTri;
if (selectedTriangles.contains(oldTri))
selectedTriangles.add(newTri);
break;
case 4:
GData4 oldQuad = (GData4) oldData;
if (!moveAdjacentData && !selectedQuads.contains(oldQuad))
continue;
GData4 newQuad = null;
switch (mani.getPosition()) {
case 0:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, newVertex, new Vertex(oldQuad.X2, oldQuad.Y2, oldQuad.Z2), new Vertex(oldQuad.X3,
oldQuad.Y3, oldQuad.Z3), new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 1:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), newVertex, new Vertex(oldQuad.X3,
oldQuad.Y3, oldQuad.Z3), new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 2:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), new Vertex(oldQuad.X2, oldQuad.Y2,
oldQuad.Z2), newVertex, new Vertex(oldQuad.X4, oldQuad.Y4, oldQuad.Z4), oldQuad.parent, linkedDatFile);
break;
case 3:
newQuad = new GData4(oldQuad.colourNumber, oldQuad.r, oldQuad.g, oldQuad.b, oldQuad.a, new Vertex(oldQuad.X1, oldQuad.Y1, oldQuad.Z1), new Vertex(oldQuad.X2, oldQuad.Y2,
oldQuad.Z2), new Vertex(oldQuad.X3, oldQuad.Y3, oldQuad.Z3), newVertex, oldQuad.parent, linkedDatFile);
break;
}
newData = newQuad;
if (selectedQuads.contains(oldQuad))
selectedQuads.add(newQuad);
break;
case 5:
GData5 oldCLin = (GData5) oldData;
if (!moveAdjacentData && !selectedCondlines.contains(oldCLin))
continue;
GData5 newCLin = null;
switch (mani.getPosition()) {
case 0:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, newVertex, new Vertex(oldCLin.X2, oldCLin.Y2, oldCLin.Z2), new Vertex(oldCLin.X3,
oldCLin.Y3, oldCLin.Z3), new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 1:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), newVertex, new Vertex(oldCLin.X3,
oldCLin.Y3, oldCLin.Z3), new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 2:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), new Vertex(oldCLin.X2, oldCLin.Y2,
oldCLin.Z2), newVertex, new Vertex(oldCLin.X4, oldCLin.Y4, oldCLin.Z4), oldCLin.parent, linkedDatFile);
break;
case 3:
newCLin = new GData5(oldCLin.colourNumber, oldCLin.r, oldCLin.g, oldCLin.b, oldCLin.a, new Vertex(oldCLin.X1, oldCLin.Y1, oldCLin.Z1), new Vertex(oldCLin.X2, oldCLin.Y2,
oldCLin.Z2), new Vertex(oldCLin.X3, oldCLin.Y3, oldCLin.Z3), newVertex, oldCLin.parent, linkedDatFile);
break;
}
newData = newCLin;
if (selectedCondlines.contains(oldCLin))
selectedCondlines.add(newCLin);
break;
}
if (selectedVertices.contains(oldVertex)) {
selectedVertices.remove(oldVertex);
selectedVertices.add(newVertex);
}
if (oldData.equals(tail))
linkedDatFile.setDrawChainTail(newData);
GData oldNext = oldData.getNext();
GData oldBefore = oldData.getBefore();
oldBefore.setNext(newData);
newData.setNext(oldNext);
Integer oldNumber = drawPerLine.getKey(oldData);
if (oldNumber != null)
drawPerLine.put(oldNumber, newData);
if (oldData.equals(og)) {
og = newData;
}
remove(oldData);
}
return og;
}
public final synchronized GData0 addVertex(Vertex vertex) {
if (vertex == null) {
vertex = new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
}
if (!vertexLinkedToPositionInFile.containsKey(vertex))
vertexLinkedToPositionInFile.put(vertex, Collections.newSetFromMap(new ThreadsafeHashMap<VertexManifestation, Boolean>()));
GData0 vertexTag = new GData0("0 !LPE VERTEX " + bigDecimalToString(vertex.X) + " " + bigDecimalToString(vertex.Y) + " " + bigDecimalToString(vertex.Z)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$)
vertexLinkedToPositionInFile.get(vertex).add(new VertexManifestation(0, vertexTag));
lineLinkedToVertices.put(vertexTag, Collections.newSetFromMap(new ThreadsafeHashMap<VertexInfo, Boolean>()));
lineLinkedToVertices.get(vertexTag).add(new VertexInfo(vertex, 0, vertexTag));
declaredVertices.put(vertexTag, new Vertex[] { vertex });
return vertexTag;
}
public final void clearVertexNormalCache() {
vertexLinkedToNormalCACHE.clear();
dataLinkedToNormalCACHE.clear();
}
public final void fillVertexNormalCache(GData data2draw) {
while ((data2draw = data2draw.getNext()) != null && !ViewIdleManager.pause[0].get()) {
data2draw.getVertexNormalMap(vertexLinkedToNormalCACHE, dataLinkedToNormalCACHE, this);
}
}
public Vector4f getVertexNormal(Vertex min) {
Vector4f result = new Vector4f(0f, 0f, 0f, 0f);
Set<VertexManifestation> linked = vertexLinkedToPositionInFile.get(min);
for (VertexManifestation m : linked) {
GData g = m.getGdata();
Vector3f n = null;
switch (g.type()) {
case 3:
GData3 g3 = (GData3) g;
n = new Vector3f(g3.xn, g3.yn, g3.zn);
break;
case 4:
GData4 g4 = (GData4) g;
n = new Vector3f(g4.xn, g4.yn, g4.zn);
break;
}
if (n != null) {
if (n.lengthSquared() != 0) {
n.normalise();
result.set(n.x + result.x, n.y + result.y, n.z + result.z);
}
}
}
if (result.lengthSquared() == 0)
return new Vector4f(0f, 0f, 1f, 1f);
result.normalise();
result.setW(1f);
return result;
}
public void setVertexAndNormal(float x, float y, float z, boolean negate, GData gd, int useCubeMapCache) {
boolean useCache = useCubeMapCache > 0;
// TODO Needs better caching since the connectivity information of TEXMAP data is unknown and the orientation of the normals can vary.
Vector4f v;
switch (gd.type()) {
case 3:
v = new Vector4f(x, y, z, 1f);
Matrix4f.transform(((GData3) gd).parent.productMatrix, v, v);
break;
case 4:
v = new Vector4f(x, y, z, 1f);
Matrix4f.transform(((GData4) gd).parent.productMatrix, v, v);
break;
default:
throw new AssertionError();
}
if (useCache) {
float[] n;
if ((n = vertexLinkedToNormalCACHE.get(new Vertex(v.x, v.y, v.z, false))) != null) {
GL11.glNormal3f(-n[0], -n[1], -n[2]);
} else {
n = dataLinkedToNormalCACHE.get(gd);
if (n != null) {
if (negate) {
GL11.glNormal3f(-n[0], -n[1], -n[2]);
} else {
GL11.glNormal3f(n[0], n[1], n[2]);
}
}
}
} else {
float[] n = dataLinkedToNormalCACHE.get(gd);
if (n != null) {
if (negate) {
GL11.glNormal3f(-n[0], -n[1], -n[2]);
} else {
GL11.glNormal3f(n[0], n[1], n[2]);
}
}
}
GL11.glVertex3f(v.x, v.y, v.z);
}
public final void delete(boolean moveAdjacentData, boolean setModified) {
if (linkedDatFile.isReadOnly())
return;
if (selectedBgPicture != null && linkedDatFile.getDrawPerLine_NOCLONE().containsValue(selectedBgPicture)) {
GData before = selectedBgPicture.getBefore();
GData next = selectedBgPicture.getNext();
linkedDatFile.getDrawPerLine_NOCLONE().removeByValue(selectedBgPicture);
before.setNext(next);
remove(selectedBgPicture);
selectedBgPicture = null;
setModified_NoSync();
}
final Set<Vertex> singleVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
final HashSet<GData0> effSelectedVertices = new HashSet<GData0>();
final HashSet<GData2> effSelectedLines = new HashSet<GData2>();
final HashSet<GData3> effSelectedTriangles = new HashSet<GData3>();
final HashSet<GData4> effSelectedQuads = new HashSet<GData4>();
final HashSet<GData5> effSelectedCondlines = new HashSet<GData5>();
selectedData.clear();
// 0. Deselect selected subfile data (for whole selected subfiles)
for (GData1 subf : selectedSubfiles) {
Set<VertexInfo> vis = lineLinkedToVertices.get(subf);
if (vis == null) continue;
for (VertexInfo vertexInfo : vis) {
if (!moveAdjacentData)
selectedVertices.remove(vertexInfo.getVertex());
GData g = vertexInfo.getLinkedData();
switch (g.type()) {
case 2:
selectedLines.remove(g);
break;
case 3:
selectedTriangles.remove(g);
break;
case 4:
selectedQuads.remove(g);
break;
case 5:
selectedCondlines.remove(g);
break;
default:
break;
}
}
}
// 1. Vertex Based Selection
{
final Set<Vertex> objectVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
{
HashMap<GData, Integer> occurMap = new HashMap<GData, Integer>();
for (Vertex vertex : selectedVertices) {
Set<VertexManifestation> occurences = vertexLinkedToPositionInFile.get(vertex);
if (occurences == null)
continue;
boolean isPureSubfileVertex = true;
for (VertexManifestation vm : occurences) {
GData g = vm.getGdata();
int val = 1;
if (occurMap.containsKey(g)) {
val = occurMap.get(g);
val++;
}
occurMap.put(g, val);
switch (g.type()) {
case 0:
GData0 meta = (GData0) g;
boolean idCheck = !lineLinkedToVertices.containsKey(meta);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (moveAdjacentData || val == 1) {
if (!idCheck) {
effSelectedVertices.add(meta);
}
}
break;
case 2:
GData2 line = (GData2) g;
idCheck = !line.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (moveAdjacentData || val == 2) {
if (!idCheck) {
selectedLines.add(line);
}
}
break;
case 3:
GData3 triangle = (GData3) g;
idCheck = !triangle.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (moveAdjacentData || val == 3) {
if (!idCheck) {
selectedTriangles.add(triangle);
}
}
break;
case 4:
GData4 quad = (GData4) g;
idCheck = !quad.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (moveAdjacentData || val == 4) {
if (!idCheck) {
selectedQuads.add(quad);
}
}
break;
case 5:
GData5 condline = (GData5) g;
idCheck = !condline.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (moveAdjacentData || val == 4) {
if (!idCheck) {
selectedCondlines.add(condline);
}
}
break;
}
}
if (isPureSubfileVertex)
objectVertices.add(vertex);
}
}
// 2. Object Based Selection
for (GData2 line : selectedLines) {
if (line.parent.equals(View.DUMMY_REFERENCE))
effSelectedLines.add(line);
Vertex[] verts = lines.get(line);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData3 triangle : selectedTriangles) {
if (triangle.parent.equals(View.DUMMY_REFERENCE))
effSelectedTriangles.add(triangle);
Vertex[] verts = triangles.get(triangle);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData4 quad : selectedQuads) {
if (quad.parent.equals(View.DUMMY_REFERENCE))
effSelectedQuads.add(quad);
Vertex[] verts = quads.get(quad);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData5 condline : selectedCondlines) {
if (condline.parent.equals(View.DUMMY_REFERENCE))
effSelectedCondlines.add(condline);
Vertex[] verts = condlines.get(condline);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
if (moveAdjacentData) {
singleVertices.addAll(selectedVertices);
singleVertices.removeAll(objectVertices);
}
// 3. Deletion of the selected data (no whole subfiles!!)
if (!effSelectedLines.isEmpty())
setModified_NoSync();
if (!effSelectedTriangles.isEmpty())
setModified_NoSync();
if (!effSelectedQuads.isEmpty())
setModified_NoSync();
if (!effSelectedCondlines.isEmpty())
setModified_NoSync();
final HashBiMap<Integer, GData> dpl = linkedDatFile.getDrawPerLine_NOCLONE();
for (GData2 gd : effSelectedLines) {
dpl.removeByValue(gd);
gd.getBefore().setNext(gd.getNext());
remove(gd);
}
for (GData3 gd : effSelectedTriangles) {
dpl.removeByValue(gd);
gd.getBefore().setNext(gd.getNext());
remove(gd);
}
for (GData4 gd : effSelectedQuads) {
dpl.removeByValue(gd);
gd.getBefore().setNext(gd.getNext());
remove(gd);
}
for (GData5 gd : effSelectedCondlines) {
dpl.removeByValue(gd);
gd.getBefore().setNext(gd.getNext());
remove(gd);
}
for (Vertex v : singleVertices) {
if (vertexLinkedToPositionInFile.containsKey(v)) {
Set<VertexManifestation> tmp = vertexLinkedToPositionInFile.get(v);
if (tmp == null)
continue;
Set<VertexManifestation> occurences = new HashSet<VertexManifestation>(tmp);
for (VertexManifestation vm : occurences) {
GData g = vm.getGdata();
if (lineLinkedToVertices.containsKey(g)) {
dpl.removeByValue(g);
g.getBefore().setNext(g.getNext());
remove(g);
setModified_NoSync();
}
}
}
}
selectedVertices.clear();
selectedLines.clear();
selectedTriangles.clear();
selectedQuads.clear();
selectedCondlines.clear();
// 4. Subfile Based Deletion
if (!selectedSubfiles.isEmpty()) {
for (GData1 gd : selectedSubfiles) {
// Remove a BFC INVERTNEXT if it is present
boolean hasInvertnext = false;
GData invertNextData = gd.getBefore();
while (invertNextData != null && invertNextData.type() != 1 && (invertNextData.type() != 6 || ((GDataBFC) invertNextData).type != BFC.INVERTNEXT)) {
invertNextData = invertNextData.getBefore();
}
if (invertNextData != null && invertNextData.type() == 6) {
hasInvertnext = true;
}
if (hasInvertnext) {
// Remove Invert Next
GDataBFC gbfc = (GDataBFC) invertNextData;
dpl.removeByValue(gbfc);
gbfc.getBefore().setNext(gbfc.getNext());
remove(gbfc);
}
dpl.removeByValue(gd);
gd.getBefore().setNext(gd.getNext());
remove(gd);
}
selectedSubfiles.clear();
setModified_NoSync();
}
if (isModified()) {
// Update Draw per line
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.addAll(dpl.keySet());
int counter = 1;
GData tail = null;
for (Integer k : ts) {
GData gdata = dpl.getValue(k);
dpl.removeByKey(k);
dpl.put(counter, gdata);
counter++;
tail = gdata;
}
if (tail != null) {
linkedDatFile.setDrawChainTail(tail);
} else {
GData0 blankLine = new GData0(""); //$NON-NLS-1$
linkedDatFile.getDrawChainStart().setNext(blankLine);
dpl.put(1, blankLine);
linkedDatFile.setDrawChainTail(blankLine);
}
if (setModified) syncWithTextEditors(true);
updateUnsavedStatus();
}
}
}
protected final void linker(GData oldData, GData newData) {
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
if (oldData.equals(linkedDatFile.getDrawChainTail()))
linkedDatFile.setDrawChainTail(newData);
GData oldNext = oldData.getNext();
GData oldBefore = oldData.getBefore();
oldBefore.setNext(newData);
newData.setNext(oldNext);
Integer oldNumber = drawPerLine.getKey(oldData);
if (oldNumber != null)
drawPerLine.put(oldNumber, newData);
remove(oldData);
}
public synchronized HashMap<GData0, Vertex[]> getDeclaredVertices() {
return new HashMap<GData0, Vertex[]>(declaredVertices);
}
public final synchronized HashMap<GData2, Vertex[]> getLines() {
return new HashMap<GData2, Vertex[]>(lines);
}
public final synchronized HashMap<GData3, Vertex[]> getTriangles() {
return new HashMap<GData3, Vertex[]>(triangles);
}
public final synchronized ThreadsafeHashMap<GData3, Vertex[]> getTriangles_NOCLONE() {
return triangles;
}
public final synchronized ThreadsafeHashMap<GData4, Vertex[]> getQuads_NOCLONE() {
return quads;
}
public final synchronized HashMap<GData4, Vertex[]> getQuads() {
return new HashMap<GData4, Vertex[]>(quads);
}
public final synchronized HashMap<GData5, Vertex[]> getCondlines() {
return new HashMap<GData5, Vertex[]>(condlines);
}
public final Vertex getVertexToReplace() {
return vertexToReplace;
}
public final void setVertexToReplace(Vertex vertexToReplace) {
this.vertexToReplace = vertexToReplace;
}
public final AtomicBoolean getResetTimer() {
return resetTimer;
}
public final Set<Vertex> getVertices() {
return vertexLinkedToPositionInFile.keySet();
}
public final synchronized void clear() {
final Editor3DWindow win = Editor3DWindow.getWindow();
vertexCountInSubfile.clear();
vertexLinkedToPositionInFile.clear();
vertexLinkedToSubfile.clear();
lineLinkedToVertices.clear();
declaredVertices.clear();
lines.clear();
triangles.clear();
quads.clear();
condlines.clear();
selectedItemIndex = -1;
win.disableSelectionTab();
selectedData.clear();
selectedVertices.clear();
selectedSubfiles.clear();
selectedLines.clear();
selectedTriangles.clear();
selectedQuads.clear();
selectedCondlines.clear();
lastSelectedVertex = null;
}
}
|
package org.objectweb.asm.util;
import org.objectweb.asm.Constants;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.CodeVisitor;
import java.io.PrintWriter;
/**
* A {@link PrintClassVisitor PrintClassVisitor} that prints the ASM code that
* generates the classes it visits. This class visitor can be used to quickly
* write ASM code to generate some given bytecode:
* <ul>
* <li>write the Java source code equivalent to the bytecode you want to
* generate;</li>
* <li>compile it with <tt>javac</tt>;</li>
* <li>make a {@link DumpClassVisitor DumpClassVisitor} visit this compiled
* class (see the {@link #main main} method);</li>
* <li>edit the generated source code, if necessary.</li>
* </ul>
* The source code printed when visiting the <tt>Hello</tt> class is the
* following:
* <p>
* <blockquote>
* <pre>
* import org.objectweb.asm.*;
* import java.io.FileOutputStream;
*
* public class Dump implements Constants {
*
* public static void main (String[] args) throws Exception {
*
* ClassWriter cw = new ClassWriter(false);
* CodeVisitor cv;
*
* cw.visit(ACC_PUBLIC + ACC_SUPER, "Hello", "java/lang/Object", null, "Hello.java");
*
* {
* cv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null);
* cv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
* cv.visitLdcInsn("hello");
* cv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
* cv.visitInsn(RETURN);
* cv.visitMaxs(2, 1);
* }
* {
* cv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null);
* cv.visitVarInsn(ALOAD, 0);
* cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
* cv.visitInsn(RETURN);
* cv.visitMaxs(1, 1);
* }
* cw.visitEnd();
*
* FileOutputStream os = new FileOutputStream("Dumped.class");
* os.write(cw.toByteArray());
* os.close();
* }
* }
* </pre>
* </blockquote>
* where <tt>Hello</tt> is defined by:
* <p>
* <blockquote>
* <pre>
* public class Hello {
*
* public static void main (String[] args) {
* System.out.println("hello");
* }
* }
* </pre>
* </blockquote>
*/
public class DumpClassVisitor extends PrintClassVisitor {
/**
* Prints the ASM source code to generate the given class to the standard
* output.
* <p>
* Usage: DumpClassVisitor <fully qualified class name>
*
* @param args the command line arguments.
*
* @throws Exception if the class cannot be found, or if an IO exception
* occurs.
*/
public static void main (final String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Prints the ASM code to generate the given class.");
System.err.println("Usage: DumpClassVisitor <fully qualified class name>");
System.exit(-1);
}
ClassReader cr = new ClassReader(args[0]);
cr.accept(new DumpClassVisitor(new PrintWriter(System.out)), true);
}
/**
* Constructs a new {@link DumpClassVisitor DumpClassVisitor} object.
*
* @param pw the print writer to be used to print the class.
*/
public DumpClassVisitor (final PrintWriter pw) {
super(pw);
}
public void visit (
final int access,
final String name,
final String superName,
final String[] interfaces,
final String sourceFile)
{
text.add("import org.objectweb.asm.*;\n");
text.add("import java.io.FileOutputStream;\n\n");
text.add("public class Dump implements Constants {\n\n");
text.add("public static void main (String[] args) throws Exception {\n\n");
text.add("ClassWriter cw = new ClassWriter(false);\n");
text.add("CodeVisitor cv;\n\n");
buf.setLength(0);
buf.append("cw.visit(");
appendAccess(access | 262144);
buf.append(", ");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, superName);
buf.append(", ");
if (interfaces != null && interfaces.length > 0) {
buf.append("new String[] {");
for (int i = 0; i < interfaces.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendConstant(buf, interfaces[i]);
}
buf.append(" }");
} else {
buf.append("null");
}
buf.append(", ");
appendConstant(buf, sourceFile);
buf.append(");\n\n");
text.add(buf.toString());
}
public void visitInnerClass (
final String name,
final String outerName,
final String innerName,
final int access)
{
buf.setLength(0);
buf.append("cw.visitInnerClass(");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, outerName);
buf.append(", ");
appendConstant(buf, innerName);
buf.append(", ");
appendAccess(access);
buf.append(");\n\n");
text.add(buf.toString());
}
public void visitField (
final int access,
final String name,
final String desc,
final Object value)
{
buf.setLength(0);
buf.append("cw.visitField(");
appendAccess(access);
buf.append(", ");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, desc);
buf.append(", ");
appendConstant(buf, value);
buf.append(");\n\n");
text.add(buf.toString());
}
public CodeVisitor visitMethod (
final int access,
final String name,
final String desc,
final String[] exceptions)
{
buf.setLength(0);
buf.append("{\n").append("cv = cw.visitMethod(");
appendAccess(access);
buf.append(", ");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, desc);
buf.append(", ");
if (exceptions != null && exceptions.length > 0) {
buf.append("new String[] {");
for (int i = 0; i < exceptions.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendConstant(buf, exceptions[i]);
}
buf.append(" });");
} else {
buf.append("null);");
}
buf.append("\n");
text.add(buf.toString());
PrintCodeVisitor pcv = new DumpCodeVisitor();
text.add(pcv.getText());
text.add("}\n");
return pcv;
}
public void visitEnd () {
text.add("cw.visitEnd();\n\n");
text.add("FileOutputStream os = new FileOutputStream(\"Dumped.class\");\n");
text.add("os.write(cw.toByteArray());\n");
text.add("os.close();\n");
text.add("}\n");
text.add("}\n");
super.visitEnd();
}
/**
* Appends a string representation of the given access modifiers to {@link
* #buf buf}.
*
* @param access some access modifiers.
*/
void appendAccess (final int access) {
boolean first = true;
if ((access & Constants.ACC_PUBLIC) != 0) {
buf.append("ACC_PUBLIC");
first = false;
}
if ((access & Constants.ACC_PRIVATE) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_PRIVATE");
first = false;
}
if ((access & Constants.ACC_PROTECTED) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_PROTECTED");
first = false;
}
if ((access & Constants.ACC_FINAL) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_FINAL");
first = false;
}
if ((access & Constants.ACC_STATIC) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_STATIC");
first = false;
}
if ((access & Constants.ACC_SYNCHRONIZED) != 0) {
if (!first) {
buf.append(" + ");
}
if ((access & 262144) != 0) {
buf.append("ACC_SUPER");
} else {
buf.append("ACC_SYNCHRONIZED");
}
first = false;
}
if ((access & Constants.ACC_VOLATILE) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_VOLATILE");
first = false;
}
if ((access & Constants.ACC_TRANSIENT) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_TRANSIENT");
first = false;
}
if ((access & Constants.ACC_NATIVE) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_NATIVE");
first = false;
}
if ((access & Constants.ACC_ABSTRACT) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_ABSTRACT");
first = false;
}
if ((access & Constants.ACC_STRICT) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_STRICT");
first = false;
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_SYNTHETIC");
first = false;
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_DEPRECATED");
}
if (first) {
buf.append("0");
}
}
/**
* Appends a string representation of the given constant to the given buffer.
*
* @param buf a string buffer.
* @param cst an {@link java.lang.Integer Integer}, {@link java.lang.Float
* Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double}
* or {@link String String} object. May be <tt>null</tt>.
*/
static void appendConstant (final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
String s = (String)cst;
buf.append("\"");
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '\n') {
buf.append("\\n");
} else if (c == '\\') {
buf.append("\\\\");
} else if (c == '"') {
buf.append("\\\"");
} else {
buf.append(c);
}
}
buf.append("\"");
} else if (cst instanceof Integer) {
buf.append("new Integer(")
.append(cst)
.append(")");
} else if (cst instanceof Float) {
buf.append("new Float(")
.append(cst)
.append("F)");
} else if (cst instanceof Long) {
buf.append("new Long(")
.append(cst)
.append("L)");
} else if (cst instanceof Double) {
buf.append("new Double(")
.append(cst)
.append(")");
}
}
}
|
package org.robockets.stronghold.robot;
import com.kauailabs.nav6.frc.IMUAdvanced;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SerialPort;
import edu.wpi.first.wpilibj.Victor;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
private static SerialPort navXSerialPort = new SerialPort(57600, SerialPort.Port.kMXP);
private static byte updateRateHz = 50;
public static IMUAdvanced navX = new IMUAdvanced(navXSerialPort, updateRateHz);
public static RobotDrive robotDrive = new RobotDrive(0, 1);
public static Victor intakeMotor = new Victor(2); //TEMP
public static Encoder intakeEncoder = new Encoder(3, 4);
public static Victor intakeVerticalMotor = new Victor(3); //TEMP
public static Victor jeffRoller1 = new Victor(4); // TEMP
public static Victor jeffRoller2 = new Victor(5); // TEMP
public static Victor shootingWheelMotor = new Victor(6);
public static Victor turnTableMotor = new Victor(7); // TEMP
public static Encoder turnTableEncoder = new Encoder(5, 6);
public static Victor hoodMotor = new Victor(8); // TEMP
public static Encoder hoodEncoder = new Encoder(7, 8);
public static Encoder driveEncoder = new Encoder(9, 10);
public RobotMap () {
navX.zeroYaw();
}
}
|
package org.subethamail.smtp.test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.wiser.Wiser;
/**
* A simple command-line tool that lets us practice with the smtp library.
*
* @author Jeff Schnitzer
*/
public class Practice
{
@SuppressWarnings("unused")
private final static Logger log = LoggerFactory.getLogger(Practice.class);
public static final int PORT = 2566;
public static void main(String[] args) throws Exception
{
Wiser wiser = new Wiser();
wiser.setHostname("localhost");
wiser.setPort(PORT);
wiser.start();
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do
{
line = in.readLine();
line = line.trim();
if ("dump".equals(line));
wiser.dumpMessages(System.out);
if (line.startsWith("dump "))
{
line = line.substring("dump ".length());
File f = new File(line);
OutputStream out = new FileOutputStream(f);
wiser.dumpMessages(new PrintStream(out));
out.close();
}
}
while (!"quit".equals(line));
wiser.stop();
}
}
|
package org.usfirst.frc.team6706.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// RobotDrive Motor
public static final int DriverFrontLeftPort = 2;
public static final int DriverRearLeftPort = 3;
public static final int DriverFrontRightPort = 0;
public static final int DriverRearRightPort = 1;
public static final int ClimbRopeMotor = 4;
public static final int CastBallMotor = 5;
public static final int GetBallMotor = 6;
//GetBall Motor Speed parameter
public static final double GetBallMotorSpeed = 0.38;
public static final double CastBallMotorSpeed = -0.5;
public static final double ClimbRopeMotorSpeed = 0.8;
//GetBall Button
public static final int CastInBall = 1;
public static final int StopCastBall = 2;
public static final int CastOutBall = 3;
public static final int GetInBall = 5;
public static final int StopGetBall = 6;
public static final int ClimbRopeUpButton = 7;
public static final int ClimbRopeHoldButton = 8;
//Drive Mode
public static final int DriveForward = 4;
public static final int DriveBack = 2;
public static final int DriveLeft = 1;
public static final int DriveRight = 3;
//Autonomous
public static final double SlowCrossSpeed = 0.4;
public static final double SlowCrossTime = 3;
public static final double FastCrossSpeed = 0.4;
public static final double FastCrossTime = 3;
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc4909.STEAMWORKS;
import org.usfirst.frc4909.STEAMWORKS.PID.*;
import com.kauailabs.navx.frc.AHRS;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.AnalogPotentiometer;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.SerialPort;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static SpeedController drivetrainLeftFrontDriveMotorController;
public static SpeedController drivetrainLeftBackDriveMotorController;
public static SpeedController drivetrainRightBackDriveMotorController;
public static SpeedController drivetrainRightFrontDriveMotorController;
public static RobotDrive drivetrainRobotDrive;
public static Encoder drivetrainLeftEncoder;
public static Encoder drivetrainRightEncoder;
public static SpeedController climberClimberMotorController;
public static Encoder climberClimberEncoder;
public static AnalogPotentiometer intakePivotPot;
public static SpeedController intakeIntakeMotor;
public static SpeedController feederFeederMotor;
public static Encoder shooterShooterEncoder;
public static SpeedController shooterShooterMotorController;
public static SpeedController intakePivotMotor;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static SpeedController loaderMotor;
public static AnalogPotentiometer loaderPivotPot;
public static DigitalInput climberSwitch;
public static PIDController shooterPID;
public static double shooterP = 0.00015;
public static double shooterI = 0.00000;
public static double shooterD = 0.00000;
public static double shooterF = 0.00050;
public static AHRS navx;
public static PowerDistributionPanel PDP;
public static void init() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
drivetrainLeftFrontDriveMotorController = new Talon(0);
LiveWindow.addActuator("Drivetrain", "LeftFrontDriveMotorController", (Talon) drivetrainLeftFrontDriveMotorController);
drivetrainLeftBackDriveMotorController = new Talon(1);
LiveWindow.addActuator("Drivetrain", "LeftBackDriveMotorController", (Talon) drivetrainLeftBackDriveMotorController);
drivetrainRightBackDriveMotorController = new Talon(3);
LiveWindow.addActuator("Drivetrain", "RightBackDriveMotorController", (Talon) drivetrainRightBackDriveMotorController);
drivetrainRightFrontDriveMotorController = new Talon(2);
LiveWindow.addActuator("Drivetrain", "RightFrontDriveMotorController", (Talon) drivetrainRightFrontDriveMotorController);
drivetrainRobotDrive = new RobotDrive(drivetrainLeftFrontDriveMotorController, drivetrainLeftBackDriveMotorController,
drivetrainRightFrontDriveMotorController, drivetrainRightBackDriveMotorController);
drivetrainRobotDrive.setSafetyEnabled(true);
drivetrainRobotDrive.setExpiration(0.1);
drivetrainRobotDrive.setSensitivity(0.5);
drivetrainRobotDrive.setMaxOutput(1.0);
drivetrainRobotDrive.setInvertedMotor(RobotDrive.MotorType.kFrontLeft, true);
drivetrainRobotDrive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, true);
drivetrainRobotDrive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true);
drivetrainRobotDrive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true);
drivetrainLeftEncoder = new Encoder(0, 1, true, EncodingType.k4X);
LiveWindow.addSensor("Drivetrain", "LeftEncoder", drivetrainLeftEncoder);
drivetrainLeftEncoder.setDistancePerPulse(1.0);
drivetrainLeftEncoder.setPIDSourceType(PIDSourceType.kDisplacement);
drivetrainRightEncoder = new Encoder(2, 3, false, EncodingType.k4X);
LiveWindow.addSensor("Drivetrain", "RightEncoder", drivetrainRightEncoder);
drivetrainRightEncoder.setDistancePerPulse(1.0);
drivetrainRightEncoder.setPIDSourceType(PIDSourceType.kRate);
climberClimberMotorController = new Talon(5);
LiveWindow.addActuator("Climber", "ClimberMotorController", (Talon) climberClimberMotorController);
climberClimberEncoder = new Encoder(4, 5, false, EncodingType.k4X);
LiveWindow.addSensor("Climber", "ClimberEncoder", climberClimberEncoder);
climberClimberEncoder.setDistancePerPulse(1.0);
climberClimberEncoder.setPIDSourceType(PIDSourceType.kRate);
intakePivotPot = new AnalogPotentiometer(0, 1.0, 0.0);
LiveWindow.addSensor("Intake", "PivotPot", intakePivotPot);
intakeIntakeMotor = new Talon(7);
LiveWindow.addActuator("Intake", "IntakeMotor", (Talon) intakeIntakeMotor);
feederFeederMotor = new Talon(6);
LiveWindow.addActuator("Feeder", "FeederMotor", (Talon) feederFeederMotor);
shooterShooterEncoder = new Encoder(6, 7, true, EncodingType.k4X);
LiveWindow.addSensor("Shooter", "ShooterEncoder", shooterShooterEncoder);
shooterShooterEncoder.setDistancePerPulse(1.0);
shooterShooterEncoder.setPIDSourceType(PIDSourceType.kRate);
shooterShooterMotorController = new Talon(4);
LiveWindow.addActuator("Shooter", "ShooterMotorController", (Talon) shooterShooterMotorController);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
shooterShooterEncoder.setDistancePerPulse(1.0/(2048.0/48.0));
shooterShooterMotorController.setInverted(true);
navx = new AHRS(SerialPort.Port.kMXP);
SmartDashboard.putNumber("P", shooterP);
SmartDashboard.putNumber("I", shooterI);
SmartDashboard.putNumber("D", shooterD);
SmartDashboard.putNumber("F", shooterF);
PDP = new PowerDistributionPanel();
shooterPID = new PIDController(shooterP, shooterI, shooterD,1);
loaderMotor = new Talon(9);
LiveWindow.addActuator("Loader", "LoaderMotor", (Talon) loaderMotor);
loaderPivotPot = new AnalogPotentiometer(1, 3600, 0.0);
LiveWindow.addSensor("Loader", "PivotPot", loaderPivotPot);
intakePivotMotor= new Talon(8);
LiveWindow.addActuator("Intake", "IntakePivotMotorController", (Talon) intakePivotMotor);
climberSwitch= new DigitalInput(8);
}
}
|
package org.vitrivr.cineast.core.data;
import java.util.EnumSet;
import java.util.HashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
public enum MediaType {
VIDEO(0, "v", "video");
private final int id;
private final String prefix, name;
/**
*
* @param id
* numeric id to use to identify the type in the persistent storage layer
* @param prefix
* the prefix of the MediaType without a trailing delimiter such as '_'
* @param name
* the name of the media type
*/
MediaType(int id, String prefix, String name) {
this.id = id;
this.prefix = prefix;
this.name = name.trim();
}
public int getId() {
return this.id;
}
/**
* @return the prefix of the MediaType without a trailing delimiter such as '_'
*/
public String getPrefix() {
return this.prefix;
}
public String getName() {
return this.name;
}
private static final TIntObjectHashMap<MediaType> idToType = new TIntObjectHashMap<>();
private static final HashMap<String, MediaType> prefixToType = new HashMap<>();
private static final HashMap<String, MediaType> nameToType = new HashMap<>();
static {
for (MediaType t : EnumSet.allOf(MediaType.class)) {
if (idToType.containsKey(t.getId())) {
throw new IllegalStateException("duplicate id (" + t.getId() + ") in Mediatype: " + t
+ " collides with " + idToType.get(t.getId()));
}
idToType.put(t.getId(), t);
if (prefixToType.containsKey(t.getPrefix())) {
throw new IllegalStateException("duplicate prefix (" + t.getPrefix() + ") in Mediatype: "
+ t + " collides with " + prefixToType.get(t.getPrefix()));
}
prefixToType.put(t.getPrefix(), t);
if (nameToType.containsKey(t.getPrefix())) {
throw new IllegalStateException("duplicate name (" + t.getName() + ") in Mediatype: " + t
+ " collides with " + nameToType.get(t.getName()));
}
nameToType.put(t.getName().toLowerCase(), t);
}
}
/**
* @return the MediaType associated with this id or null in case there is none
*/
public static final MediaType fromId(int id) {
return idToType.get(id);
}
/**
* @return the MediaType associated with this prefix or null in case there is none
*/
public static final MediaType fromPrefix(String prefix) {
if (prefix == null) {
return null;
}
return prefixToType.get(prefix);
}
/**
* @return the MediaType associated with this name or null in case there is none
*/
public static final MediaType fromName(String name) {
if (name == null) {
return null;
}
return nameToType.get(name.trim().toLowerCase());
}
public static final boolean existsId(int id) {
return idToType.containsKey(id);
}
public static final boolean existsPrefix(String prefix) {
return prefixToType.containsKey(prefix);
}
public static final boolean existsName(String name) {
return nameToType.containsKey(name.trim().toLowerCase());
}
}
|
package protocolsupport.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_9_R1.MinecraftServer;
import net.minecraft.server.v1_9_R1.PropertyManager;
import protocolsupport.api.ProtocolSupportAPI;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.api.chat.components.TextComponent;
import protocolsupport.api.chat.modifiers.Modifier;
import protocolsupport.api.tab.TabAPI;
import protocolsupport.api.title.TitleAPI;
public class CommandHandler implements CommandExecutor, TabCompleter {
private static final String DEBUG_PROPERTY = "debug";
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!sender.hasPermission("protocolsupport.admin")) {
sender.sendMessage(ChatColor.RED + "You have no power here!");
return true;
}
if ((args.length == 1) && args[0].equalsIgnoreCase("list")) {
for (ProtocolVersion version : ProtocolVersion.values()) {
if (version.getName() != null) {
sender.sendMessage(ChatColor.GOLD+"["+version.getName()+"]: "+ChatColor.GREEN+getPlayersStringForProtocol(version));
}
}
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("debug")) {
@SuppressWarnings("deprecation")
PropertyManager manager = MinecraftServer.getServer().getPropertyManager();
if (!manager.getBoolean(DEBUG_PROPERTY, false)) {
manager.setProperty(DEBUG_PROPERTY, Boolean.TRUE);
sender.sendMessage(ChatColor.GOLD + "Enabled debug");
} else {
manager.setProperty(DEBUG_PROPERTY, Boolean.FALSE);
sender.sendMessage(ChatColor.GOLD + "Disabled debug");
}
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("testtitle")) {
TextComponent title = new TextComponent("Test title");
Modifier titlemodifier = new Modifier();
titlemodifier.setColor(ChatColor.AQUA);
titlemodifier.setBold(true);
title.setModifier(titlemodifier);
TextComponent subtitle = new TextComponent("Test subtitle");
Modifier subtitlemodifier = new Modifier();
subtitlemodifier.setColor(ChatColor.BLUE);
subtitlemodifier.setUnderlined(true);
subtitle.setModifier(subtitlemodifier);
for (Player player : Bukkit.getOnlinePlayers()) {
TitleAPI.sendSimpleTitle(player, title, subtitle, 20, 60, 20);
}
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("testtab")) {
TextComponent header = new TextComponent("Test header");
Modifier headermodifier = new Modifier();
headermodifier.setColor(ChatColor.AQUA);
headermodifier.setBold(true);
header.setModifier(headermodifier);
TextComponent footer = new TextComponent("Test footer");
Modifier footermodifier = new Modifier();
footermodifier.setColor(ChatColor.BLUE);
footermodifier.setUnderlined(true);
footer.setModifier(footermodifier);
for (Player player : Bukkit.getOnlinePlayers()) {
TabAPI.sendHeaderFooter(player, header, footer);
}
return true;
}
return false;
}
private String getPlayersStringForProtocol(ProtocolVersion version) {
StringBuilder sb = new StringBuilder();
for (Player player : Bukkit.getOnlinePlayers()) {
if (ProtocolSupportAPI.getProtocolVersion(player) == version) {
sb.append(player.getName());
sb.append(", ");
}
}
if (sb.length() > 2) {
sb.delete(sb.length() - 2, sb.length());
}
return sb.toString();
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
ArrayList<String> completions = new ArrayList<String>();
if ("list".startsWith(args[0])) {
completions.add("list");
}
if ("debug".startsWith(args[0])) {
completions.add("debug");
}
if ("testtitle".startsWith(args[0])) {
completions.add("testtitle");
}
if ("testtab".startsWith(args[0])) {
completions.add("testtab");
}
return completions;
}
}
|
package benchmark;
import graphql.language.AstPrinter;
import graphql.language.Document;
import graphql.parser.Parser;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
@Warmup(iterations = 2, time = 5, batchSize = 3)
@Measurement(iterations = 3, time = 10, batchSize = 4)
public class AstPrinterBenchmark {
/**
* Note: this query is a redacted version of a real query
*/
private static final Document document = Parser.parse("query fang($slip: dinner!) {\n" +
" instinctive(thin: $slip) {\n" +
" annoy {\n" +
" ...account\n" +
" }\n" +
" massive {\n" +
" ...cellar\n" +
" }\n" +
" used {\n" +
" ...rinse\n" +
" }\n" +
" distinct(sedate: [disarm]) {\n" +
" ...lamp\n" +
" }\n" +
" venomous {\n" +
" uninterested\n" +
" }\n" +
" correct {\n" +
" ...plane\n" +
" }\n" +
" drown\n" +
" talk {\n" +
" house\n" +
" womanly\n" +
" royal {\n" +
" ...snore\n" +
" }\n" +
" gray\n" +
" normal\n" +
" proud\n" +
" crate\n" +
" billowy {\n" +
" frogs\n" +
" abstracted\n" +
" market\n" +
" corn\n" +
" }\n" +
" tip {\n" +
" ...public\n" +
" }\n" +
" stick {\n" +
" ...precious\n" +
" }\n" +
" null {\n" +
" ...precious\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n" +
"fragment account on bath {\n" +
" purpose\n" +
" festive\n" +
" ruddy\n" +
"}\n" +
"\n" +
"fragment cellar on thunder {\n" +
" debonair\n" +
" immense\n" +
" object\n" +
" moon\n" +
" icy {\n" +
" furniture\n" +
" historical\n" +
" team\n" +
" root\n" +
" }\n" +
"}\n" +
"\n" +
"fragment rinse on song {\n" +
" reply {\n" +
" sticks\n" +
" unbecoming\n" +
" }\n" +
" love {\n" +
" annoying\n" +
" sign\n" +
" }\n" +
"}\n" +
"\n" +
"fragment lamp on heartbreaking {\n" +
" innocent\n" +
" decorate\n" +
" pancake\n" +
" arithmetic\n" +
" grey\n" +
" brass\n" +
" pocket\n" +
"}\n" +
"\n" +
"fragment snore on tired {\n" +
" share\n" +
" baseball\n" +
" suspend\n" +
"}\n" +
"\n" +
"fragment settle on incompetent {\n" +
" name\n" +
" juggle\n" +
" depressed\n" +
"}\n" +
"\n" +
"fragment few on puffy {\n" +
" ticket\n" +
" puny\n" +
" copy\n" +
" coast\n" +
"}\n" +
"\n" +
"fragment plane on seat {\n" +
" ice\n" +
" mug\n" +
" wobble\n" +
" clear\n" +
" toys {\n" +
" ...few\n" +
" }\n" +
"}\n" +
"\n" +
"fragment public on basin {\n" +
" different\n" +
" fang\n" +
" slip\n" +
" dinner\n" +
" instinctive\n" +
" thin {\n" +
" annoy {\n" +
" account\n" +
" massive\n" +
" cellar\n" +
" used\n" +
" rinse {\n" +
" distinct\n" +
" }\n" +
" sedate {\n" +
" disarm\n" +
" }\n" +
" lamp {\n" +
" venomous\n" +
" }\n" +
" }\n" +
" uninterested {\n" +
" ...settle\n" +
" }\n" +
" }\n" +
"}\n" +
"\n" +
"fragment precious on drown {\n" +
" talk\n" +
" house\n" +
" womanly\n" +
" royal {\n" +
" snore {\n" +
" gray\n" +
" }\n" +
" normal {\n" +
" proud\n" +
" crate\n" +
" billowy\n" +
" frogs\n" +
" abstracted {\n" +
" ...snore\n" +
" }\n" +
" corn {\n" +
" tip\n" +
" public\n" +
" }\n" +
" stick {\n" +
" ...settle\n" +
" }\n" +
" null {\n" +
" ...few\n" +
" }\n" +
" marry\n" +
" bath {\n" +
" purpose\n" +
" festive\n" +
" }\n" +
" ruddy\n" +
" help\n" +
" thunder\n" +
" debonair {\n" +
" immense\n" +
" }\n" +
" object\n" +
" }\n" +
" }\n" +
"}");
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void benchMarkAstPrinterThroughput(Blackhole blackhole) {
printAst(blackhole);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public void benchMarkAstPrinterAvgTime(Blackhole blackhole) {
printAst(blackhole);
}
public static void printAst(Blackhole blackhole) {
blackhole.consume(AstPrinter.printAst(document));
}
}
|
package br.com.datapoa;
import java.io.IOException;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.gson.Gson;
import br.com.datapoa.entities.DataEntity;
import br.com.datapoa.entities.DataPackages;
import br.com.datapoa.resources.DataResource;
import br.com.datapoa.resources.DataResourceBuilder;
@RunWith(MockitoJUnitRunner.class)
public class DataClientTest extends TestCase{
String resourceId = "03b349a2-22bd-4de3-9df4-839c2c42d969";
Integer limit = 5;
@Test
public void testGivenRealResourceWhenRequestItShouldReturnDataEntity() throws IOException
{
//given
DataResourceBuilder builder = new DataResourceBuilder().resource(resourceId);
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
DataEntity result = dpClient.doRequest();
// then
assertNotNull(result);
assertNotNull(result.getResult());
assertNotNull(result.getResult().getFields());
assertNotNull(result.getResult().getRecords());
assertNotNull(result.getResult().getLinks());
}
@Test
public void testGivenPackageActionItShouldReturnDataPackages() throws IOException
{
//given
String packageRequestAction = DataPoaCommon.getProvider().getPackageListAction();
DataResourceBuilder builder = new DataResourceBuilder().action(packageRequestAction);
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
DataPackages result = dpClient.doRequest(DataPackages.class);
// then
assertNotNull(result);
assertEquals(true, result.isSuccess());
assertEquals(false, result.hasError());
assertNotNull(result.getResult());
}
@Test
public void testGivenGroupListActionItShouldReturnDataPackages() throws IOException
{
//given
String groupListAction = DataPoaCommon.getProvider().getGroupListAction();
DataResourceBuilder builder = new DataResourceBuilder().action(groupListAction);
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
Gson result = dpClient.doRequest(Gson.class);
// then
assertNotNull(result);
}
@Test
public void testGivenCustomizedClassResultWhenRequestItShouldReturnCustomizedEntity() throws IOException
{
//given
DataResourceBuilder builder = new DataResourceBuilder().resource(resourceId);
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
StubCustomizedResultEntity result = dpClient.doRequest(StubCustomizedResultEntity.class);
// then
assertNotNull(result);
assertTrue(result.isCustomized());
// and also
assertNotNull(result.getResult());
assertNotNull(result.getResult().getFields());
assertNotNull(result.getResult().getRecords());
assertNotNull(result.getResult().getLinks());
}
@Test
public void testGivenFilterResultWhenRequestItShouldReturnDataPoaEntity() throws IOException
{
//given
DataResourceBuilder builder = new DataResourceBuilder().resource(resourceId).filter("test filter");
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
DataEntity result = dpClient.doRequest();
// then
assertNotNull(result);
assertNotNull(result.getResult());
}
@Test(expected = IOException.class)
public void testGivenInvalidRealResourceWhenRequestItShouldRaiseError() throws IOException
{
//given
DataResourceBuilder builder = new DataResourceBuilder().resource("INVALIDRESOURCE");
DataResource dpResource = builder.build();
DataClient dpClient = new DataClient(dpResource);
// when
dpClient.doRequest();
// then raise IOException
}
class StubCustomizedResultEntity extends DataEntity{
public boolean isCustomized()
{
return true;
}
}
}
|
package com.cleeng.api;
import com.cleeng.api.domain.*;
import com.cleeng.api.domain.async.*;
import org.junit.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
@SuppressWarnings("unchecked")
public class CleengImplTest {
private String publisherToken = "IEiuf3fJzAorVvxgBYiHiHXGk8oFPckTMSOn8hS1--lOti30";
private String customerToken = "H1vV9WyS18ETxUTuItOnoCcukoQFfyF_DWaBDw9nU3JRvIYm";
private Cleeng api;
private double sleepRatio = 1;
@Before
public void setUp() throws MalformedURLException {
this.api = CleengFactory.createSandboxApi(publisherToken);
}
@After
public void tearDown() {
this.api = null;
}
@Test
public void testCreateSubscriptionOffer() throws IOException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final OfferResponse response = this.api.createSubscriptionOffer( offerData );
assertNotNull(response);
assertNotNull(response.result.accessToTags);
assertEquals("offer title should equal", offerData.title, response.result.title);
}
@Test
public void updateSubscriptionOffer() throws IOException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title updated",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final OfferResponse response = this.api.updateSubscriptionOffer(offerData, "S222742070_PL");
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
}
@Test
public void testCreateSubscriptionOfferAsync() throws IOException, InterruptedException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final SubscriptionOfferData offerData2 = new SubscriptionOfferData(12.34,
"week",
"title",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final AsyncRequestCallback<OfferResponse> callback = new AsyncRequestCallback<OfferResponse>(OfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(offerData, callback));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
requests.add(new AsyncRequest(offerData2, new AsyncRequestCallback<OfferResponse>(OfferResponse.class)));
this.api.createSubscriptionOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final OfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Average rating should match", 4, response.result.averageRating);
}
@Test
public void testUpdateSubscriptionOfferAsync() throws IOException, InterruptedException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title updated",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final AsyncRequestCallback<OfferResponse> callback = new AsyncRequestCallback<OfferResponse>(OfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateOfferRequest(offerData, callback, "S222742070_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class), "S222742070_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<OfferResponse>(OfferResponse.class), "S222742070_PL"));
this.api.updateSubscriptionOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final OfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Average rating should match", offerData.title, response.result.title);
}
@Test
public void testCreateSingleOffer() throws IOException {
final SingleOfferData offerData = new SingleOfferData(12.34,
"title",
"http:
"description",
null,
"7777",
"778",
"8787",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final SingleOfferResponse response = this.api.createSingleOffer(offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("videoId should match", offerData.videoId, response.result.videoId);
}
@Test
public void testUpdateSingleOffer() throws IOException {
final SingleOfferData offerData = new SingleOfferData(12.34,
"title updated",
"http:
"description",
null,
"videoIdUpdated",
"778",
"8787",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final SingleOfferResponse response = this.api.updateSingleOffer("A127679757_PL", offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("videoId should match", offerData.videoId, response.result.videoId);
}
@Test
public void testCreateSingleOfferAsync() throws IOException, InterruptedException {
final SingleOfferData offerData = new SingleOfferData(12.34,
"title",
"http:
"description",
null,
"7777",
"778",
"8787",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final AsyncRequestCallback<SingleOfferResponse> callback = new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(offerData, callback));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class)));
this.api.createSingleOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final SingleOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Average rating should match", true, response.result.active);
}
@Test
public void testUpdateSingleOfferAsync() throws IOException, InterruptedException {
final SingleOfferData offerData = new SingleOfferData(12.34,
"new title 2",
"http:
"description",
null,
"7777",
"778",
"8787",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final AsyncRequestCallback<SingleOfferResponse> callback = new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateOfferRequest(offerData, callback, "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<SingleOfferResponse>(SingleOfferResponse.class), "A127679757_PL"));
this.api.updateSingleOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final SingleOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Average rating should match", offerData.title, response.result.title);
}
@Test
public void testCreateEventOffer() throws IOException {
final EventOfferDataRequest offerData = new EventOfferDataRequest(12.34,
"GBP",
"titleval",
"http:
"desc",
"9A",
"90",
"http:
1999999990,
1999999999,
"America/New_York",
null,
"7777",
"2",
"teaser",
true,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final EventOfferResponse response = this.api.createEventOffer(offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("teaser should match", offerData.teaser, response.result.teaser);
}
@Test
public void testUpdateEventOffer() throws IOException {
final EventOfferDataRequest offerData = new EventOfferDataRequest(12.34,
"GBP",
"titleval updated",
"http:
"desc",
"9A",
"90",
"http:
1999999990,
1999999999,
"America/New_York",
null,
"7777",
"2",
"teaser updated",
true,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final EventOfferResponse response = this.api.updateEventOffer(offerData, "E575167459_PL");
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("teaser should match", offerData.teaser, response.result.teaser);
}
@Test
public void testCreateEventOfferAsync() throws IOException, InterruptedException {
final EventOfferDataRequest offerData = new EventOfferDataRequest(12.34,
"GBP",
"titleval",
"http:
"desc",
"9A",
"90",
"http:
1999999990,
1999999999,
"America/New_York",
null,
"7777",
"2",
"teaser",
true,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final AsyncRequestCallback<EventOfferResponse> callback = new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(offerData, callback));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class)));
this.api.createEventOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final EventOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", true, response.result.active);
}
@Test
public void testUpdateEventOfferAsync() throws IOException, InterruptedException {
final EventOfferDataRequest offerData = new EventOfferDataRequest(12.34,
"GBP",
"titleval updated",
"http:
"desc",
"9A",
"90",
"http:
1999999990,
1999999999,
"America/New_York",
null,
"7777",
"2",
"teaser",
true,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final AsyncRequestCallback<EventOfferResponse> callback = new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateOfferRequest(offerData, callback, "E575167459_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class), "E575167459_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class), "E575167459_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class), "E575167459_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class), "E575167459_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<EventOfferResponse>(EventOfferResponse.class), "E575167459_PL"));
this.api.updateEventOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final EventOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", offerData.title, response.result.title);
}
@Test
public void testCreateRentalOffer() throws IOException {
final RentalOfferData offerData = new RentalOfferData(12.34,
"title",
48,
"http:
"description",
null,
"7777",
"2",
"some text",
Arrays.asList("Sport", "Entertainment")
);
final RentalOfferResponse response = this.api.createRentalOffer(offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("period should match", offerData.period, response.result.period);
}
@Test
public void testCreateRentalOfferAsync() throws IOException, InterruptedException {
final RentalOfferData offerData = new RentalOfferData(12.34,
"title",
48,
"http:
"description",
null,
"7777",
"2",
"some text",
Arrays.asList("Sport", "Entertainment")
);
final AsyncRequestCallback<RentalOfferResponse> callback = new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(offerData, callback));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class)));
this.api.createRentalOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final RentalOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", true, response.result.active);
}
@Test
public void testUpdateRentalOffer() throws IOException {
final RentalOfferData offerData = new RentalOfferData(12.34,
"title updated",
24,
"http:
"description updated",
null,
"7777",
"3",
"some text 2",
Arrays.asList("Sport", "Entertainment")
);
final RentalOfferResponse response = this.api.updateRentalOffer(offerData, "R802832039_PL");
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("period should match", offerData.period, response.result.period);
}
@Test
public void testUpdateRentalOfferAsync() throws IOException, InterruptedException {
final RentalOfferData offerData = new RentalOfferData(12.34,
"title updated",
24,
"http:
"description updated",
null,
"7777",
"2",
"some text",
Arrays.asList("Sport", "Entertainment")
);
final AsyncRequestCallback<RentalOfferResponse> callback = new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateOfferRequest(offerData, callback, "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<RentalOfferResponse>(RentalOfferResponse.class), "R802832039_PL"));
this.api.updateRentalOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final RentalOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", offerData.title, response.result.title);
}
@Test
public void testCreatePassOffer() throws IOException {
final PassOfferData offerData = new PassOfferData(12.34,
null,
1900000000,
"title",
"http:
null,
"description",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final PassOfferResponse response = this.api.createPassOffer(offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.title);
assertEquals("period should match", offerData.expiresAt, response.result.expiresAt);
}
@Test
public void testUpdatePassOffer() throws IOException {
final PassOfferData offerData = new PassOfferData(12.34,
null,
1900000001,
"title",
"http:
null,
"description",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final OfferResponse response = this.api.updatePassOffer(offerData, "P808240899_PL");
assertNotNull(response);
assertEquals("offer title should equal", offerData.url, response.result.url);
assertEquals("period should match", offerData.expiresAt, response.result.expiresAt);
}
@Test
public void testCreatePassOfferAsync() throws IOException, InterruptedException {
final PassOfferData offerData = new PassOfferData(12.34,
null,
1900000000,
"title",
"http:
null,
"description",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final AsyncRequestCallback<PassOfferResponse> callback = new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(offerData, callback));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
requests.add(new AsyncRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class)));
this.api.createPassOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final PassOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", true, response.result.active);
}
@Test
public void testUpdatePassOfferAsync() throws IOException, InterruptedException {
final PassOfferData offerData = new PassOfferData(12.34,
null,
1900000000,
"title 2",
"http:
null,
"description",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final AsyncRequestCallback<PassOfferResponse> callback = new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateOfferRequest(offerData, callback, "P808240899_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class), "P808240899_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class), "P808240899_PL"));
requests.add(new AsyncUpdateOfferRequest(offerData, new AsyncRequestCallback<PassOfferResponse>(PassOfferResponse.class), "P808240899_PL"));
this.api.updatePassOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final PassOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("Active should match", offerData.title, response.result.title);
}
@Test
public void testCreatePassOfferError() throws IOException {
final PassOfferData offerData = new PassOfferData(12.34,
"month",
1900000000,
"title",
"http:
null,
"description",
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL","DE")
);
final PassOfferResponse response = this.api.createPassOffer(offerData);
assertNotNull(response);
assertNull(response.result);
assertNotNull(response.error);
assertEquals("error code should match ", 8, response.error.code);
}
@Test
public void testListSubscriptionOffers() throws IOException {
final Criteria criteria = new Criteria(true);
final ListSubscriptionOffersResponse response = this.api.listSubscriptionOffers(criteria, 0, 10);
assertNotNull(response);
assertEquals("list length should match", 10, response.result.items.size());
}
@Test
public void testListSubscriptionOffersAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<ListSubscriptionOffersResponse> callback = new AsyncRequestCallback<ListSubscriptionOffersResponse>(ListSubscriptionOffersResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncListRequest(new Criteria(true), callback, 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSubscriptionOffersResponse>(ListSubscriptionOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSubscriptionOffersResponse>(ListSubscriptionOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSubscriptionOffersResponse>(ListSubscriptionOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSubscriptionOffersResponse>(ListSubscriptionOffersResponse.class), 0, 10));
this.api.listSubscriptionOffersAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final ListSubscriptionOffersResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.items.size() > 0);
}
@Test
public void testListSingleOffers() throws IOException {
final Criteria criteria = new Criteria(true);
final ListSingleOffersResponse response = this.api.listSingleOffers(criteria, 0, 10);
assertNotNull(response);
assertEquals("list length should match", 10, response.result.items.size());
}
@Test
public void testListSingleOffersAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<ListSingleOffersResponse> callback = new AsyncRequestCallback<ListSingleOffersResponse>(ListSingleOffersResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncListRequest(new Criteria(true), callback, 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSingleOffersResponse>(ListSingleOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSingleOffersResponse>(ListSingleOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSingleOffersResponse>(ListSingleOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListSingleOffersResponse>(ListSingleOffersResponse.class), 0, 10));
this.api.listSingleOffersAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final ListSingleOffersResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.items.size() > 0);
}
@Test
public void testListVodOffers() throws IOException {
final Criteria criteria = new Criteria(true);
final ListVodOffersResponse response = this.api.listVodOffers(criteria, 0, 10);
assertNotNull(response);
assertEquals("list length should match", 10, response.result.items.size());
}
@Test
public void testListVodOffersAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<ListVodOffersResponse> callback = new AsyncRequestCallback<ListVodOffersResponse>(ListVodOffersResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncListRequest(new Criteria(true), callback, 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListVodOffersResponse>(ListVodOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListVodOffersResponse>(ListVodOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListVodOffersResponse>(ListVodOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListVodOffersResponse>(ListVodOffersResponse.class), 0, 10));
this.api.listVodOffersAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final ListVodOffersResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.items.size() > 0);
}
@Test
public void testListPassOffers() throws IOException {
final Criteria criteria = new Criteria(true);
final ListPassOffersResponse response = this.api.listPassOffers(criteria, 0, 10);
assertNotNull(response);
assertEquals("list length should match", 10, response.result.items.size());
}
@Test
public void testListPassOffersAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<ListPassOffersResponse> callback = new AsyncRequestCallback<ListPassOffersResponse>(ListPassOffersResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncListRequest(new Criteria(true), callback, 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListPassOffersResponse>(ListPassOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListPassOffersResponse>(ListPassOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListPassOffersResponse>(ListPassOffersResponse.class), 0, 10));
requests.add(new AsyncListRequest(new Criteria(true), new AsyncRequestCallback<ListPassOffersResponse>(ListPassOffersResponse.class), 0, 10));
this.api.listPassOffersAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final ListPassOffersResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.items.size() > 0);
}
@Test
public void testPrepareRemoteAuth() throws IOException {
final CustomerData customerData = new CustomerData("johndoe@gmail.com", "en_US", "GBP", "PL");
final FlowDescription flowDescription = new FlowDescription("8", "http:
final PrepareRemoteAuthResponse response = this.api.prepareRemoteAuth(customerData, flowDescription);
assertNotNull(response);
assertTrue(response.result.url.length() > 0);
}
@Test
public void testPrepareRemoteAuthAsync() throws IOException, InterruptedException {
final CustomerData customerData = new CustomerData("johndoe@gmail.com", "en_US", "GBP", "PL");
final FlowDescription flowDescription = new FlowDescription("8", "http:
final AsyncRequestCallback<PrepareRemoteAuthResponse> callback = new AsyncRequestCallback<PrepareRemoteAuthResponse>(PrepareRemoteAuthResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncPrepareRemoteAuthRequest(customerData, flowDescription, callback));
this.api.prepareRemoteAuthAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
final PrepareRemoteAuthResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.url.length() > 0);
}
@Test
public void testGenerateCustomerToken() throws IOException {
final TokenResponse response = this.api.generateCustomerToken("testjohndoe2@gmail.com");
assertNotNull(response);
assertNull(response.error);
assertNotNull(response.result.token);
}
@Test
public void testGenerateCustomerTokenAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<TokenResponse> callback = new AsyncRequestCallback<TokenResponse>(TokenResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncTokenRequest(callback, "testjohndoe2@gmail.com"));
final List<String> tokens = new ArrayList<String>();
final int count = 100;
for (int i = 0; i < count; i++) {
requests.add(new AsyncTokenRequest(new AsyncRequestCallback<TokenResponse>(TokenResponse.class), "testjohndoe2@gmail.com"));
}
this.api.generateCustomerTokenAsync(requests);
TimeUnit.MILLISECONDS.sleep(this.getSleepTime(requests.size()));
for (int j = 0; j < requests.size(); j++) {
tokens.add(((AsyncRequestCallback<TokenResponse>) requests.get(j).callback).getResponse().result.token);
}
assertEquals("Tokens array should match", 101, tokens.size());
}
@Test
@Ignore
public void testUpdateCustomerPassword() throws IOException {
final String customerEmail = "user@gmail.com";
final String resetPasswordToken = "161b51af14ddf305cf2ee2d24b8617f3d24da45e";
final String newPassword = "newpass2001";
final BooleanResponse response = this.api.updateCustomerPassword(customerEmail, resetPasswordToken, newPassword);
assertNotNull(response);
assertNull(response.error);
assertTrue(response.result.success);
}
@Test
@Ignore
public void testUpdateCustomerPasswordAsync() throws IOException, InterruptedException {
final String customerEmail = "testjohndoe2@gmail.com";
//Provide valid reset token
final String resetPasswordToken = "161b51af14ddf305cf2ee2d24b8617f3d24da45e";
final String newPassword = "newpass2002";
final AsyncRequestCallback<BooleanResponse> callback = new AsyncRequestCallback<BooleanResponse>(BooleanResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(new ResetPasswordParams(customerEmail, resetPasswordToken, newPassword), callback));
this.api.updateCustomerPasswordAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final BooleanResponse response = callback.getResponse();
assertTrue(response.result.success);
}
@Test
public void testUpdateCustomerEmail() throws IOException, InterruptedException {
final BooleanResponse syncResponse = this.api.updateCustomerEmail("john2000doe@domain.com", "john2002doe@domain.com");
assertNotNull(syncResponse);
assertNull(syncResponse.error);
assertTrue(syncResponse.result.success);
final AsyncRequestCallback<BooleanResponse> callback = new AsyncRequestCallback<BooleanResponse>(BooleanResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(new UpdateCustomerEmailParams("john2002doe@domain.com", "john2000doe@domain.com"), callback));
this.api.updateCustomerEmailAsync(requests);
TimeUnit.SECONDS.sleep(5);
final BooleanResponse response = callback.getResponse();
assertTrue(response.result.success);
}
@Test
public void testGenerateCheckoutUrlForSubscription() throws IOException {
final UrlResponse response = this.api.generateCheckoutUrl("john2001doe@domain.com", new FlowDescription("S972283213_PL", "http:
assertNotNull("Response object should not be null", response);
assertTrue("Response url should have lenght > 0", response.result.url.length() > 0);
}
@Test
public void testUpdateCustomerSubscription() throws IOException, InterruptedException {
String offerId = "S972283213_PL";
String customerEmail = "john2001doe@domain.com";
UpdateCustomerSubscriptionOfferData offerData = new UpdateCustomerSubscriptionOfferData("cancelled", "1717356800");
final UpdateCustomerSubscriptionResponse response = this.api.updateCustomerSubscription(offerId, customerEmail, offerData);
Assert.assertNotNull(response);
Assert.assertEquals("Response status should be cancelled", "cancelled", response.result.status);
}
@Test
public void testUpdateCustomerSubscriptionAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<UpdateCustomerSubscriptionResponse> callback = new AsyncRequestCallback<UpdateCustomerSubscriptionResponse>(UpdateCustomerSubscriptionResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(new UpdateCustomerSubscriptionParams("john2001doe@domain.com", "S972283213_PL", new UpdateCustomerSubscriptionOfferData("cancelled", "1717356800")), callback));
this.api.updateCustomerSubscriptionAsync(requests);
TimeUnit.SECONDS.sleep(5);
final UpdateCustomerSubscriptionResponse response = callback.getResponse();
Assert.assertNotNull(response);
Assert.assertEquals("Response status should be cancelled", "cancelled", response.result.status);
}
@Test
public void testRequestPasswordReset() throws IOException {
final BooleanResponse response = this.api.requestPasswordReset("testjohndoe2@gmail.com");
assertNotNull(response);
assertNull(response.error);
assertTrue(response.result.success);
}
@Test
public void testRequestPasswordResetAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<BooleanResponse> callback = new AsyncRequestCallback<BooleanResponse>(BooleanResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncTokenRequest(callback, "testjohndoe2@gmail.com"));
this.api.requestPasswordResetAsync(requests);
TimeUnit.MILLISECONDS.sleep(2000);
final BooleanResponse response = callback.getResponse();
assertTrue(response.result.success);
}
@Test
public void testGenerateCustomerTokenFromPassword() throws IOException {
final TokenResponse response = this.api.generateCustomerTokenFromPassword("john2000doepass", "john2000doe@domain.com");
assertNotNull(response);
assertNull(response.error);
assertNotNull(response.result.token);
}
@Test
public void testGenerateCustomerTokenFromPasswordAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<TokenResponse> callback = new AsyncRequestCallback<TokenResponse>(TokenResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncGenerateCustomerTokenFromPasswordRequest(this.publisherToken, "john2000doepass", "john2000doe@domain.com", callback));
requests.add(new AsyncGenerateCustomerTokenFromPasswordRequest(this.publisherToken, "john2000doepass", "john2000doe@domain.com", new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
requests.add(new AsyncGenerateCustomerTokenFromPasswordRequest(this.publisherToken, "john2000doepass", "john2000doe@domain.com", new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
requests.add(new AsyncGenerateCustomerTokenFromPasswordRequest(this.publisherToken, "john2000doepass", "john2000doe@domain.com", new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
requests.add(new AsyncGenerateCustomerTokenFromPasswordRequest(this.publisherToken, "john2000doepass", "john2000doe@domain.com", new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
this.api.generateCustomerTokenFromPasswordAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final TokenResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("Token should be present in response object", response.result.token.length() > 0);
}
@Test
public void testGenerateCustomerTokenFromFacebook() throws IOException {
final TokenResponse response = this.api.generateCustomerTokenFromFacebook("john2001doe");
assertNotNull(response);
assertNull(response.error);
assertNotNull(response.result.token);
}
@Test
public void testGenerateCustomerTokenFromFacebookAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<TokenResponse> callback = new AsyncRequestCallback<TokenResponse>(TokenResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncTokenRequest(callback, "john2001doe"));
requests.add(new AsyncTokenRequest(new AsyncRequestCallback<TokenResponse>(TokenResponse.class), "john2001doe"));
requests.add(new AsyncTokenRequest(new AsyncRequestCallback<TokenResponse>(TokenResponse.class), "john2001doe"));
requests.add(new AsyncTokenRequest(new AsyncRequestCallback<TokenResponse>(TokenResponse.class), "john2001doe"));
requests.add(new AsyncTokenRequest(new AsyncRequestCallback<TokenResponse>(TokenResponse.class), "john2001doe"));
this.api.generateCustomerTokenFromFacebookAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final TokenResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("Token should be present in response object", response.result.token.length() > 0);
}
@Test
public void testGetAccessStatus() throws IOException {
final GetAccessStatusResponse response = this.api.getAccessStatus(this.customerToken, "A334745341_PL", "78.129.213.71");
assertNotNull(response.result);
assertEquals("Access granted should match", true, response.result.accessGranted);
assertEquals("ExpiresAt should match", 1519237275, response.result.expiresAt);
assertEquals("PurchasedDirectly should match", false, response.result.purchasedDirectly);
}
@Test
public void testGetAccessStatusAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<GetAccessStatusResponse> callback = new AsyncRequestCallback<GetAccessStatusResponse>(GetAccessStatusResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncGetAccessStatusRequest(this.customerToken, "A334745341_PL", "78.129.213.71", callback));
requests.add(new AsyncGetAccessStatusRequest(this.customerToken, "A334745341_PL", "78.129.213.71", new AsyncRequestCallback<GetAccessStatusResponse>(GetAccessStatusResponse.class)));
this.api.getAccessStatusAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final GetAccessStatusResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("Access should be granted", response.result.accessGranted);
}
@Test
public void testGetAccessibleTags() throws IOException {
final GetAccessibleTagsResponse response = this.api.getAccessibleTags(this.publisherToken, this.customerToken);
assertNotNull(response.result);
assertNotNull(response.result.tags);
}
@Test
public void testGetAccessibleTagsAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<GetAccessibleTagsResponse> callback = new AsyncRequestCallback<GetAccessibleTagsResponse>(GetAccessibleTagsResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncGetAccessibleTagsRequest(this.publisherToken, this.customerToken, callback));
requests.add(new AsyncGetAccessibleTagsRequest(this.publisherToken, this.customerToken, new AsyncRequestCallback<GetAccessibleTagsResponse>(GetAccessibleTagsResponse.class)));
requests.add(new AsyncGetAccessibleTagsRequest(this.publisherToken, this.customerToken, new AsyncRequestCallback<GetAccessibleTagsResponse>(GetAccessibleTagsResponse.class)));
this.api.getAccessibleTagsAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final GetAccessibleTagsResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("List should contain items", response.result.tags.size() > 0);
}
@Test
public void testGetCustomer() throws IOException {
final GetCustomerResponse response = this.api.getCustomer(this.customerToken);
assertNotNull(response.result);
}
@Test
public void testGetCustomerAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<GetCustomerResponse> callback = new AsyncRequestCallback<GetCustomerResponse>(GetCustomerResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(this.customerToken, callback));
requests.add(new AsyncRequest(this.customerToken, new AsyncRequestCallback<GetCustomerResponse>(GetCustomerResponse.class)));
requests.add(new AsyncRequest(this.customerToken, new AsyncRequestCallback<GetCustomerResponse>(GetCustomerResponse.class)));
this.api.getCustomerAsync(requests);
long sleepTime = getSleepTime(requests.size());
TimeUnit.MILLISECONDS.sleep(sleepTime);
final GetCustomerResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("List should contain items", "PL", response.result.country);
}
@Test
public void testCreateVodOffer() throws IOException {
final VodOfferData offerData = new VodOfferData(12.34,
"some title",
"http:
"description",
null,
"iuyiu",
"playerC",
"playerCodeH",
"7",
"7",
"hd",
null,
Arrays.asList("Sport"),
Arrays.asList("PL", "DE"),
false,
"whitelist",
"http:
);
final VodOfferResponse response = this.api.createVodOffer(offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.vod.title);
}
@Test
public void testCreateVodOfferAsync() throws IOException, InterruptedException {
final VodOfferData offerData = new VodOfferData(12.34,
"some title",
"http:
"description",
null,
"vidoeId",
"playerC",
"playerCodeH",
"7",
"7",
"hd",
null,
Arrays.asList("Sport"),
Arrays.asList("PL", "DE"),
false,
"whitelist",
"http:
);
final AsyncRequestCallback<VodOfferResponse> callback = new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncCreateVodOfferRequest(this.publisherToken, offerData, callback));
requests.add(new AsyncCreateVodOfferRequest(this.publisherToken, offerData, new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class)));
requests.add(new AsyncCreateVodOfferRequest(this.publisherToken, offerData, new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class)));
this.api.createVodOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final VodOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("List should contain items", offerData.title, response.result.vod.title);
}
@Test
public void testGetVodOffer() throws IOException {
final VodOfferResponse response = this.api.getVodOffer("R262528011_PL");
assertNotNull(response);
assertEquals("offer title should equal", "hd", response.result.vod.videoQuality);
}
@Test
public void testGetVodOfferAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<VodOfferResponse> callback = new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncGetVodOfferRequest(this.publisherToken, "R262528011_PL", callback));
requests.add(new AsyncGetVodOfferRequest(this.publisherToken, "R262528011_PL", new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class)));
requests.add(new AsyncGetVodOfferRequest(this.publisherToken, "R262528011_PL", new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class)));
this.api.getVodOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final VodOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("List should contain items", "hd", response.result.vod.videoQuality);
}
@Test
public void testUpdateVodOffer() throws IOException {
final VodOfferData offerData = new VodOfferData(12.34,
"some updated title",
"http:
"description",
null,
"videoId",
"playerCode",
"playerCodeHead",
"7",
"7",
"hd",
null,
Arrays.asList("Sport"),
Arrays.asList("PL", "DE"),
false,
"whitelist",
"http:
);
final VodOfferResponse response = this.api.updateVodOffer("R262528011_PL", offerData);
assertNotNull(response);
assertEquals("offer title should equal", offerData.title, response.result.vod.title);
}
@Test
public void testUpdateVodOfferAsync() throws IOException, InterruptedException {
final VodOfferData offerData = new VodOfferData(12.34,
"some title",
"http:
"description",
null,
"videoIdUpdated",
"playerC",
"playerCodeH",
"7",
"7",
"hd",
null,
Arrays.asList("Sport"),
Arrays.asList("PL", "DE"),
false,
"whitelist",
"http:
);
final AsyncRequestCallback<VodOfferResponse> callback = new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncUpdateVodOfferRequest(this.publisherToken, offerData, callback, "R262528011_PL"));
requests.add(new AsyncUpdateVodOfferRequest(this.publisherToken, offerData, new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class), "R262528011_PL"));
requests.add(new AsyncUpdateVodOfferRequest(this.publisherToken, offerData, new AsyncRequestCallback<VodOfferResponse>(VodOfferResponse.class), "R262528011_PL"));
this.api.updateVodOfferAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final VodOfferResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertEquals("List should contain items", offerData.videoId, response.result.vod.videoId);
}
@Test
public void testGenerateCheckoutUrl() throws IOException {
final UrlResponse response = this.api.generateCheckoutUrl("testjohndoe2@gmail.com", new FlowDescription("A962575346_PL", "http:
assertNotNull("Response object should not be null", response);
assertTrue("Response url should have lenght > 0", response.result.url.length() > 0);
}
@Test
public void testGenerateCheckoutUrlAsync() throws IOException, InterruptedException {
final AsyncRequestCallback<UrlResponse> callback = new AsyncRequestCallback<UrlResponse>(UrlResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncGenerateCheckoutUrlRequest(this.publisherToken, "testjohndoe2@gmail.com", new FlowDescription("A962575346_PL", "http:
requests.add(new AsyncGenerateCheckoutUrlRequest(this.publisherToken, "testjohndoe2@gmail.com", new FlowDescription("A962575346_PL", "http:
requests.add(new AsyncGenerateCheckoutUrlRequest(this.publisherToken, "testjohndoe2@gmail.com", new FlowDescription("A962575346_PL", "http:
this.api.generateCheckoutUrlAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final UrlResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("Response url should have lenght > 0", response.result.url.length() > 0);
}
@Test
public void testRegisterCustomer() throws IOException {
final UUID uuid = UUID.randomUUID();
final CustomerData customerData = new CustomerData(uuid.toString() + "@domain.com", "en_US", "GBP", "PL", "xxxxxxxxxxxxx");
final TokenResponse response = this.api.registerCustomer(customerData);
this.customerToken = response.result.token;
assertNotNull(response);
assertTrue(response.result.token.length() > 0);
}
@Test
@Ignore
public void testRegisterMyCustomer() throws IOException {
final CustomerData customerData = new CustomerData("user@gmail.com", "en_US", "GBP", "PL", "mycleengpassword", "mycleengussr");
final TokenResponse response = this.api.registerCustomer(customerData);
assertNotNull(response);
assertTrue(response.result.token.length() > 0);
}
@Test
public void testRegisterCustomerAsync() throws IOException, InterruptedException {
final UUID uuid1 = UUID.randomUUID();
final CustomerData input1 = new CustomerData(uuid1.toString() + "@domain.com", "en_US", "GBP", "PL", "xxxxxxxxxxxxx");
final UUID uuid2 = UUID.randomUUID();
final CustomerData input2 = new CustomerData(uuid2.toString() + "@domain.com", "en_US", "GBP", "PL", "xxxxxxxxxxxxx");
final UUID uuid3 = UUID.randomUUID();
final CustomerData input3 = new CustomerData(uuid3.toString() + "@domain.com", "en_US", "GBP", "PL", "xxxxxxxxxxxxx");
final AsyncRequestCallback<TokenResponse> callback = new AsyncRequestCallback<TokenResponse>(TokenResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(input1, callback));
requests.add(new AsyncRequest(input2, new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
requests.add(new AsyncRequest(input3, new AsyncRequestCallback<TokenResponse>(TokenResponse.class)));
this.api.registerCustomerAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final TokenResponse response = callback.getResponse();
assertNotNull("Response object should not be null", response);
assertTrue("Response token should have lenght > 0", response.result.token.length() > 0);
}
@Test
public void testGenerateMyAccountUrl() throws IOException {
final String customerEmail = "testjohndoe2@gmail.com";
final List<String> modules = new ArrayList<String>();
final UrlResponse response = this.api.generateMyAccountUrl(customerEmail, modules);
assertNotNull(response);
assertTrue(response.result.url.length() > 0);
}
@Test
public void testGenerateMyAccountUrlAsync() throws IOException, InterruptedException {
final List<String> modules = new ArrayList<String>();
final GenerateMyAccountUrlParams input = new GenerateMyAccountUrlParams("testjohndoe2@gmail.com", modules);
final AsyncRequestCallback<UrlResponse> callback = new AsyncRequestCallback<UrlResponse>(UrlResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(input, callback));
this.api.generateMyAccountUrlAsync(requests);
TimeUnit.MILLISECONDS.sleep(getSleepTime(requests.size()));
final UrlResponse response = callback.getResponse();
assertNotNull(response);
assertTrue(response.result.url.length() > 0);
}
@Test
@Ignore
public void testListOfferIdsByVideoId() throws IOException {
final ListOfferIdsByVideoIdResponse response = this.api.listOfferIdsByVideoId("7777");
assertNotNull(response);
assertTrue(response.result.offerIds.size() > 0);
}
@Test
@Ignore
public void testListOfferIdsByVideoIdAsync() throws IOException, InterruptedException {
final VideoIdParams input = new VideoIdParams("7777");
final AsyncRequestCallback<ListOfferIdsByVideoIdResponse> callback = new AsyncRequestCallback<ListOfferIdsByVideoIdResponse>(ListOfferIdsByVideoIdResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(input, callback));
this.api.listOfferIdsByVideoIdAsync(requests);
TimeUnit.MILLISECONDS.sleep(16000);
final ListOfferIdsByVideoIdResponse response = callback.getResponse();
assertNotNull(response);
assertTrue(response.result.offerIds.size() > 0);
}
@Test
public void testGetAccessStatusForDevice() throws IOException {
final GetAccessStatusForDeviceResponse response = this.api.getAccessStatusForDevice(this.customerToken, "S222742070_PL", "1", "roku");
assertNotNull(response);
assertTrue(response.result.accessGranted);
}
@Test
public void testGetAccessStatusForDeviceAsync() throws IOException, InterruptedException {
final GetAccessStatusForDeviceParams params = new GetAccessStatusForDeviceParams(this.customerToken, "S222742070_PL", "1", "roku");
final GetAccessStatusForDeviceParams params2 = new GetAccessStatusForDeviceParams(this.customerToken, "S222742070_PL", "1", "roku");
final AsyncRequestCallback<GetAccessStatusForDeviceResponse> callback = new AsyncRequestCallback<GetAccessStatusForDeviceResponse>(GetAccessStatusForDeviceResponse.class);
final AsyncRequestCallback<GetAccessStatusForDeviceResponse> callback2 = new AsyncRequestCallback<GetAccessStatusForDeviceResponse>(GetAccessStatusForDeviceResponse.class);
final List<AsyncRequest> requests = new ArrayList<AsyncRequest>();
requests.add(new AsyncRequest(params, callback));
requests.add(new AsyncRequest(params2, callback2));
this.api.getAccessStatusForDeviceAsync(requests);
TimeUnit.SECONDS.sleep(10);
final GetAccessStatusForDeviceResponse response = callback.getResponse();
final GetAccessStatusForDeviceResponse response2 = callback2.getResponse();
assertNotNull(response);
assertNotNull(response2);
assertTrue(response.result.accessGranted);
assertTrue(response2.result.accessGranted);
}
@Test
public void testInvokeBatchAsync() throws IOException, InterruptedException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final OfferRequest createOffer = new OfferRequest("createSubscriptionOffer", OfferParams.create(this.publisherToken, offerData));
final ListRequest listOffers = new ListRequest("listSubscriptionOffers", ListParams.create(this.publisherToken, new Criteria(true), 0, 10));
final BatchAsyncRequest batch = new BatchAsyncRequest();
batch.addRequest(createOffer);
batch.addRequest(listOffers);
this.api.invokeBatchAsync(batch);
TimeUnit.SECONDS.sleep(4);
final BatchResponse response = batch.getResponse();
Assert.assertNotNull(response);
Assert.assertEquals("Number of responses should match number of requests in a batch", 2, response.responses.size());
}
@Test
public void testInvokeBatch() throws IOException, InterruptedException {
final SubscriptionOfferData offerData = new SubscriptionOfferData(12.34,
"week",
"title",
"http:
"description",
null,
0,
9,
Arrays.asList("Sport"),
true,
"whitelist",
Arrays.asList("PL", "DE")
);
final OfferRequest createOffer = new OfferRequest("createSubscriptionOffer", OfferParams.create(this.publisherToken, offerData));
final ListRequest listOffers = new ListRequest("listSubscriptionOffers", ListParams.create(this.publisherToken, new Criteria(true), 0, 10));
final BatchRequest batch = new BatchRequest();
batch.addRequest(createOffer);
batch.addRequest(listOffers);
final BatchResponse response = this.api.invokeBatch(batch);
Assert.assertNotNull(response);
Assert.assertEquals("Number of responses should match number of requests in a batch", 2, response.responses.size());
}
private long getSleepTime(int requests) {
double sleepTime = this.sleepRatio * requests * 1000;
return (long) sleepTime;
}
}
|
package com.github.nsnjson;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.*;
import org.junit.*;
public class DriverTest extends AbstractFormatTest {
@Test
public void processTestNull() {
shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation());
}
@Test
public void processTestNumberInt() {
NumericNode value = getNumberInt();
shouldBeConsistencyWhenGivenNumber(value, getNumberIntPresentation(value));
}
@Test
public void processTestNumberLong() {
NumericNode value = getNumberLong();
shouldBeConsistencyWhenGivenNumber(value, getNumberLongPresentation(value));
}
@Test
public void processTestNumberDouble() {
NumericNode value = getNumberDouble();
shouldBeConsistencyWhenGivenNumber(value, getNumberDoublePresentation(value));
}
@Test
public void processTestEmptyString() {
TextNode value = getEmptyString();
shouldBeConsistencyWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestString() {
TextNode value = getString();
shouldBeConsistencyWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestBooleanTrue() {
BooleanNode value = getBooleanTrue();
shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestBooleanFalse() {
BooleanNode value = getBooleanFalse();
shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestEmptyArray() {
shouldBeConsistencyWhenGivenArray(getEmptyArray(), getEmptyArrayPresentation());
}
@Test
public void processTestArray() {
ArrayNode array = getArray();
shouldBeConsistencyWhenGivenArray(array, getArrayPresentation(array));
}
@Test
public void processTestEmptyObject() {
shouldBeConsistencyWhenGivenObject(getEmptyObject(), getEmptyObjectPresentation());
}
@Test
public void processTestObject() {
ObjectNode object = getObject();
shouldBeConsistencyWhenGivenObject(object, getObjectPresentation(object));
}
private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenString(TextNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenBoolean(BooleanNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenArray(ArrayNode array, ObjectNode presentation) {
assertConsistency(array, presentation);
}
private void shouldBeConsistencyWhenGivenObject(ObjectNode object, ObjectNode presentation) {
assertConsistency(object, presentation);
}
private static void assertConsistency(JsonNode value, ObjectNode presentation) {
assertConsistencyByEncoding(value);
assertConsistencyByDecoding(presentation);
}
private static void assertConsistencyByEncoding(JsonNode value) {
Assert.assertEquals(value, Driver.decode(Driver.encode(value)));
}
private static void assertConsistencyByDecoding(ObjectNode presentation) {
Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation)));
}
}
|
package com.qiniu.qbox.testing;
import junit.framework.TestCase;
import com.qiniu.qbox.Config;
import com.qiniu.qbox.auth.CallRet;
import com.qiniu.qbox.auth.DigestAuthClient;
import com.qiniu.qbox.rs.BucketsRet;
import com.qiniu.qbox.rs.DeleteRet;
import com.qiniu.qbox.rs.DropRet;
import com.qiniu.qbox.rs.GetRet;
import com.qiniu.qbox.rs.PublishRet;
import com.qiniu.qbox.rs.PutAuthRet;
import com.qiniu.qbox.rs.PutFileRet;
import com.qiniu.qbox.rs.RSClient;
import com.qiniu.qbox.rs.RSService;
import com.qiniu.qbox.rs.StatRet;
public class RsTest extends TestCase {
public final String DEMO_DOMAIN = "junit-bucket.qiniudn.com" ;
public final String key = "logo.png" ;
public final String expectedHash = "FmDZwqadA4-ib_15hYfQpb7UXUYR" ;
public RSService rs ;
public String bucketName ;
// use fixed buckets
public final String srcBucket = "junit_bucket_src";
public final String destBucket = "junit_bucket_dest";
public void setUp() {
Config.ACCESS_KEY = System.getenv("QINIU_ACCESS_KEY");
Config.SECRET_KEY = System.getenv("QINIU_SECRET_KEY");
Config.UP_HOST = System.getenv("QINIU_UP_HOST") ;
Config.RS_HOST = System.getenv("QINIU_RS_HOST") ;
Config.IO_HOST = System.getenv("QINIU_IO_HOST") ;
bucketName = System.getenv("QINIU_TEST_BUCKET") ;
assertNotNull(Config.ACCESS_KEY) ;
assertNotNull(Config.SECRET_KEY) ;
assertNotNull(Config.UP_HOST) ;
assertNotNull(Config.RS_HOST) ;
assertNotNull(Config.IO_HOST) ;
assertNotNull(bucketName) ;
DigestAuthClient conn = new DigestAuthClient();
rs = new RSService(conn, bucketName) ;
}
public void testPutFile() throws Exception {
String dir = System.getProperty("user.dir") ;
String absFilePath = dir + "/testdata/" + key ;
PutAuthRet putAuthRet = rs.putAuth() ;
String authorizedUrl = putAuthRet.getUrl() ;
@SuppressWarnings("deprecation")
PutFileRet putFileRet = RSClient.putFile(authorizedUrl, bucketName, key, "", absFilePath, "", "") ;
assertTrue(putFileRet.ok() && expectedHash.equals(putFileRet.getHash())) ;
}
public void testRsGet() throws Exception {
GetRet getRet = rs.get(key, key) ;
assertTrue(getRet.ok() && expectedHash.equals(getRet.getHash())) ;
}
public void testRsStat() throws Exception {
StatRet statRet = rs.stat(key) ;
assertTrue(statRet.ok() && expectedHash.equals(statRet.getHash())) ;
}
public void testRsGetIfNotModified() throws Exception {
GetRet getIfNotModifiedRet = rs.getIfNotModified(key, key, expectedHash) ;
assertTrue(getIfNotModifiedRet.ok() && expectedHash.equals(getIfNotModifiedRet.getHash())) ;
}
public void testPublish() throws Exception {
PublishRet publishRet = rs.publish(DEMO_DOMAIN);
assertTrue(publishRet.ok()) ;
}
public void testUnpublish() throws Exception {
PublishRet unpublishRet = rs.unpublish(DEMO_DOMAIN);
assertTrue(unpublishRet.ok()) ;
}
public void testDelete() throws Exception {
DeleteRet deleteRet = rs.delete(key) ;
assertTrue(deleteRet.ok()) ;
}
public void testMkBucket() throws Exception {
String newBucketName = "a-new-bucketname-for-junit-test" ;
CallRet mkBucketRet = rs.mkBucket(newBucketName) ;
assertTrue(mkBucketRet.ok()) ;
}
public void testDropBucket() throws Exception {
String delBucketName = "a-new-bucketname-for-junit-test" ;
DigestAuthClient conn = new DigestAuthClient() ;
RSService rs = new RSService(conn, delBucketName) ;
DropRet dropRet = rs.drop() ;
assertTrue(dropRet.ok()) ;
}
public void testMove() throws Exception {
String srcKey = "src-key-move";
String destKey = "dest-key-move";
String entryUriSrc = srcBucket + ":" + srcKey;
String entryUriDest = destBucket + ":" + destKey;
DigestAuthClient conn = new DigestAuthClient();
rs = new RSService(conn, srcBucket) ;
try {
// upload a file to the source bucket
String dir = System.getProperty("user.dir");
String absFilePath = dir + "/testdata/" + key;
PutAuthRet putAuthRet = rs.putAuth();
String authorizedUrl = putAuthRet.getUrl();
@SuppressWarnings("deprecation")
PutFileRet putFileRet = RSClient.putFile(authorizedUrl, srcBucket,
srcKey, "", absFilePath, "", "");
assertTrue(putFileRet.ok()&& expectedHash.equals(putFileRet.getHash()));
// move
rs = new RSService(conn, srcBucket);
CallRet moveRet = rs.move(entryUriSrc, entryUriDest);
assertTrue(moveRet.ok());
// stat to check the result
// stat the src, should not exist!
rs = new RSService(conn, srcBucket);
StatRet srcStatRet = rs.stat(srcKey);
assertTrue(!srcStatRet.ok());
// stat the dest, should exist!
rs = new RSService(conn, destBucket);
StatRet statRet = rs.stat(destKey);
assertTrue(statRet.ok() && expectedHash.equals(statRet.getHash()));
} finally {
// delete file in the dest bucket
rs = new RSService(conn, destBucket);
DeleteRet destDeleteRet = rs.delete(destKey);
assertTrue(destDeleteRet.ok());
}
}
public void testCopy() throws Exception {
String srcKey = "src-key-copy";
String destKey = "dest-key-copy";
String entryUriSrc = srcBucket + ":" + srcKey;
String entryUriDest = destBucket + ":" + destKey;
DigestAuthClient conn = new DigestAuthClient();
rs = new RSService(conn, srcBucket) ;
try {
// upload a file to the source bucket
String dir = System.getProperty("user.dir");
String absFilePath = dir + "/testdata/" + key;
PutAuthRet putAuthRet = rs.putAuth();
String authorizedUrl = putAuthRet.getUrl();
@SuppressWarnings("deprecation")
PutFileRet putFileRet = RSClient.putFile(authorizedUrl, srcBucket,
srcKey, "", absFilePath, "", "");
assertTrue(putFileRet.ok()&& expectedHash.equals(putFileRet.getHash()));
// copy
rs = new RSService(conn, srcBucket);
CallRet copyRet = rs.copy(entryUriSrc, entryUriDest);
assertTrue(copyRet.ok());
// stat to check the result
// file should exist in the source bucket
rs = new RSService(conn, srcBucket);
StatRet srcStatRet = rs.stat(srcKey);
assertTrue(srcStatRet.ok()&& expectedHash.equals(srcStatRet.getHash()));
// file should exist in the dest bucket
rs = new RSService(conn, destBucket);
StatRet statRet = rs.stat(destKey);
assertTrue(statRet.ok() && expectedHash.equals(statRet.getHash())) ;
} finally {
// delete the file in the source/dest bucket
rs = new RSService(conn, srcBucket);
DeleteRet srcDeleteRet = rs.delete(srcKey);
assertTrue(srcDeleteRet.ok());
rs = new RSService(conn, destBucket);
DeleteRet destDeleteRet = rs.delete(destKey);
assertTrue(destDeleteRet.ok());
}
}
public void testBuckets() throws Exception {
// just test ret.ok().
// it is not a good way to compare wheter the result contains all the
// existing buckets. Because it's a shared account, other users may also
// create or drop bucket at the same time.
BucketsRet ret = rs.buckets();
assertTrue(ret.ok());
}
}
|
package edu.msu.nscl.olog.api;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.msu.nscl.olog.api.OlogClientImpl.OlogClientBuilder;
import static edu.msu.nscl.olog.api.LogBuilder.*;
import static edu.msu.nscl.olog.api.PropertyBuilder.*;
import static edu.msu.nscl.olog.api.TagBuilder.*;
import static edu.msu.nscl.olog.api.LogbookBuilder.*;
public class ErrorIT {
private static LogbookBuilder validLogbook = logbook("Valid Logbook");
private static LogbookBuilder validLogbook2 = logbook("Valid Logbook2");
private static TagBuilder validTag = tag("Valid Tag");
private static PropertyBuilder validProperty = property("Valid Property")
.attribute("Valid Attribute");
private static Log validLog;
private static LogbookBuilder inValidLogbook = logbook("InValid Logbook");
private static TagBuilder inValidTag = tag("InValid Tag");
private static PropertyBuilder inValidProperty = property("InValid Property");
private static OlogClient client;
@BeforeClass
public static void setup() {
try {
client = OlogClientBuilder.serviceURL()
.withHTTPAuthentication(true).create();
client.set(validTag);
client.set(validLogbook.owner("test"));
client.set(validLogbook2.owner("test"));
client.set(validProperty);
validLog = client.set(log()
.description("Valid Log Entry for error condition tests.")
.appendToLogbook(validLogbook).level("Info"));
} catch (Exception e) {
e.printStackTrace();
}
}
@AfterClass
public static void tearDown() {
client.deleteTag(validTag.build().getName());
client.deleteLogbook(validLogbook.build().getName());
client.deleteLogbook(validLogbook2.build().getName());
client.deleteProperty(validProperty.build().getName());
client.delete(validLog.getId());
}
@Test(expected = OlogException.class)
public void setLogWithNoLogbook() {
LogBuilder log = log().description("log with no logbook").level("Info");
client.set(log);
}
@Test(expected = OlogException.class)
public void setLogWithNoLevel() {
LogBuilder log = log().description("log with no level")
.appendToLogbook(validLogbook);
client.set(log);
}
@Test(expected = OlogException.class)
public void setLogWithInvalidLogbook() {
LogBuilder log = log().description("log with invalid logbook")
.level("Info").appendToLogbook(inValidLogbook);
client.set(log);
}
@Test(expected = OlogException.class)
public void setLogWithInvalidTag() {
LogBuilder log = log().description("log with invalid tag")
.level("Info").appendToLogbook(validLogbook)
.appendTag(inValidTag);
client.set(log);
}
@Test(expected = OlogException.class)
public void setLogWithInvalidProperty() {
LogBuilder log = log().description("log with invalid property")
.level("Info").appendToLogbook(validLogbook)
.appendProperty(inValidProperty);
client.set(log);
}
@Test(expected = OlogException.class)
public void setLogWithInvalidAttribute() {
LogBuilder log = log()
.description("log with invalid attribute")
.level("Info")
.appendToLogbook(validLogbook)
.appendProperty(validProperty.attribute("invalidAttribute", ""));
client.set(log);
}
@Test(expected = OlogException.class)
public void setTagOnInvalidLog() {
Collection<Long> logIds = new ArrayList<Long>();
logIds.add(validLog.getId());
logIds.add(12345L);
client.set(validTag, logIds);
Log queryLog = client.getLog(validLog.getId());
assertTrue(
"invalid request to add tag to logs partially executed, unexpected modification of validLog",
validLog.equals(queryLog));
}
@Test(expected = OlogException.class)
public void setInvalidTagOnLog() {
client.update(inValidTag, validLog.getId());
assertTrue("invalid request to add invalid tag to log",
validLog.equals(client.getLog(validLog.getId())));
}
@Test(expected = OlogException.class)
public void setLogbookOnInvalidLog() {
Collection<Long> logIds = new ArrayList();
logIds.add(validLog.getId());
logIds.add(12345L);
client.set(validLogbook2, logIds);
Log queryLog = client.getLog(validLog.getId());
assertTrue(
"invalid request to add logbook2 to logs partially executed, unexpected modification of validLog",
validLog.equals(queryLog));
}
}
|
package guitests;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import org.eclipse.egit.github.core.RepositoryId;
import org.junit.Test;
import org.loadui.testfx.utils.FXTestUtils;
import prefs.PanelInfo;
import prefs.Preferences;
import ui.TestController;
import ui.UI;
import ui.components.FilterTextField;
import ui.components.KeyboardShortcuts;
import ui.issuepanel.FilterPanel;
import ui.issuepanel.PanelControl;
import util.PlatformEx;
import util.events.ShowRenamePanelEvent;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class UseGlobalConfigsTest extends UITest {
@Override
public void launchApp() {
// isTestMode in UI checks for testconfig too so we don't need to specify --test=true here.
FXTestUtils.launchApp(TestUI.class, "--testconfig=true");
}
@Test
public void useGlobalConfigTest() {
// Override setupMethod() if you want to do stuff to the JSON beforehand
UI ui = TestController.getUI();
PanelControl panels = ui.getPanelControl();
selectAll();
type("dummy");
pushKeys(KeyCode.TAB);
type("dummy");
pushKeys(KeyCode.TAB);
type("test");
pushKeys(KeyCode.TAB);
type("test");
click("Sign in");
ComboBox<String> repositorySelector = findOrWaitFor("#repositorySelector");
waitForValue(repositorySelector);
assertEquals("dummy/dummy", repositorySelector.getValue());
pushKeys(KeyboardShortcuts.MAXIMIZE_WINDOW);
// Make a new board
click("Boards");
click("Save as");
// Somehow the text field cannot be populated by typing on the CI, use setText instead.
// TODO find out why
((TextField) find("#boardnameinput")).setText("Empty Board");
click("OK");
PlatformEx.runAndWait(() -> UI.events.triggerEvent(new ShowRenamePanelEvent(0)));
type("Renamed panel");
push(KeyCode.ENTER);
FilterPanel filterPanel0 = (FilterPanel) panels.getPanel(0);
assertEquals("Renamed panel", filterPanel0.getNameText().getText());
FilterTextField filterTextField0 = filterPanel0.getFilterTextField();
waitUntilNodeAppears(filterTextField0);
click(filterTextField0);
type("is");
pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON);
type("issue");
push(KeyCode.ENTER);
// Load dummy2/dummy2 too
pushKeys(KeyboardShortcuts.CREATE_RIGHT_PANEL);
PlatformEx.waitOnFxThread();
FilterPanel filterPanel1 = (FilterPanel) panels.getPanel(1);
FilterTextField filterTextField1 = filterPanel1.getFilterTextField();
waitUntilNodeAppears(filterTextField1);
click(filterTextField1);
type("repo");
pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON);
type("dummy2/dummy2");
pushKeys(KeyCode.ENTER);
Label renameButton1 = filterPanel1.getRenameButton();
click(renameButton1);
type("Dummy 2 panel");
push(KeyCode.ENTER);
assertEquals("Dummy 2 panel", filterPanel1.getNameText().getText());
pushKeys(KeyboardShortcuts.CREATE_LEFT_PANEL);
PlatformEx.waitOnFxThread();
sleep(500);
FilterPanel filterPanel2 = (FilterPanel) panels.getPanel(0);
FilterTextField filterTextField2 = filterPanel2.getFilterTextField();
click(filterTextField2);
type("is");
pushKeys(KeyCode.SHIFT, KeyCode.SEMICOLON);
type("open");
assertEquals("is:open", filterTextField2.getText());
pushKeys(KeyCode.ENTER);
PlatformEx.runAndWait(() -> UI.events.triggerEvent(new ShowRenamePanelEvent(0)));
type("Open issues");
push(KeyCode.ENTER);
assertEquals("Open issues", filterPanel2.getNameText().getText());
// Make a new board
click("Boards");
click("Save as");
// Text field cannot be populated by typing on the CI, use setText instead
((TextField) find("#boardnameinput")).setText("Dummy Board");
click("OK");
// Then exit program...
click("File");
click("Quit");
// ...and check if the test JSON is still there...
File testConfig = new File(Preferences.DIRECTORY, Preferences.TEST_CONFIG_FILE);
if (!(testConfig.exists() && testConfig.isFile())) {
fail();
}
// ...then check that the JSON file contents are correct.
Preferences testPref = TestController.loadTestPreferences();
// Credentials
assertEquals("test", testPref.getLastLoginUsername());
assertEquals("test", testPref.getLastLoginPassword());
// Last viewed repository
RepositoryId lastViewedRepository = testPref.getLastViewedRepository().get();
assertEquals("dummy/dummy", lastViewedRepository.generateId());
// Boards
Map<String, List<PanelInfo>> boards = testPref.getAllBoards();
List<PanelInfo> emptyBoard = boards.get("Empty Board");
assertEquals(1, emptyBoard.size());
assertEquals("", emptyBoard.get(0).getPanelFilter());
assertEquals("Panel", emptyBoard.get(0).getPanelName());
List<PanelInfo> dummyBoard = boards.get("Dummy Board");
assertEquals(3, dummyBoard.size());
assertEquals("is:open", dummyBoard.get(0).getPanelFilter());
assertEquals("is:issue", dummyBoard.get(1).getPanelFilter());
assertEquals("repo:dummy2/dummy2", dummyBoard.get(2).getPanelFilter());
assertEquals("Open issues", dummyBoard.get(0).getPanelName());
assertEquals("Renamed panel", dummyBoard.get(1).getPanelName());
assertEquals("Dummy 2 panel", dummyBoard.get(2).getPanelName());
// Panels
List<String> lastOpenFilters = testPref.getLastOpenFilters();
List<String> lastOpenPanelNames = testPref.getPanelNames();
assertEquals("is:open", lastOpenFilters.get(0));
assertEquals("is:issue", lastOpenFilters.get(1));
assertEquals("repo:dummy2/dummy2", lastOpenFilters.get(2));
assertEquals("Open issues", lastOpenPanelNames.get(0));
assertEquals("Renamed panel", lastOpenPanelNames.get(1));
assertEquals("Dummy 2 panel", lastOpenPanelNames.get(2));
}
}
|
package org.json.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONPointerException;
import org.json.XML;
import org.junit.Test;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
/**
* JSONObject, along with JSONArray, are the central classes of the reference app.
* All of the other classes interact with them, and JSON functionality would
* otherwise be impossible.
*/
public class JSONObjectTest {
/**
* JSONObject built from a bean, but only using a null value.
* Nothing good is expected to happen.
* Expects NullPointerException
*/
@Test(expected=NullPointerException.class)
public void jsonObjectByNullBean() {
assertNull("Expected an exception",new JSONObject((MyBean)null));
}
/**
* The JSON parser is permissive of unambiguous unquoted keys and values.
* Such JSON text should be allowed, even if it does not strictly conform
* to the spec. However, after being parsed, toString() should emit strictly
* conforming JSON text.
*/
@Test
public void unquotedText() {
String str = "{key1:value1, key2:42}";
JSONObject jsonObject = new JSONObject(str);
String textStr = jsonObject.toString();
assertTrue("expected key1", textStr.contains("\"key1\""));
assertTrue("expected value1", textStr.contains("\"value1\""));
assertTrue("expected key2", textStr.contains("\"key2\""));
assertTrue("expected 42", textStr.contains("42"));
}
@Test
public void testLongFromString(){
String str = "26315000000253009";
JSONObject json = new JSONObject();
json.put("key", str);
final Object actualKey = json.opt("key");
assert str.equals(actualKey) : "Incorrect key value. Got " + actualKey
+ " expected " + str;
final long actualLong = json.optLong("key");
assert actualLong != 0 : "Unable to extract long value for string " + str;
assert 26315000000253009L == actualLong : "Incorrect key value. Got "
+ actualLong + " expected " + str;
final String actualString = json.optString("key");
assert str.equals(actualString) : "Incorrect key value. Got "
+ actualString + " expected " + str;
}
/**
* A JSONObject can be created with no content
*/
@Test
public void emptyJsonObject() {
JSONObject jsonObject = new JSONObject();
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* A JSONObject can be created from another JSONObject plus a list of names.
* In this test, some of the starting JSONObject keys are not in the
* names list.
*/
@Test
public void jsonObjectByNames() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"nullKey\":null,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e67"+
"}";
String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"};
JSONObject jsonObject = new JSONObject(str);
// validate JSON
JSONObject jsonObjectByName = new JSONObject(jsonObject, keys);
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString());
assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey")));
assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map is null.
* the JSONObject(JsonTokener) ctor is not tested directly since it already
* has full coverage from other tests.
*/
@Test
public void jsonObjectByNullMap() {
Map<String, Object> map = null;
JSONObject jsonObject = new JSONObject(map);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test all of the map entries are valid JSON types.
*/
@Test
public void jsonObjectByMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("trueKey", new Boolean(true));
map.put("falseKey", new Boolean(false));
map.put("stringKey", "hello world!");
map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
map.put("intKey", new Long(42));
map.put("doubleKey", new Double(-23.45e67));
JSONObject jsonObject = new JSONObject(map);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
/**
* Verifies that the constructor has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyConstructor() {
final JSONObject expected = new JSONObject("{\"myKey\":10}");
@SuppressWarnings("rawtypes")
Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10));
JSONObject jaRaw = new JSONObject(myRawC);
Map<String, Object> myCStrObj = Collections.singletonMap("myKey",
(Object) Integer.valueOf(10));
JSONObject jaStrObj = new JSONObject(myCStrObj);
Map<String, Integer> myCStrInt = Collections.singletonMap("myKey",
Integer.valueOf(10));
JSONObject jaStrInt = new JSONObject(myCStrInt);
Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey",
(Object) Integer.valueOf(10));
JSONObject jaObjObj = new JSONObject(myCObjObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
}
/**
* Tests Number serialization.
*/
@Test
public void verifyNumberOutput(){
/**
* MyNumberContainer is a POJO, so call JSONObject(bean),
* which builds a map of getter names/values
* The only getter is getMyNumber (key=myNumber),
* whose return value is MyNumber. MyNumber extends Number,
* but is not recognized as such by wrap() per current
* implementation, so wrap() returns the default new JSONObject(bean).
* The only getter is getNumber (key=number), whose return value is
* BigDecimal(42).
*/
JSONObject jsonObject = new JSONObject(new MyNumberContainer());
String actual = jsonObject.toString();
String expected = "{\"myNumber\":{\"number\":42}}";
assertEquals("Not Equal", expected , actual);
/**
* JSONObject.put() handles objects differently than the
* bean constructor. Where the bean ctor wraps objects before
* placing them in the map, put() inserts the object without wrapping.
* In this case, a MyNumber instance is the value.
* The MyNumber.toString() method is responsible for
* returning a reasonable value: the string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new MyNumber());
actual = jsonObject.toString();
expected = "{\"myNumber\":42}";
assertEquals("Not Equal", expected , actual);
/**
* Calls the JSONObject(Map) ctor, which calls wrap() for values.
* AtomicInteger is a Number, but is not recognized by wrap(), per
* current implementation. However, the type is
* 'java.util.concurrent.atomic', so due to the 'java' prefix,
* wrap() inserts the value as a string. That is why 42 comes back
* wrapped in quotes.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42)));
actual = jsonObject.toString();
expected = "{\"myNumber\":\"42\"}";
assertEquals("Not Equal", expected , actual);
/**
* JSONObject.put() inserts the AtomicInteger directly into the
* map not calling wrap(). In toString()->write()->writeValue(),
* AtomicInteger is recognized as a Number, and converted via
* numberToString() into the unquoted string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new AtomicInteger(42));
actual = jsonObject.toString();
expected = "{\"myNumber\":42}";
assertEquals("Not Equal", expected , actual);
/**
* Calls the JSONObject(Map) ctor, which calls wrap() for values.
* Fraction is a Number, but is not recognized by wrap(), per
* current implementation. As a POJO, Fraction is handled as a
* bean and inserted into a contained JSONObject. It has 2 getters,
* for numerator and denominator.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2)));
assertEquals(1, jsonObject.length());
assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length());
assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator"));
assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator"));
/**
* JSONObject.put() inserts the Fraction directly into the
* map not calling wrap(). In toString()->write()->writeValue(),
* Fraction is recognized as a Number, and converted via
* numberToString() into the unquoted string '4/2'. But the
* BigDecimal sanity check fails, so writeValue() defaults
* to returning a safe JSON quoted string. Pretty slick!
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new Fraction(4,2));
actual = jsonObject.toString();
expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed
assertEquals("Not Equal", expected , actual);
}
/**
* Verifies that the put Collection has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyPutCollection() {
final JSONObject expected = new JSONObject("{\"myCollection\":[10]}");
@SuppressWarnings("rawtypes")
Collection myRawC = Collections.singleton(Integer.valueOf(10));
JSONObject jaRaw = new JSONObject();
jaRaw.put("myCollection", myRawC);
Collection<Object> myCObj = Collections.singleton((Object) Integer
.valueOf(10));
JSONObject jaObj = new JSONObject();
jaObj.put("myCollection", myCObj);
Collection<Integer> myCInt = Collections.singleton(Integer
.valueOf(10));
JSONObject jaInt = new JSONObject();
jaInt.put("myCollection", myCInt);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
}
/**
* Verifies that the put Map has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyPutMap() {
final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}");
@SuppressWarnings("rawtypes")
Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10));
JSONObject jaRaw = new JSONObject();
jaRaw.put("myMap", myRawC);
Map<String, Object> myCStrObj = Collections.singletonMap("myKey",
(Object) Integer.valueOf(10));
JSONObject jaStrObj = new JSONObject();
jaStrObj.put("myMap", myCStrObj);
Map<String, Integer> myCStrInt = Collections.singletonMap("myKey",
Integer.valueOf(10));
JSONObject jaStrInt = new JSONObject();
jaStrInt.put("myMap", myCStrInt);
Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey",
(Object) Integer.valueOf(10));
JSONObject jaObjObj = new JSONObject();
jaObjObj.put("myMap", myCObjObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map entries are not valid JSON types.
* The actual conversion is kind of interesting.
*/
@Test
public void jsonObjectByMapWithUnsupportedValues() {
Map<String, Object> jsonMap = new HashMap<String, Object>();
// Just insert some random objects
jsonMap.put("key1", new CDL());
jsonMap.put("key2", new Exception());
JSONObject jsonObject = new JSONObject(jsonMap);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0);
assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test one of the map values is null
*/
@Test
public void jsonObjectByMapWithNullValue() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("trueKey", new Boolean(true));
map.put("falseKey", new Boolean(false));
map.put("stringKey", "hello world!");
map.put("nullKey", null);
map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
map.put("intKey", new Long(42));
map.put("doubleKey", new Double(-23.45e67));
JSONObject jsonObject = new JSONObject(map);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
/**
* JSONObject built from a bean. In this case all but one of the
* bean getters return valid JSON types
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectByBean() {
/**
* Default access classes have to be mocked since JSONObject, which is
* not in the same package, cannot call MyBean methods by reflection.
*/
MyBean myBean = mock(MyBean.class);
when(myBean.getDoubleKey()).thenReturn(-23.45e7);
when(myBean.getIntKey()).thenReturn(42);
when(myBean.getStringKey()).thenReturn("hello world!");
when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!");
when(myBean.isTrueKey()).thenReturn(true);
when(myBean.isFalseKey()).thenReturn(false);
when(myBean.getStringReaderKey()).thenReturn(
new StringReader("") {
});
JSONObject jsonObject = new JSONObject(myBean);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 8 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 8);
assertTrue("expected 0 items in stringReaderKey", ((Map<?, ?>) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey")));
assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey")));
// sorry, mockito artifact
assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2);
assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0);
assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0);
}
/**
* A bean is also an object. But in order to test the JSONObject
* ctor that takes an object and a list of names,
* this particular bean needs some public
* data members, which have been added to the class.
*/
@Test
public void jsonObjectByObjectAndNames() {
String[] keys = {"publicString", "publicInt"};
// just need a class that has public data members
MyPublicClass myPublicClass = new MyPublicClass();
JSONObject jsonObject = new JSONObject(myPublicClass, keys);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString")));
assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt")));
}
/**
* Exercise the JSONObject from resource bundle functionality.
* The test resource bundle is uncomplicated, but provides adequate test coverage.
*/
@Test
public void jsonObjectByResourceBundle() {
JSONObject jsonObject = new
JSONObject("org.json.junit.StringsResourceBundle",
Locale.getDefault());
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2);
assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello")));
assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world")));
assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
}
/**
* Exercise the JSONObject.accumulate() method
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectAccumulate() {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("myArray", true);
jsonObject.accumulate("myArray", false);
jsonObject.accumulate("myArray", "hello world!");
jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!");
jsonObject.accumulate("myArray", 42);
jsonObject.accumulate("myArray", -23.45e7);
// include an unsupported object for coverage
try {
jsonObject.accumulate("myArray", Double.NaN);
fail("Expected exception");
} catch (JSONException ignored) {}
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1")));
assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
}
/**
* Exercise the JSONObject append() functionality
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectAppend() {
JSONObject jsonObject = new JSONObject();
jsonObject.append("myArray", true);
jsonObject.append("myArray", false);
jsonObject.append("myArray", "hello world!");
jsonObject.append("myArray", "h\be\tllo w\u1234orld!");
jsonObject.append("myArray", 42);
jsonObject.append("myArray", -23.45e7);
// include an unsupported object for coverage
try {
jsonObject.append("myArray", Double.NaN);
fail("Expected exception");
} catch (JSONException ignored) {}
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/")));
assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
}
/**
* Exercise the JSONObject doubleToString() method
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectDoubleToString() {
String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" };
Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67,
Double.NaN, Double.NEGATIVE_INFINITY };
for (int i = 0; i < expectedStrs.length; ++i) {
String actualStr = JSONObject.doubleToString(doubles[i]);
assertTrue("value expected ["+expectedStrs[i]+
"] found ["+actualStr+ "]",
expectedStrs[i].equals(actualStr));
}
}
/**
* Exercise some JSONObject get[type] and opt[type] methods
*/
@Test
public void jsonObjectValues() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"trueStrKey\":\"true\","+
"\"falseStrKey\":\"false\","+
"\"stringKey\":\"hello world!\","+
"\"intKey\":42,"+
"\"intStrKey\":\"43\","+
"\"longKey\":1234567890123456789,"+
"\"longStrKey\":\"987654321098765432\","+
"\"doubleKey\":-23.45e7,"+
"\"doubleStrKey\":\"00001.000\","+
"\"BigDecimalStrKey\":\"19007199254740993.35481234487103587486413587843213584\","+
"\"negZeroKey\":-0.0,"+
"\"negZeroStrKey\":\"-0.0\","+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{\"myKey\":\"myVal\"}"+
"}";
JSONObject jsonObject = new JSONObject(str);
assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey"));
assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey"));
assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey"));
assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey"));
assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey"));
assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey"));
assertTrue("stringKey should be string",
jsonObject.getString("stringKey").equals("hello world!"));
assertTrue("doubleKey should be double",
jsonObject.getDouble("doubleKey") == -23.45e7);
assertTrue("doubleStrKey should be double",
jsonObject.getDouble("doubleStrKey") == 1);
assertTrue("doubleKey can be float",
jsonObject.getFloat("doubleKey") == -23.45e7f);
assertTrue("doubleStrKey can be float",
jsonObject.getFloat("doubleStrKey") == 1f);
assertTrue("opt doubleKey should be double",
jsonObject.optDouble("doubleKey") == -23.45e7);
assertTrue("opt doubleKey with Default should be double",
jsonObject.optDouble("doubleStrKey", Double.NaN) == 1);
assertTrue("opt negZeroKey should be double",
Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d) == 0);
assertTrue("opt negZeroStrKey with Default should be double",
Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d) == 0);
assertTrue("optNumber negZeroKey should return Double",
jsonObject.optNumber("negZeroKey") instanceof Double);
assertTrue("optNumber negZeroStrKey should return Double",
jsonObject.optNumber("negZeroStrKey") instanceof Double);
assertTrue("optNumber negZeroKey should be -0.0",
Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d) == 0);
assertTrue("optNumber negZeroStrKey should be -0.0",
Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d) == 0);
assertTrue("optFloat doubleKey should be float",
jsonObject.optFloat("doubleKey") == -23.45e7f);
assertTrue("optFloat doubleKey with Default should be float",
jsonObject.optFloat("doubleStrKey", Float.NaN) == 1f);
assertTrue("intKey should be int",
jsonObject.optInt("intKey") == 42);
assertTrue("opt intKey should be int",
jsonObject.optInt("intKey", 0) == 42);
assertTrue("opt intKey with default should be int",
jsonObject.getInt("intKey") == 42);
assertTrue("intStrKey should be int",
jsonObject.getInt("intStrKey") == 43);
assertTrue("longKey should be long",
jsonObject.getLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey should be long",
jsonObject.optLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey with default should be long",
jsonObject.optLong("longKey", 0) == 1234567890123456789L);
assertTrue("longStrKey should be long",
jsonObject.getLong("longStrKey") == 987654321098765432L);
assertTrue("optNumber int should return Integer",
jsonObject.optNumber("intKey") instanceof Integer);
assertTrue("optNumber long should return Long",
jsonObject.optNumber("longKey") instanceof Long);
assertTrue("optNumber double should return Double",
jsonObject.optNumber("doubleKey") instanceof Double);
assertTrue("optNumber Str int should return Integer",
jsonObject.optNumber("intStrKey") instanceof Integer);
assertTrue("optNumber Str long should return Long",
jsonObject.optNumber("longStrKey") instanceof Long);
assertTrue("optNumber Str double should return Double",
jsonObject.optNumber("doubleStrKey") instanceof Double);
assertTrue("optNumber BigDecimalStrKey should return BigDecimal",
jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal);
assertTrue("xKey should not exist",
jsonObject.isNull("xKey"));
assertTrue("stringKey should exist",
jsonObject.has("stringKey"));
assertTrue("opt stringKey should string",
jsonObject.optString("stringKey").equals("hello world!"));
assertTrue("opt stringKey with default should string",
jsonObject.optString("stringKey", "not found").equals("hello world!"));
JSONArray jsonArray = jsonObject.getJSONArray("arrayKey");
assertTrue("arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
jsonArray = jsonObject.optJSONArray("arrayKey");
assertTrue("opt arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey");
assertTrue("objectKey should be JSONObject",
jsonObjectInner.get("myKey").equals("myVal"));
}
/**
* Check whether JSONObject handles large or high precision numbers correctly
*/
@Test
public void stringToValueNumbersTest() {
assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double);
assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double);
assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String);
assertTrue( "0.2 should be a Double!",
JSONObject.stringToValue( "0.2" ) instanceof Double );
assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!",
JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double );
/**
* This test documents a need for BigDecimal conversion.
*/
Object obj = JSONObject.stringToValue( "299792.457999999984" );
assertTrue( "evaluates to 299792.458 double instead of 299792.457999999984 BigDecimal!",
obj.equals(new Double(299792.458)) );
assertTrue( "1 should be an Integer!",
JSONObject.stringToValue( "1" ) instanceof Integer );
assertTrue( "Integer.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer );
assertTrue( "Large integers should be a Long!",
JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long );
assertTrue( "Long.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long );
String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString();
assertTrue( "Really large integers currently evaluate to string",
JSONObject.stringToValue(str).equals("9223372036854775808"));
}
/**
* This test documents numeric values which could be numerically
* handled as BigDecimal or BigInteger. It helps determine what outputs
* will change if those types are supported.
*/
@Test
public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() {
// Valid JSON Numbers, probably should return BigDecimal or BigInteger objects
String str =
"{"+
"\"numberWithDecimals\":299792.457999999984,"+
"\"largeNumber\":12345678901234567890,"+
"\"preciseNumber\":0.2000000000000000111,"+
"\"largeExponent\":-23.45e2327"+
"}";
JSONObject jsonObject = new JSONObject(str);
// Comes back as a double, but loses precision
assertTrue( "numberWithDecimals currently evaluates to double 299792.458",
jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) );
Object obj = jsonObject.get( "largeNumber" );
assertTrue("largeNumber currently evaluates to string",
"12345678901234567890".equals(obj));
// comes back as a double but loses precision
assertTrue( "preciseNumber currently evaluates to double 0.2",
jsonObject.get( "preciseNumber" ).equals(new Double(0.2)));
obj = jsonObject.get( "largeExponent" );
assertTrue("largeExponent should currently evaluates as a string",
"-23.45e2327".equals(obj));
}
/**
* This test documents how JSON-Java handles invalid numeric input.
*/
@Test
public void jsonInvalidNumberValues() {
// Number-notations supported by Java and invalid as JSON
String str =
"{"+
"\"hexNumber\":-0x123,"+
"\"tooManyZeros\":00,"+
"\"negativeInfinite\":-Infinity,"+
"\"negativeNaN\":-NaN,"+
"\"negativeFraction\":-.01,"+
"\"tooManyZerosFraction\":00.001,"+
"\"negativeHexFloat\":-0x1.fffp1,"+
"\"hexFloat\":0x1.0P-1074,"+
"\"floatIdentifier\":0.1f,"+
"\"doubleIdentifier\":0.1d"+
"}";
JSONObject jsonObject = new JSONObject(str);
Object obj;
obj = jsonObject.get( "hexNumber" );
assertFalse( "hexNumber must not be a number (should throw exception!?)",
obj instanceof Number );
assertTrue("hexNumber currently evaluates to string",
obj.equals("-0x123"));
assertTrue( "tooManyZeros currently evaluates to string",
jsonObject.get( "tooManyZeros" ).equals("00"));
obj = jsonObject.get("negativeInfinite");
assertTrue( "negativeInfinite currently evaluates to string",
obj.equals("-Infinity"));
obj = jsonObject.get("negativeNaN");
assertTrue( "negativeNaN currently evaluates to string",
obj.equals("-NaN"));
assertTrue( "negativeFraction currently evaluates to double -0.01",
jsonObject.get( "negativeFraction" ).equals(new Double(-0.01)));
assertTrue( "tooManyZerosFraction currently evaluates to double 0.001",
jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001)));
assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875",
jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875)));
assertTrue("hexFloat currently evaluates to double 4.9E-324",
jsonObject.get("hexFloat").equals(new Double(4.9E-324)));
assertTrue("floatIdentifier currently evaluates to double 0.1",
jsonObject.get("floatIdentifier").equals(new Double(0.1)));
assertTrue("doubleIdentifier currently evaluates to double 0.1",
jsonObject.get("doubleIdentifier").equals(new Double(0.1)));
}
/**
* Tests how JSONObject get[type] handles incorrect types
*/
@Test
public void jsonObjectNonAndWrongValues() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"trueStrKey\":\"true\","+
"\"falseStrKey\":\"false\","+
"\"stringKey\":\"hello world!\","+
"\"intKey\":42,"+
"\"intStrKey\":\"43\","+
"\"longKey\":1234567890123456789,"+
"\"longStrKey\":\"987654321098765432\","+
"\"doubleKey\":-23.45e7,"+
"\"doubleStrKey\":\"00001.000\","+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{\"myKey\":\"myVal\"}"+
"}";
JSONObject jsonObject = new JSONObject(str);
try {
jsonObject.getBoolean("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("expecting an exception message",
"JSONObject[\"nonKey\"] not found.".equals(e.getMessage()));
}
try {
jsonObject.getBoolean("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a Boolean.".
equals(e.getMessage()));
}
try {
jsonObject.getString("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getString("trueKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"trueKey\"] not a string.".
equals(e.getMessage()));
}
try {
jsonObject.getDouble("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getDouble("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a number.".
equals(e.getMessage()));
}
try {
jsonObject.getFloat("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getFloat("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a number.".
equals(e.getMessage()));
}
try {
jsonObject.getInt("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getInt("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not an int.".
equals(e.getMessage()));
}
try {
jsonObject.getLong("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getLong("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a long.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONArray("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONArray("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONArray.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONObject("nonKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONObject("stringKey");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONObject.".
equals(e.getMessage()));
}
}
/**
* This test documents an unexpected numeric behavior.
* A double that ends with .0 is parsed, serialized, then
* parsed again. On the second parse, it has become an int.
*/
@Test
public void unexpectedDoubleToIntConversion() {
String key30 = "key30";
String key31 = "key31";
JSONObject jsonObject = new JSONObject();
jsonObject.put(key30, new Double(3.0));
jsonObject.put(key31, new Double(3.1));
assertTrue("3.0 should remain a double",
jsonObject.getDouble(key30) == 3);
assertTrue("3.1 should remain a double",
jsonObject.getDouble(key31) == 3.1);
// turns 3.0 into 3.
String serializedString = jsonObject.toString();
JSONObject deserialized = new JSONObject(serializedString);
assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer);
assertTrue("3.0 can still be interpreted as a double",
deserialized.getDouble(key30) == 3.0);
assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1);
}
/**
* Document behaviors of big numbers. Includes both JSONObject
* and JSONArray tests
*/
@SuppressWarnings("boxing")
@Test
public void bigNumberOperations() {
/**
* JSONObject tries to parse BigInteger as a bean, but it only has
* one getter, getLowestBitSet(). The value is lost and an unhelpful
* value is stored. This should be fixed.
*/
BigInteger bigInteger = new BigInteger("123456789012345678901234567890");
JSONObject jsonObject = new JSONObject(bigInteger);
Object obj = jsonObject.get("lowestSetBit");
assertTrue("JSONObject only has 1 value", jsonObject.length() == 1);
assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet",
obj instanceof Integer);
assertTrue("this bigInteger lowestBitSet happens to be 1",
obj.equals(1));
/**
* JSONObject tries to parse BigDecimal as a bean, but it has
* no getters, The value is lost and no value is stored.
* This should be fixed.
*/
BigDecimal bigDecimal = new BigDecimal(
"123456789012345678901234567890.12345678901234567890123456789");
jsonObject = new JSONObject(bigDecimal);
assertTrue("large bigDecimal is not stored", jsonObject.length() == 0);
/**
* JSONObject put(String, Object) method stores and serializes
* bigInt and bigDec correctly. Nothing needs to change.
*/
jsonObject = new JSONObject();
jsonObject.put("bigInt", bigInteger);
assertTrue("jsonObject.put() handles bigInt correctly",
jsonObject.get("bigInt").equals(bigInteger));
assertTrue("jsonObject.getBigInteger() handles bigInt correctly",
jsonObject.getBigInteger("bigInt").equals(bigInteger));
assertTrue("jsonObject.optBigInteger() handles bigInt correctly",
jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger));
assertTrue("jsonObject serializes bigInt correctly",
jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}"));
jsonObject = new JSONObject();
jsonObject.put("bigDec", bigDecimal);
assertTrue("jsonObject.put() handles bigDec correctly",
jsonObject.get("bigDec").equals(bigDecimal));
assertTrue("jsonObject.getBigDecimal() handles bigDec correctly",
jsonObject.getBigDecimal("bigDec").equals(bigDecimal));
assertTrue("jsonObject.optBigDecimal() handles bigDec correctly",
jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal));
assertTrue("jsonObject serializes bigDec correctly",
jsonObject.toString().equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
/**
* exercise some exceptions
*/
try {
jsonObject.getBigDecimal("bigInt");
fail("expected an exeption");
} catch (JSONException ignored) {}
obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE);
assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE));
try {
jsonObject.getBigInteger("bigDec");
fail("expected an exeption");
} catch (JSONException ignored) {}
jsonObject.put("stringKey", "abc");
try {
jsonObject.getBigDecimal("stringKey");
fail("expected an exeption");
} catch (JSONException ignored) {}
obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE);
assertTrue("expected BigInteger", obj instanceof BigInteger);
assertEquals(bigDecimal.toBigInteger(), obj);
/**
* JSONObject.numberToString() works correctly, nothing to change.
*/
String str = JSONObject.numberToString(bigInteger);
assertTrue("numberToString() handles bigInteger correctly",
str.equals("123456789012345678901234567890"));
str = JSONObject.numberToString(bigDecimal);
assertTrue("numberToString() handles bigDecimal correctly",
str.equals("123456789012345678901234567890.12345678901234567890123456789"));
/**
* JSONObject.stringToValue() turns bigInt into an accurate string,
* and rounds bigDec. This incorrect, but users may have come to
* expect this behavior. Change would be marginally better, but
* might inconvenience users.
*/
obj = JSONObject.stringToValue(bigInteger.toString());
assertTrue("stringToValue() turns bigInteger string into string",
obj instanceof String);
obj = JSONObject.stringToValue(bigDecimal.toString());
assertTrue("stringToValue() changes bigDecimal string",
!obj.toString().equals(bigDecimal.toString()));
/**
* wrap() vs put() big number behavior is now the same.
*/
// bigInt map ctor
Map<String, Object> map = new HashMap<String, Object>();
map.put("bigInt", bigInteger);
jsonObject = new JSONObject(map);
String actualFromMapStr = jsonObject.toString();
assertTrue("bigInt in map (or array or bean) is a string",
actualFromMapStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigInt put
jsonObject = new JSONObject();
jsonObject.put("bigInt", bigInteger);
String actualFromPutStr = jsonObject.toString();
assertTrue("bigInt from put is a number",
actualFromPutStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigDec map ctor
map = new HashMap<String, Object>();
map.put("bigDec", bigDecimal);
jsonObject = new JSONObject(map);
actualFromMapStr = jsonObject.toString();
assertTrue("bigDec in map (or array or bean) is a bigDec",
actualFromMapStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigDec put
jsonObject = new JSONObject();
jsonObject.put("bigDec", bigDecimal);
actualFromPutStr = jsonObject.toString();
assertTrue("bigDec from put is a number",
actualFromPutStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigInt,bigDec put
JSONArray jsonArray = new JSONArray();
jsonArray.put(bigInteger);
jsonArray.put(bigDecimal);
actualFromPutStr = jsonArray.toString();
assertTrue("bigInt, bigDec from put is a number",
actualFromPutStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger));
assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal));
assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger));
assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal));
jsonArray.put(Boolean.TRUE);
try {
jsonArray.getBigInteger(2);
fail("should not be able to get big int");
} catch (Exception ignored) {}
try {
jsonArray.getBigDecimal(2);
fail("should not be able to get big dec");
} catch (Exception ignored) {}
assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE));
assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE));
// bigInt,bigDec list ctor
List<Object> list = new ArrayList<Object>();
list.add(bigInteger);
list.add(bigDecimal);
jsonArray = new JSONArray(list);
String actualFromListStr = jsonArray.toString();
assertTrue("bigInt, bigDec in list is a bigInt, bigDec",
actualFromListStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
// bigInt bean ctor
MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890"));
jsonObject = new JSONObject(myBigNumberBean);
String actualFromBeanStr = jsonObject.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigInt from bean ctor is a bigInt",
actualFromBeanStr.contains("123456789012345678901234567890"));
// bigDec bean ctor
myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789"));
jsonObject = new JSONObject(myBigNumberBean);
actualFromBeanStr = jsonObject.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigDec from bean ctor is a bigDec",
actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789"));
// bigInt,bigDec wrap()
obj = JSONObject.wrap(bigInteger);
assertTrue("wrap() returns big num",obj.equals(bigInteger));
obj = JSONObject.wrap(bigDecimal);
assertTrue("wrap() returns string",obj.equals(bigDecimal));
}
/**
* The purpose for the static method getNames() methods are not clear.
* This method is not called from within JSON-Java. Most likely
* uses are to prep names arrays for:
* JSONObject(JSONObject jo, String[] names)
* JSONObject(Object object, String names[]),
*/
@Test
public void jsonObjectNames() {
JSONObject jsonObject;
// getNames() from null JSONObject
assertTrue("null names from null Object",
null == JSONObject.getNames((Object)null));
// getNames() from object with no fields
assertTrue("null names from Object with no fields",
null == JSONObject.getNames(new MyJsonString()));
// getNames from new JSONOjbect
jsonObject = new JSONObject();
String [] names = JSONObject.getNames(jsonObject);
assertTrue("names should be null", names == null);
// getNames() from empty JSONObject
String emptyStr = "{}";
jsonObject = new JSONObject(emptyStr);
assertTrue("empty JSONObject should have null names",
null == JSONObject.getNames(jsonObject));
// getNames() from JSONObject
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"}";
jsonObject = new JSONObject(str);
names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = new JSONArray(names);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
List<?> docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3);
assertTrue(
"expected to find trueKey",
((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1);
assertTrue(
"expected to find falseKey",
((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1);
assertTrue(
"expected to find stringKey",
((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
/**
* getNames() from an enum with properties has an interesting result.
* It returns the enum values, not the selected enum properties
*/
MyEnumField myEnumField = MyEnumField.VAL1;
names = JSONObject.getNames(myEnumField);
// validate JSON
jsonArray = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3);
assertTrue(
"expected to find VAL1",
((List<?>) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1);
assertTrue(
"expected to find VAL2",
((List<?>) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1);
assertTrue(
"expected to find VAL3",
((List<?>) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1);
/**
* A bean is also an object. But in order to test the static
* method getNames(), this particular bean needs some public
* data members.
*/
MyPublicClass myPublicClass = new MyPublicClass();
names = JSONObject.getNames(myPublicClass);
// validate JSON
jsonArray = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
docList = JsonPath.read(doc, "$");
assertTrue("expected 2 items", docList.size() == 2);
assertTrue(
"expected to find publicString",
((List<?>) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1);
assertTrue(
"expected to find publicInt",
((List<?>) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1);
}
/**
* Populate a JSONArray from an empty JSONObject names() method.
* It should be empty.
*/
@Test
public void emptyJsonObjectNamesToJsonAray() {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.names();
assertTrue("jsonArray should be null", jsonArray == null);
}
/**
* Populate a JSONArray from a JSONObject names() method.
* Confirm that it contains the expected names.
*/
@Test
public void jsonObjectNamesToJsonAray() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"}";
JSONObject jsonObject = new JSONObject(str);
JSONArray jsonArray = jsonObject.names();
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1);
assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1);
assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
}
/**
* Exercise the JSONObject increment() method.
*/
@SuppressWarnings("cast")
@Test
public void jsonObjectIncrement() {
String str =
"{"+
"\"keyLong\":9999999991,"+
"\"keyDouble\":1.1"+
"}";
JSONObject jsonObject = new JSONObject(str);
jsonObject.increment("keyInt");
jsonObject.increment("keyInt");
jsonObject.increment("keyLong");
jsonObject.increment("keyDouble");
jsonObject.increment("keyInt");
jsonObject.increment("keyLong");
jsonObject.increment("keyDouble");
/**
* JSONObject constructor won't handle these types correctly, but
* adding them via put works.
*/
jsonObject.put("keyFloat", 1.1f);
jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780"));
jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1"));
jsonObject.increment("keyFloat");
jsonObject.increment("keyFloat");
jsonObject.increment("keyBigInt");
jsonObject.increment("keyBigDec");
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt")));
assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong")));
assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble")));
assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt")));
assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec")));
assertEquals(Float.valueOf(3.1f), jsonObject.query("/keyFloat"));
/**
* float f = 3.1f; double df = (double) f; double d = 3.1d;
* System.out.println
* (Integer.toBinaryString(Float.floatToRawIntBits(f)));
* System.out.println
* (Long.toBinaryString(Double.doubleToRawLongBits(df)));
* System.out.println
* (Long.toBinaryString(Double.doubleToRawLongBits(d)));
*
* - Float:
* seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm
* 1000000010001100110011001100110
* - Double
* seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
* 10000000 10001100110011001100110
* 100000000001000110011001100110011000000000000000000000000000000
* 100000000001000110011001100110011001100110011001100110011001101
*/
/**
* Examples of well documented but probably unexpected behavior in
* java / with 32-bit float to 64-bit float conversion.
*/
assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d );
assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d );
Double d1 = new Double( 1.1f );
Double d2 = new Double( "1.1f" );
assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) );
assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) );
// Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject
JSONObject jo = new JSONObject();
jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double
assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) );
JSONObject inc = new JSONObject();
inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value )
assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float );
inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double!
// this.put(key, (Float) value + 1);
// 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done.
// 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects!
// 3. A float+float operation will be performed and results into a float primitive.
// 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method
// put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa
assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Float );
// correct implementation (with change of behavior) would be:
// this.put(key, new Float((Float) value + 1));
// Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not
// really in the the scope of a JSON-library (IMHO.)
}
/**
* Exercise JSONObject numberToString() method
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectNumberToString() {
String str;
Double dVal;
Integer iVal = 1;
str = JSONObject.numberToString(iVal);
assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str));
dVal = 12.34;
str = JSONObject.numberToString(dVal);
assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str));
dVal = 12.34e27;
str = JSONObject.numberToString(dVal);
assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str));
// trailing .0 is truncated, so it doesn't quite match toString()
dVal = 5000000.0000000;
str = JSONObject.numberToString(dVal);
assertTrue("expected 5000000 actual "+str, str.equals("5000000"));
}
/**
* Exercise JSONObject put() and similar() methods
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectPut() {
String expectedStr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{"+
"\"myKey1\":\"myVal1\","+
"\"myKey2\":\"myVal2\","+
"\"myKey3\":\"myVal3\","+
"\"myKey4\":\"myVal4\""+
"}"+
"}";
JSONObject jsonObject = new JSONObject();
jsonObject.put("trueKey", true);
jsonObject.put("falseKey", false);
Integer [] intArray = { 0, 1, 2 };
jsonObject.put("arrayKey", Arrays.asList(intArray));
Map<String, Object> myMap = new HashMap<String, Object>();
myMap.put("myKey1", "myVal1");
myMap.put("myKey2", "myVal2");
myMap.put("myKey3", "myVal3");
myMap.put("myKey4", "myVal4");
jsonObject.put("objectKey", myMap);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3);
assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0")));
assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2")));
assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4);
assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1")));
assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2")));
assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3")));
assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4")));
jsonObject.remove("trueKey");
JSONObject expectedJsonObject = new JSONObject(expectedStr);
assertTrue("unequal jsonObjects should not be similar",
!jsonObject.similar(expectedJsonObject));
assertTrue("jsonObject should not be similar to jsonArray",
!jsonObject.similar(new JSONArray()));
String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}";
String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}";
JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr);
JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr);
assertTrue("different values should not be similar",
!aCompareValueJsonObject.similar(bCompareValueJsonObject));
String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}";
String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}";
JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr);
JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr);
assertTrue("different nested JSONObjects should not be similar",
!aCompareObjectJsonObject.similar(bCompareObjectJsonObject));
String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}";
String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}";
JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr);
JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr);
assertTrue("different nested JSONArrays should not be similar",
!aCompareArrayJsonObject.similar(bCompareArrayJsonObject));
}
/**
* Exercise JSONObject toString() method
*/
@Test
public void jsonObjectToString() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{"+
"\"myKey1\":\"myVal1\","+
"\"myKey2\":\"myVal2\","+
"\"myKey3\":\"myVal3\","+
"\"myKey4\":\"myVal4\""+
"}"+
"}";
JSONObject jsonObject = new JSONObject(str);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected 3 arrayKey items", ((List<?>)(JsonPath.read(doc, "$.arrayKey"))).size() == 3);
assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0")));
assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2")));
assertTrue("expected 4 objectKey items", ((Map<?,?>)(JsonPath.read(doc, "$.objectKey"))).size() == 4);
assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1")));
assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2")));
assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3")));
assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4")));
}
/**
* Exercise JSONObject toString() method with various indent levels.
*/
@Test
public void jsonObjectToStringIndent() {
String jsonObject0Str =
"{"+
"\"key1\":" +
"[1,2," +
"{\"key3\":true}" +
"],"+
"\"key2\":" +
"{\"key1\":\"val1\",\"key2\":" +
"{\"key2\":\"val2\"}" +
"},"+
"\"key3\":" +
"[" +
"[1,2.1]" +
"," +
"[null]" +
"]"+
"}";
String jsonObject1Str =
"{\n" +
" \"key1\": [\n" +
" 1,\n" +
" 2,\n" +
" {\"key3\": true}\n" +
" ],\n" +
" \"key2\": {\n" +
" \"key1\": \"val1\",\n" +
" \"key2\": {\"key2\": \"val2\"}\n" +
" },\n" +
" \"key3\": [\n" +
" [\n" +
" 1,\n" +
" 2.1\n" +
" ],\n" +
" [null]\n" +
" ]\n" +
"}";
String jsonObject4Str =
"{\n" +
" \"key1\": [\n" +
" 1,\n" +
" 2,\n" +
" {\"key3\": true}\n" +
" ],\n" +
" \"key2\": {\n" +
" \"key1\": \"val1\",\n" +
" \"key2\": {\"key2\": \"val2\"}\n" +
" },\n" +
" \"key3\": [\n" +
" [\n" +
" 1,\n" +
" 2.1\n" +
" ],\n" +
" [null]\n" +
" ]\n" +
"}";
JSONObject jsonObject = new JSONObject(jsonObject0Str);
assertEquals("toString()",jsonObject0Str, jsonObject.toString());
assertEquals("toString(0)",jsonObject0Str, jsonObject.toString(0));
assertEquals("toString(1)",jsonObject1Str, jsonObject.toString(1));
assertEquals("toString(4)",jsonObject4Str, jsonObject.toString(4));
JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject()));
assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2));
}
/**
* Explores how JSONObject handles maps. Insert a string/string map
* as a value in a JSONObject. It will remain a map. Convert the
* JSONObject to string, then create a new JSONObject from the string.
* In the new JSONObject, the value will be stored as a nested JSONObject.
* Confirm that map and nested JSONObject have the same contents.
*/
@Test
public void jsonObjectToStringSuppressWarningOnCastToMap() {
JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("abc", "def");
jsonObject.put("key", map);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1);
assertTrue("expected def", "def".equals(jsonObject.query("/key/abc")));
}
/**
* Explores how JSONObject handles collections. Insert a string collection
* as a value in a JSONObject. It will remain a collection. Convert the
* JSONObject to string, then create a new JSONObject from the string.
* In the new JSONObject, the value will be stored as a nested JSONArray.
* Confirm that collection and nested JSONArray have the same contents.
*/
@Test
public void jsonObjectToStringSuppressWarningOnCastToCollection() {
JSONObject jsonObject = new JSONObject();
Collection<String> collection = new ArrayList<String>();
collection.add("abc");
// ArrayList will be added as an object
jsonObject.put("key", collection);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1);
assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0")));
}
/**
* Exercises the JSONObject.valueToString() method for various types
*/
@Test
public void valueToString() {
assertTrue("null valueToString() incorrect",
"null".equals(JSONObject.valueToString(null)));
MyJsonString jsonString = new MyJsonString();
assertTrue("jsonstring valueToString() incorrect",
"my string".equals(JSONObject.valueToString(jsonString)));
assertTrue("boolean valueToString() incorrect",
"true".equals(JSONObject.valueToString(Boolean.TRUE)));
assertTrue("non-numeric double",
"null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY)));
String jsonObjectStr =
"{"+
"\"key1\":\"val1\","+
"\"key2\":\"val2\","+
"\"key3\":\"val3\""+
"}";
JSONObject jsonObject = new JSONObject(jsonObjectStr);
assertTrue("jsonObject valueToString() incorrect",
JSONObject.valueToString(jsonObject).equals(jsonObject.toString()));
String jsonArrayStr =
"[1,2,3]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
assertTrue("jsonArray valueToString() incorrect",
JSONObject.valueToString(jsonArray).equals(jsonArray.toString()));
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "val1");
map.put("key2", "val2");
map.put("key3", "val3");
assertTrue("map valueToString() incorrect",
jsonObject.toString().equals(JSONObject.valueToString(map)));
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(new Integer(1));
collection.add(new Integer(2));
collection.add(new Integer(3));
assertTrue("collection valueToString() expected: "+
jsonArray.toString()+ " actual: "+
JSONObject.valueToString(collection),
jsonArray.toString().equals(JSONObject.valueToString(collection)));
Integer[] array = { new Integer(1), new Integer(2), new Integer(3) };
assertTrue("array valueToString() incorrect",
jsonArray.toString().equals(JSONObject.valueToString(array)));
}
@SuppressWarnings("boxing")
@Test
public void valueToStringConfirmException() {
Map<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(1, "myValue");
// this is the test, it should not throw an exception
String str = JSONObject.valueToString(myMap);
// confirm result, just in case
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str);
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1")));
}
/**
* Exercise the JSONObject wrap() method. Sometimes wrap() will change
* the object being wrapped, other times not. The purpose of wrap() is
* to ensure the value is packaged in a way that is compatible with how
* a JSONObject value or JSONArray value is supposed to be stored.
*/
@Test
public void wrapObject() {
// wrap(null) returns NULL
assertTrue("null wrap() incorrect",
JSONObject.NULL == JSONObject.wrap(null));
// wrap(Integer) returns Integer
Integer in = new Integer(1);
assertTrue("Integer wrap() incorrect",
in == JSONObject.wrap(in));
/**
* This test is to document the preferred behavior if BigDecimal is
* supported. Previously bd returned as a string, since it
* is recognized as being a Java package class. Now with explicit
* support for big numbers, it remains a BigDecimal
*/
Object bdWrap = JSONObject.wrap(BigDecimal.ONE);
assertTrue("BigDecimal.ONE evaluates to ONE",
bdWrap.equals(BigDecimal.ONE));
// wrap JSONObject returns JSONObject
String jsonObjectStr =
"{"+
"\"key1\":\"val1\","+
"\"key2\":\"val2\","+
"\"key3\":\"val3\""+
"}";
JSONObject jsonObject = new JSONObject(jsonObjectStr);
assertTrue("JSONObject wrap() incorrect",
jsonObject == JSONObject.wrap(jsonObject));
// wrap collection returns JSONArray
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(new Integer(1));
collection.add(new Integer(2));
collection.add(new Integer(3));
JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection));
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1")));
assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2")));
// wrap Array returns JSONArray
Integer[] array = { new Integer(1), new Integer(2), new Integer(3) };
JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array));
// validate JSON
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1")));
assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2")));
// validate JSON
doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString());
assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1")));
assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2")));
// wrap map returns JSONObject
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "val1");
map.put("key2", "val2");
map.put("key3", "val3");
JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map));
// validate JSON
doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1")));
assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2")));
assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3")));
}
/**
* RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways.
*/
@Test
public void jsonObjectParseControlCharacters(){
for(int i = 0;i<=0x001f;i++){
final String charString = String.valueOf((char)i);
final String source = "{\"key\":\""+charString+"\"}";
try {
JSONObject jo = new JSONObject(source);
assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key")));
} catch (JSONException ex) {
assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error",
i=='\0' || i=='\n' || i=='\r'
);
}
}
}
/**
* Explore how JSONObject handles parsing errors.
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectParsingErrors() {
try {
// does not start with '{'
String str = "abc";
assertNull("Expected an exception",new JSONObject(str));
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"A JSONObject text must begin with '{' at 1 [character 2 line 1]",
e.getMessage());
}
try {
// does not end with '}'
String str = "{";
assertNull("Expected an exception",new JSONObject(str));
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"A JSONObject text must end with '}' at 1 [character 2 line 1]",
e.getMessage());
}
try {
// key with no ':'
String str = "{\"myKey\" = true}";
assertNull("Expected an exception",new JSONObject(str));
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Expected a ':' after a key at 10 [character 11 line 1]",
e.getMessage());
}
try {
// entries with no ',' separator
String str = "{\"myKey\":true \"myOtherKey\":false}";
assertNull("Expected an exception",new JSONObject(str));
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Expected a ',' or '}' at 15 [character 16 line 1]",
e.getMessage());
}
try {
// append to wrong key
String str = "{\"myKey\":true, \"myOtherKey\":false}";
JSONObject jsonObject = new JSONObject(str);
jsonObject.append("myKey", "hello");
fail("Expected an exception");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"JSONObject[myKey] is not a JSONArray.",
e.getMessage());
}
try {
// increment wrong key
String str = "{\"myKey\":true, \"myOtherKey\":false}";
JSONObject jsonObject = new JSONObject(str);
jsonObject.increment("myKey");
fail("Expected an exception");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Unable to increment [\"myKey\"].",
e.getMessage());
}
try {
// invalid key
String str = "{\"myKey\":true, \"myOtherKey\":false}";
JSONObject jsonObject = new JSONObject(str);
jsonObject.get(null);
fail("Expected an exception");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Null key.",
e.getMessage());
}
try {
// invalid numberToString()
JSONObject.numberToString((Number)null);
fail("Expected an exception");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Null pointer",
e.getMessage());
}
try {
// null put key
JSONObject jsonObject = new JSONObject("{}");
jsonObject.put(null, 0);
fail("Expected an exception");
} catch (NullPointerException ignored) {
}
try {
// multiple putOnce key
JSONObject jsonObject = new JSONObject("{}");
jsonObject.putOnce("hello", "world");
jsonObject.putOnce("hello", "world!");
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("", true);
}
try {
// test validity of invalid double
JSONObject.testValidity(Double.NaN);
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("", true);
}
try {
// test validity of invalid float
JSONObject.testValidity(Float.NEGATIVE_INFINITY);
fail("Expected an exception");
} catch (JSONException e) {
assertTrue("", true);
}
}
/**
* Confirm behavior when putOnce() is called with null parameters
*/
@Test
public void jsonObjectPutOnceNull() {
JSONObject jsonObject = new JSONObject();
jsonObject.putOnce(null, null);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* Exercise JSONObject opt(key, default) method.
*/
@Test
public void jsonObjectOptDefault() {
String str = "{\"myKey\": \"myval\", \"hiKey\": null}";
JSONObject jsonObject = new JSONObject(str);
assertTrue("optBigDecimal() should return default BigDecimal",
BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0);
assertTrue("optBigInteger() should return default BigInteger",
BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0);
assertTrue("optBoolean() should return default boolean",
jsonObject.optBoolean("myKey", true));
assertTrue("optInt() should return default int",
42 == jsonObject.optInt("myKey", 42));
assertTrue("optEnum() should return default Enum",
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONObject() should return null ",
null==jsonObject.optJSONObject("myKey"));
assertTrue("optLong() should return default long",
42l == jsonObject.optLong("myKey", 42l));
assertTrue("optDouble() should return default double",
42.3d == jsonObject.optDouble("myKey", 42.3d));
assertTrue("optFloat() should return default float",
42.3f == jsonObject.optFloat("myKey", 42.3f));
assertTrue("optNumber() should return default Number",
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi")));
}
/**
* Exercise JSONObject opt(key, default) method when the key doesn't exist.
*/
@Test
public void jsonObjectOptNoKey() {
JSONObject jsonObject = new JSONObject();
assertNull(jsonObject.opt(null));
assertTrue("optBigDecimal() should return default BigDecimal",
BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0);
assertTrue("optBigInteger() should return default BigInteger",
BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0);
assertTrue("optBoolean() should return default boolean",
jsonObject.optBoolean("myKey", true));
assertTrue("optInt() should return default int",
42 == jsonObject.optInt("myKey", 42));
assertTrue("optEnum() should return default Enum",
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONObject() should return null ",
null==jsonObject.optJSONObject("myKey"));
assertTrue("optLong() should return default long",
42l == jsonObject.optLong("myKey", 42l));
assertTrue("optDouble() should return default double",
42.3d == jsonObject.optDouble("myKey", 42.3d));
assertTrue("optFloat() should return default float",
42.3f == jsonObject.optFloat("myKey", 42.3f));
assertTrue("optNumber() should return default Number",
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi")));
}
/**
* Verifies that the opt methods properly convert string values.
*/
@Test
public void jsonObjectOptStringConversion() {
JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}");
assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true);
assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false);
assertTrue("unexpected optInt value",jo.optInt("int",0)==123);
assertTrue("unexpected optLong value",jo.optLong("int",0)==123l);
assertTrue("unexpected optDouble value",jo.optDouble("int",0.0d)==123.0d);
assertTrue("unexpected optFloat value",jo.optFloat("int",0.0f)==123.0f);
assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0);
assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0);
assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0);
assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l);
}
/**
* Verifies that the opt methods properly convert string values to numbers and coerce them consistently.
*/
@Test
public void jsonObjectOptCoercion() {
JSONObject jo = new JSONObject("{\"largeNumberStr\":\"19007199254740993.35481234487103587486413587843213584\"}");
// currently the parser doesn't recognize BigDecimal, to we have to put it manually
jo.put("largeNumber", new BigDecimal("19007199254740993.35481234487103587486413587843213584"));
// Test type coercion from larger to smaller
assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumber",null));
assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumber",null));
assertEquals(1.9007199254740992E16, jo.optDouble("largeNumber"),0.0);
assertEquals(1.90071995E16f, jo.optFloat("largeNumber"),0.0f);
assertEquals(19007199254740993l, jo.optLong("largeNumber"));
assertEquals(1874919425, jo.optInt("largeNumber"));
// conversion from a string
assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumberStr",null));
assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumberStr",null));
assertEquals(1.9007199254740992E16, jo.optDouble("largeNumberStr"),0.0);
assertEquals(1.90071995E16f, jo.optFloat("largeNumberStr"),0.0f);
assertEquals(19007199254740993l, jo.optLong("largeNumberStr"));
assertEquals(1874919425, jo.optInt("largeNumberStr"));
// the integer portion of the actual value is larger than a double can hold.
assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumber"));
assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumber"));
assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumberStr"));
assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr"));
assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
}
/**
* Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently.
*/
@Test
public void jsonObjectOptBigDecimal() {
JSONObject jo = new JSONObject().put("int", 123).put("long", 654L)
.put("float", 1.234f).put("double", 2.345d)
.put("bigInteger", new BigInteger("1234"))
.put("bigDecimal", new BigDecimal("1234.56789"))
.put("nullVal", JSONObject.NULL);
assertEquals(new BigDecimal("123"),jo.optBigDecimal("int", null));
assertEquals(new BigDecimal("654"),jo.optBigDecimal("long", null));
assertEquals(new BigDecimal(1.234f),jo.optBigDecimal("float", null));
assertEquals(new BigDecimal(2.345d),jo.optBigDecimal("double", null));
assertEquals(new BigDecimal("1234"),jo.optBigDecimal("bigInteger", null));
assertEquals(new BigDecimal("1234.56789"),jo.optBigDecimal("bigDecimal", null));
assertNull(jo.optBigDecimal("nullVal", null));
}
/**
* Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently.
*/
@Test
public void jsonObjectOptBigInteger() {
JSONObject jo = new JSONObject().put("int", 123).put("long", 654L)
.put("float", 1.234f).put("double", 2.345d)
.put("bigInteger", new BigInteger("1234"))
.put("bigDecimal", new BigDecimal("1234.56789"))
.put("nullVal", JSONObject.NULL);
assertEquals(new BigInteger("123"),jo.optBigInteger("int", null));
assertEquals(new BigInteger("654"),jo.optBigInteger("long", null));
assertEquals(new BigInteger("1"),jo.optBigInteger("float", null));
assertEquals(new BigInteger("2"),jo.optBigInteger("double", null));
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null));
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null));
assertNull(jo.optBigDecimal("nullVal", null));
}
/**
* Confirm behavior when JSONObject put(key, null object) is called
*/
@Test
public void jsonObjectputNull() {
// put null should remove the item.
String str = "{\"myKey\": \"myval\"}";
JSONObject jsonObjectRemove = new JSONObject(str);
jsonObjectRemove.remove("myKey");
assertEquals("jsonObject should be empty",0 ,jsonObjectRemove.length());
JSONObject jsonObjectPutNull = new JSONObject(str);
jsonObjectPutNull.put("myKey", (Object) null);
assertEquals("jsonObject should be empty",0 ,jsonObjectPutNull.length());
}
/**
* Exercise JSONObject quote() method
* This purpose of quote() is to ensure that for strings with embedded
* quotes, the quotes are properly escaped.
*/
@Test
public void jsonObjectQuote() {
String str;
str = "";
String quotedStr;
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped quotes, found "+quotedStr,
"\"\"".equals(quotedStr));
str = "\"\"";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped quotes, found "+quotedStr,
"\"\\\"\\\"\"".equals(quotedStr));
str = "</";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped frontslash, found "+quotedStr,
"\"<\\/\"".equals(quotedStr));
str = "AB\bC";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped backspace, found "+quotedStr,
"\"AB\\bC\"".equals(quotedStr));
str = "ABC\n";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped newline, found "+quotedStr,
"\"ABC\\n\"".equals(quotedStr));
str = "AB\fC";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped formfeed, found "+quotedStr,
"\"AB\\fC\"".equals(quotedStr));
str = "\r";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped return, found "+quotedStr,
"\"\\r\"".equals(quotedStr));
str = "\u1234\u0088";
quotedStr = JSONObject.quote(str);
assertTrue("quote() expected escaped unicode, found "+quotedStr,
"\"\u1234\\u0088\"".equals(quotedStr));
}
/**
* Confirm behavior when JSONObject stringToValue() is called for an
* empty string
*/
@Test
public void stringToValue() {
String str = "";
String valueStr = (String)(JSONObject.stringToValue(str));
assertTrue("stringToValue() expected empty String, found "+valueStr,
"".equals(valueStr));
}
/**
* Confirm behavior when toJSONArray is called with a null value
*/
@Test
public void toJSONArray() {
assertTrue("toJSONArray() with null names should be null",
null == new JSONObject().toJSONArray(null));
}
/**
* Exercise the JSONObject write() method
*/
@Test
public void write() throws IOException {
String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}";
String expectedStr = str;
JSONObject jsonObject = new JSONObject(str);
StringWriter stringWriter = new StringWriter();
try {
String actualStr = jsonObject.write(stringWriter).toString();
assertTrue("write() expected " +expectedStr+
" but found " +actualStr,
expectedStr.equals(actualStr));
} finally {
stringWriter.close();
}
}
/**
* Confirms that exceptions thrown when writing values are wrapped properly.
*/
@Test
public void testJSONWriterException() throws IOException {
final JSONObject jsonObject = new JSONObject();
jsonObject.put("someKey",new BrokenToString());
// test single element JSONObject
try(StringWriter writer = new StringWriter();) {
jsonObject.write(writer).toString();
fail("Expected an exception, got a String value");
} catch (JSONException e) {
assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage());
} catch(Exception e) {
fail("Expected JSONException");
}
//test multiElement
jsonObject.put("somethingElse", "a value");
try (StringWriter writer = new StringWriter()) {
jsonObject.write(writer).toString();
fail("Expected an exception, got a String value");
} catch (JSONException e) {
assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage());
} catch(Exception e) {
fail("Expected JSONException");
}
// test a more complex object
try (StringWriter writer = new StringWriter()) {
new JSONObject()
.put("somethingElse", "a value")
.put("someKey", new JSONArray()
.put(new JSONObject().put("key1", new BrokenToString())))
.write(writer).toString();
fail("Expected an exception, got a String value");
} catch (JSONException e) {
assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage());
} catch(Exception e) {
fail("Expected JSONException");
}
// test a more slightly complex object
try (StringWriter writer = new StringWriter()) {
new JSONObject()
.put("somethingElse", "a value")
.put("someKey", new JSONArray()
.put(new JSONObject().put("key1", new BrokenToString()))
.put(12345)
)
.write(writer).toString();
fail("Expected an exception, got a String value");
} catch (JSONException e) {
assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage());
} catch(Exception e) {
fail("Expected JSONException");
}
}
/**
* Exercise the JSONObject write() method
*/
/*
@Test
public void writeAppendable() {
String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}";
String expectedStr = str;
JSONObject jsonObject = new JSONObject(str);
StringBuilder stringBuilder = new StringBuilder();
Appendable appendable = jsonObject.write(stringBuilder);
String actualStr = appendable.toString();
assertTrue("write() expected " +expectedStr+
" but found " +actualStr,
expectedStr.equals(actualStr));
}
*/
/**
* Exercise the JSONObject write(Writer, int, int) method
*/
@Test
public void write3Param() throws IOException {
String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}";
String str2 =
"{\n" +
" \"key1\": \"value1\",\n" +
" \"key2\": [\n" +
" 1,\n" +
" false,\n" +
" 3.14\n" +
" ]\n" +
" }";
JSONObject jsonObject = new JSONObject(str0);
String expectedStr = str0;
StringWriter stringWriter = new StringWriter();
try {
String actualStr = jsonObject.write(stringWriter,0,0).toString();
assertEquals(expectedStr, actualStr);
} finally {
stringWriter.close();
}
expectedStr = str2;
stringWriter = new StringWriter();
try {
String actualStr = jsonObject.write(stringWriter,2,1).toString();
assertEquals(expectedStr, actualStr);
} finally {
stringWriter.close();
}
}
/**
* Exercise the JSONObject write(Appendable, int, int) method
*/
/*
@Test
public void write3ParamAppendable() {
String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}";
String str2 =
"{\n" +
" \"key1\": \"value1\",\n" +
" \"key2\": [\n" +
" 1,\n" +
" false,\n" +
" 3.14\n" +
" ]\n" +
" }";
JSONObject jsonObject = new JSONObject(str0);
String expectedStr = str0;
StringBuilder stringBuilder = new StringBuilder();
Appendable appendable = jsonObject.write(stringBuilder,0,0);
String actualStr = appendable.toString();
assertEquals(expectedStr, actualStr);
expectedStr = str2;
stringBuilder = new StringBuilder();
appendable = jsonObject.write(stringBuilder,2,1);
actualStr = appendable.toString();
assertEquals(expectedStr, actualStr);
}
*/
/**
* Exercise the JSONObject equals() method
*/
@Test
public void equals() {
String str = "{\"key\":\"value\"}";
JSONObject aJsonObject = new JSONObject(str);
assertTrue("Same JSONObject should be equal to itself",
aJsonObject.equals(aJsonObject));
}
/**
* JSON null is not the same as Java null. This test examines the differences
* in how they are handled by JSON-java.
*/
@Test
public void jsonObjectNullOperations() {
/**
* The Javadoc for JSONObject.NULL states:
* "JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls
* undefined."
*
* Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc):
* undefined value: primitive value used when a variable has not been assigned a value
* Undefined type: type whose sole value is the undefined value
* null value: primitive value that represents the intentional absence of any object value
* Null type: type whose sole value is the null value
* Java SE8 language spec (included to help explain the javadoc):
* The Kinds of Types and Values ...
* There is also a special null type, the type of the expression null, which has no name.
* Because the null type has no name, it is impossible to declare a variable of the null
* type or to cast to the null type. The null reference is the only possible value of an
* expression of null type. The null reference can always be assigned or cast to any reference type.
* In practice, the programmer can ignore the null type and just pretend that null is merely
* a special literal that can be of any reference type.
* Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008
* No mention of null
* ECMA-404 1st Edition / October 2013:
* JSON Text ...
* These are three literal name tokens: ...
* null
*
* There seems to be no best practice to follow, it's all about what we
* want the code to do.
*/
// add JSONObject.NULL then convert to string in the manner of XML.toString()
JSONObject jsonObjectJONull = new JSONObject();
Object obj = JSONObject.NULL;
jsonObjectJONull.put("key", obj);
Object value = jsonObjectJONull.opt("key");
assertTrue("opt() JSONObject.NULL should find JSONObject.NULL",
obj.equals(value));
value = jsonObjectJONull.get("key");
assertTrue("get() JSONObject.NULL should find JSONObject.NULL",
obj.equals(value));
if (value == null) {
value = "";
}
String string = value instanceof String ? (String)value : null;
assertTrue("XML toString() should convert JSONObject.NULL to null",
string == null);
// now try it with null
JSONObject jsonObjectNull = new JSONObject();
obj = null;
jsonObjectNull.put("key", obj);
value = jsonObjectNull.opt("key");
assertNull("opt() null should find null", value);
// what is this trying to do? It appears to test absolutely nothing...
// if (value == null) {
// value = "";
// string = value instanceof String ? (String)value : null;
// assertTrue("should convert null to empty string", "".equals(string));
try {
value = jsonObjectNull.get("key");
fail("get() null should throw exception");
} catch (Exception ignored) {}
/**
* XML.toString() then goes on to do something with the value
* if the key val is "content", then value.toString() will be
* called. This will evaluate to "null" for JSONObject.NULL,
* and the empty string for null.
* But if the key is anything else, then JSONObject.NULL will be emitted
* as <key>null</key> and null will be emitted as ""
*/
String sJONull = XML.toString(jsonObjectJONull);
assertTrue("JSONObject.NULL should emit a null value",
"<key>null</key>".equals(sJONull));
String sNull = XML.toString(jsonObjectNull);
assertTrue("null should emit an empty string", "".equals(sNull));
}
@Test(expected = JSONPointerException.class)
public void queryWithNoResult() {
new JSONObject().query("/a/b");
}
@Test
public void optQueryWithNoResult() {
assertNull(new JSONObject().optQuery("/a/b"));
}
@Test(expected = IllegalArgumentException.class)
public void optQueryWithSyntaxError() {
new JSONObject().optQuery("invalid");
}
@Test(expected = JSONException.class)
public void invalidEscapeSequence() {
String json = "{ \"\\url\": \"value\" }";
assertNull("Expected an exception",new JSONObject(json));
}
/**
* Exercise JSONObject toMap() method.
*/
@Test
public void toMap() {
String jsonObjectStr =
"{" +
"\"key1\":" +
"[1,2," +
"{\"key3\":true}" +
"]," +
"\"key2\":" +
"{\"key1\":\"val1\",\"key2\":" +
"{\"key2\":null}," +
"\"key3\":42" +
"}," +
"\"key3\":" +
"[" +
"[\"value1\",2.1]" +
"," +
"[null]" +
"]" +
"}";
JSONObject jsonObject = new JSONObject(jsonObjectStr);
Map<?,?> map = jsonObject.toMap();
assertTrue("Map should not be null", map != null);
assertTrue("Map should have 3 elements", map.size() == 3);
List<?> key1List = (List<?>)map.get("key1");
assertTrue("key1 should not be null", key1List != null);
assertTrue("key1 list should have 3 elements", key1List.size() == 3);
assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1)));
assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2)));
Map<?,?> key1Value3Map = (Map<?,?>)key1List.get(2);
assertTrue("Map should not be null", key1Value3Map != null);
assertTrue("Map should have 1 element", key1Value3Map.size() == 1);
assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE));
Map<?,?> key2Map = (Map<?,?>)map.get("key2");
assertTrue("key2 should not be null", key2Map != null);
assertTrue("key2 map should have 3 elements", key2Map.size() == 3);
assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1"));
assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42)));
Map<?,?> key2Val2Map = (Map<?,?>)key2Map.get("key2");
assertTrue("key2 map key 2 should not be null", key2Val2Map != null);
assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2"));
assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null);
List<?> key3List = (List<?>)map.get("key3");
assertTrue("key3 should not be null", key3List != null);
assertTrue("key3 list should have 3 elements", key3List.size() == 2);
List<?> key3Val1List = (List<?>)key3List.get(0);
assertTrue("key3 list val 1 should not be null", key3Val1List != null);
assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2);
assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1"));
assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1")));
List<?> key3Val2List = (List<?>)key3List.get(1);
assertTrue("key3 list val 2 should not be null", key3Val2List != null);
assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1);
assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null);
// Assert that toMap() is a deep copy
jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1");
assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1"));
// assert that the new map is mutable
assertTrue("Removing a key should succeed", map.remove("key3") != null);
assertTrue("Map should have 2 elements", map.size() == 2);
}
/**
* test class for verifying write errors.
* @author John Aylward
*
*/
private static class BrokenToString {
@Override
public String toString() {
throw new IllegalStateException("Something went horribly wrong!");
}
}
}
|
package model;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.Logger;
import play.libs.Json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Match extends UntypedActor {
private final ActorRef out;
public static int idCnt = 0;
public static Map<Integer, ActorRef> outMap = new HashMap<>();
public static List<Integer> waitList = new ArrayList<>();
public static Props props(ActorRef out) {
Logger.info("Match: props()");
return Props.create(Match.class, out);
}
public Match(ActorRef out) {
Logger.info("Match: Match()");
this.out = out;
idCnt++;
outMap.put(idCnt, out);
// send id
ObjectNode authResult = Json.newObject();
authResult.put("cmd", "authResult");
authResult.put("id", idCnt);
out.tell(authResult.toString(), self());
}
@Override
public void onReceive(Object obj) throws Exception {
Logger.info("Match: onReceive(): [obj: " + obj.toString() + "]");
Logger.info("Match: onReceive(): [self(): " + self() + "] [sender(): " + sender() + "]");
Logger.info("Match: onReceive(): [self().path(): " + self().path() + "] [sender().path(): " + sender().path() + "]");
if (obj instanceof String) {
JsonNode json = Json.parse(obj.toString());
String cmd = json.get("cmd").asText();
if (cmd.equals("match")) {
if (waitList.size() == 0) {
waitList.add(json.get("id").asInt());
ObjectNode matchResult = Json.newObject();
matchResult.put("cmd", "matchResult");
matchResult.put("state", "wait");
out.tell(matchResult.toString(), self());
} else {
int enemyId = waitList.get(0);
waitList.remove(0);
ActorRef enemyOut = outMap.get(enemyId);
ObjectNode matchResult = Json.newObject();
matchResult.put("cmd", "matchResult");
matchResult.put("state", "match");
matchResult.put("gameServerUrl", "ws://xxx/");
matchResult.put("enemyId", enemyId);
out.tell(matchResult.toString(), self());
matchResult.put("enemyId", json.get("id").asInt());
enemyOut.tell(matchResult.toString(), self());
}
} else {
out.tell("unknown command: " + cmd, self());
}
}
}
@Override
public void postStop() throws Exception {
Logger.info("Match: postStop()");
}
}
|
package uk.co.omegaprime;
import au.com.bytecode.opencsv.CSVReader;
import uk.co.omegaprime.thunder.*;
import uk.co.omegaprime.thunder.schema.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.zip.ZipInputStream;
public class BitemporalSparseLoader {
private static final Schema<String> ID_BB_GLOBAL_SCHEMA = new Latin1StringSchema(20);
private static final Schema<Integer> SOURCE_ID_SCHEMA = IntegerSchema.INSTANCE;
public static class SourceTemporalFieldKey {
public static Schema<SourceTemporalFieldKey> SCHEMA = Schema.zipWith(ID_BB_GLOBAL_SCHEMA, SourceTemporalFieldKey::getIDBBGlobal,
SOURCE_ID_SCHEMA, SourceTemporalFieldKey::getSourceID,
SourceTemporalFieldKey::new);
private final String idBBGlobal;
private final int sourceID;
public SourceTemporalFieldKey(String idBBGlobal, int sourceID) {
this.idBBGlobal = idBBGlobal;
this.sourceID = sourceID;
}
public String getIDBBGlobal() { return idBBGlobal; }
public int getSourceID() { return sourceID; }
}
public static class SparseSourceTemporalFieldValue<T> {
public static <T> Schema<SparseSourceTemporalFieldValue<T>> schema(Schema<T> tSchema) {
return Schema.zipWith(Schema.nullable(IntegerSchema.INSTANCE), SparseSourceTemporalFieldValue::getToSourceID,
tSchema, SparseSourceTemporalFieldValue::getValue,
SparseSourceTemporalFieldValue::new);
}
private final Integer toSourceID;
private final T value;
public SparseSourceTemporalFieldValue(Integer toSourceID, T value) {
this.toSourceID = toSourceID;
this.value = value;
}
public Integer getToSourceID() { return toSourceID; }
public T getValue() { return value; }
}
// TODO: the interface of this is inconsistent with SparseTemporalCursor. With STC you setPosition
// but don't learn about whether you are positioned or not until you actually do an operation,
// with this one you moveTo and then immediately learn whether you are positioned or not.
public static class SparseSourceTemporalCursor<V> {
private final Cursor<SourceTemporalFieldKey, SparseSourceTemporalFieldValue<V>> cursor;
private final SubcursorView<String, Integer, SparseSourceTemporalFieldValue<V>> subcursor;
private final int currentSourceID;
private boolean positioned;
public SparseSourceTemporalCursor(Cursor<SourceTemporalFieldKey, SparseSourceTemporalFieldValue<V>> cursor, int currentSourceID) {
this.cursor = cursor;
this.subcursor = new SubcursorView<>(cursor, ID_BB_GLOBAL_SCHEMA, SOURCE_ID_SCHEMA);
this.currentSourceID = currentSourceID;
}
public boolean moveTo(String idBBGlobal) {
positioned = false;
subcursor.setPosition(idBBGlobal);
if (subcursor.moveFloor(currentSourceID)) {
final SparseSourceTemporalFieldValue<V> value = subcursor.getValue();
if (value.getToSourceID() == null || value.getToSourceID() > currentSourceID) {
positioned = true;
}
}
return positioned;
}
public String getKey() {
return cursor.getKey().getIDBBGlobal();
}
public V getValue() {
if (!positioned) throw new IllegalStateException("May not getValue() if we aren't positioned");
return subcursor.getValue().getValue();
}
public boolean delete() {
if (positioned) {
subcursor.put(new SparseSourceTemporalFieldValue<V>(currentSourceID, getValue()));
positioned = false;
return true;
} else {
return false;
}
}
public V put(V value) {
final V existingValue;
if (positioned) {
existingValue = getValue();
if (Objects.equals(existingValue, value)) {
return value;
}
subcursor.put(new SparseSourceTemporalFieldValue<V>(currentSourceID, existingValue));
} else {
existingValue = null;
}
subcursor.put(currentSourceID, new SparseSourceTemporalFieldValue<>(null, value));
return existingValue;
}
private boolean isAlive() {
SparseSourceTemporalFieldValue<V> temporalValue = cursor.getValue();
return (cursor.getKey().getSourceID() <= currentSourceID && (temporalValue.getToSourceID() == null || temporalValue.getToSourceID() > currentSourceID));
}
private boolean scanForwardForAlive() {
do {
if (isAlive()) {
subcursor.setPosition(cursor.getKey().getIDBBGlobal());
return true;
}
} while (cursor.moveNext());
return false;
}
public boolean moveFirst() { return cursor.moveFirst() && scanForwardForAlive(); }
public boolean moveNext() { return cursor.moveNext() && scanForwardForAlive(); }
}
public static class TemporalFieldKey {
public static Schema<TemporalFieldKey> SCHEMA;
static {
final Schema<Pair<String, LocalDate>> SCHEMA0 = Schema.zip(new Latin1StringSchema(20), LocalDateSchema.INSTANCE);
SCHEMA = Schema.zipWith(SCHEMA0, (TemporalFieldKey key) -> new Pair<>(key.getIDBBGlobal(), key.getDate()),
IntegerSchema.INSTANCE, TemporalFieldKey::getSourceID,
(Pair<String, LocalDate> pair, Integer sourceID) -> new TemporalFieldKey(pair.k, pair.v, sourceID));
}
private final String idBBGlobal;
private final LocalDate date;
private final int sourceID;
public TemporalFieldKey(String idBBGlobal, LocalDate date, int sourceID) {
this.idBBGlobal = idBBGlobal;
this.date = date;
this.sourceID = sourceID;
}
public String getIDBBGlobal() { return idBBGlobal; }
public LocalDate getDate() { return date; }
public int getSourceID() { return sourceID; }
}
public static class SparseTemporalFieldValue<V> {
public static <T> Schema<SparseTemporalFieldValue<T>> schema(Schema<T> tSchema) {
final Schema<Pair<LocalDate, Integer>> SCHEMA0 = Schema.<LocalDate, Integer>zip(Schema.nullable(LocalDateSchema.INSTANCE), Schema.nullable(IntegerSchema.INSTANCE));
return Schema.zipWith(SCHEMA0, (SparseTemporalFieldValue<T> value) -> new Pair<>(value.getToDate(), value.getToSourceID()),
tSchema, SparseTemporalFieldValue::getValue,
(Pair<LocalDate, Integer> pair, T value) -> new SparseTemporalFieldValue<>(pair.k, pair.v, value));
}
private final LocalDate toDate;
private final Integer toSourceID;
private final V value;
public SparseTemporalFieldValue(LocalDate toDate, Integer toSourceID, V value) {
this.toDate = toDate;
this.toSourceID = toSourceID;
this.value = value;
}
public LocalDate getToDate() { return toDate; }
public Integer getToSourceID() { return toSourceID; } // Invariant: must not be greater than the maximum source ID
public V getValue() { return value; }
public SparseTemporalFieldValue<V> setToDate(LocalDate toDate) { return new SparseTemporalFieldValue<>(toDate, toSourceID, value); }
// NB: assumes that LKD is a monotonically increasing function of sourceID
// NB: this is an estimate in that it may return a maximum that is higher than the true value: it is guaranteed
// to never return one lower than the true value. (This can happen when toSourceID < the maximum source ID, in
// which case our maxAchievableLKD may be higher than what is achievable in reality since we only work with the
// penultimateSourceLKD here rather than the full mapping from source ID to LKD.)
public LocalDate estimateMaximumToDate(LocalDate penultimateSourceLKD, LocalDate maxSourceLKD) {
if (maxSourceLKD == null) throw new IllegalArgumentException("maxSourceLKD argument must not be null, though penultimateSourceLKD may be");
final LocalDate maxAchievableLKD = (toSourceID == null || penultimateSourceLKD == null) ? maxSourceLKD : penultimateSourceLKD;
return (toDate == null || maxAchievableLKD.isBefore(toDate)) ? maxAchievableLKD : toDate;
}
}
public static class SparseTemporalCursor<V> {
private final Cursor<TemporalFieldKey, SparseTemporalFieldValue<V>> cursor;
private final int currentSourceID;
private final SubcursorView<String, Pair<LocalDate, Integer>, SparseTemporalFieldValue<V>> subcursor;
private final Cursorlike<Pair<LocalDate, Integer>, SparseTemporalFieldValue<V>> subcursorForCurrentSourceID;
private LocalDate lastKnownDate;
private LocalDate priorLastKnownDate;
public SparseTemporalCursor(Cursor<TemporalFieldKey, SparseTemporalFieldValue<V>> cursor, int currentSourceID) {
this.cursor = cursor;
this.currentSourceID = currentSourceID;
this.subcursor = new SubcursorView<>(cursor, ID_BB_GLOBAL_SCHEMA, Schema.zip(LocalDateSchema.INSTANCE, SOURCE_ID_SCHEMA));
this.subcursorForCurrentSourceID = new FilteredView<>(subcursor, this::isValidAtCurrentSource);
}
private boolean isValidAtCurrentSource(Pair<LocalDate, Integer> key, SparseTemporalFieldValue<V> value) {
return key.v <= currentSourceID && (value.toSourceID == null || value.toSourceID > currentSourceID);
}
public void setPosition(String idBBGlobal, LocalDate priorLastKnownDate, LocalDate lastKnownDate) {
this.subcursor.setPosition(idBBGlobal);
this.priorLastKnownDate = priorLastKnownDate;
this.lastKnownDate = lastKnownDate;
}
public boolean moveTo(LocalDate date) {
if (!this.subcursorForCurrentSourceID.moveFloor(new Pair<>(date, currentSourceID))) {
return false;
} else {
final LocalDate toDate = this.subcursorForCurrentSourceID.getValue().getToDate();
return toDate == null || toDate.isAfter(date);
}
}
public void put(LocalDate date, V value) {
putDelete(date, Maybe.of(value));
}
public void delete(LocalDate date) {
putDelete(date, Maybe.empty());
}
// TODO: currently this assumes that the currentSourceID is the maximum one. Should document that this is the only supported mode. (get maybe could support more though?)
private void putDelete(LocalDate date, Maybe<V> value) {
if (subcursor.moveFloor(new Pair<>(date, currentSourceID))) {
boolean found = false;
Pair<LocalDate, Integer> existingFieldKey;
SparseTemporalFieldValue<V> existingFieldValue = null;
do {
existingFieldKey = subcursor.getKey();
if (subcursor.getKey().k.isAfter(date)) {
break;
}
existingFieldValue = cursor.getValue();
if (existingFieldValue.getToDate() == null || existingFieldValue.getToDate().isAfter(date)) {
if (existingFieldValue.getToSourceID() == null) {
found = true;
break;
}
}
} while (subcursor.moveNext());
if (found) {
if (value.isPresent() && existingFieldValue.getValue().equals(value.get())) {
return;
}
// This range intersects the date we are trying to add
// We already have a tuple in the DB of the form (FromSource, ToSource, FromDate, ToDate):
// (S_f, null, F, T) -> v
// We need to split this into at most 4 tuples:
// 1. (S_f, null, F, D) -> v
// 2. (S_f, null, D+1, T) -> v
// 3. (S_f, S, D, D+1) -> v
// 4. (S, null, D, D+1) -> v'
// Where:
// a) Any tuple may be omitted if FromDate >= min(ToDate, max(LKBD( [FromSource, ISNULL(ToSource, S)) ))
// b) The D+1 ToDate for tuple 3 may be set to null if D+1 is > max(LKBD( [FromSource, S) ))
// c) Tuple 3 may be omitted if S_f >= S
// d) The D+1 ToDate for tuple 4 may be set to null if D+1 is > the LKBD for S
{
// Tuple 1
final SparseTemporalFieldValue<V> proposedValue = new SparseTemporalFieldValue<>(date, null, existingFieldValue.getValue());
if (existingFieldKey.k.isBefore(proposedValue.estimateMaximumToDate(priorLastKnownDate, lastKnownDate))) {
subcursor.put(proposedValue);
} else {
subcursor.delete();
}
}
// Tuple 2
if (date.plusDays(1).isBefore(existingFieldValue.estimateMaximumToDate(priorLastKnownDate, lastKnownDate))) {
subcursor.put(new Pair<>(date.plusDays(1), existingFieldKey.v),
existingFieldValue);
}
// Tuple 3
if (existingFieldKey.v < currentSourceID) {
final LocalDate proposedToDate = date.isBefore(priorLastKnownDate) ? date.plusDays(1) : null;
subcursor.put(new Pair<>(date, existingFieldKey.v),
new SparseTemporalFieldValue<V>(proposedToDate, currentSourceID, existingFieldValue.getValue()));
}
}
}
// Tuple 4
if (value.isPresent()) {
final LocalDate proposedToDate = date.isBefore(lastKnownDate) ? date.plusDays(1) : null;
subcursor.put(new Pair<>(date, currentSourceID),
new SparseTemporalFieldValue<V>(proposedToDate, null, value.get()));
}
}
}
public static class Source {
public static final Schema<Source> SCHEMA = Schema.zipWith(new Latin1StringSchema(10), Source::getPartition,
LocalDateSchema.INSTANCE, Source::getDate,
Source::new);
private final String partition;
private final LocalDate date;
public Source(String partition, LocalDate date) {
this.partition = partition;
this.date = date;
}
public String getPartition() { return partition; }
public LocalDate getDate() { return date; }
}
private static LocalDate maxDate(LocalDate a, LocalDate b) {
if (a == null) return b;
if (b == null) return a;
return a.isAfter(b) ? a : b;
}
public static void load(Database db, Transaction tx, LocalDate date, String delivery, ZipInputStream zis) throws IOException {
final CSVReader reader = new CSVReader(new InputStreamReader(zis), '|');
String[] headers = reader.readNext();
if (headers == null || headers.length == 1) {
// Empty file
return;
}
final Cursor<Integer, Source> sourceCursor = db.createIndex(tx, "Source", IntegerSchema.INSTANCE, Source.SCHEMA).createCursor(tx);
final int sourceID = sourceCursor.moveLast() ? sourceCursor.getKey() + 1 : 0;
sourceCursor.put(sourceID, new Source(delivery, date));
final SparseSourceTemporalCursor<String> lastKnownDeliveryCursor = new SparseSourceTemporalCursor<>(db.createIndex(tx, "LastKnownDelivery", SourceTemporalFieldKey.SCHEMA, SparseSourceTemporalFieldValue.schema(new Latin1StringSchema(10))).createCursor(tx), sourceID);
final SparseSourceTemporalCursor<LocalDate> itemLastKnownDateCursor = new SparseSourceTemporalCursor<>(db.createIndex(tx, "ItemLastKnownDate", SourceTemporalFieldKey.SCHEMA, SparseSourceTemporalFieldValue.schema(LocalDateSchema.INSTANCE) ).createCursor(tx), sourceID);
final SparseSourceTemporalCursor<LocalDate> deliveryLastKnownDateCursor = new SparseSourceTemporalCursor<>(db.createIndex(tx, "DeliveryLastKnownDate", SourceTemporalFieldKey.SCHEMA, SparseSourceTemporalFieldValue.schema(LocalDateSchema.INSTANCE) ).createCursor(tx), sourceID); // Actually keyed by delivery, not ID_BB_GLOBAL
// Given:
// * idBBGlobal
// * sourceID
// The last known date of the item is the max of:
// * itemLastKnownDateCursor(sourceID, idBBGlobal)
// * deliveryLastKnownDateCursor(sourceID, lastKnownDeliveryCursor(sourceID, idBBGlobal))
// The last known date monotonically increases as we add more sources to the chain, and
// tells you the final date over which a static field with a missing end date should be valid.
// When we see a new source we update the corresponding deliveryLastKnownDateCursor, which implicitly
// pads forward all statics for anything currently in that delivery. When we change the delivery in
// which a idBBGlobal appears we update itemLastKnownDateCursor to record the LKD in the old delivery.
// This is necessary because the new delivery may have a lower date than the one we are moving from
// but we don't want to reduce the LKD for this idBBGlobal.
deliveryLastKnownDateCursor.moveTo(delivery);
final LocalDate deliveryPriorLastKnownDate = deliveryLastKnownDateCursor.put(date);
int idBBGlobalIx = -1;
final SparseTemporalCursor<String>[] cursors = (SparseTemporalCursor<String>[]) new SparseTemporalCursor[headers.length];
for (int i = 0; i < headers.length; i++) {
if (headers[i].equals("ID_BB_GLOBAL")) {
idBBGlobalIx = i;
} else {
final String indexName = headers[i].replace(" ", "");
final Index<TemporalFieldKey, SparseTemporalFieldValue<String>> index = db.createIndex(tx, indexName, TemporalFieldKey.SCHEMA, SparseTemporalFieldValue.schema(new Latin1StringSchema(64)));
cursors[i] = new SparseTemporalCursor<>(index.createCursor(tx), sourceID);
}
}
if (idBBGlobalIx < 0) {
throw new IllegalArgumentException("No ID_BB_GLOBAL field");
}
int items = 0;
long startTime = System.nanoTime();
final HashSet<String> seenIdBBGlobals = new HashSet<>();
String[] line;
while ((line = reader.readNext()) != null) {
if (line.length < headers.length) {
continue;
}
final String idBBGlobal = line[idBBGlobalIx];
seenIdBBGlobals.add(idBBGlobal);
final LocalDate itemLastKnownDate = itemLastKnownDateCursor.moveTo(idBBGlobal) ? itemLastKnownDateCursor.getValue() : null;
lastKnownDeliveryCursor.moveTo(idBBGlobal);
final String oldDelivery = lastKnownDeliveryCursor.put(delivery);
final LocalDate oldDeliveryPriorLastKnownDate
= delivery.equals(oldDelivery) ? deliveryPriorLastKnownDate
: (oldDelivery != null && deliveryLastKnownDateCursor.moveTo(oldDelivery)) ? deliveryLastKnownDateCursor.getValue()
: null;
final LocalDate priorLastKnownDate = maxDate(oldDeliveryPriorLastKnownDate, itemLastKnownDate);
final LocalDate lastKnownDate = maxDate(priorLastKnownDate, date);
if (oldDelivery != null && !delivery.equals(oldDelivery) && priorLastKnownDate != null) {
itemLastKnownDateCursor.put(priorLastKnownDate);
}
for (int i = 0; i < headers.length; i++) {
if (i == idBBGlobalIx) continue;
final SparseTemporalCursor<String> cursor = cursors[i];
final String value = line[i].trim();
items++;
cursor.setPosition(idBBGlobal, priorLastKnownDate, lastKnownDate);
if (value.length() != 0) {
cursor.put(date, value);
} else {
cursor.delete(date);
}
}
}
/*
if (lastKnownDeliveryCursor.moveFirst()) {
do {
if (lastKnownDeliveryCursor.getKey().getSourceID() <= sourceID) {
final SparseSourceTemporalFieldValue<String> lastKnownDelivery = lastKnownDeliveryCursor.getValue();
if (lastKnownDelivery.getToSourceID() == null || lastKnownDelivery.getToSourceID() > sourceID) {
}
}
} while (lastKnownDeliveryCursor.moveNext());
}
*/
// Kill off any product that we expected to be in this delivery but was not
if (lastKnownDeliveryCursor.moveFirst()) {
do {
final String idBBGlobal = lastKnownDeliveryCursor.getKey();
if (seenIdBBGlobals.contains(idBBGlobal)) continue;
lastKnownDeliveryCursor.put(null);
itemLastKnownDateCursor.moveTo(idBBGlobal);
itemLastKnownDateCursor.put(deliveryPriorLastKnownDate);
} while (lastKnownDeliveryCursor.moveNext());
}
long duration = System.nanoTime() - startTime;
System.out.println("Loaded " + items + " in " + duration + "ns (" + (duration / items) + "ns/item)");
}
}
|
package org.jnosql.artemis.reflection;
import org.jnosql.artemis.PreparedStatement;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
public final class DynamicQueryMethodReturn {
private final Method method;
private final Object[] args;
private final Class<?> typeClass;
private final java.util.function.Function<String, List<?>> queryConverter;
private final Function<String, PreparedStatement> prepareConverter;
private DynamicQueryMethodReturn(Method method, Object[] args, Class<?> typeClass, Function<String, List<?>> queryConverter,
Function<String, PreparedStatement> prepareConverter) {
this.method = method;
this.args = args;
this.typeClass = typeClass;
this.queryConverter = queryConverter;
this.prepareConverter = prepareConverter;
}
public Method getMethod() {
return method;
}
public Object[] getArgs() {
return args;
}
public Class<?> getTypeClass() {
return typeClass;
}
public Function<String, List<?>> getQueryConverter() {
return queryConverter;
}
public Function<String, PreparedStatement> getPrepareConverter() {
return prepareConverter;
}
public static DynamicQueryMethodReturnBuilder builder() {
return new DynamicQueryMethodReturnBuilder();
}
public static class DynamicQueryMethodReturnBuilder {
private Method method;
private Object[] args;
private Class<?> typeClass;
private java.util.function.Function<String, List<?>> queryConverter;
private Function<String, PreparedStatement> prepareConverter;
private DynamicQueryMethodReturnBuilder() {
}
public DynamicQueryMethodReturnBuilder withMethod(Method method) {
this.method = method;
return this;
}
public DynamicQueryMethodReturnBuilder withArgs(Object[] args) {
this.args = args;
return this;
}
public DynamicQueryMethodReturnBuilder withTypeClass(Class<?> typeClass) {
this.typeClass = typeClass;
return this;
}
public DynamicQueryMethodReturnBuilder withQueryConverter(Function<String, List<?>> queryConverter) {
this.queryConverter = queryConverter;
return this;
}
public DynamicQueryMethodReturnBuilder withPrepareConverter(Function<String, PreparedStatement> prepareConverter) {
this.prepareConverter = prepareConverter;
return this;
}
public DynamicQueryMethodReturn build() {
Objects.requireNonNull(method, "method is required");
Objects.requireNonNull(typeClass, "typeClass is required");
Objects.requireNonNull(queryConverter, "queryConverter is required");
Objects.requireNonNull(prepareConverter, "prepareConverter is required");
return new DynamicQueryMethodReturn(method, args, typeClass, queryConverter, prepareConverter);
}
}
}
|
package fi.uta.fsd.metka.storage.repository.impl;
import fi.uta.fsd.Logger;
import fi.uta.fsd.metka.enums.*;
import fi.uta.fsd.metka.model.access.calls.*;
import fi.uta.fsd.metka.model.access.enums.StatusCode;
import fi.uta.fsd.metka.model.configuration.Configuration;
import fi.uta.fsd.metka.model.configuration.Operation;
import fi.uta.fsd.metka.model.data.RevisionData;
import fi.uta.fsd.metka.model.data.change.ContainerChange;
import fi.uta.fsd.metka.model.data.change.RowChange;
import fi.uta.fsd.metka.model.data.container.*;
import fi.uta.fsd.metka.model.data.value.Value;
import fi.uta.fsd.metka.model.general.DateTimeUserPair;
import fi.uta.fsd.metka.model.general.RevisionKey;
import fi.uta.fsd.metka.names.Fields;
import fi.uta.fsd.metka.storage.cascade.CascadeInstruction;
import fi.uta.fsd.metka.storage.cascade.Cascader;
import fi.uta.fsd.metka.storage.entity.RevisionEntity;
import fi.uta.fsd.metka.storage.repository.*;
import fi.uta.fsd.metka.storage.repository.enums.RemoveResult;
import fi.uta.fsd.metka.storage.repository.enums.ReturnResult;
import fi.uta.fsd.metka.storage.response.OperationResponse;
import fi.uta.fsd.metka.storage.response.RevisionableInfo;
import fi.uta.fsd.metka.storage.restrictions.RestrictionValidator;
import fi.uta.fsd.metka.storage.restrictions.ValidateResult;
import fi.uta.fsd.metkaAmqp.Messenger;
import fi.uta.fsd.metkaAmqp.payloads.FileRemovalPayload;
import fi.uta.fsd.metkaAmqp.payloads.RevisionPayload;
import fi.uta.fsd.metkaAuthentication.AuthenticationUtil;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.File;
import java.util.List;
/**
* Performs a removal to given transfer data if possible
*
* Valid results are:
* SUCCESS_DRAFT - Draft was removed successfully, user should be moved to latest approved revision
* SUCCESS_LOGICAL - Logical removal was performed successfully, new up to date data should be loaded for the revision
* SUCCESS_REVISIONABLE - Draft was removed but no further revisions existed for the revisionable so the revisionable was removed also.
* All other return values are errors
* TODO: Should cascaded removals halt the original remove if they fail?
*/
@Repository
public class RevisionRemoveRepositoryImpl implements RevisionRemoveRepository {
@PersistenceContext(name = "entityManager")
private EntityManager em;
@Autowired
private RevisionRepository revisions;
@Autowired
private RevisionRestoreRepository restore;
@Autowired
private RevisionableRepository revisionables;
@Autowired
private ConfigurationRepository configurations;
@Autowired
private RestrictionValidator validator;
@Autowired
private Cascader cascader;
@Autowired
private Messenger messenger;
@Override
public OperationResponse remove(RevisionKey key, DateTimeUserPair info) {
if(info == null) {
info = DateTimeUserPair.build();
}
Pair<ReturnResult, RevisionData> dataPair = revisions.getRevisionData(key);
if(dataPair.getLeft() != ReturnResult.REVISION_FOUND) {
return OperationResponse.build(RemoveResult.ALREADY_REMOVED);
}
if(dataPair.getRight().getState() == RevisionState.DRAFT) {
return removeDraft(key, info);
} else if(dataPair.getRight().getState() == RevisionState.APPROVED) {
RevisionableInfo revInfo = revisions.getRevisionableInfo(key.getId()).getRight();
if(!revInfo.getRemoved()) {
return removeLogical(key, info, false);
}
}
return OperationResponse.build(RemoveResult.ALREADY_REMOVED);
}
@Override
public OperationResponse removeDraft(RevisionKey key, DateTimeUserPair info) {
if(info == null) {
info = DateTimeUserPair.build();
}
Pair<ReturnResult, RevisionData> pair = revisions.getRevisionData(key);
if(pair.getLeft() != ReturnResult.REVISION_FOUND) {
return OperationResponse.build(RemoveResult.NOT_FOUND);
}
RemoveResult result = allowRemoval(pair.getRight());
if(result != RemoveResult.ALLOW_REMOVAL) {
return OperationResponse.build(result);
}
RevisionData data = pair.getRight();
if(data.getState() != RevisionState.DRAFT) {
return OperationResponse.build(RemoveResult.NOT_DRAFT);
}
if(!AuthenticationUtil.isHandler(data)) {
Logger.error(getClass(), "User " + AuthenticationUtil.getUserName() + " tried to remove draft belonging to " + data.getHandler());
return OperationResponse.build(RemoveResult.WRONG_USER);
}
RevisionableInfo revInfo = revisions.getRevisionableInfo(data.getKey().getId()).getRight();
OperationResponse response = validateAndCascade(data, info, OperationType.REMOVE_DRAFT, revInfo);
if(!response.getResult().equals(RemoveResult.ALLOW_REMOVAL.name())) {
return response;
}
RevisionEntity revision = em.find(RevisionEntity.class, fi.uta.fsd.metka.storage.entity.key.RevisionKey.fromModelKey(data.getKey()));
RevisionData revisionData = revisions.getRevisionData(revision.getKey().getRevisionableId(), revision.getKey().getRevisionNo()).getRight();
if (revisionData != null && revisionData.getConfiguration().getType().equals(ConfigurationType.STUDY)) {
checkFileStates(revisions.getRevisionData(revision.getKey().getRevisionableId(), revision.getKey().getRevisionNo()).getRight(), info);
}
if(revision == null) {
Logger.error(getClass(), "Draft revision with key "+data.getKey()+" was slated for removal but was not found from database.");
} else {
revisions.removeRevision(revision.getKey().toModelKey());
}
if(revInfo != null && revInfo.getApproved() == null) {
revisionables.removeRevisionable(data.getKey().getId());
finalizeFinalRevisionRemoval(data, info);
result = RemoveResult.SUCCESS_REVISIONABLE;
} else {
revisionables.updateRevisionableRevisionNumber(data.getKey().getId());
finalizeDraftRemoval(data, info);
result = RemoveResult.SUCCESS_DRAFT;
}
messenger.sendAmqpMessage(messenger.FD_REMOVE, new RevisionPayload(data));
addRemoveIndexCommand(data.getKey(), result);
return OperationResponse.build(result);
}
@Override
public OperationResponse removeLogical(RevisionKey key, DateTimeUserPair info, boolean isCascadeRemove) {
if(info == null) {
info = DateTimeUserPair.build();
}
Pair<ReturnResult, RevisionData> pair = revisions.getRevisionData(key);
if(pair.getLeft() != ReturnResult.REVISION_FOUND) {
return OperationResponse.build(RemoveResult.NOT_FOUND);
}
RemoveResult result;
if (!isCascadeRemove) {
result = allowRemoval(pair.getRight());
if(result != RemoveResult.ALLOW_REMOVAL) {
return OperationResponse.build(result);
}
}
pair = revisions.getRevisionData(key.getId().toString());
// NOTICE: These could be moved to restrictions quite easily
if(pair.getLeft() != ReturnResult.REVISION_FOUND) {
// This should never happen since we found the revision data provided for this method
return OperationResponse.build(RemoveResult.NOT_FOUND);
}
if(pair.getRight().getState() == RevisionState.DRAFT) {
return OperationResponse.build(RemoveResult.OPEN_DRAFT);
}
RevisionData data = pair.getRight();
OperationResponse response = validateAndCascade(data, info, OperationType.REMOVE_LOGICAL, null);
if(!response.getResult().equals(RemoveResult.ALLOW_REMOVAL.name())) {
return response;
}
if(revisionables.logicallyRemoveRevisionable(info, data.getKey().getId())) {
return OperationResponse.build(RemoveResult.ALREADY_REMOVED);
}
/*if(data.getConfiguration().getType() == ConfigurationType.STUDY) {
propagateStudyLogicalRemoval(data);
} else if(data.getConfiguration().getType() == ConfigurationType.STUDY_VARIABLES) {
propagateStudyVariablesLogicalRemoval(data);
}*/
// TODO: What do we do about study errors and binder pages in this case?
finalizeLogicalRemoval(data, info, isCascadeRemove);
result = RemoveResult.SUCCESS_LOGICAL;
messenger.sendAmqpMessage(messenger.FD_REMOVE, new RevisionPayload(data));
addRemoveIndexCommand(data.getKey(), result);
return OperationResponse.build(result);
}
private void finalizeFinalRevisionRemoval(RevisionData data, DateTimeUserPair info) {
switch(data.getConfiguration().getType()) {
case STUDY_ATTACHMENT: {
finalizeFinalStudyAttachmentRevisionRemoval(data, info);
break;
}
case STUDY_VARIABLES: {
finalizeFinalStudyVariablesRevisionRemoval(data, info);
break;
}
case STUDY_VARIABLE: {
finalizeFinalStudyVariableRevisionRemoval(data, info);
break;
}
default: {
break;
}
}
}
private void finalizeFinalStudyVariablesRevisionRemoval(RevisionData data, DateTimeUserPair info) {
// The latest revision for study should always be a draft in this case since we can't create new variables draft without study being a draft
// and if we're performing the final revision removal then there has not been an approve operation between the events
Pair<StatusCode, ValueDataField> fieldPair = data.dataField(ValueDataFieldCall.get(Fields.STUDY));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
Pair<ReturnResult, RevisionData> revPair = revisions.getRevisionData(fieldPair.getRight().getActualValueFor(Language.DEFAULT));
if(revPair.getLeft() == ReturnResult.REVISION_FOUND) {
RevisionData study = revPair.getRight();
Pair<StatusCode, ContainerDataField> conPair = study.dataField(ContainerDataFieldCall.get(Fields.STUDYVARIABLES));
if(conPair.getLeft() == StatusCode.FIELD_FOUND) {
fieldPair = data.dataField(ValueDataFieldCall.get(Fields.LANGUAGE));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND) {
String varLang = fieldPair.getRight().getActualValueFor(Language.DEFAULT);
Pair<StatusCode, DataRow> rowPair = conPair.getRight().getRowWithFieldValue(Language.DEFAULT, Fields.VARIABLESLANGUAGE, new Value(varLang));
if(rowPair.getLeft() == StatusCode.ROW_FOUND) {
conPair.getRight().removeRow(rowPair.getRight().getRowId(), study.getChanges(), info);
revisions.updateRevisionData(study);
}
}
}
}
}
fieldPair = data.dataField(ValueDataFieldCall.get(Fields.FILE));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
Pair<ReturnResult, RevisionData> revPair = revisions.getRevisionData(fieldPair.getRight().getActualValueFor(Language.DEFAULT));
if(revPair.getLeft() == ReturnResult.REVISION_FOUND) {
RevisionData attachment = revPair.getRight();
fieldPair = attachment.dataField(ValueDataFieldCall.get(Fields.VARIABLES));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
attachment.dataField(ValueDataFieldCall.set(Fields.VARIABLES, new Value(""), Language.DEFAULT).setInfo(info));
revisions.updateRevisionData(attachment);
}
}
}
}
private void finalizeFinalStudyVariableRevisionRemoval(RevisionData data, DateTimeUserPair info) {
// The latest revision for study should always be a draft in this case since we can't create new variable draft without study variables being a draft
// and if we're performing the final revision removal then there has not been an approve operation between the events
Pair<StatusCode, ValueDataField> fieldPair = data.dataField(ValueDataFieldCall.get(Fields.VARIABLES));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
Pair<ReturnResult, RevisionData> revPair = revisions.getRevisionData(fieldPair.getRight().getActualValueFor(Language.DEFAULT));
if(revPair.getLeft() == ReturnResult.REVISION_FOUND) {
RevisionData variables = revPair.getRight();
Pair<StatusCode, ReferenceContainerDataField> conPair = variables.dataField(ReferenceContainerDataFieldCall.get(Fields.VARIABLES));
if(conPair.getLeft() == StatusCode.FIELD_FOUND) {
Pair<StatusCode, ReferenceRow> rowPair = conPair.getRight().getReferenceIncludingValue(data.getKey().asPartialKey());
if(rowPair.getLeft() == StatusCode.ROW_FOUND) {
conPair.getRight().removeReference(rowPair.getRight().getRowId(), variables.getChanges(), info);
}
}
ContainerDataField variableGroups = variables.dataField(ContainerDataFieldCall.get(Fields.VARGROUPS)).getRight();
if(variableGroups != null) {
for(DataRow dataRow : variableGroups.getRowsFor(Language.DEFAULT)) {
conPair = dataRow.dataField(ReferenceContainerDataFieldCall.get(Fields.VARGROUPVARS));
if(conPair.getRight() != null) {
// See that respective rows are removed from VARGROUPVARS
// Remove from variables list
ReferenceRow reference = conPair.getRight().getReferenceIncludingValue(data.getKey().asPartialKey()).getRight();
if(reference != null) {
conPair.getRight().removeReference(reference.getRowId(), variables.getChanges(), info).getLeft();
// Since variable should always be only in one group at a time we can break out.
break;
}
}
}
}
revisions.updateRevisionData(variables);
}
}
}
private void finalizeFinalStudyAttachmentRevisionRemoval(RevisionData data, DateTimeUserPair info) {
// The latest revision for study should always be a draft in this case since we can't create new attachment draft without study being a draft
// and if we're performing the final revision removal then there has not been an approve operation between the events
Pair<StatusCode, ValueDataField> fieldPair = data.dataField(ValueDataFieldCall.get(Fields.STUDY));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
Pair<ReturnResult, RevisionData> revPair = revisions.getRevisionData(fieldPair.getRight().getActualValueFor(Language.DEFAULT));
if(revPair.getLeft() == ReturnResult.REVISION_FOUND) {
RevisionData study = revPair.getRight();
Pair<StatusCode, ReferenceContainerDataField> conPair = study.dataField(ReferenceContainerDataFieldCall.get(Fields.FILES));
if(conPair.getLeft() == StatusCode.FIELD_FOUND) {
Pair<StatusCode, ReferenceRow> rowPair = conPair.getRight().getReferenceIncludingValue(data.getKey().asPartialKey());
if(rowPair.getLeft() == StatusCode.ROW_FOUND) {
conPair.getRight().removeReference(rowPair.getRight().getRowId(), study.getChanges(), info);
revisions.updateRevisionData(study);
}
}
}
}
// Remove the associated file as well
if (data.getField(Fields.FILE) != null) {
String path = ((ValueDataField) data.getField(Fields.FILE)).getActualValueFor(Language.DEFAULT);
File file = new File(path);
if (file.exists() && file.isFile()) {
file.delete();
}
}
// TODO: Remove link from study variables if it still exists
}
private void finalizeDraftRemoval(RevisionData data, DateTimeUserPair info) {
switch(data.getConfiguration().getType()) {
case STUDY_ATTACHMENT: {
finalizeStudyAttachmentDraftRemoval(data, info);
break;
}
case STUDY_VARIABLES: {
finalizeStudyVariablesDraftRemoval(data, info);
break;
}
case STUDY_VARIABLE: {
finalizeStudyVariableDraftRemoval(data, info);
break;
}
default: {
break;
}
}
}
private void checkFileStates(RevisionData data, DateTimeUserPair info){
ReferenceContainerDataField files = (ReferenceContainerDataField)data.getField(Fields.FILES);
if (files == null)
return;
Pair<ReturnResult, RevisionData> latestPair = revisions.getRevisionData(data.getKey().getId().toString(), true);
if (!latestPair.getLeft().equals(ReturnResult.REVISION_FOUND))
return;
for (ReferenceRow row: files.getReferences()) {
String fileId = row.getActualValue();
Pair<ReturnResult, RevisionableInfo> currAttachment = revisions.getRevisionableInfo(Long.parseLong(fileId.split("-")[0]));
ValueDataField field = (ValueDataField) latestPair.getRight().getField(Fields.APPROVED_FILES);
if (field == null){
continue;
}
String value = field.getCurrentFor(Language.DEFAULT).getActualValue();
if (value == null ||currAttachment.getLeft().equals(ReturnResult.REVISIONABLE_NOT_FOUND)){
continue;
}
if (value.contains(fileId.split("-")[0]) && currAttachment.getRight().getRemoved()) {
restore.restore(Long.parseLong(fileId.split("-")[0]));
} else if (!field.getCurrentFor(Language.DEFAULT).getActualValue().contains(fileId.split("-")[0]) && !currAttachment.getRight().getRemoved()) {
if (currAttachment.getRight().getApproved() != currAttachment.getRight().getCurrent()){
removeDraft(new RevisionKey(Long.parseLong(fileId.split("-")[0]), Integer.parseInt(fileId.split("-")[1])), info);
}
remove(new RevisionKey(Long.parseLong(fileId.split("-")[0]), Integer.parseInt(fileId.split("-")[1])), info);
}
}
}
private void finalizeStudyAttachmentDraftRemoval(RevisionData data, DateTimeUserPair info) {
List<Integer> revisionNos = revisions.getAllRevisionNumbers(data.getKey().getId()); // Last number is the newest revision
if(revisionNos.isEmpty()) {
return;
}
checkStudyAttachmentStudy(data, info, revisionNos);
checkStudyAttachmentStudyVariables(data, info, revisionNos);
checkStudyAttachmentVariables(data,info);
}
private void checkStudyAttachmentStudy(RevisionData attachment, DateTimeUserPair info, List<Integer> revisionNos) {
ValueDataField field = attachment.dataField(ValueDataFieldCall.get(Fields.STUDY)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
return;
}
RevisionData study = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT)).getRight();
if(study == null) {
return;
}
ReferenceContainerDataField container = study.dataField(ReferenceContainerDataFieldCall.get(Fields.FILES)).getRight();
if(container == null || !container.hasValidRows()) {
return;
}
ReferenceRow row = container.getReferenceWithValue(attachment.getKey().asCongregateKey()).getRight();
if(row == null) {
return;
}
container.replaceRow(row.getRowId(), ReferenceRow.build(container, new Value(attachment.getKey().getId() + "-" + revisionNos.get(revisionNos.size() - 1)), info),
study.getChanges());
revisions.updateRevisionData(study);
}
private void checkStudyAttachmentStudyVariables(RevisionData data, DateTimeUserPair info, List<Integer> revisionNos) {
ValueDataField variablesField = data.dataField(ValueDataFieldCall.get(Fields.VARIABLES)).getRight();
if (variablesField == null) {
return;
}
RevisionData variables = revisions.getRevisionData(variablesField.getActualValueFor(Language.DEFAULT)).getRight();
if(variables == null) {
return;
}
//if attachment reference is not changed , return
if(variables.dataField(ValueDataFieldCall.get(Fields.FILE)).getRight().getActualValueFor(Language.DEFAULT)
.equals(data.getKey().getId() + "-" + revisionNos.get(revisionNos.size() - 1))) {
return;
}
variables.dataField(ValueDataFieldCall.set(Fields.FILE, new Value(data.getKey().getId() + "-" + revisionNos.get(revisionNos.size() - 1)), Language.DEFAULT)
.setInfo(info)
.setChangeMap(variables.getChanges()));
revisions.updateRevisionData(variables);
}
private void checkStudyAttachmentVariables(RevisionData data,DateTimeUserPair info) {
ValueDataField variablesField = data.dataField(ValueDataFieldCall.get(Fields.VARIABLES)).getRight();
if (variablesField == null) {
return;
}
RevisionData variables = revisions.getRevisionData(variablesField.getActualValueFor(Language.DEFAULT)).getRight();
if(variables == null) {
return;
}
ReferenceContainerDataField variablesContainer = variables.dataField(ReferenceContainerDataFieldCall.get(Fields.VARIABLES)).getRight();
List<ReferenceRow> varRows = variablesContainer.getReferences();
for (ReferenceRow row : varRows) {
restore.restore(Long.parseLong(row.getActualValue().split("-")[0]));
}
}
private void finalizeStudyVariableDraftRemoval(RevisionData data, DateTimeUserPair info) {
List<Integer> revisionNos = revisions.getAllRevisionNumbers(data.getKey().getId()); // Last number is the newest revision
if(revisionNos.isEmpty()) {
return;
}
ValueDataField field = data.dataField(ValueDataFieldCall.get(Fields.VARIABLES)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
return;
}
RevisionData variables = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT)).getRight();
if(variables == null) {
return;
}
ReferenceContainerDataField container = variables.dataField(ReferenceContainerDataFieldCall.get(Fields.VARIABLES)).getRight();
if(container == null || !container.hasValidRows()) {
return;
}
ReferenceRow row = container.getReferenceWithValue(data.getKey().asCongregateKey()).getRight();
if(row == null) {
return;
}
container.replaceRow(row.getRowId(), ReferenceRow.build(container, new Value(data.getKey().getId() + "-" + revisionNos.get(revisionNos.size() - 1)), info),
variables.getChanges());
ContainerDataField variableGroups = variables.dataField(ContainerDataFieldCall.get(Fields.VARGROUPS)).getRight();
if(variableGroups != null) {
for(DataRow dataRow : variableGroups.getRowsFor(Language.DEFAULT)) {
container = dataRow.dataField(ReferenceContainerDataFieldCall.get(Fields.VARGROUPVARS)).getRight();
if(container != null) {
// See that respective rows are removed from VARGROUPVARS
// Remove from variables list
ReferenceRow reference = container.getReferenceIncludingValue(data.getKey().asPartialKey()).getRight();
if(reference != null) {
container.replaceRow(reference.getRowId(), ReferenceRow.build(container, new Value(data.getKey().getId() + "-" + revisionNos.get(revisionNos.size() - 1)), info),
variables.getChanges());
// Since variable should always be only in one group at a time we can break out.
break;
}
}
}
}
revisions.updateRevisionData(variables);
}
private void finalizeStudyVariablesDraftRemoval(RevisionData data, DateTimeUserPair info) {
List<Integer> revisionNos = revisions.getAllRevisionNumbers(data.getKey().getId()); // Last number is the newest revision
if(revisionNos.isEmpty()) {
return;
}
ValueDataField field = data.dataField(ValueDataFieldCall.get(Fields.STUDY)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
// Something weird has happened but this is not the place to react to it, just return
return;
}
RevisionData study = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT)).getRight();
if(study == null || study.getState() != RevisionState.DRAFT) {
return;
}
ContainerDataField variables = study.dataField(ContainerDataFieldCall.get(Fields.STUDYVARIABLES)).getRight();
if(variables == null || !variables.hasValidRows()) {
return;
}
DataRow row = variables.getRowWithFieldValue(Language.DEFAULT, Fields.VARIABLES, new Value(data.getKey().asCongregateKey())).getRight();
if(row == null) {
return;
}
ContainerChange cc = (ContainerChange)study.getChange(Fields.STUDYVARIABLES);
if(cc == null) {
cc = new ContainerChange(Fields.STUDYVARIABLES);
study.putChange(cc);
}
RowChange rc = cc.get(row.getRowId());
if(rc == null) {
rc = new RowChange(row.getRowId());
cc.put(rc);
}
row.dataField(ValueDataFieldCall.set(Fields.VARIABLES, new Value(data.getKey().getId()+"-"+revisionNos.get(revisionNos.size()-1)), Language.DEFAULT).setInfo(info).setChangeMap(rc.getChanges()));
revisions.updateRevisionData(study);
}
private void finalizeLogicalRemoval(RevisionData data, DateTimeUserPair info, boolean isCascade) {
// TODO: Generalize this and other respective cases with configuration analysis
// Since we don't have a mapping object for references we need to do this by type for now.
// It might be handy to do some processing of data configurations when they are saved and to form a reference web from them.
// This would allow for automatic clean operations at certain key points like this. Basically collecting the foreign keys
// and enabling cascade effects.
switch(data.getConfiguration().getType()) {
case STUDY_ERROR: {
revisions.sendStudyErrorMessageIfNeeded(data, configurations.findConfiguration(data.getConfiguration()).getRight());
break;
}
case STUDY_VARIABLES: {
if(!isCascade) {
Pair<StatusCode, ValueDataField> fieldPair = data.dataField(ValueDataFieldCall.get(Fields.STUDY));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND && fieldPair.getRight().hasValueFor(Language.DEFAULT)) {
Pair<ReturnResult, RevisionData> revPair = revisions.getRevisionData(fieldPair.getRight().getActualValueFor(Language.DEFAULT));
if(revPair.getLeft() == ReturnResult.REVISION_FOUND) {
RevisionData study = revPair.getRight();
Pair<StatusCode, ContainerDataField> conPair = study.dataField(ContainerDataFieldCall.get(Fields.STUDYVARIABLES));
if(conPair.getLeft() == StatusCode.FIELD_FOUND) {
fieldPair = data.dataField(ValueDataFieldCall.get(Fields.LANGUAGE));
if(fieldPair.getLeft() == StatusCode.FIELD_FOUND) {
String varLang = fieldPair.getRight().getActualValueFor(Language.DEFAULT);
Pair<StatusCode, DataRow> rowPair = conPair.getRight().getRowWithFieldValue(Language.DEFAULT, Fields.VARIABLESLANGUAGE, new Value(varLang));
if(rowPair.getLeft() == StatusCode.ROW_FOUND) {
conPair.getRight().removeRow(rowPair.getRight().getRowId(), study.getChanges(), info);
revisions.updateRevisionData(study);
}
}
}
}
}
}
break;
}
case STUDY_ATTACHMENT: {
if(!isCascade) {
ValueDataField field = data.dataField(ValueDataFieldCall.get(Fields.STUDY)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
break;
}
String value = field.getActualValueFor(Language.DEFAULT);
RevisionData study = null;
if(value.split("-").length > 1) {
study = revisions.getRevisionData(Long.parseLong(value.split("-")[0]), Integer.parseInt(value.split("-")[1])).getRight();
} else {
study = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT)).getRight();
}
if(study == null) {
break;
}
messenger.sendAmqpMessage(messenger.FB_FILE_REMOVAL, new FileRemovalPayload(data, study));
}
break;
}
case STUDY_VARIABLE: {
if(!isCascade) {
ValueDataField field = data.dataField(ValueDataFieldCall.get(Fields.VARIABLES)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
return;
}
RevisionData variables = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT)).getRight();
if(variables == null) {
return;
}
ReferenceContainerDataField container = variables.dataField(ReferenceContainerDataFieldCall.get(Fields.VARIABLES)).getRight();
if(container == null || !container.hasValidRows()) {
return;
}
ReferenceRow row = container.getReferenceWithValue(data.getKey().asCongregateKey()).getRight();
if(row == null) {
return;
}
container.removeReference(row.getRowId(), variables.getChanges(), info);
ContainerDataField variableGroups = variables.dataField(ContainerDataFieldCall.get(Fields.VARGROUPS)).getRight();
if(variableGroups != null) {
for(DataRow dataRow : variableGroups.getRowsFor(Language.DEFAULT)) {
container = dataRow.dataField(ReferenceContainerDataFieldCall.get(Fields.VARGROUPVARS)).getRight();
if(container != null) {
// See that respective rows are removed from VARGROUPVARS
// Remove from variables list
ReferenceRow reference = container.getReferenceIncludingValue(data.getKey().asPartialKey()).getRight();
if(reference != null) {
container.removeReference(reference.getRowId(), variables.getChanges(), info).getLeft();
// Since variable should always be only in one group at a time we can break out.
break;
}
}
}
}
revisions.updateRevisionData(variables);
}
break;
}
default: {
break;
}
}
}
private OperationResponse validateAndCascade(RevisionData data, DateTimeUserPair info, OperationType opType, RevisionableInfo revInfo) {
Pair<ReturnResult, Configuration> confPair = configurations.findConfiguration(data.getConfiguration());
if(confPair.getLeft() != ReturnResult.CONFIGURATION_FOUND) {
Logger.error(getClass(), "Could not find configuration for data "+data.toString());
return OperationResponse.build(RemoveResult.CONFIGURATION_NOT_FOUND);
}
// Do validation
ReturnResult rr = ReturnResult.OPERATION_SUCCESSFUL;
for(Operation operation : confPair.getRight().getRestrictions()) {
if(!(operation.getType() == OperationType.REMOVE
|| operation.getType() == (opType)
|| (opType == OperationType.REMOVE_DRAFT && revInfo != null && revInfo.getApproved() == null && operation.getType() == OperationType.REMOVE_REVISIONABLE)
|| operation.getType() == OperationType.ALL)) {
continue;
}
ValidateResult vr = validator.validate(data, operation.getTargets(), confPair.getRight());
if(!vr.getResult()) {
return OperationResponse.build(vr);
}
}
// Do cascade
for(Operation operation : confPair.getRight().getCascade()) {
if(!(operation.getType() == OperationType.REMOVE
|| operation.getType() == (opType)
|| operation.getType() == OperationType.ALL)) {
continue;
}
if(!cascader.cascade(CascadeInstruction.build(opType, info), data, operation.getTargets(), confPair.getRight())) {
rr = ReturnResult.CASCADE_FAILURE;
}
}
// Do REMOVE_REVISIONABLE cascade, results don't matter
if(opType == OperationType.REMOVE_DRAFT && revInfo != null && revInfo.getApproved() == null) {
for(Operation operation : confPair.getRight().getCascade()) {
if(operation.getType() != OperationType.REMOVE_REVISIONABLE) {
continue;
}
if(!cascader.cascade(CascadeInstruction.build(OperationType.REMOVE_REVISIONABLE, info), data, operation.getTargets(), confPair.getRight())) {
rr = ReturnResult.CASCADE_FAILURE;
}
}
}
// If cascade fails then don't approve this revision
if(rr != ReturnResult.OPERATION_SUCCESSFUL) {
return OperationResponse.build(RemoveResult.CASCADE_FAILURE);
}
return OperationResponse.build(RemoveResult.ALLOW_REMOVAL);
}
private RemoveResult allowRemoval(RevisionData data) {
switch(data.getConfiguration().getType()) {
case STUDY_ATTACHMENT:
case STUDY_VARIABLES:
case STUDY_VARIABLE:
return checkStudyAttachmentRemoval(data);
default:
return RemoveResult.ALLOW_REMOVAL;
}
}
private RemoveResult checkStudyAttachmentRemoval(RevisionData data) {
ValueDataField field = data.dataField(ValueDataFieldCall.get(Fields.STUDY)).getRight();
if(field == null || !field.hasValueFor(Language.DEFAULT)) {
return RemoveResult.ALLOW_REMOVAL;
}
Pair<ReturnResult, RevisionData> pair = revisions.getRevisionData(field.getActualValueFor(Language.DEFAULT));
if(pair.getLeft() != ReturnResult.REVISION_FOUND) {
return RemoveResult.ALLOW_REMOVAL;
}
return AuthenticationUtil.isHandler(pair.getRight())
? RemoveResult.ALLOW_REMOVAL
: (pair.getRight().getState() != RevisionState.DRAFT
? RemoveResult.STUDY_NOT_DRAFT
: RemoveResult.WRONG_USER);
}
private void addRemoveIndexCommand(RevisionKey key, RemoveResult result) {
switch(result) {
case SUCCESS_REVISIONABLE:
// TODO: In case of study we should check that references pointing to this study will get removed from revisions (from which point is the question).
case SUCCESS_DRAFT:
// One remove operation should be enough for both of these since there should only be one affected document
revisions.removeRevisionFromIndex(key);
break;
case SUCCESS_LOGICAL:
// In this case we need to reindex all affected documents instead
revisions.indexRevision(key);
/*List<Integer> nos = revisions.getAllRevisionNumbers(key.getId());
for(Integer no : nos) {
Pair<ReturnResult, RevisionData> pair = revisions.getRevisionData(key.getId(), key.getNo());
if(pair.getLeft() == ReturnResult.REVISION_FOUND) {
revisions.indexRevision(pair.getRight().getKey());
}
}*/
break;
default:
// Errors don't need special handling
break;
}
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package com.esp8266.mkspiffs;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import processing.app.PreferencesData;
import processing.app.Editor;
import processing.app.Base;
import processing.app.BaseNoGui;
import processing.app.Platform;
import processing.app.Sketch;
import processing.app.tools.Tool;
import processing.app.helpers.ProcessUtils;
import processing.app.debug.TargetPlatform;
/**
* Example Tools menu entry.
*/
public class ESP8266FS implements Tool {
Editor editor;
public void init(Editor editor) {
this.editor = editor;
}
public String getMenuTitle() {
return "ESP8266 Sketch Data Upload";
}
private int listenOnProcess(String[] arguments){
try {
final Process p = ProcessUtils.exec(arguments);
Thread thread = new Thread() {
public void run() {
try {
String line;
BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) System.out.println(line);
input.close();
} catch (Exception e){}
}
};
thread.start();
int res = p.waitFor();
thread.join();
return res;
} catch (Exception e){
return -1;
}
}
private void sysExec(final String[] arguments){
Thread thread = new Thread() {
public void run() {
try {
if(listenOnProcess(arguments) != 0){
editor.statusError("SPIFFS Upload failed!");
} else {
editor.statusNotice("SPIFFS Image Uploaded");
}
} catch (Exception e){
editor.statusError("SPIFFS Upload failed!");
}
}
};
thread.start();
}
private long getIntPref(String name){
String data = BaseNoGui.getBoardPreferences().get(name);
if(data == null || data.contentEquals("")) return 0;
if(data.startsWith("0x")) return Long.parseLong(data.substring(2), 16);
else return Integer.parseInt(data);
}
private void createAndUpload(){
if(!PreferencesData.get("target_platform").contentEquals("esp8266")){
System.err.println();
editor.statusError("SPIFFS Not Supported on "+PreferencesData.get("target_platform"));
return;
}
if(!BaseNoGui.getBoardPreferences().containsKey("build.spiffs_start") || !BaseNoGui.getBoardPreferences().containsKey("build.spiffs_end")){
System.err.println();
editor.statusError("SPIFFS Not Defined for "+BaseNoGui.getBoardPreferences().get("name"));
return;
}
long spiStart, spiEnd, spiPage, spiBlock;
try {
spiStart = getIntPref("build.spiffs_start");
spiEnd = getIntPref("build.spiffs_end");
spiPage = getIntPref("build.spiffs_pagesize");
if(spiPage == 0) spiPage = 256;
spiBlock = getIntPref("build.spiffs_blocksize");
if(spiBlock == 0) spiBlock = 4096;
} catch(Exception e){
editor.statusError(e);
return;
}
TargetPlatform platform = BaseNoGui.getTargetPlatform();
String esptoolCmd = platform.getTool("esptool").get("cmd");
File esptool;
esptool = new File(platform.getFolder()+"/tools", esptoolCmd);
if(!esptool.exists()){
esptool = new File(PreferencesData.get("runtime.tools.esptool.path"), esptoolCmd);
if (!esptool.exists()) {
System.err.println();
editor.statusError("SPIFFS Error: esptool not found!");
return;
}
}
File tool;
if(!PreferencesData.get("runtime.os").contentEquals("windows")) tool = new File(platform.getFolder()+"/tools", "mkspiffs");
else tool = new File(platform.getFolder()+"/tools", "mkspiffs.exe");
if(!tool.exists()){
System.err.println();
editor.statusError("SPIFFS Error: mkspiffs not found!");
return;
}
int fileCount = 0;
File dataFolder = editor.getSketch().prepareDataFolder();
if(dataFolder.exists() && dataFolder.isDirectory()){
File[] files = dataFolder.listFiles();
if(files.length > 0){
for(File file : files){
if(!file.isDirectory() && file.isFile() && !file.getName().startsWith(".")) fileCount++;
}
}
}
String dataPath = dataFolder.getAbsolutePath();
String toolPath = tool.getAbsolutePath();
String esptoolPath = esptool.getAbsolutePath();
String sketchName = editor.getSketch().getName();
String buildPath = BaseNoGui.getBuildFolder().getAbsolutePath();
String imagePath = buildPath+"/"+sketchName+".spiffs.bin";
String serialPort = PreferencesData.get("serial.port");
String resetMethod = BaseNoGui.getBoardPreferences().get("upload.resetmethod");
String uploadSpeed = BaseNoGui.getBoardPreferences().get("upload.speed");
String uploadAddress = BaseNoGui.getBoardPreferences().get("build.spiffs_start");
Object[] options = { "Yes", "No" };
String title = "SPIFFS Create";
String message = "No files have been found in your data folder!\nAre you sure you want to create an empty SPIFFS image?";
if(fileCount == 0 && JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]) != JOptionPane.YES_OPTION){
System.err.println();
editor.statusError("SPIFFS Warning: mkspiffs canceled!");
return;
}
editor.statusNotice("SPIFFS Creating Image...");
System.out.println("[SPIFFS] data : "+dataPath);
System.out.println("[SPIFFS] size : "+((spiEnd - spiStart)/1024));
System.out.println("[SPIFFS] page : "+spiPage);
System.out.println("[SPIFFS] block : "+spiBlock);
try {
if(listenOnProcess(new String[]{toolPath, "-c", dataPath, "-p", spiPage+"", "-b", spiBlock+"", "-s", (spiEnd - spiStart)+"", imagePath}) != 0){
System.err.println();
editor.statusError("SPIFFS Create Failed!");
return;
}
} catch (Exception e){
editor.statusError(e);
editor.statusError("SPIFFS Create Failed!");
return;
}
editor.statusNotice("SPIFFS Uploading Image...");
System.out.println("[SPIFFS] upload : "+imagePath);
System.out.println("[SPIFFS] reset : "+resetMethod);
System.out.println("[SPIFFS] port : "+serialPort);
System.out.println("[SPIFFS] speed : "+uploadSpeed);
System.out.println("[SPIFFS] address: "+uploadAddress);
System.out.println();
sysExec(new String[]{esptoolPath, "-cd", resetMethod, "-cb", uploadSpeed, "-cp", serialPort, "-ca", uploadAddress, "-cf", imagePath});
}
public void run() {
createAndUpload();
}
}
|
package pp.arithmetic.easy;
public class _190_reverseBits {
public static void main(String[] args) {
int i = reverseBits(1);
System.out.println(i);
}
// you need treat n as an unsigned value
public static int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += n & 1;
n >>= 1;
if (i < 31) {
result <<= 1;
}
}
return result;
}
/**
*
* -
* - ,
* - n/10, _9_isPalindrome
* - _234_isPalindrome
* -
* - n/10Int _7_reverse
* - >>1 _190_reverseBits
*/
}
|
class Decoder {
private static String[] options =
{"segundo", "minuto", "hora", "dia", "semana", "mes", "ano"};
private static boolean equiv(String r, String s) {
int len = Math.min(r.length(), s.length());
return r.regionMatches(true, 0, s, 0, len);
}
public int answer(String s) {
String[] query = s.split(" ");
int op = this.select(query);
Date d = this.detect(query);
double answ = this.convert(op, d);
System.out.println("op: " + op + " | date: " + d);
System.out.println("Answer: " + answ);
return 0;
}
// selects what conversion the decoder should do
private int select(String[] s) {
int i;
for (String subs: s) {
i = 0;
for (String op: options) {
if (Decoder.equiv(subs, op)) {
return i;
}
i++;
}
}
return -1;
}
// detects from what to convert from
private Date detect(String[] s) {
boolean first = true;
Date d = new Date();
for (int i = 0; i < s.length; i++) {
for (String op: options) {
if (!first && Decoder.equiv(s[i], op) && s[i - 1].matches("[0-9]+")) {
switch (op) {
case "segundo":
d.sec += Integer.parseInt(s[i - 1]);
break;
case "minuto":
d.min += Integer.parseInt(s[i - 1]);
break;
case "hora":
d.hour += Integer.parseInt(s[i - 1]);
break;
case "dia":
d.day += Integer.parseInt(s[i - 1]);
break;
case "semana":
d.week += Integer.parseInt(s[i - 1]);
break;
case "mes":
d.mon += Integer.parseInt(s[i - 1]);
break;
case "ano":
d.yr += Integer.parseInt(s[i - 1]);
break;
}
}
else if (first && Decoder.equiv(s[i], op)) {
first = false;
}
}
}
return d;
}
private double convert(int op, Date d) {
switch (op) {
case 0: return this.seconds(d);
case 1: return this.minutes(d);
case 2: return this.hours(d);
case 3: return this.days(d);
case 4: return this.weeks(d);
case 5: return this.months(d);
case 6: return this.years(d);
}
return 0;
}
private int seconds(Date d) {
int s = 0;
s += d.yr * 365 * 24 * 60 * 60;
s += d.mon * 30 * 24 * 60 * 60;
s += d.week * 7 * 24 * 60 * 60;
s += d.day * 24 * 60 * 60;
s += d.hour * 60 * 60;
s += d.min * 60;
s += d.sec;
return s;
}
private double minutes(Date d) {
double m = 0.0;
m += d.yr * 365 * 24 * 60;
m += d.mon * 30 * 24 * 60;
m += d.week * 7 * 24 * 60;
m += d.day * 24 * 60;
m += d.hour * 60;
m += d.min;
m += d.sec / 60.0;
return m;
}
private double hours(Date d) {
double h = 0.0;
h += d.yr * 365 * 24;
h += d.mon * 30 * 24;
h += d.week * 7 * 24;
h += d.day * 24;
h += d.hour;
h += d.min / 60.0;
h += d.sec / 60.0 / 60.0;
return h;
}
private double days(Date d) {
double b = 0.0;
b += d.yr * 365;
b += d.mon * 30;
b += d.week * 7;
b += d.day;
b += d.hour / 24.0;
b += d.min / 60.0 / 24.0;
b += d.sec / 60.0 / 60.0 / 24.0;
return b;
}
private double weeks(Date d) {
double w = 0.0;
w += d.yr * 12 * 4;
w += d.mon * 4;
w += d.week;
w += d.day / 7.0;
w += d.hour / 24.0 / 7.0;
w += d.min / 60.0 / 24.0 / 7.0;
w += d.sec / 60.0 / 60.0 / 24.0 / 7.0;
return w;
}
private double months(Date d) {
double m = 0.0;
m += d.yr * 12;
m += d.mon;
m += d.week / 4.0;
m += d.day / 30.0;
m += d.hour / 24.0 / 30.0;
m += d.min / 60.0 / 24.0 / 30.0;
m += d.sec / 60.0 / 60.0 / 24.0 / 30.0;
return m;
}
private double years(Date d) {
double y = 0.0;
y += d.yr;
y += d.mon / 12.0;
y += d.week / 4.0 / 12.0;
y += d.day / 30.0 / 12.0;
y += d.hour / 24.0 / 30.0 / 12.0;
y += d.min / 60.0 / 24.0 / 30.0 / 12.0;
y += d.sec / 60.0 / 60.0 / 24.0 / 30.0 / 12.0;
return y;
}
}
|
package net.sf.taverna.t2.workbench.views.monitor;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.List;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import net.sf.taverna.t2.activities.dataflow.DataflowActivity;
import net.sf.taverna.t2.lang.observer.Observer;
import net.sf.taverna.t2.monitor.MonitorManager.MonitorMessage;
import net.sf.taverna.t2.provenance.api.ProvenanceAccess;
import net.sf.taverna.t2.provenance.connector.ProvenanceConnector;
import net.sf.taverna.t2.provenance.lineageservice.Dependencies;
import net.sf.taverna.t2.provenance.lineageservice.LineageQueryResultRecord;
import net.sf.taverna.t2.workbench.icons.WorkbenchIcons;
import net.sf.taverna.t2.workbench.models.graph.GraphElement;
import net.sf.taverna.t2.workbench.models.graph.GraphEventManager;
import net.sf.taverna.t2.workbench.models.graph.GraphNode;
import net.sf.taverna.t2.workbench.models.graph.svg.SVGGraphController;
import net.sf.taverna.t2.workbench.reference.config.DataManagementConfiguration;
import net.sf.taverna.t2.workbench.ui.zaria.UIComponentSPI;
import net.sf.taverna.t2.workbench.views.graph.menu.ResetDiagramAction;
import net.sf.taverna.t2.workbench.views.graph.menu.ZoomInAction;
import net.sf.taverna.t2.workbench.views.graph.menu.ZoomOutAction;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.swing.gvt.GVTTreeRendererAdapter;
import org.apache.batik.swing.gvt.GVTTreeRendererEvent;
import org.apache.log4j.Logger;
public class MonitorViewComponent extends JPanel implements UIComponentSPI {
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(MonitorViewComponent.class);
private static final long serialVersionUID = 1L;
private SVGGraphController graphController;
protected JSVGCanvas svgCanvas;
protected JSVGScrollPane svgScrollPane;
protected JLabel statusLabel;
protected ProvenanceConnector provenanceConnector;
public enum Status {
RUNNING, COMPLETE
}
private String sessionId;
protected GVTTreeRendererAdapter gvtTreeRendererAdapter;
private GraphMonitor graphMonitor;
public MonitorViewComponent() {
super(new BorderLayout());
setBorder(LineBorder.createGrayLineBorder());
svgCanvas = new JSVGCanvas();
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
gvtTreeRendererAdapter = new GVTTreeRendererAdapter() {
public void gvtRenderingCompleted(GVTTreeRendererEvent arg0) {
// svgScrollPane.reset();
// MonitorViewComponent.this.revalidate();
}
};
svgCanvas.addGVTTreeRendererListener(gvtTreeRendererAdapter);
JPanel diagramAndControls = new JPanel();
diagramAndControls.setLayout(new BorderLayout());
svgScrollPane = new MySvgScrollPane(svgCanvas);
diagramAndControls.add(graphActionsToolbar(), BorderLayout.NORTH);
diagramAndControls.add(svgScrollPane, BorderLayout.CENTER);
add(diagramAndControls, BorderLayout.CENTER);
statusLabel = new JLabel();
statusLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
add(statusLabel, BorderLayout.SOUTH);
// setProvenanceConnector();
}
protected JToolBar graphActionsToolbar() {
JToolBar toolBar = new JToolBar();
toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
toolBar.setFloatable(false);
JButton resetDiagramButton = new JButton();
resetDiagramButton.setBorder(new EmptyBorder(0, 2, 0, 2));
JButton zoomInButton = new JButton();
zoomInButton.setBorder(new EmptyBorder(0, 2, 0, 2));
JButton zoomOutButton = new JButton();
zoomOutButton.setBorder(new EmptyBorder(0, 2, 0, 2));
Action resetDiagramAction = svgCanvas.new ResetTransformAction();
ResetDiagramAction.setResultsAction(resetDiagramAction);
resetDiagramAction.putValue(Action.SHORT_DESCRIPTION, "Reset Diagram");
resetDiagramAction.putValue(Action.SMALL_ICON, WorkbenchIcons.refreshIcon);
resetDiagramButton.setAction(resetDiagramAction);
Action zoomInAction = svgCanvas.new ZoomAction(1.2);
ZoomInAction.setResultsAction(zoomInAction);
zoomInAction.putValue(Action.SHORT_DESCRIPTION, "Zoom In");
zoomInAction.putValue(Action.SMALL_ICON, WorkbenchIcons.zoomInIcon);
zoomInButton.setAction(zoomInAction);
Action zoomOutAction = svgCanvas.new ZoomAction(1/1.2);
ZoomOutAction.setResultsAction(zoomOutAction);
zoomOutAction.putValue(Action.SHORT_DESCRIPTION, "Zoom Out");
zoomOutAction.putValue(Action.SMALL_ICON, WorkbenchIcons.zoomOutIcon);
zoomOutButton.setAction(zoomOutAction);
toolBar.add(resetDiagramButton);
toolBar.add(zoomInButton);
toolBar.add(zoomOutButton);
return toolBar;
}
public void setStatus(Status status) {
switch (status) {
case RUNNING :
statusLabel.setText("Workflow running");
statusLabel.setIcon(WorkbenchIcons.workingIcon);
break;
case COMPLETE :
statusLabel.setText("Workflow complete");
statusLabel.setIcon(WorkbenchIcons.greentickIcon);
break;
}
}
public void setProvenanceConnector(ProvenanceConnector connector) {
if (connector != null) {
provenanceConnector = connector;
setSessionId(provenanceConnector.getSessionID());
}
}
public Observer<MonitorMessage> setDataflow(Dataflow dataflow) {
SVGGraphController svgGraphController = new SVGGraphController(dataflow, true, svgCanvas);
svgGraphController.setGraphEventManager(new MonitorGraphEventManager(this, provenanceConnector, dataflow, getSessionId()));
setGraphController(svgGraphController);
graphMonitor = new GraphMonitor(svgGraphController, this);
return graphMonitor;
}
public ImageIcon getIcon() {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return "Monitor View Component";
}
public void onDisplay() {
// TODO Auto-generated method stub
}
public void onDispose() {
if (graphMonitor != null) {
graphMonitor.onDispose();
}
if (svgScrollPane != null) {
svgScrollPane.removeAll();
svgScrollPane = null;
}
if (svgCanvas != null) {
svgCanvas.stopProcessing();
svgCanvas.removeGVTTreeRendererListener(gvtTreeRendererAdapter);
svgCanvas = null;
}
}
@Override
protected void finalize() throws Throwable {
onDispose();
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getSessionId() {
return sessionId;
}
public void setGraphController(SVGGraphController graphController) {
this.graphController = graphController;
}
public SVGGraphController getGraphController() {
return graphController;
}
class MySvgScrollPane extends JSVGScrollPane {
private static final long serialVersionUID = 6890422410714378543L;
public MySvgScrollPane(JSVGCanvas canvas) {
super(canvas);
}
public void reset() {
super.resizeScrollBars();
super.reset();
}
}
}
class MonitorGraphEventManager implements GraphEventManager {
private static Logger logger = Logger
.getLogger(MonitorGraphEventManager.class);
private final ProvenanceConnector provenanceConnector;
private final Dataflow dataflow;
private String localName;
private List<LineageQueryResultRecord> intermediateValues;
private Runnable runnable;
private String sessionID;
private String targetWorkflowID;
static int MINIMUM_HEIGHT = 500;
static int MINIMUM_WIDTH = 800;
private MonitorViewComponent monitorViewComponent;
private ProvenanceResultsPanel provResultsPanel;
public MonitorGraphEventManager(MonitorViewComponent monitorViewComponent, ProvenanceConnector provenanceConnector,
Dataflow dataflow, String sessionID) {
this.monitorViewComponent = monitorViewComponent;
this.provenanceConnector = provenanceConnector;
this.dataflow = dataflow;
this.sessionID = sessionID;
}
/**
* Retrieve the provenance for a dataflow object
*/
public void mouseClicked(final GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
Object dataflowObject = graphElement.getDataflowObject();
GraphElement parent = graphElement.getParent();
if (parent instanceof GraphNode) {
parent = parent.getParent();
}
if (monitorViewComponent.getGraphController().getDataflowSelectionModel() != null) {
monitorViewComponent.getGraphController().getDataflowSelectionModel().addSelection(dataflowObject);
}
// no popup if provenance is switched off
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
JPanel fetchButtonPanel = new JPanel();
fetchButtonPanel.setLayout(new BorderLayout());
JButton fetchResults = new JButton("Fetch Results");
fetchResults.setToolTipText("Retrieve provenance again - in case you need to get any new results");
fetchButtonPanel.add(fetchResults, BorderLayout.WEST);
topPanel.add(fetchButtonPanel);
fetchResults.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProvenanceAccess provenanceAccess = new ProvenanceAccess(DataManagementConfiguration.getInstance().getConnectorType());
//TODO use the new provenance access API with the nested workflow if required to get the results
Dependencies fetchPortData = provenanceAccess.fetchPortData(sessionID, targetWorkflowID, localName, null, null);
intermediateValues = fetchPortData.getRecords();
if (intermediateValues.size() > 0) {
frame.setTitle("Intermediate results for "
+ localName);
for (LineageQueryResultRecord record : intermediateValues) {
logger.info("LQRR: "
+ record.toString());
}
provResultsPanel
.setLineageRecords(intermediateValues);
logger
.info("Intermediate results retrieved for dataflow instance: "
+ sessionID
+ " processor: "
+ localName
+ " nested: " + targetWorkflowID);
} else {
frame.setTitle("Currently no intermediate results for service "
+ localName + ". Click \'Fetch Results\' to try again.");
}
}
});
final JPanel provenancePanel = new JPanel();
provenancePanel.setLayout(new BorderLayout());
if (provenanceConnector != null) {
if (dataflowObject != null) {
if (dataflowObject instanceof Processor) {
if (provenanceConnector != null) {
//Is it a nested workflow that has been clicked on or a processor inside it?
// if (((Processor) dataflowObject).getActivityList().get(0) instanceof DataflowActivity) {
// localName = null;
// } else {
localName = ((Processor) dataflowObject).getLocalName();
frame.setTitle("Fetching intermediate results for service " + localName);
//if the processor is inside a nested workflow then get the nested workflow id. There
//no parent on a top level workflow
// if (parent == null) {
// nestedWorkflowID = null;
// } else {
//is it inside a nested workflow?
if (parent != null && parent.getDataflowObject() instanceof Processor) {
if (((Processor)parent.getDataflowObject()).getActivityList().get(0) instanceof DataflowActivity) {
Activity<?> activity = ((Processor)parent.getDataflowObject()).getActivityList().get(0);
targetWorkflowID = ((DataflowActivity)activity).getNestedDataflow().getInternalIdentier();
}
} else {
targetWorkflowID = dataflow.getInternalIdentier();
}
// String internalIdentier = dataflow.getInternalIdentier();
provResultsPanel = new ProvenanceResultsPanel();
provResultsPanel.setContext(provenanceConnector
.getInvocationContext());
provenancePanel.add(provResultsPanel,
BorderLayout.CENTER);
runnable = new Runnable() {
public void run() {
try {
logger.info("Retrieving intermediate results for dataflow instance: "
+ sessionID
+ " processor: "
+ localName
+ " nested: " + targetWorkflowID);
ProvenanceAccess provenanceAccess = new ProvenanceAccess(DataManagementConfiguration.getInstance().getConnectorType());
//TODO use the new provenance access API with the nested workflow if required to get the results
Dependencies fetchPortData = provenanceAccess.fetchPortData(sessionID, targetWorkflowID, localName, null, null);
intermediateValues = fetchPortData.getRecords();
// intermediateValues = provenanceConnector
// .getIntermediateValues(sessionID,
// localName, null, null);
if (intermediateValues.size() > 0) {
frame.setTitle("Intermediate results for "
+ localName);
for (LineageQueryResultRecord record : intermediateValues) {
logger.info("LQRR: "
+ record.toString());
}
provResultsPanel
.setLineageRecords(intermediateValues);
frame.setVisible(true);
// frame.setVisible(true);
logger
.info("Intermediate results retrieved for dataflow instance: "
+ sessionID
+ " processor: "
+ localName
+ " nested: " + targetWorkflowID);
} else {
// JOptionPane.showMessageDialog(null,
// "Currently no intermediate results available for processor " + localName + "\nData may still be being processed",
// "No results yet",
// JOptionPane.INFORMATION_MESSAGE);
// frame.setVisible(false);
frame.setTitle("Currently no intermediate results for service "
+ localName + ". Click \'Fetch Results\' to try again.");
frame.setVisible(true);
}
} catch (Exception e) {
logger
.warn("Could not retrieve intermediate results: "
+ e.getStackTrace());
frame.setVisible(false);
JOptionPane.showMessageDialog(null,
"Could not retrieve intermediate results:\n"
+ e,
"Problem retrieving results",
JOptionPane.ERROR_MESSAGE);
}
}
};
runnable.run();
// timer = new Timer(
// "Retrieve intermediate results for dataflow: "
// + internalIdentier + ", processor: "
// + localName);
// timer.schedule(timerTask, 1, 50000);
//kill the timer when the user closes the frame
// frame.addWindowListener(new WindowClosingListener(timer, timerTask));
}
panel.add(topPanel, BorderLayout.NORTH);
panel.add(provenancePanel, BorderLayout.CENTER);
panel.setMinimumSize(new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT - 100));
frame.add(new JScrollPane(panel));
frame.setSize(new Dimension(800,500));
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Dimension resizedSize = frame.getSize();
int newWidth = resizedSize.width < MINIMUM_WIDTH ? MINIMUM_WIDTH : resizedSize.width;
int newHeight = resizedSize.height < MINIMUM_HEIGHT ? MINIMUM_HEIGHT : resizedSize.height;
frame.setSize(new Dimension(newWidth, newHeight));
}
});
}
}
} else {
//tell the user that provenance is switched off
}
}
public void mouseDown(GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
// TODO Auto-generated method stub
}
public void mouseMoved(GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
// TODO Auto-generated method stub
}
public void mouseUp(GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
// TODO Auto-generated method stub
}
public void mouseOut(GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
// TODO Auto-generated method stub
}
public void mouseOver(GraphElement graphElement, short button,
boolean altKey, boolean ctrlKey, boolean metaKey, int x, int y,
int screenX, int screenY) {
// TODO Auto-generated method stub
}
}
|
package com.mparticle.sdk.model.eventprocessing;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
public final class AttributionEvent extends Event {
public AttributionEvent() {
super(Type.ATTRIBUTION);
}
@JsonProperty("partner_name")
private String partner;
@JsonProperty("publisher_name")
private String publisher;
@JsonProperty("campaign_name")
private String campaign;
@JsonProperty("attributes")
private Map<String, String> attributes;
public String getPartner() {
return partner;
}
public void setPartner(String partner) {
this.partner = partner;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCampaign() {
return campaign;
}
public void setCampaign(String campaign) {
this.campaign = campaign;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
|
package org.gbif.occurrence.ws.client;
import org.gbif.api.model.common.search.SearchResponse;
import org.gbif.api.model.occurrence.Occurrence;
import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest;
import org.gbif.api.service.occurrence.OccurrenceSearchService;
import java.util.List;
import javax.annotation.Nullable;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.gbif.api.model.common.paging.PagingConstants.PARAM_LIMIT;
import static org.gbif.api.model.common.search.SearchConstants.QUERY_PARAM;
import static org.gbif.ws.paths.OccurrencePaths.CATALOG_NUMBER_PATH;
import static org.gbif.ws.paths.OccurrencePaths.COLLECTION_CODE_PATH;
import static org.gbif.ws.paths.OccurrencePaths.EVENT_ID_PATH;
import static org.gbif.ws.paths.OccurrencePaths.IDENTIFIED_BY_PATH;
import static org.gbif.ws.paths.OccurrencePaths.INSTITUTION_CODE_PATH;
import static org.gbif.ws.paths.OccurrencePaths.OCCURRENCE_PATH;
import static org.gbif.ws.paths.OccurrencePaths.PARENT_EVENT_ID_PATH;
import static org.gbif.ws.paths.OccurrencePaths.RECORDED_BY_PATH;
import static org.gbif.ws.paths.OccurrencePaths.RECORD_NUMBER_PATH;
import static org.gbif.ws.paths.OccurrencePaths.OCCURRENCE_ID_PATH;
import static org.gbif.ws.paths.OccurrencePaths.ORGANISM_ID_PATH;
import static org.gbif.ws.paths.OccurrencePaths.LOCALITY_PATH;
import static org.gbif.ws.paths.OccurrencePaths.SAMPLING_PROTOCOL_PATH;
import static org.gbif.ws.paths.OccurrencePaths.WATER_BODY_PATH;
import static org.gbif.ws.paths.OccurrencePaths.STATE_PROVINCE_PATH;
/**
* Ws client for {@link OccurrenceSearchService}.
*/
@RequestMapping(
value = OCCURRENCE_PATH,
produces = MediaType.APPLICATION_JSON_VALUE
)
public interface OccurrenceWsSearchClient extends OccurrenceSearchService {
String SEARCH_PATH ="search/";
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH
)
@ResponseBody
@Override
SearchResponse<Occurrence, OccurrenceSearchParameter> search(@RequestBody OccurrenceSearchRequest occurrenceSearchRequest);
@RequestMapping(
method = RequestMethod.GET,
value = CATALOG_NUMBER_PATH
)
@ResponseBody
@Override
List<String> suggestCatalogNumbers(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + COLLECTION_CODE_PATH
)
@ResponseBody
@Override
List<String> suggestCollectionCodes(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + RECORDED_BY_PATH
)
@ResponseBody
@Override
List<String> suggestRecordedBy(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + RECORD_NUMBER_PATH
)
@ResponseBody
@Override
List<String> suggestRecordNumbers(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + INSTITUTION_CODE_PATH
)
@ResponseBody
@Override
List<String> suggestInstitutionCodes(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + OCCURRENCE_ID_PATH
)
@ResponseBody
@Override
List<String> suggestOccurrenceIds(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + ORGANISM_ID_PATH
)
@ResponseBody
@Override
List<String> suggestOrganismIds(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + LOCALITY_PATH
)
@ResponseBody
@Override
List<String> suggestLocalities(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + WATER_BODY_PATH
)
@ResponseBody
@Override
List<String> suggestWaterBodies(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + STATE_PROVINCE_PATH
)
@ResponseBody
@Override
List<String> suggestStateProvinces(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + IDENTIFIED_BY_PATH
)
@ResponseBody
@Override
List<String> suggestIdentifiedBy(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + SAMPLING_PROTOCOL_PATH
)
@ResponseBody
@Override
List<String> suggestSamplingProtocol(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + EVENT_ID_PATH
)
@ResponseBody
@Override
List<String> suggestEventId(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
@RequestMapping(
method = RequestMethod.GET,
value = SEARCH_PATH + PARENT_EVENT_ID_PATH
)
@ResponseBody
@Override
List<String> suggestParentEventId(@RequestParam(QUERY_PARAM) String prefix, @RequestParam(PARAM_LIMIT) @Nullable Integer limit);
}
|
package org.opencb.opencga.storage.variant;
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.*;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.mongodb.MongoDBCollection;
import org.opencb.datastore.mongodb.MongoDataStore;
import org.opencb.datastore.mongodb.MongoDataStoreManager;
import org.opencb.opencga.lib.auth.MongoCredentials;
/**
* @author Cristina Yenyxe Gonzalez Garcia <cyenyxe@ebi.ac.uk>
* @author Alejandro Aleman Ramos <aaleman@cipf.es>
*/
public class VariantMongoQueryBuilder implements VariantQueryBuilder {
private final MongoDataStoreManager mongoManager;
private final MongoDataStore db;
public VariantMongoQueryBuilder(MongoCredentials credentials) throws UnknownHostException {
// Mongo configuration
mongoManager = new MongoDataStoreManager(credentials.getMongoHost(), credentials.getMongoPort());
db = mongoManager.get(credentials.getMongoDbName());
}
@Override
public QueryResult getAllVariantsByRegion(Region region, QueryOptions options) {
List<String> chunkIds = getChunkIds(region);
MongoDBCollection coll = db.getCollection("variants");
BasicDBObject query = new BasicDBObject("chunkIds", new BasicDBObject("$in", chunkIds));
query.append("end", new BasicDBObject("$gte", region.getStart())).append("start", new BasicDBObject("$lte", region.getEnd()));
QueryResult queryResult = coll.find(query, options);
return queryResult;
}
@Override
public QueryResult getAllVariantsByRegionAndStudy(Region region, String studyName, QueryOptions options) {
List<String> chunkIds = getChunkIds(region);
MongoDBCollection coll = db.getCollection("variants");
BasicDBObject query = new BasicDBObject("files.studyId", studyName);
query.append("chunkIds", new BasicDBObject("$in", chunkIds));
query.append("end", new BasicDBObject("$gte", region.getStart())).append("start", new BasicDBObject("$lte", region.getEnd()));
QueryResult queryResult = coll.find(query, options);
return queryResult;
}
@Override
public List<QueryResult> getAllVariantsByRegionListAndStudy(List<Region> regions, String studyName, QueryOptions options) {
List<QueryResult> allResults = new LinkedList<>();
for (Region r : regions) {
QueryResult queryResult = getAllVariantsByRegionAndStudy(r, studyName, options);
allResults.add(queryResult);
}
return allResults;
}
@Override
public QueryResult getVariantsHistogramByRegion(Region region, String studyName, boolean histogramLogarithm, int histogramMax) {
return null;
}
@Override
public QueryResult getStatsByVariant(Variant variant, QueryOptions options) {
return null;
}
@Override
public QueryResult getSimpleStatsByVariant(Variant variant, QueryOptions options) {
return null;
}
@Override
public QueryResult getEffectsByVariant(Variant variant, QueryOptions options) {
return null;
}
@Override
public boolean close() {
db.close();
return true;
}
private List<String> getChunkIds(Region region) {
List<String> chunkIds = new LinkedList<>();
int chunkSize = (region.getEnd() - region.getStart() > VariantVcfMongoDataWriter.CHUNK_SIZE_BIG) ?
VariantVcfMongoDataWriter.CHUNK_SIZE_BIG : VariantVcfMongoDataWriter.CHUNK_SIZE_SMALL;
int ks = chunkSize / 1000;
int chunkStart = region.getStart() / chunkSize;
int chunkEnd = region.getEnd() / chunkSize;
for (int i = chunkStart; i <= chunkEnd; i++) {
String chunkId = region.getChromosome() + "_" + i + "_" + ks + "k";
chunkIds.add(chunkId);
}
return chunkIds;
}
// @Override
// public List<VariantStats> getRecordsStats(Map<String, String> options) {
// return null;
// @Override
// public List<VariantEffect> getEffect(Map<String, String> options) {
// return null;
// @Override
// public VariantAnalysisInfo getAnalysisInfo(Map<String, String> options) {
// return null;
// private String buildRowkey(String chromosome, String position) {
// if (chromosome.length() > 2) {
// if (chromosome.substring(0, 2).equals("chr")) {
// chromosome = chromosome.substring(2);
// if (chromosome.length() < 2) {
// chromosome = "0" + chromosome;
// if (position.length() < 10) {
// while (position.length() < 10) {
// position = "0" + position;
// return chromosome + "_" + position;
// @Override
// public List<VariantInfo> getRecords(Map<String, String> options) {
// return null;
// public QueryResult<VariantInfo> getRecordsMongo(int page, int start, int limit, MutableInt count, Map<String, String> options) {
// long startTime = System.currentTimeMillis();
// QueryResult<VariantInfo> queryResult = new QueryResult<>();
// List<VariantInfo> res = new ArrayList<>();
// String studyId = options.get("studyId");
// DBCollection coll = db.getCollection("variants");
// DBObject elemMatch = new BasicDBObject("studyId", studyId);
// DBObject query = new BasicDBObject();
// BasicDBList orList = new BasicDBList();
// Map<String, List<String>> sampleGenotypes = processSamplesGT(options);
// System.out.println("map = " + options);
// if (options.containsKey("region_list") && !options.get("region_list").equals("")) {
// String[] regions = options.get("region_list").split(",");
// Pattern pattern = Pattern.compile("(\\w+):(\\d+)-(\\d+)");
// Matcher matcher, matcherChr;
// for (int i = 0; i < regions.length; i++) {
// String region = regions[i];
// matcher = pattern.matcher(region);
// if (matcher.find()) {
// String chr = matcher.group(1);
// int s = Integer.valueOf(matcher.group(2));
// int e = Integer.valueOf(matcher.group(3));
// DBObject regionClause = new BasicDBObject("chr", chr);
// regionClause.put("pos", new BasicDBObject("$gte", s).append("$lte", e));
// orList.add(regionClause);
// } else {
// Pattern patternChr = Pattern.compile("(\\w+)");
// matcherChr = patternChr.matcher(region);
// if (matcherChr.find()) {
// String chr = matcherChr.group();
// DBObject regionClause = new BasicDBObject("chr", chr);
// orList.add(regionClause);
// query.put("$or", orList);
// } else if (options.containsKey("genes") && !options.get("genes").equals("")) {
// orList = processGeneList(options.get("genes"));
// if (orList.ks() > 0) {
// query.put("$or", orList);
// } else {
// queryResult.setWarningMsg("Wrong gene name");
// queryResult.setResult(res);
// queryResult.setNumResults(res.ks());
// return queryResult;
// if (options.containsKey("conseq_type") && !options.get("conseq_type").equals("")) {
// String[] cts = options.get("conseq_type").split(",");
// BasicDBList ctList = new BasicDBList();
// for (String ct : cts) {
// ctList.add(ct);
// elemMatch.put("effects", new BasicDBObject("$in", ctList));
// if (sampleGenotypes.ks() > 0) {
// for (Map.Entry<String, List<String>> entry : sampleGenotypes.entrySet()) {
// BasicDBList gtList = new BasicDBList();
// for (String gt : entry.getValue()) {
// gtList.add(gt);
// elemMatch.put("samples." + entry.getKey() + ".GT", new BasicDBObject("$in", gtList));
// if (options.containsKey("miss_gt") && !options.get("miss_gt").equalsIgnoreCase("")) {
// Integer val = Integer.valueOf(options.get("miss_gt"));
// Object missGt = getMongoOption(options.get("option_miss_gt"), val);
// elemMatch.put("stats.missGenotypes", missGt);
// if (options.containsKey("maf_1000g_controls") && !options.get("maf_1000g_controls").equalsIgnoreCase("")) {
// elemMatch.put("attributes.1000G_maf", new BasicDBObject("$lte", options.get("maf_1000g_controls")));
// query.put("studies", new BasicDBObject("$elemMatch", elemMatch));
// System.out.println("
// System.out.println(query);
// System.out.println("
// long dbStart = System.currentTimeMillis();
// DBObject sort = null;
// DBCursor cursor;
// if (options.containsKey("sort")) {
// sort = getQuerySort(options.get("sort"));
// System.out.println(sort);
// cursor = coll.find(query).sort(sort).skip(start).limit(limit);
// } else {
// cursor = coll.find(query).skip(start).limit(limit);
// count.setValue(cursor.count());
// queryResult.setDbTime(dbStart - System.currentTimeMillis());
// for (DBObject obj : cursor) {
// BasicDBObject elem = (BasicDBObject) obj;
// VariantInfo vi = new VariantInfo();
// VariantStats vs = new VariantStats();
// String chr = elem.getString("chr");
// int pos = elem.getInt("pos");
// vi.setChromosome(chr);
// vi.setPosition(pos);
// BasicDBList studies = (BasicDBList) elem.get("studies");
// Iterator<Object> it = studies.iterator();
// while (it.hasNext()) {
// BasicDBObject study = (BasicDBObject) it.next();
// if (study.getString("studyId").equalsIgnoreCase(studyId)) {
// BasicDBObject stats = (BasicDBObject) study.get("stats");
// String ref = study.getString("ref");
// BasicDBList alt = (BasicDBList) study.get("alt");
// vi.setRef(ref);
// vi.setAlt(Joiner.on(",").join(alt.toArray()));
// vs.setMaf((float) stats.getDouble("maf"));
// vs.setMgf((float) stats.getDouble("mgf"));
// vs.setMafAllele(stats.getString("alleleMaf"));
// vs.setMgfGenotype(stats.getString("genotypeMaf"));
// vs.setMissingAlleles(stats.getInt("missAllele"));
// vs.setMissingGenotypes(stats.getInt("missGenotypes"));
// vs.setMendelianErrors(stats.getInt("mendelErr"));
// vs.setCasesPercentDominant((float) stats.getDouble("casesPercentDominant"));
// vs.setControlsPercentDominant((float) stats.getDouble("controlsPercentDominant"));
// vs.setCasesPercentRecessive((float) stats.getDouble("casesPercentRecessive"));
// vs.setControlsPercentRecessive((float) stats.getDouble("controlsPercentRecessive"));
// BasicDBObject samples = (BasicDBObject) study.get("samples");
// for (String sampleName : samples.keySet()) {
// DBObject sample = (DBObject) samples.get(sampleName);
// if (sample.containsField("GT")) {
// String sampleGT = (String) sample.get("GT");
// vi.addSammpleGenotype(sampleName, sampleGT);
// vi.setSnpid((String) study.get("snpId"));
// if (study.containsField("effects")) {
// BasicDBList conseqTypes = (BasicDBList) study.get("effects");
// conseqTypes.remove("");
// String cts = Joiner.on(",").join(conseqTypes.iterator());
// vi.addConsequenceTypes(cts);
// if (study.containsField("genes")) {
// BasicDBList genesList = (BasicDBList) study.get("genes");
// String genes = Joiner.on(",").join(genesList.iterator());
// vi.addGenes(genes);
// if (study.containsField("attributes")) {
// BasicDBObject attr = (BasicDBObject) study.get("attributes");
// if (attr.containsField("1000G_maf")) {
// vi.addControl("1000G_maf", (String) attr.get("1000G_maf"));
// vi.addControl("1000G_amaf", (String) attr.get("1000G_amaf"));
// vi.addControl("1000G_gt", (String) attr.get("1000G_gt"));
// if (attr.containsField("EVS_maf")) {
// vi.addControl("EVS_maf", (String) attr.get("EVS_maf"));
// vi.addControl("EVS_amaf", (String) attr.get("EVS_amaf"));
// vi.addControl("EVS_gt", (String) attr.get("EVS_gt"));
// continue;
// vi.addStats(vs);
// res.add(vi);
// queryResult.setResult(res);
// queryResult.setTime(startTime - System.currentTimeMillis());
// return queryResult;
// private DBObject getQuerySort(String sort) {
// DBObject res = new BasicDBObject();
// // sort=[{"property":"stats_id_snp","direction":"ASC"}],
//// Pattern pattern = Pattern.compile("(\\w+):(\\d+)-(\\d+)");
// Pattern pattern = Pattern.compile("\"property\":\"(\\w+)\",\"direction\":\"(ASC|DESC)\"");
// Matcher matcher = pattern.matcher(sort);
// if (matcher.find()) {
// String field = matcher.group(1);
// String direction = matcher.group(2);
// int dir = 1;
// if (direction.equalsIgnoreCase("ASC")) {
// dir = 1;
// } else if (direction.equalsIgnoreCase("DESC")) {
// dir = -1;
// switch (field) {
// case "chromosome":
// res.put("chr", dir);
// res.put("pos", dir);
// break;
// case "snpid":
// res.put("studies.snpId", dir);
// break;
// case "consecuente_types":
// res.put("studies.effects", dir);
// break;
// case "genes":
// res.put("studies.genes.1", dir);
// break;
// return res;
// private Object getMongoOption(String option, float val) {
// Object res = null;
// switch (option) {
// case ("<"):
// res = new BasicDBObject("$lt", val);
// break;
// case ("<="):
// res = new BasicDBObject("$lte", val);
// break;
// case (">"):
// res = new BasicDBObject("$gt", val);
// break;
// case (">="):
// res = new BasicDBObject("$gte", val);
// break;
// case ("="):
// res = val;
// break;
// case ("!="):
// res = new BasicDBObject("$ne", val);
// break;
// return res;
// private BasicDBList processGeneList(String genes) {
// BasicDBList list = new BasicDBList();
// Client wsRestClient = Client.create();
// ObjectMapper mapper = new ObjectMapper();
// String response = webResource.path(genes).path("info").queryParam("of", "json").get(String.class);
// try {
// JsonNode actualObj = mapper.readTree(response);
// Iterator<JsonNode> it = actualObj.iterator();
// Iterator<JsonNode> aux;
// while (it.hasNext()) {
// JsonNode node = it.next();
// if (node.isArray()) {
// aux = node.iterator();
// while (aux.hasNext()) {
// JsonNode auxNode = aux.next();
// DBObject regionClause = new BasicDBObject("chr", auxNode.get("chromosome").asText());
// regionClause.put("pos", new BasicDBObject("$gte", auxNode.get("start").asInt()).append("$lte", auxNode.get("end").asInt()));
// list.add(regionClause);
// } catch (IOException e) {
// e.printStackTrace();
// return list;
// private Map<String, List<String>> processSamplesGT(Map<String, String> options) {
// Map<String, List<String>> samplesGenotypes = new LinkedHashMap<>(10);
// List<String> genotypesList;
// String key, val;
// for (Map.Entry<String, String> entry : options.entrySet()) {
// key = entry.getKey();
// val = entry.getValue();
// if (key.startsWith("sampleGT_")) {
// String sampleName = key.replace("sampleGT_", "").replace("[]", "");
// String[] genotypes = val.split(",");
// if (samplesGenotypes.containsKey(sampleName)) {
// genotypesList = samplesGenotypes.get(sampleName);
// } else {
// genotypesList = new ArrayList<>();
// samplesGenotypes.put(sampleName, genotypesList);
// for (int i = 0; i < genotypes.length; i++) {
// genotypesList.add(genotypes[i]);
// return samplesGenotypes;
// public QueryResult<VariantAnalysisInfo> getAnalysisInfo(String studyId) {
// long start = System.currentTimeMillis();
// QueryResult<VariantAnalysisInfo> qres = new QueryResult<>();
// VariantAnalysisInfo vi = new VariantAnalysisInfo();
// DBCollection coll = db.getCollection("studies");
// DBCollection collV = db.getCollection("variants");
// long dbStart = System.currentTimeMillis();
// DBObject study = coll.findOne(new BasicDBObject("name", studyId));
// if (study != null) {
// Iterator<Object> it = ((BasicDBList) study.get("samples")).iterator();
// while (it.hasNext()) {
// vi.addSample((String) it.next());
// BasicDBObject gs = (BasicDBObject) study.get("globalStats");
// for (String elem : gs.keySet()) {
// if (!elem.equalsIgnoreCase("consequenceTypes")) {
// double val = gs.getDouble(elem);
// vi.addGlobalStats(elem, val);
// } else {
// BasicDBObject cts = (BasicDBObject) gs.get("consequenceTypes");
// for (String ct : cts.keySet()) {
// vi.addConsequenceType(ct, cts.getInt(ct));
// qres.setDbTime(System.currentTimeMillis() - dbStart);
// qres.setResult(Arrays.asList(vi));
// qres.setTime(System.currentTimeMillis() - start);
// return qres;
}
|
package org.camunda.bpm.modeler.ui.property.tabs.dialog;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Stack;
import org.camunda.bpm.modeler.emf.util.CommandUtil;
import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.ui.action.RedoAction;
import org.eclipse.emf.edit.ui.action.UndoAction;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.emf.workspace.IWorkspaceCommandStack;
import org.eclipse.jface.commands.ActionHandler;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
/**
* Dialog which handle undo and redo command for the current command stack size
*
* CANCEL button and ESC key close the dialog and nothing was changed
*
* @author kristin.polenz
*
*/
public class ModelerDialog extends Dialog {
private EObject model;
protected ModelerDialog(Shell parentShell, EObject model) {
super(parentShell);
this.model = model;
}
private CommandStackListener commandStackListener;
private TransactionalEditingDomain editingDomain;
private IHandlerService handlerService;
private List<IHandlerActivation> actionActivationList = new ArrayList<IHandlerActivation>();
private Stack<Command> undoStack;
// CTRL+Z implementation to execute it when
// the dialog is closed via ESC key or cancel button
@Override
public void create() {
super.create();
registerUndoListener();
// create handler to handle undo / redo commands in this dialog
handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
// create undo action to activate handler for this action
UndoAction undoAction = new UndoAction(editingDomain);
undoAction.setActionDefinitionId(ActionFactory.UNDO.getCommandId());
// enabled undo action to execute the command
undoAction.setEnabled(true);
// create redo action to activate handler for this action
RedoAction redoAction = new RedoAction(editingDomain);
redoAction.setActionDefinitionId(ActionFactory.REDO.getCommandId());
// enabled redo action to execute the command
redoAction.setEnabled(true);
// activate handler for the given action
// note: it is necessary to deactivate the handlers in the dialog close method
IHandlerActivation undoActionActivation = handlerService.activateHandler(undoAction.getActionDefinitionId(), new ActionHandler(undoAction));
IHandlerActivation redoActionActivation = handlerService.activateHandler(redoAction.getActionDefinitionId(), new ActionHandler(redoAction));
actionActivationList.add(undoActionActivation);
actionActivationList.add(redoActionActivation);
}
private void registerUndoListener() {
undoStack = new Stack<Command>();
commandStackListener = new CommandStackListener() {
@Override
public void commandStackChanged(EventObject event) {
final IWorkspaceCommandStack transactionalCommandStack = (IWorkspaceCommandStack) event.getSource();
Command lastCommand = transactionalCommandStack.getMostRecentCommand();
Command undoCommand = transactionalCommandStack.getUndoCommand();
transactionalCommandStack.getOperationHistory().canUndo(IOperationHistory.GLOBAL_UNDO_CONTEXT);
boolean isUndo = !lastCommand.equals(undoCommand);
if (!isUndo) {
undoStack.push(lastCommand);
} else {
if (undoStack.isEmpty()) {
// close dialog on undo behind open command
// prevents the user from editing a detached (i.e. newly created and
// removed via undo) FormField object
// redo the command that happened prior to dialog open
// we need to do this to make sure that the user cannot undo things he did
// before the dialog got opened (while the dialog is active)
// must close dialog asynchronously to not interfere with undo action processing
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
// remove listener to prepare for close
removeUndoListener();
// after this operation the openCommand is on top of the command stack
transactionalCommandStack.redo();
// set null so that no undo is done during close
cancelPressed();
}
});
} else {
Command commandsTop = undoStack.peek();
// only pop undo stack if undo (EMF-wise) is actually possible
// if it is no more possible, a miss match between
// the last command (successfully undone by EMF) and the current undoStack top exists
// we use this miss match to figure out if EMF was able to undo the last command
if (lastCommand.equals(commandsTop)) {
undoStack.pop();
}
}
}
}
};
editingDomain = TransactionUtil.getEditingDomain(model);
CommandStack commandStack = editingDomain.getCommandStack();
commandStack.addCommandStackListener(commandStackListener);
}
protected void removeUndoListener() {
CommandStack commandStack = editingDomain.getCommandStack();
commandStack.removeCommandStackListener(commandStackListener);
}
private void undoChanges() {
removeUndoListener();
while (!undoStack.isEmpty()) {
Command command = undoStack.pop();
internalUndoChange(command);
}
}
private void internalUndoChange(Command command) {
CommandUtil.undo(editingDomain, command);
}
// deactivate undo / redo action handler
private void deactivateHandlerActivation() {
handlerService.deactivateHandlers(actionActivationList);
}
@Override
public boolean close() {
removeUndoListener();
deactivateHandlerActivation();
return super.close();
}
@Override
protected void cancelPressed() {
undoChanges();
super.cancelPressed();
}
@Override
protected void handleShellCloseEvent() {
undoChanges();
super.handleShellCloseEvent();
}
}
|
package org.metaborg.spoofax.core.stratego;
import java.io.File;
import javax.annotation.Nullable;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.context.IContext;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.core.InterpreterErrorExit;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.core.InterpreterExit;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.core.UndefinedStrategyException;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoString;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.strategoxt.HybridInterpreter;
import org.strategoxt.lang.Context;
import org.strategoxt.stratego_aterm.aterm_escape_strings_0_0;
import org.strategoxt.stratego_aterm.pp_aterm_box_0_0;
import org.strategoxt.stratego_gpp.box2text_string_0_1;
import com.google.inject.Inject;
/**
* Common code for using Stratego transformations in Spoofax.
*/
public class StrategoCommon implements IStrategoCommon {
private static final ILogger logger = LoggerUtils.logger(StrategoCommon.class);
private final IStrategoRuntimeService strategoRuntimeService;
private final ITermFactoryService termFactoryService;
@Inject public StrategoCommon(IStrategoRuntimeService strategoRuntimeService,
ITermFactoryService termFactoryService) {
this.strategoRuntimeService = strategoRuntimeService;
this.termFactoryService = termFactoryService;
}
@Override public @Nullable IStrategoTerm invoke(ILanguageComponent component, IContext context, IStrategoTerm input,
String strategy) throws MetaborgException {
if(component.facet(StrategoRuntimeFacet.class) == null) {
return null;
}
final HybridInterpreter runtime = strategoRuntimeService.runtime(component, context, true);
return invoke(runtime, input, strategy);
}
@Override public @Nullable IStrategoTerm invoke(ILanguageImpl impl, IContext context, IStrategoTerm input,
String strategy) throws MetaborgException {
for(ILanguageComponent component : impl.components()) {
if(component.facet(StrategoRuntimeFacet.class) == null) {
continue;
}
final HybridInterpreter runtime = strategoRuntimeService.runtime(component, context, true);
final IStrategoTerm result = invoke(runtime, input, strategy);
if(result != null) {
return result;
}
}
return null;
}
@Override public @Nullable IStrategoTerm invoke(ILanguageImpl impl, FileObject location, IStrategoTerm input,
String strategy) throws MetaborgException {
for(ILanguageComponent component : impl.components()) {
if(component.facet(StrategoRuntimeFacet.class) == null) {
continue;
}
// TODO: do we really want to be typesmart? Does that need to be configurable?
final HybridInterpreter runtime = strategoRuntimeService.runtime(component, location, true);
final IStrategoTerm result = invoke(runtime, input, strategy);
if(result != null) {
return result;
}
}
return null;
}
@Override public @Nullable IStrategoTerm invoke(HybridInterpreter runtime, IStrategoTerm input, String strategy)
throws MetaborgException {
runtime.setCurrent(input);
try {
boolean success = runtime.invoke(strategy);
if(!success) {
return null;
}
return runtime.current();
} catch(InterpreterException e) {
handleException(e, runtime, strategy);
throw new MetaborgException("Invoking Stratego strategy failed unexpectedly", e);
}
}
private void handleException(InterpreterException ex, HybridInterpreter runtime, String strategy) throws MetaborgException {
final String trace = traceToString(runtime.getCompiledContext().getTrace());
try {
throw ex;
} catch(InterpreterErrorExit e) {
final String message;
final IStrategoTerm term = e.getTerm();
final String innerTrace = e.getTrace() != null ? traceToString(e.getTrace()) : trace;
if(term != null) {
final String termString;
final IStrategoString ppTerm = prettyPrint(term);
if(ppTerm != null) {
termString = ppTerm.stringValue();
} else {
termString = term.toString();
}
message = logger.format("Invoking Stratego strategy {} failed at term:\n\t{}\n{}", strategy, termString, innerTrace);
} else {
message = logger.format("Invoking Stratego strategy {} failed.\n{}", strategy, innerTrace);
}
throw new MetaborgException(message, e);
} catch(InterpreterExit e) {
final String message =
logger.format("Invoking Stratego strategy {} failed with exit code {}", strategy, e.getValue());
throw new MetaborgException(message + "\n" + trace, e);
} catch(UndefinedStrategyException e) {
final String message =
logger.format("Invoking Stratego strategy {} failed, strategy is undefined", strategy);
throw new MetaborgException(message + "\n" + trace, e);
} catch(InterpreterException e) {
final Throwable cause = e.getCause();
if(cause != null && cause instanceof InterpreterException) {
handleException((InterpreterException) cause, runtime, strategy);
} else {
throw new MetaborgException("Invoking Stratego strategy failed unexpectedly:" + "\n" + trace, e);
}
}
}
private String traceToString(String[] trace) {
StringBuilder sb = new StringBuilder();
sb.append("Stratego trace:");
for(String frame : trace) {
sb.append("\n\t");
sb.append(frame);
}
return sb.toString();
}
private String traceToString(IStrategoList trace) {
StringBuilder sb = new StringBuilder();
sb.append("Stratego trace:");
for(IStrategoTerm frame : trace) {
sb.append("\n\t");
sb.append(Tools.asJavaString(frame));
}
return sb.toString();
}
@Override public IStrategoString localLocationTerm(File localLocation) {
final ITermFactory termFactory = termFactoryService.getGeneric();
final String locationPath = localLocation.getAbsolutePath();
final IStrategoString locationPathTerm = termFactory.makeString(locationPath);
return locationPathTerm;
}
@Override public IStrategoString localResourceTerm(File localResource, File localLocation) {
final ITermFactory termFactory = termFactoryService.getGeneric();
final String resourcePath = localLocation.toURI().relativize(localResource.toURI()).getPath();
final IStrategoString resourcePathTerm = termFactory.makeString(resourcePath);
return resourcePathTerm;
}
@Override public IStrategoTerm builderInputTerm(IStrategoTerm ast, FileObject resource, FileObject location)
throws MetaborgException {
final ITermFactory termFactory = termFactoryService.getGeneric();
// TODO: support selected node
final IStrategoTerm node = ast;
// TODO: support position
final IStrategoTerm position = termFactory.makeList();
final String locationURI = location.getName().getURI();
final IStrategoString locationTerm = termFactory.makeString(locationURI);
String resourceURI;
try {
resourceURI = location.getName().getRelativeName(resource.getName());
} catch(FileSystemException e) {
resourceURI = resource.getName().getURI();
}
final IStrategoString resourceTerm = termFactory.makeString(resourceURI);
return termFactory.makeTuple(node, position, ast, resourceTerm, locationTerm);
}
@Override public String toString(IStrategoTerm term) {
if(term instanceof IStrategoString) {
return ((IStrategoString) term).stringValue();
} else {
final IStrategoString pp = prettyPrint(term);
if(pp != null) {
return pp.stringValue();
} else {
logger.error("Could not pretty print ATerm, falling back to non-pretty printed ATerm");
return term.toString();
}
}
}
@Override public IStrategoString prettyPrint(IStrategoTerm term) {
final Context context = strategoRuntimeService.genericRuntime().getCompiledContext();
final ITermFactory termFactory = termFactoryService.getGeneric();
org.strategoxt.stratego_aterm.Main.init(context);
term = aterm_escape_strings_0_0.instance.invoke(context, term);
term = pp_aterm_box_0_0.instance.invoke(context, term);
term = box2text_string_0_1.instance.invoke(context, term, termFactory.makeInt(120));
return (IStrategoString) term;
}
}
|
package org.oscm.ui.dialog.classic.marketplace;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.oscm.internal.intf.MarketplaceService;
import org.oscm.internal.marketplace.POOrganization;
import org.oscm.internal.types.exception.NonUniqueBusinessKeyException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.vo.VOMarketplace;
import org.oscm.ui.beans.BaseBean;
import org.oscm.ui.beans.MarketplaceConfigurationBean;
import org.oscm.ui.stubs.FacesContextStub;
public class ManageAccessCtrlTest {
private ManageAccessCtrl ctrl;
private ManageAccessModel model;
private MarketplaceConfigurationBean configuration;
private MarketplaceService marketplaceService;
private static final String MARKETPLACE_ID = "marketplace1";
private static final String MARKETPLACE_NAME = "marketplace1Name";
@Before
public void setup() {
new FacesContextStub(Locale.ENGLISH);
marketplaceService = mock(MarketplaceService.class);
ctrl = spy(new ManageAccessCtrl());
model = new ManageAccessModel();
configuration = new MarketplaceConfigurationBean();
ctrl.setModel(model);
ctrl.setConfiguration(configuration);
ctrl.setMarketplaceService(marketplaceService);
}
@Test
public void testInitializedMarketplaces() {
// given
doReturn(getSampleMarketplaces()).when(marketplaceService)
.getMarketplacesOwned();
// when
ctrl.initialize();
// then
verify(marketplaceService, times(1)).getMarketplacesOwned();
assertEquals(2, model.getSelectableMarketplaces().size());
}
@Test
public void testSelectedMarketplace() throws Exception {
// given
model.setSelectedMarketplaceId(MARKETPLACE_ID);
doReturn(createSampleMarketplace(MARKETPLACE_NAME, MARKETPLACE_ID))
.when(marketplaceService).getMarketplaceById(MARKETPLACE_ID);
// when
ctrl.marketplaceChanged();
// then
verify(marketplaceService, times(1)).getMarketplaceById(MARKETPLACE_ID);
}
@Test
public void testNotSelectedMarketplace() throws Exception {
// given
model.setSelectedMarketplaceId(null);
// when
ctrl.marketplaceChanged();
// then
verify(marketplaceService, times(0)).getMarketplaceById(MARKETPLACE_ID);
assertEquals(false, model.isSelectedMarketplaceRestricted());
}
@Test
public void testAccessChange() throws Exception {
// given
ctrl.getModel().setSelectedMarketplaceId(MARKETPLACE_ID);
ctrl.getModel().setSelectedMarketplaceRestricted(true);
// when
ctrl.accessChanged();
// then
verify(marketplaceService, times(1))
.getAllOrganizations(MARKETPLACE_ID);
}
@Test
public void testSave_organizationsLists() throws Exception {
// given
setupValuesForSaveAction(true);
doNothing().when(marketplaceService).closeMarketplace(anyString(),
Matchers.anySetOf(Long.class), Matchers.anySetOf(Long.class));
// when
String result = ctrl.save();
// then
assertEquals(0, model.getAuthorizedOrganizations().size());
assertEquals(0, model.getUnauthorizedOrganizations().size());
assertEquals(BaseBean.OUTCOME_SUCCESS, result);
}
@Test
public void testSave_closeMarketplace() throws Exception {
// given
setupValuesForSaveAction(true);
doNothing().when(marketplaceService).closeMarketplace(anyString(),
Matchers.anySetOf(Long.class), Matchers.anySetOf(Long.class));
// when
String result = ctrl.save();
// then
verify(marketplaceService, times(1)).closeMarketplace(MARKETPLACE_ID,
model.getAuthorizedOrganizations(),
model.getUnauthorizedOrganizations());
assertEquals(BaseBean.OUTCOME_SUCCESS, result);
}
@Test
public void testSave_openMarketplace()
throws OperationNotPermittedException, ObjectNotFoundException,
NonUniqueBusinessKeyException {
// given
setupValuesForSaveAction(false);
doNothing().when(marketplaceService).openMarketplace(anyString());
// when
String result = ctrl.save();
// then
verify(marketplaceService, times(1)).openMarketplace(MARKETPLACE_ID);
assertEquals(BaseBean.OUTCOME_SUCCESS, result);
}
private void setupValuesForSaveAction(boolean restrictMarketplace)
throws OperationNotPermittedException, ObjectNotFoundException,
NonUniqueBusinessKeyException {
model.setSelectedMarketplaceId(MARKETPLACE_ID);
model.setOrganizations(preparePOOrganizationsList());
model.setSelectedMarketplaceRestricted(restrictMarketplace);
VOMarketplace marketplace = createSampleMarketplace(MARKETPLACE_NAME,
MARKETPLACE_ID);
marketplace.setRestricted(restrictMarketplace);
doNothing().when(ctrl).addMessage(any(String.class));
}
private List<VOMarketplace> getSampleMarketplaces() {
VOMarketplace marketplace1 = createSampleMarketplace(
"TestMarketplace1", "c34567fg");
VOMarketplace marketplace2 = createSampleMarketplace(
"TestMarketplace2", "45tf7s20");
List<VOMarketplace> marketplaces = new ArrayList<>();
marketplaces.add(marketplace1);
marketplaces.add(marketplace2);
return marketplaces;
}
private VOMarketplace createSampleMarketplace(String name, String id) {
VOMarketplace marketplace = new VOMarketplace();
marketplace.setMarketplaceId(id);
marketplace.setName(name);
return marketplace;
}
private List<POOrganization> preparePOOrganizationsList() {
List<POOrganization> organizations = new ArrayList<>();
organizations.add(preparePOOrganization(1L, "org1", true));
organizations.add(preparePOOrganization(2L, "org2", false));
return organizations;
}
private POOrganization preparePOOrganization(long key,
String organizationId, boolean selected) {
POOrganization poOrganization = new POOrganization();
poOrganization.setOrganizationId(organizationId);
poOrganization.setKey(key);
poOrganization.setName(organizationId + "Name");
poOrganization.setSelected(selected);
return poOrganization;
}
}
|
package inovapap.sp.gtfs;
public class Trips {
private String routeId;
private String serviceId;
private String tripId;
private String tripHeadsign;
private int directionId;
private int shapeId;
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;
import java.net.URL;
import java.util.Random;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
BufferedImage i1 = makeImage(getClass().getResource("test.png"));
BufferedImage i2 = makeImage(getClass().getResource("test.jpg"));
RandomDissolve randomDissolve = new RandomDissolve(i1, i2);
JButton button = new JButton("change");
button.addActionListener(e -> randomDissolve.animationStart());
add(randomDissolve);
add(button, BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
private BufferedImage makeImage(URL url) {
ImageIcon icon = new ImageIcon(url);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
icon.paintIcon(this, g2, 0, 0);
g2.dispose();
// BufferedImage img = null;
// try {
// img = ImageIO.read(url);
// } catch (IOException ex) {
// ex.printStackTrace();
return img;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class RandomDissolve extends JComponent implements ActionListener {
private static final int STAGES = 16;
private final Random rnd = new Random();
private final Timer animator;
private final transient BufferedImage image1;
private final transient BufferedImage image2;
private transient BufferedImage buf;
private boolean mode = true;
private int currentStage;
private int[] src;
private int[] dst;
private int[] step;
protected RandomDissolve(BufferedImage i1, BufferedImage i2) {
super();
this.image1 = i1;
this.image2 = i2;
this.buf = copyImage(mode ? image2 : image1);
animator = new Timer(10, this);
}
private boolean nextStage() {
if (currentStage > 0) {
currentStage = currentStage - 1;
for (int i = 0; i < step.length; i++) {
if (step[i] == currentStage) {
src[i] = dst[i];
}
}
return true;
} else {
return false;
}
}
private static BufferedImage copyImage(BufferedImage image) {
int w = image.getWidth();
int h = image.getHeight();
BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = result.createGraphics();
g2.drawRenderedImage(image, null);
g2.dispose();
return result;
}
private static int[] getData(BufferedImage image) {
WritableRaster wr = image.getRaster();
DataBufferInt dbi = (DataBufferInt) wr.getDataBuffer();
return dbi.getData();
// return ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
}
public void animationStart() {
currentStage = STAGES;
buf = copyImage(mode ? image2 : image1);
src = getData(buf);
dst = getData(copyImage(mode ? image1 : image2));
step = new int[src.length];
mode ^= true;
for (int i = 0; i < step.length; i++) {
step[i] = rnd.nextInt(currentStage);
}
animator.start();
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());
g2.drawImage(buf, 0, 0, buf.getWidth(), buf.getHeight(), this);
g2.dispose();
}
@Override public void actionPerformed(ActionEvent e) {
if (nextStage()) {
repaint();
} else {
animator.stop();
}
}
}
|
package org.nutz.mvc.testapp.views;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.mvc.testapp.BaseWebappTest;
import org.nutz.mvc.view.RawView;
import org.nutz.mvc.view.RawView.RangeRange;
public class RawViewTest extends BaseWebappTest {
@Test
public void test_raw(){
get("/views/raw");
assertEquals("ABC", resp.getContent());
get("/views/raw2");
assertEquals(3, resp.getContent().length());
get("/views/raw3");
assertEquals(3, resp.getContent().length());
get("/views/raw4");
assertEquals("", resp.getContent());
get("/views/raw5");
assertTrue(resp.getHeader().get("Content-Type").startsWith("application/json"));
}
// @Test
public void test_raw2() throws Throwable {
File src = new File("H://main_qt");
File dst = new File("H://cache.tmp");
RangeRange rangeRange = new RangeRange(0, src.length());
// RawView.writeFileRange(src, new FileOutputStream(dst), rangeRange);
// System.out.println(Lang.digest("md5", src));
// System.out.println(Lang.digest("md5", dst));
List<RangeRange> rs = new ArrayList<RawView.RangeRange>();
RawView.parseRange("bytes=0-,-1000000,22222-22222222222", rs, Long.MAX_VALUE);
System.out.println(Json.toJson(rs));
src = new File("H://raw");
FileOutputStream out = new FileOutputStream(src);
for (int i = 0; i < 255; i++) {
out.write(i);
}
out.flush();
out.close();
rs = new ArrayList<RawView.RangeRange>();
RawView.parseRange("bytes=0-127", rs, 256);
rangeRange = rs.get(0);
RawView.writeFileRange(src, new FileOutputStream(dst), rangeRange);
System.out.println(dst.length());
FileInputStream in = new FileInputStream(dst);
for (int i = 0; i < 128; i++) {
if (in.read() != i) {
System.out.println("ERR");
}
}
rs = new ArrayList<RawView.RangeRange>();
RawView.parseRange("bytes=128-", rs, 256);
rangeRange = rs.get(0);
RawView.writeFileRange(src, new FileOutputStream(dst), rangeRange);
in = new FileInputStream(dst);
for (int i = 0; i < 128; i++) {
if (in.read() != (i + 128)) {
System.out.println("ERR");
}
}
rs = new ArrayList<RawView.RangeRange>();
RawView.parseRange("bytes=-64", rs, 256);
rangeRange = rs.get(0);
RawView.writeFileRange(src, new FileOutputStream(dst), rangeRange);
in = new FileInputStream(dst);
for (int i = 0; i < 64; i++) {
if (in.read() != (i + 128 + 64)) {
System.out.println("ERR");
}
}
System.out.println("
}
}
|
package org.lockss.test;
import java.io.*;
import java.net.*;
import java.util.*;
public class MockDatagramSocket extends DatagramSocket{
/**
* This class is a mock implementation of DatagramSocket to be used for unit testing
*/
private boolean isClosed = false;
private Vector sentPackets;
private Vector receiveQueue;
//stubs for DatagramSocket methods
public MockDatagramSocket() throws SocketException{
sentPackets = new Vector();
receiveQueue = new Vector();
}
/**
* @param port this is ignored and only here to override the
* DatagramSocket contructor
*/
public MockDatagramSocket(int port) throws SocketException{
this();
}
/**
* @param port this is ignored and only here to override the
* DatagramSocket contructor
* @param host ditto
*/
public MockDatagramSocket(int port, InetAddress laddr) throws SocketException{
this();
}
/**
* Flags this as a closed socket. Can be tested with isClosed method
*@see #isClosed
*/
public void close(){
this.isClosed = true;
}
/**
* Stubbed
*/
public void connect(InetAddress address, int port){
}
/**
* Stubbed
*/
public void disconnect(){
}
/**
* Stubbed
*/
public InetAddress getInetAddress(){
return null;
}
/**
* Stubbed
*/
public InetAddress getLocalAddress(){
return null;
}
/**
* Stubbed
*/
public int getLocalPort(){
return -1;
}
/**
* Stubbed
*/
public int getPort(){
return -1;
}
/**
* Stubbed
*/
public int getReceiverBufferSize(){
return -1;
}
/**
* Stubbed
*/
public int getSendBufferSize(){
return -1;
}
/**
* Stubbed
*/
public int getSoTimeout(){
return -1;
}
/**
* If packets have been preloaded using addToReceiveQueue, will copy the top one
* into p
* @param p pre-allocated packet to receive data from queued packet
* @throws IOException if no packets have been queued
* @see #addToReceiveQueue
*/
public void receive(DatagramPacket p) throws IOException{
if (receiveQueue.size() == 0){
throw new IOException("receive called in "+
"org.lockss.test.MockDatagramSocket without "+
"receivedPackets set");
}
DatagramPacket returnPacket = (DatagramPacket)receiveQueue.remove(0);
p.setPort(returnPacket.getPort());
p.setAddress(returnPacket.getAddress());
p.setData(returnPacket.getData());
}
/**
* Take p and add it to the queue of "sent" packets. This queue can be read using
* getSentPackets()
* @param p packet to "send"
* @see #getSentPackets
*/
public void send(DatagramPacket p){
sentPackets.add(p);
}
public static void setDatagramSocketImplFactory(DatagramSocketImplFactory fac){
}
public void setReceiveBufferSize(int size){
}
public void setSendBufferSize(int size){
}
public void setSoTimeout(int timeout){
}
//non-DatagramSocket methods
/**
* @return true if close() has been called on this socket, false otherwise
* @see #close
*/
public boolean isClosed(){
return this.isClosed;
}
/**
* @return a vector containing all packets which have been queued using send(p)
* @see #send
*/
public Vector getSentPackets(){
return sentPackets;
}
/**
* @param packet DatagramPacket to add to the queue of packets to feed back when
* receive(p) is called
* @see #receive
*/
public void addToReceiveQueue(DatagramPacket packet){
receiveQueue.add(packet);
}
}
|
package org.eigenbase.util;
import org.eigenbase.relopt.RelTrait;
import java.util.*;
// REVIEW jvs 7-Jan-2003: using inheritance from HashMap seems a little
// dangerous since method like entrySet() won't work as expected; should
// probably define a separate MultiMap interface and use aggregation rather
// than inheritance in the implementation
/**
* Map which contains more than one value per key.
*
* <p>
* You can either use a <code>MultiMap</code> as a regular map, or you can use
* the additional methods {@link #putMulti} and {@link #getMulti}. Values are
* returned in the order in which they were added.
* </p>
*
* @author jhyde
* @version $Id$
*
* @since May 18, 2003
*/
public class MultiMap<K,V>
{
private final Map<K,Object> map = new HashMap<K,Object>();
private Object get(K key)
{
return map.get(key);
}
private Object put(K key, V value)
{
return map.put(key, value);
}
/**
* Returns a list of values for a given key; returns an empty list if not
* found.
*
* @post return != null
*/
public List<V> getMulti(K key)
{
Object o = get(key);
if (o == null) {
return Collections.emptyList();
} else if (o instanceof ValueList) {
return (ValueList<V>) o;
} else {
return Collections.singletonList((V) o);
}
}
/**
* Adds a value for this key.
*/
public void putMulti(
K key,
V value)
{
final Object o = put(key, value);
if (o != null) {
// We knocked something out. It might be a list, or a singleton
// object.
ValueList<V> list;
if (o instanceof ValueList) {
list = (ValueList<V>) o;
} else {
list = new ValueList<V>();
list.add((V) o);
}
list.add(value);
map.put(key, list);
}
}
/**
* Removes a value for this key.
*/
public boolean removeMulti(
K key,
V value)
{
final Object o = get(key);
if (o == null) {
// key not found, so nothing changed
return false;
} else {
if (o instanceof ValueList) {
ValueList<V> list = (ValueList<V>) o;
if (list.remove(value)) {
if (list.size() == 1) {
// now just one value left, so forget the list, and
// keep its only element
put(key, list.get(0));
}
return true;
} else {
// nothing changed
return false;
}
} else {
if (o.equals(value)) {
// have just removed the last value belonging to this key,
// so remove the key.
remove(key);
return true;
} else {
// the value they asked to remove was not the one present,
// so nothing changed
return false;
}
}
}
}
/**
* Like entrySet().iterator(), but returns one Map.Entry per value
* rather than one per key.
*/
public EntryIter entryIterMulti()
{
return new EntryIter();
}
public Object remove(K key)
{
return map.remove(key);
}
public boolean containsKey(K key)
{
return map.containsKey(key);
}
public void clear()
{
map.clear();
}
/**
* Holder class, ensures that user's values are never interpreted as
* multiple values.
*/
private static class ValueList<V> extends ArrayList<V>
{
}
/**
* Implementation for entryIterMulti(). Note that this assumes that
* empty ValueLists will never be encountered, and also preserves
* this property when remove() is called.
*/
private class EntryIter implements Iterator<Map.Entry<K,V>>
{
K key;
Iterator<K> keyIter;
List<V> valueList;
Iterator<V> valueIter;
EntryIter()
{
keyIter = map.keySet().iterator();
if (keyIter.hasNext()) {
nextKey();
} else {
valueList = Collections.emptyList();
valueIter = valueList.iterator();
}
}
private void nextKey()
{
key = keyIter.next();
valueList = getMulti(key);
valueIter = valueList.iterator();
}
public boolean hasNext()
{
return keyIter.hasNext() || valueIter.hasNext();
}
public Map.Entry<K,V> next()
{
if (!valueIter.hasNext()) {
nextKey();
}
final K savedKey = key;
final V value = valueIter.next();
return new Map.Entry<K,V>() {
public K getKey()
{
return savedKey;
}
public V getValue()
{
return value;
}
public boolean equals(Object o)
{
throw new UnsupportedOperationException();
}
public int hashCode()
{
throw new UnsupportedOperationException();
}
public V setValue(V value)
{
throw new UnsupportedOperationException();
}
};
}
public void remove()
{
if (valueList instanceof ValueList) {
valueIter.remove();
if (valueList.isEmpty()) {
keyIter.remove();
}
} else {
keyIter.remove();
}
}
}
}
// End MultiMap.java
|
package org.eigenbase.util;
import java.io.*;
import java.math.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import junit.framework.*;
import junit.textui.*;
import org.eigenbase.runtime.*;
import org.eigenbase.test.DiffTestCase;
/**
* Unit test for {@link Util} and other classes in this package.
*
* @author jhyde
* @version $Id$
* @since Jul 12, 2004
*/
public class UtilTest
extends TestCase
{
public UtilTest(String name)
{
super(name);
}
public static Test suite()
throws Exception
{
TestSuite suite = new TestSuite();
suite.addTestSuite(UtilTest.class);
return suite;
}
public void testPrintEquals()
{
assertPrintEquals("\"x\"", "x", true);
}
public void testPrintEquals2()
{
assertPrintEquals("\"x\"", "x", false);
}
public void testPrintEquals3()
{
assertPrintEquals("null", null, true);
}
public void testPrintEquals4()
{
assertPrintEquals("", null, false);
}
public void testPrintEquals5()
{
assertPrintEquals("\"\\\\\\\"\\r\\n\"", "\\\"\r\n", true);
}
public void testScientificNotation()
{
BigDecimal bd;
bd = new BigDecimal("0.001234");
TestUtil.assertEqualsVerbose(
"1.234E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("0.001");
TestUtil.assertEqualsVerbose(
"1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("-0.001");
TestUtil.assertEqualsVerbose(
"-1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("1");
TestUtil.assertEqualsVerbose(
"1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1");
TestUtil.assertEqualsVerbose(
"-1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("1.0");
TestUtil.assertEqualsVerbose(
"1.0E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345");
TestUtil.assertEqualsVerbose(
"1.2345E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.00");
TestUtil.assertEqualsVerbose(
"1.234500E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.001");
TestUtil.assertEqualsVerbose(
"1.2345001E4",
Util.toScientificNotation(bd));
//test truncate
bd = new BigDecimal("1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"1.2345678901234567890E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"-1.2345678901234567890E0",
Util.toScientificNotation(bd));
}
public void testToJavaId()
throws UnsupportedEncodingException
{
assertEquals(
"ID$0$foo",
Util.toJavaId("foo", 0));
assertEquals(
"ID$0$foo_20_bar",
Util.toJavaId("foo bar", 0));
assertEquals(
"ID$0$foo__bar",
Util.toJavaId("foo_bar", 0));
assertEquals(
"ID$100$_30_bar",
Util.toJavaId("0bar", 100));
assertEquals(
"ID$0$foo0bar",
Util.toJavaId("foo0bar", 0));
assertEquals(
"ID$0$it_27_s_20_a_20_bird_2c__20_it_27_s_20_a_20_plane_21_",
Util.toJavaId("it's a bird, it's a plane!", 0));
// Try some funny non-ASCII charsets
assertEquals(
"ID$0$_f6__cb__c4__ca__ae__c1__f9__cb_",
Util.toJavaId(
"\u00f6\u00cb\u00c4\u00ca\u00ae\u00c1\u00f9\u00cb",
0));
assertEquals(
"ID$0$_f6cb__c4ca__aec1__f9cb_",
Util.toJavaId("\uf6cb\uc4ca\uaec1\uf9cb", 0));
byte [] bytes1 = { 3, 12, 54, 23, 33, 23, 45, 21, 127, -34, -92, -113 };
assertEquals(
"ID$0$_3__c_6_17__21__17__2d__15__7f__6cd9__fffd_",
Util.toJavaId(new String(bytes1, "EUC-JP"),
0));
byte [] bytes2 =
{ 64, 32, 43, -45, -23, 0, 43, 54, 119, -32, -56, -34 };
assertEquals(
"ID$0$_30c__3617__2117__2d15__7fde__a48f_",
Util.toJavaId(new String(bytes1, "UTF-16"),
0));
}
private void assertPrintEquals(
String expect,
String in,
boolean nullMeansNull)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Util.printJavaString(pw, in, nullMeansNull);
pw.flush();
String out = sw.toString();
assertEquals(expect, out);
}
/**
* Tests whether {@link EnumeratedValues} serialize correctly.
*/
public void testSerializeEnumeratedValues()
throws IOException, ClassNotFoundException
{
UnserializableEnum unser =
(UnserializableEnum) serializeAndDeserialize(
UnserializableEnum.Foo);
assertFalse(unser == UnserializableEnum.Foo);
SerializableEnum ser =
(SerializableEnum) serializeAndDeserialize(SerializableEnum.Foo);
assertTrue(ser == SerializableEnum.Foo);
}
private static Object serializeAndDeserialize(Object e1)
throws IOException, ClassNotFoundException
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(e1);
out.flush();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object o = in.readObject();
return o;
}
/**
* Unit-test for {@link BitString}.
*/
public void testBitString()
{
// Powers of two, minimal length.
final BitString b0 = new BitString("", 0);
final BitString b1 = new BitString("1", 1);
final BitString b2 = new BitString("10", 2);
final BitString b4 = new BitString("100", 3);
final BitString b8 = new BitString("1000", 4);
final BitString b16 = new BitString("10000", 5);
final BitString b32 = new BitString("100000", 6);
final BitString b64 = new BitString("1000000", 7);
final BitString b128 = new BitString("10000000", 8);
final BitString b256 = new BitString("100000000", 9);
// other strings
final BitString b0_1 = new BitString("", 1);
final BitString b0_12 = new BitString("", 12);
// conversion to hex strings
assertEquals(
"",
b0.toHexString());
assertEquals(
"1",
b1.toHexString());
assertEquals(
"2",
b2.toHexString());
assertEquals(
"4",
b4.toHexString());
assertEquals(
"8",
b8.toHexString());
assertEquals(
"10",
b16.toHexString());
assertEquals(
"20",
b32.toHexString());
assertEquals(
"40",
b64.toHexString());
assertEquals(
"80",
b128.toHexString());
assertEquals(
"100",
b256.toHexString());
assertEquals(
"0",
b0_1.toHexString());
assertEquals(
"000",
b0_12.toHexString());
// to byte array
assertByteArray("01", "1", 1);
assertByteArray("01", "1", 5);
assertByteArray("01", "1", 8);
assertByteArray("00, 01", "1", 9);
assertByteArray("", "", 0);
assertByteArray("00", "0", 1);
assertByteArray("00", "0000", 2); // bit count less than string
assertByteArray("00", "000", 5); // bit count larger than string
assertByteArray("00", "0", 8); // precisely 1 byte
assertByteArray("00, 00", "00", 9); // just over 1 byte
// from hex string
assertReversible("");
assertReversible("1");
assertReversible("10");
assertReversible("100");
assertReversible("1000");
assertReversible("10000");
assertReversible("100000");
assertReversible("1000000");
assertReversible("10000000");
assertReversible("100000000");
assertReversible("01");
assertReversible("001010");
assertReversible("000000000100");
}
private static void assertReversible(String s)
{
assertEquals(
s,
BitString.createFromBitString(s).toBitString(),
s);
assertEquals(
s,
BitString.createFromHexString(s).toHexString());
}
private void assertByteArray(
String expected,
String bits,
int bitCount)
{
byte [] bytes = BitString.toByteArrayFromBitString(bits, bitCount);
final String s = toString(bytes);
assertEquals(expected, s);
}
/**
* Converts a byte array to a hex string like "AB, CD".
*/
private String toString(byte [] bytes)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (i > 0) {
buf.append(", ");
}
String s = Integer.toString(b, 16);
buf.append((b < 16) ? ("0" + s) : s);
}
return buf.toString();
}
/**
* Tests {@link CastingList} and {@link Util#cast}.
*/
public void testCastingList()
{
final List<Number> numberList = new ArrayList<Number>();
numberList.add(new Integer(1));
numberList.add(null);
numberList.add(new Integer(2));
List<Integer> integerList = Util.cast(numberList, Integer.class);
assertEquals(3, integerList.size());
assertEquals(new Integer(2), integerList.get(2));
// Nulls are OK.
assertNull(integerList.get(1));
// Can update the underlying list.
integerList.set(1, 345);
assertEquals(new Integer(345), integerList.get(1));
integerList.set(1, null);
assertNull(integerList.get(1));
// Can add a member of the wrong type to the underlying list.
numberList.add(new Double(3.1415));
assertEquals(4, integerList.size());
// Access a member which is of the wrong type.
try {
integerList.get(3);
fail("expected exception");
} catch (ClassCastException e) {
}
}
public void testIterableProperties()
{
Properties properties = new Properties();
properties.put("foo", "george");
properties.put("bar", "ringo");
StringBuilder sb = new StringBuilder();
for (
Map.Entry<String, String> entry : Util.toMap(properties).entrySet())
{
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append(";");
}
assertEquals("bar=ringo;foo=george;", sb.toString());
assertEquals(2, Util.toMap(properties).entrySet().size());
properties.put("nonString", 34);
try {
for (
Map.Entry<String, String> entry
: Util.toMap(properties).entrySet())
{
String s = entry.getValue();
Util.discard(s);
}
fail("expected exception");
} catch (ClassCastException e) {
}
}
/**
* Tests the difference engine, {@link DiffTestCase#diff}.
*/
public void testDiffLines() {
String[] before = {
"Get a dose of her in jackboots and kilt",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The News of The World",
"Yes you could say she was attractively built.",
"Yeah yeah yeah."
};
String[] after = {
"Get a dose of her in jackboots and kilt",
"(they call her \"Polythene Pam\")",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The Sunday Times",
"seem more interesting.",
"Yes you could say she was attractively built."
};
String diff = DiffTestCase.diffLines(
Arrays.asList(before), Arrays.asList(after));
assertEquals(
diff,
TestUtil.fold("1a2\n" +
"> (they call her \"Polythene Pam\")\n" +
"3c4,5\n" +
"< She's the kind of a girl that makes The News of The World\n" +
"
"> She's the kind of a girl that makes The Sunday Times\n" +
"> seem more interesting.\n" +
"5d6\n" +
"< Yeah yeah yeah.\n"));
}
/**
* Tests the {@link Util#toPosix(TimeZone, boolean)} method.
*/
public void testPosixTimeZone()
{
// NOTE jvs 31-July-2007: First two tests are disabled since
// not everyone may have patched their system yet for recent
// DST change.
// Pacific Standard Time. Effective 2007, the local time changes from
// PST to PDT at 02:00 LST to 03:00 LDT on the second Sunday in March
// and returns at 02:00 LDT to 01:00 LST on the first Sunday in
// November.
if (false) {
assertEquals("PST-8PDT,M3.2.0,M11.1.0",
Util.toPosix(TimeZone.getTimeZone("PST"), false));
assertEquals("PST-8PDT1,M3.2.0/2,M11.1.0/2",
Util.toPosix(TimeZone.getTimeZone("PST"), true));
}
// Tokyo has +ve offset, no DST
assertEquals("JST9",
Util.toPosix(TimeZone.getTimeZone("Asia/Tokyo"), true));
// Sydney, Australia lies ten hours east of GMT and makes a one hour
// shift forward during daylight savings. Being located in the southern
// hemisphere, daylight savings begins on the last Sunday in October at
// 2am and ends on the last Sunday in March at 3am.
// (Uses STANDARD_TIME time-transition mode.)
try {
TimeZone timezone = TimeZone.getTimeZone("Australia/Sydney");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date testDate = format.parse("2008-10-3");
if (timezone.inDaylightTime(testDate)) {
assertEquals("EST10EST1,M10.5.0/2,M3.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
} else {
assertEquals("EST10EST1,M10.1.0/2,M4.1.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
}
} catch (ParseException pe) {
fail("Problem parsing test date");
}
// Paris, France. (Uses UTC_TIME time-transition mode.)
assertEquals("CET1CEST1,M3.5.0/2,M10.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Europe/Paris"), true));
assertEquals("UTC0",
Util.toPosix(TimeZone.getTimeZone("UTC"), true));
}
/**
* Runs the test suite.
*/
public static void main(String [] args)
throws Exception
{
TestRunner.run(suite());
}
/**
* Enumeration which extends BasicValue does NOT serialize correctly.
*/
private static class UnserializableEnum
extends EnumeratedValues.BasicValue
{
public static final UnserializableEnum Foo =
new UnserializableEnum("foo", 1);
public static final UnserializableEnum Bar =
new UnserializableEnum("bar", 2);
public UnserializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
}
/**
* Enumeration which serializes correctly.
*/
private static class SerializableEnum
extends EnumeratedValues.SerializableValue
{
public static final SerializableEnum Foo =
new SerializableEnum("foo", 1);
public static final SerializableEnum Bar =
new SerializableEnum("bar", 2);
public SerializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
protected Object readResolve()
throws ObjectStreamException
{
switch (_ordinal) {
case 1:
return Foo;
case 2:
return Bar;
default:
throw new IllegalArgumentException();
}
}
}
}
// End UtilTest.java
|
package mondrian.rolap;
import mondrian.olap.*;
import mondrian.test.SqlPattern;
import mondrian.test.TestContext;
import java.util.List;
/**
* <code>VirtualCubeTest</code> shows virtual cube tests.
*
* @author remberson
* @since Feb 14, 2003
* @version $Id$
*/
public class VirtualCubeTest extends BatchTestCase {
public VirtualCubeTest() {
}
public VirtualCubeTest(String name) {
super(name);
}
/**
* This method demonstrates bug 1449929
*/
public void testNoTimeDimension() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\">\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Unit Sales]\"/>\n" +
"</VirtualCube>",
null, null);
checkXxx(testContext);
}
public void testCalculatedMeasureAsDefaultMeasureInVC() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\" defaultMeasure=\"Profit\">\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" " +
"name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Unit Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Profit]\"/>\n" +
"</VirtualCube>",
null, null);
String query1 = "select from [Sales vs Warehouse]";
String query2 = "select from [Sales vs Warehouse] where measures.profit";
assertQueriesReturnSimilarResults(query1,query2, testContext);
}
public void testDefaultMeasureInVCForIncorrectMeasureName() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\" defaultMeasure=\"Profit Error\">\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" " +
"name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Unit Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Profit]\"/>\n" +
"</VirtualCube>",
null, null);
String query1 = "select from [Sales vs Warehouse]";
String query2 = "select from [Sales vs Warehouse] " +
"where measures.[Warehouse Sales]";
assertQueriesReturnSimilarResults(query1,query2, testContext);
}
public void testDefaultMeasureInVCForCaseSensitivity() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\" defaultMeasure=\"PROFIT\">\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" " +
"name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Unit Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Profit]\"/>\n" +
"</VirtualCube>",
null, null);
String queryWithoutFilter = "select from [Sales vs Warehouse]";
String queryWithFirstMeasure = "select from [Sales vs Warehouse] " +
"where measures.[Warehouse Sales]";
String queryWithDefaultMeasureFilter = "select from [Sales vs Warehouse] " +
"where measures.[Profit]";
if (MondrianProperties.instance().CaseSensitive.get()) {
assertQueriesReturnSimilarResults(queryWithoutFilter,
queryWithFirstMeasure, testContext);
} else {
assertQueriesReturnSimilarResults(queryWithoutFilter,
queryWithDefaultMeasureFilter, testContext);
}
}
public void testWithTimeDimension() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\">\n" +
"<VirtualCubeDimension name=\"Time\"/>\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Unit Sales]\"/>\n" +
"</VirtualCube>",
null, null);
checkXxx(testContext);
}
private void checkXxx(TestContext testContext) {
// I do not know/believe that the return values are correct.
testContext.assertQueryReturns(
"select\n" +
"{ [Measures].[Warehouse Sales], [Measures].[Unit Sales] }\n" +
"ON COLUMNS,\n" +
"{[Product].[All Products]}\n" +
"ON ROWS\n" +
"from [Sales vs Warehouse]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Warehouse Sales]}\n" +
"{[Measures].[Unit Sales]}\n" +
"Axis
"{[Product].[All Products]}\n" +
"Row #0: 196,770.888\n" +
"Row #0: 266,773\n"));
}
/**
* Query a virtual cube that contains a non-conforming dimension that
* does not have ALL as its default member.
*/
public void testNonDefaultAllMember() {
// Create a virtual cube with a non-conforming dimension (Warehouse)
// that does not have ALL as its default member.
TestContext testContext = createContextWithNonDefaultAllMember();
testContext.assertQueryReturns(
"select {[Warehouse].defaultMember} on columns, " +
"{[Measures].[Warehouse Cost]} on rows from [Warehouse (Default USA)]",
fold("Axis
"{}\n" +
"Axis
"{[Warehouse].[USA]}\n" +
"Axis
"{[Measures].[Warehouse Cost]}\n" +
"Row #0: 89,043.253\n"));
// There is a value for [USA] -- because it is the default member and
// the hierarchy has no all member -- but not for [USA].[CA].
testContext.assertQueryReturns(
"select {[Warehouse].defaultMember, [Warehouse].[USA].[CA]} on columns, " +
"{[Measures].[Warehouse Cost], [Measures].[Sales Count]} on rows " +
"from [Warehouse (Default USA) and Sales]",
fold(
"Axis
"{}\n" +
"Axis
"{[Warehouse].[USA]}\n" +
"{[Warehouse].[USA].[CA]}\n" +
"Axis
"{[Measures].[Warehouse Cost]}\n" +
"{[Measures].[Sales Count]}\n" +
"Row #0: 89,043.253\n" +
"Row #0: 25,789.086\n" +
"Row #1: 86,837\n" +
"Row #1: \n"));
}
public void testNonDefaultAllMember2() {
TestContext testContext = createContextWithNonDefaultAllMember();
testContext.assertQueryReturns(
"select { measures.[unit sales] } on 0 \n" +
"from [warehouse (Default USA) and Sales]",
fold(
"Axis
"{}\n" +
"Axis
"{[Measures].[Unit Sales]}\n" +
"Row #0: 266,773\n"));
}
/**
* Creates a TestContext containing a cube
* "Warehouse (Default USA) and Sales".
*/
private TestContext createContextWithNonDefaultAllMember() {
return TestContext.create(
null,
// Warehouse cube where the default member in the Warehouse
// dimension is USA.
"<Cube name=\"Warehouse (Default USA)\">\n" +
" <Table name=\"inventory_fact_1997\"/>\n" +
"\n" +
" <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" +
" <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n" +
" <DimensionUsage name=\"Store\" source=\"Store\" foreignKey=\"store_id\"/>\n" +
" <Dimension name=\"Warehouse\" foreignKey=\"warehouse_id\">\n" +
" <Hierarchy hasAll=\"false\" defaultMember=\"[USA]\" primaryKey=\"warehouse_id\"> \n" +
" <Table name=\"warehouse\"/>\n" +
" <Level name=\"Country\" column=\"warehouse_country\" uniqueMembers=\"true\"/>\n" +
" <Level name=\"State Province\" column=\"warehouse_state_province\"\n" +
" uniqueMembers=\"true\"/>\n" +
" <Level name=\"City\" column=\"warehouse_city\" uniqueMembers=\"false\"/>\n" +
" <Level name=\"Warehouse Name\" column=\"warehouse_name\" uniqueMembers=\"true\"/>\n" +
" </Hierarchy>\n" +
" </Dimension>\n" +
" <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n" +
" <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n" +
"</Cube>",
// Virtual cube based on [Warehouse (Default USA)]
"<VirtualCube name=\"Warehouse (Default USA) and Sales\">\n" +
" <VirtualCubeDimension name=\"Product\"/>\n" +
" <VirtualCubeDimension name=\"Store\"/>\n" +
" <VirtualCubeDimension name=\"Time\"/>\n" +
" <VirtualCubeDimension cubeName=\"Warehouse (Default USA)\" name=\"Warehouse\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales 2\" name=\"[Measures].[Sales Count]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales 2\" name=\"[Measures].[Store Cost]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales 2\" name=\"[Measures].[Store Sales]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales 2\" name=\"[Measures].[Unit Sales]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Store Invoice]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Supply Time]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Units Ordered]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Units Shipped]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Warehouse Cost]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Warehouse Sales]\"/>\n" +
"</VirtualCube>",
null, null);
}
public void testMemberVisibility() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Warehouse and Sales Member Visibility\">\n" +
" <VirtualCubeDimension cubeName=\"Sales\" name=\"Customers\"/>\n" +
" <VirtualCubeDimension name=\"Time\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Sales Count]\" visible=\"true\" />\n" +
" <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Store Cost]\" visible=\"false\" />\n" +
" <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Store Sales]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse\" name=\"[Measures].[Units Shipped]\" visible=\"false\" />\n" +
" <CalculatedMember name=\"Profit\" dimension=\"Measures\" visible=\"false\" >\n" +
" <Formula>[Measures].[Store Sales] - [Measures].[Store Cost]</Formula>\n" +
" </CalculatedMember>\n" +
"</VirtualCube>",
null, null);
Result result = testContext.executeQuery(
"select {[Measures].[Sales Count],\n" +
" [Measures].[Store Cost],\n" +
" [Measures].[Store Sales],\n" +
" [Measures].[Units Shipped],\n" +
" [Measures].[Profit]} on columns\n" +
"from [Warehouse and Sales Member Visibility]");
assertVisibility(result, 0, "Sales Count", true); // explicitly visible
assertVisibility(result, 1, "Store Cost", false); // explicitly invisible
assertVisibility(result, 2, "Store Sales", true); // visible by default
assertVisibility(result, 3, "Units Shipped", false); // explicitly invisible
assertVisibility(result, 4, "Profit", false); // explicitly invisible
}
private void assertVisibility(
Result result, int ordinal, String expectedName,
boolean expectedVisibility)
{
List<Position> columnPositions = result.getAxes()[0].getPositions();
Member measure = columnPositions.get(ordinal).get(0);
assertEquals(expectedName, measure.getName());
assertEquals(
Boolean.valueOf(expectedVisibility),
measure.getPropertyValue(Property.VISIBLE.name));
}
/**
* Test an expression for the format_string of a calculated member that
* evaluates calculated members based on a virtual cube. One cube has cache
* turned on, the other cache turned off.
*
* <p>Since evaluation of the format_string used to happen after the
* aggregate cache was cleared, this used to fail, this should be solved
* with the caching of the format string.
*
* <p>Without caching of format string, the query returns green for all
* styles.
*/
public void testFormatStringExpressionCubeNoCache() {
TestContext testContext = TestContext.create(
null, null,
"<Cube name=\"Warehouse No Cache\" cache=\"false\">\n" +
" <Table name=\"inventory_fact_1997\"/>\n" +
"\n" +
" <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" +
" <DimensionUsage name=\"Store\" source=\"Store\" foreignKey=\"store_id\"/>\n" +
" <Measure name=\"Units Shipped\" column=\"units_shipped\" aggregator=\"sum\" formatString=\"
"</Cube>\n" +
"<VirtualCube name=\"Warehouse and Sales Format Expression Cube No Cache\">\n" +
" <VirtualCubeDimension name=\"Store\"/>\n" +
" <VirtualCubeDimension name=\"Time\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Store Cost]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Store Sales]\"/>\n" +
" <VirtualCubeMeasure cubeName=\"Warehouse No Cache\" name=\"[Measures].[Units Shipped]\"/>\n" +
" <CalculatedMember name=\"Profit\" dimension=\"Measures\">\n" +
" <Formula>[Measures].[Store Sales] - [Measures].[Store Cost]</Formula>\n" +
" </CalculatedMember>\n" +
" <CalculatedMember name=\"Profit Per Unit Shipped\" dimension=\"Measures\">\n" +
" <Formula>[Measures].[Profit] / [Measures].[Units Shipped]</Formula>\n" +
" <CalculatedMemberProperty name=\"FORMAT_STRING\" expression=\"IIf(([Measures].[Profit Per Unit Shipped] > 2.0), '|0.#|style=green', '|0.#|style=red')\"/>\n" +
" </CalculatedMember>\n" +
"</VirtualCube>",
null, null);
testContext.assertQueryReturns(
"select {[Measures].[Profit Per Unit Shipped]} ON COLUMNS, " +
"{[Store].[All Stores].[USA].[CA], [Store].[All Stores].[USA].[OR], [Store].[All Stores].[USA].[WA]} ON ROWS " +
"from [Warehouse and Sales Format Expression Cube No Cache] " +
"where [Time].[1997]",
fold(
"Axis
"{[Time].[1997]}\n" +
"Axis
"{[Measures].[Profit Per Unit Shipped]}\n" +
"Axis
"{[Store].[All Stores].[USA].[CA]}\n" +
"{[Store].[All Stores].[USA].[OR]}\n" +
"{[Store].[All Stores].[USA].[WA]}\n" +
"Row #0: |1.6|style=red\n" +
"Row #1: |2.1|style=green\n" +
"Row #2: |1.5|style=red\n"));
}
public void testCalculatedMeasure()
{
// calculated measures reference measures defined in the base cube
assertQueryReturns(
"select\n" +
"{[Measures].[Profit Growth], " +
"[Measures].[Profit], " +
"[Measures].[Average Warehouse Sale] }\n" +
"ON COLUMNS\n" +
"from [Warehouse and Sales]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Profit Growth]}\n" +
"{[Measures].[Profit]}\n" +
"{[Measures].[Average Warehouse Sale]}\n" +
"Row #0: 0.0%\n" +
"Row #0: $339,610.90\n" +
"Row #0: $2.21\n"));
}
public void testLostData()
{
assertQueryReturns(
"select {[Time].Members} on columns,\n" +
" {[Product].Children} on rows\n" +
"from [Sales]",
fold(
"Axis
"{}\n" +
"Axis
"{[Time].[1997]}\n" +
"{[Time].[1997].[Q1]}\n" +
"{[Time].[1997].[Q1].[1]}\n" +
"{[Time].[1997].[Q1].[2]}\n" +
"{[Time].[1997].[Q1].[3]}\n" +
"{[Time].[1997].[Q2]}\n" +
"{[Time].[1997].[Q2].[4]}\n" +
"{[Time].[1997].[Q2].[5]}\n" +
"{[Time].[1997].[Q2].[6]}\n" +
"{[Time].[1997].[Q3]}\n" +
"{[Time].[1997].[Q3].[7]}\n" +
"{[Time].[1997].[Q3].[8]}\n" +
"{[Time].[1997].[Q3].[9]}\n" +
"{[Time].[1997].[Q4]}\n" +
"{[Time].[1997].[Q4].[10]}\n" +
"{[Time].[1997].[Q4].[11]}\n" +
"{[Time].[1997].[Q4].[12]}\n" +
"{[Time].[1998]}\n" +
"{[Time].[1998].[Q1]}\n" +
"{[Time].[1998].[Q1].[1]}\n" +
"{[Time].[1998].[Q1].[2]}\n" +
"{[Time].[1998].[Q1].[3]}\n" +
"{[Time].[1998].[Q2]}\n" +
"{[Time].[1998].[Q2].[4]}\n" +
"{[Time].[1998].[Q2].[5]}\n" +
"{[Time].[1998].[Q2].[6]}\n" +
"{[Time].[1998].[Q3]}\n" +
"{[Time].[1998].[Q3].[7]}\n" +
"{[Time].[1998].[Q3].[8]}\n" +
"{[Time].[1998].[Q3].[9]}\n" +
"{[Time].[1998].[Q4]}\n" +
"{[Time].[1998].[Q4].[10]}\n" +
"{[Time].[1998].[Q4].[11]}\n" +
"{[Time].[1998].[Q4].[12]}\n" +
"Axis
"{[Product].[All Products].[Drink]}\n" +
"{[Product].[All Products].[Food]}\n" +
"{[Product].[All Products].[Non-Consumable]}\n" +
"Row #0: 24,597\n" +
"Row #0: 5,976\n" +
"Row #0: 1,910\n" +
"Row #0: 1,951\n" +
"Row #0: 2,115\n" +
"Row #0: 5,895\n" +
"Row #0: 1,948\n" +
"Row #0: 2,039\n" +
"Row #0: 1,908\n" +
"Row #0: 6,065\n" +
"Row #0: 2,205\n" +
"Row #0: 1,921\n" +
"Row #0: 1,939\n" +
"Row #0: 6,661\n" +
"Row #0: 1,898\n" +
"Row #0: 2,344\n" +
"Row #0: 2,419\n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #0: \n" +
"Row #1: 191,940\n" +
"Row #1: 47,809\n" +
"Row #1: 15,604\n" +
"Row #1: 15,142\n" +
"Row #1: 17,063\n" +
"Row #1: 44,825\n" +
"Row #1: 14,393\n" +
"Row #1: 15,055\n" +
"Row #1: 15,377\n" +
"Row #1: 47,440\n" +
"Row #1: 17,036\n" +
"Row #1: 15,741\n" +
"Row #1: 14,663\n" +
"Row #1: 51,866\n" +
"Row #1: 14,232\n" +
"Row #1: 18,278\n" +
"Row #1: 19,356\n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #1: \n" +
"Row #2: 50,236\n" +
"Row #2: 12,506\n" +
"Row #2: 4,114\n" +
"Row #2: 3,864\n" +
"Row #2: 4,528\n" +
"Row #2: 11,890\n" +
"Row #2: 3,838\n" +
"Row #2: 3,987\n" +
"Row #2: 4,065\n" +
"Row #2: 12,343\n" +
"Row #2: 4,522\n" +
"Row #2: 4,035\n" +
"Row #2: 3,786\n" +
"Row #2: 13,497\n" +
"Row #2: 3,828\n" +
"Row #2: 4,648\n" +
"Row #2: 5,021\n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n" +
"Row #2: \n"));
assertQueryReturns(
"select\n" +
" {[Measures].[Unit Sales]} on 0,\n" +
" {[Product].Children} on 1\n" +
"from [Warehouse and Sales]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Unit Sales]}\n" +
"Axis
"{[Product].[All Products].[Drink]}\n" +
"{[Product].[All Products].[Food]}\n" +
"{[Product].[All Products].[Non-Consumable]}\n" +
"Row #0: 24,597\n" +
"Row #1: 191,940\n" +
"Row #2: 50,236\n"));
}
/**
* Tests a calc measure which combines a measures from the Sales cube with a
* measures from the Warehouse cube.
*/
public void testCalculatedMeasureAcrossCubes()
{
assertQueryReturns(
"with member [Measures].[Shipped per Ordered] as ' [Measures].[Units Shipped] / [Measures].[Unit Sales] ', format_string='#.00%'\n" +
" member [Measures].[Profit per Unit Shipped] as ' [Measures].[Profit] / [Measures].[Units Shipped] '\n" +
"select\n" +
" {[Measures].[Unit Sales], \n" +
" [Measures].[Units Shipped],\n" +
" [Measures].[Shipped per Ordered],\n" +
" [Measures].[Profit per Unit Shipped]} on 0,\n" +
" NON EMPTY Crossjoin([Product].Children, [Time].[1997].Children) on 1\n" +
"from [Warehouse and Sales]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Unit Sales]}\n" +
"{[Measures].[Units Shipped]}\n" +
"{[Measures].[Shipped per Ordered]}\n" +
"{[Measures].[Profit per Unit Shipped]}\n" +
"Axis
"{[Product].[All Products].[Drink], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q4]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q4]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q4]}\n" +
"Row #0: 5,976\n" +
"Row #0: 4637.0\n" +
"Row #0: 77.59%\n" +
"Row #0: $1.50\n" +
"Row #1: 5,895\n" +
"Row #1: 4501.0\n" +
"Row #1: 76.35%\n" +
"Row #1: $1.60\n" +
"Row #2: 6,065\n" +
"Row #2: 6258.0\n" +
"Row #2: 103.18%\n" +
"Row #2: $1.15\n" +
"Row #3: 6,661\n" +
"Row #3: 5802.0\n" +
"Row #3: 87.10%\n" +
"Row #3: $1.38\n" +
"Row #4: 47,809\n" +
"Row #4: 37153.0\n" +
"Row #4: 77.71%\n" +
"Row #4: $1.64\n" +
"Row #5: 44,825\n" +
"Row #5: 35459.0\n" +
"Row #5: 79.11%\n" +
"Row #5: $1.62\n" +
"Row #6: 47,440\n" +
"Row #6: 41545.0\n" +
"Row #6: 87.57%\n" +
"Row #6: $1.47\n" +
"Row #7: 51,866\n" +
"Row #7: 34706.0\n" +
"Row #7: 66.91%\n" +
"Row #7: $1.91\n" +
"Row #8: 12,506\n" +
"Row #8: 9161.0\n" +
"Row #8: 73.25%\n" +
"Row #8: $1.76\n" +
"Row #9: 11,890\n" +
"Row #9: 9227.0\n" +
"Row #9: 77.60%\n" +
"Row #9: $1.65\n" +
"Row #10: 12,343\n" +
"Row #10: 9986.0\n" +
"Row #10: 80.90%\n" +
"Row #10: $1.59\n" +
"Row #11: 13,497\n" +
"Row #11: 9291.0\n" +
"Row #11: 68.84%\n" +
"Row #11: $1.86\n"));
}
/**
* Tests a calc member defined in the cube.
*/
public void testCalculatedMemberInSchema() {
TestContext testContext =
TestContext.createSubstitutingCube(
"Warehouse and Sales",
null,
" <CalculatedMember name=\"Shipped per Ordered\" dimension=\"Measures\">\n" +
" <Formula>[Measures].[Units Shipped] / [Measures].[Unit Sales]</Formula>\n" +
" <CalculatedMemberProperty name=\"FORMAT_STRING\" value=\"
" </CalculatedMember>\n");
testContext.assertQueryReturns(
"select\n" +
" {[Measures].[Unit Sales], \n" +
" [Measures].[Shipped per Ordered]} on 0,\n" +
" NON EMPTY Crossjoin([Product].Children, [Time].[1997].Children) on 1\n" +
"from [Warehouse and Sales]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Unit Sales]}\n" +
"{[Measures].[Shipped per Ordered]}\n" +
"Axis
"{[Product].[All Products].[Drink], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Drink], [Time].[1997].[Q4]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Food], [Time].[1997].[Q4]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q1]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q2]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q3]}\n" +
"{[Product].[All Products].[Non-Consumable], [Time].[1997].[Q4]}\n" +
"Row #0: 5,976\n" +
"Row #0: 77.6%\n" +
"Row #1: 5,895\n" +
"Row #1: 76.4%\n" +
"Row #2: 6,065\n" +
"Row #2: 103.2%\n" +
"Row #3: 6,661\n" +
"Row #3: 87.1%\n" +
"Row #4: 47,809\n" +
"Row #4: 77.7%\n" +
"Row #5: 44,825\n" +
"Row #5: 79.1%\n" +
"Row #6: 47,440\n" +
"Row #6: 87.6%\n" +
"Row #7: 51,866\n" +
"Row #7: 66.9%\n" +
"Row #8: 12,506\n" +
"Row #8: 73.3%\n" +
"Row #9: 11,890\n" +
"Row #9: 77.6%\n" +
"Row #10: 12,343\n" +
"Row #10: 80.9%\n" +
"Row #11: 13,497\n" +
"Row #11: 68.8%\n"));
}
public void testAllMeasureMembers()
{
// result should exclude measures that are not explicitly defined
// in the virtual cube (e.g., [Profit last Period])
assertQueryReturns(
"select\n" +
"{[Measures].allMembers} on columns\n" +
"from [Warehouse and Sales]",
fold("Axis
"{}\n" +
"Axis
"{[Measures].[Sales Count]}\n" +
"{[Measures].[Store Cost]}\n" +
"{[Measures].[Store Sales]}\n" +
"{[Measures].[Unit Sales]}\n" +
"{[Measures].[Store Invoice]}\n" +
"{[Measures].[Supply Time]}\n" +
"{[Measures].[Units Ordered]}\n" +
"{[Measures].[Units Shipped]}\n" +
"{[Measures].[Warehouse Cost]}\n" +
"{[Measures].[Warehouse Profit]}\n" +
"{[Measures].[Warehouse Sales]}\n" +
"{[Measures].[Profit]}\n" +
"{[Measures].[Profit Growth]}\n" +
"{[Measures].[Average Warehouse Sale]}\n" +
"{[Measures].[Profit Per Unit Shipped]}\n" +
"Row #0: 86,837\n" +
"Row #0: 225,627.23\n" +
"Row #0: 565,238.13\n" +
"Row #0: 266,773\n" +
"Row #0: 102,278.409\n" +
"Row #0: 10,425\n" +
"Row #0: 227238.0\n" +
"Row #0: 207726.0\n" +
"Row #0: 89,043.253\n" +
"Row #0: 107,727.635\n" +
"Row #0: 196,770.888\n" +
"Row #0: $339,610.90\n" +
"Row #0: 0.0%\n" +
"Row #0: $2.21\n" +
"Row #0: $1.63\n"));
}
/**
* Test a virtual cube where one of the dimensions contains an
* ordinalColumn property
*/
public void testOrdinalColumn()
{
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs HR\">\n" +
"<VirtualCubeDimension name=\"Store\"/>\n" +
"<VirtualCubeDimension cubeName=\"HR\" name=\"Position\"/>\n" +
"<VirtualCubeMeasure cubeName=\"HR\" name=\"[Measures].[Org Salary]\"/>\n" +
"</VirtualCube>",
null, null);
testContext.assertQueryReturns(
"select {[Measures].[Org Salary]} on columns, " +
"non empty " +
"crossjoin([Store].[Store Country].members, [Position].[Store Management].children) " +
"on rows from [Sales vs HR]",
fold(
"Axis
"{}\n" +
"Axis
"{[Measures].[Org Salary]}\n" +
"Axis
"{[Store].[All Stores].[Canada], [Position].[All Position].[Store Management].[Store Manager]}\n" +
"{[Store].[All Stores].[Canada], [Position].[All Position].[Store Management].[Store Assistant Manager]}\n" +
"{[Store].[All Stores].[Canada], [Position].[All Position].[Store Management].[Store Shift Supervisor]}\n" +
"{[Store].[All Stores].[Mexico], [Position].[All Position].[Store Management].[Store Manager]}\n" +
"{[Store].[All Stores].[Mexico], [Position].[All Position].[Store Management].[Store Assistant Manager]}\n" +
"{[Store].[All Stores].[Mexico], [Position].[All Position].[Store Management].[Store Shift Supervisor]}\n" +
"{[Store].[All Stores].[USA], [Position].[All Position].[Store Management].[Store Manager]}\n" +
"{[Store].[All Stores].[USA], [Position].[All Position].[Store Management].[Store Assistant Manager]}\n" +
"{[Store].[All Stores].[USA], [Position].[All Position].[Store Management].[Store Shift Supervisor]}\n" +
"Row #0: $462.86\n" +
"Row #1: $394.29\n" +
"Row #2: $565.71\n" +
"Row #3: $13,254.55\n" +
"Row #4: $11,443.64\n" +
"Row #5: $17,705.46\n" +
"Row #6: $4,069.80\n" +
"Row #7: $3,417.72\n" +
"Row #8: $5,145.96\n"));
}
public void testDefaultMeasureProperty() {
TestContext testContext = TestContext.create(
null, null,
"<VirtualCube name=\"Sales vs Warehouse\" defaultMeasure=\"Unit Sales\">\n" +
"<VirtualCubeDimension name=\"Product\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Warehouse\" " +
"name=\"[Measures].[Warehouse Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Unit Sales]\"/>\n" +
"<VirtualCubeMeasure cubeName=\"Sales\" " +
"name=\"[Measures].[Profit]\"/>\n" +
"</VirtualCube>",
null, null);
String queryWithoutFilter = "select"+
" from [Sales vs Warehouse]";
String queryWithDeflaultMeasureFilter = "select "+
"from [Sales vs Warehouse] where measures.[Unit Sales]";
assertQueriesReturnSimilarResults(queryWithoutFilter,
queryWithDeflaultMeasureFilter, testContext);
}
/**
* Checks that a given MDX query results in a particular SQL statement
* being generated.
*
* @param mdxQuery MDX query
* @param patterns Set of patterns, one for each dialect.
* @param clearCache whether to clear cache before running the query
*/
protected void assertQuerySql(
String mdxQuery,
SqlPattern[] patterns,
boolean clearCache) {
assertQuerySqlOrNot(getTestContext(), mdxQuery, patterns, false, clearCache);
}
/**
* Checks that native set caching considers base cubes in the cache key.
* Native sets referencing different base cubes do not share the cached result.
*/
public void testNativeSetCaching() {
if (!MondrianProperties.instance().EnableNativeCrossJoin.get() &&
!MondrianProperties.instance().EnableNativeNonEmpty.get()) {
// Only run the tests if either native CrossJoin or native NonEmpty
// is enabled.
return;
}
String query1 =
"With " +
"Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([Product].[Product Family].Members, [Store].[Store Country].Members)' " +
"Select " +
"{[Store Sales]} on columns, " +
"Non Empty Generate([*NATIVE_CJ_SET], {([Product].CurrentMember,[Store].CurrentMember)}) on rows " +
"From [Warehouse and Sales]";
String query2 =
"With " +
"Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([Product].[Product Family].Members, [Store].[Store Country].Members)' " +
"Select " +
"{[Warehouse Sales]} on columns, " +
"Non Empty Generate([*NATIVE_CJ_SET], {([Product].CurrentMember,[Store].CurrentMember)}) on rows " +
"From [Warehouse and Sales]";
String necjSql1;
String necjSql2;
if (MondrianProperties.instance().EnableNativeCrossJoin.get()) {
necjSql1 =
"select " +
"\"product_class\".\"product_family\", " +
"\"store\".\"store_country\" " +
"from " +
"\"product\" as \"product\", " +
"\"product_class\" as \"product_class\", " +
"\"sales_fact_1997\" as \"sales_fact_1997\", " +
"\"store\" as \"store\" " +
"where " +
"\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" " +
"and \"sales_fact_1997\".\"product_id\" = \"product\".\"product_id\" " +
"and \"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\" " +
"group by \"product_class\".\"product_family\", \"store\".\"store_country\" " +
"order by 1 ASC, 2 ASC";
necjSql2 =
"select " +
"\"product_class\".\"product_family\", " +
"\"store\".\"store_country\" " +
"from " +
"\"product\" as \"product\", " +
"\"product_class\" as \"product_class\", " +
"\"inventory_fact_1997\" as \"inventory_fact_1997\", " +
"\"store\" as \"store\" " +
"where " +
"\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" " +
"and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" " +
"and \"inventory_fact_1997\".\"store_id\" = \"store\".\"store_id\" " +
"group by \"product_class\".\"product_family\", \"store\".\"store_country\" " +
"order by 1 ASC, 2 ASC";
} else {
// NECJ is truend off so native NECJ SQL will not be generated;
// however, because the NECJ set should not find match in the cache,
// each NECJ input will still be joined with the correct
// fact table if NonEmpty condition is natively evaluated.
necjSql1 =
"select " +
"\"store\".\"store_country\" " +
"from " +
"\"store\" as \"store\", " +
"\"sales_fact_1997\" as \"sales_fact_1997\" " +
"where " +
"\"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\" " +
"group by \"store\".\"store_country\" " +
"order by 1 ASC";
necjSql2 =
"select " +
"\"store\".\"store_country\" " +
"from " +
"\"store\" as \"store\", " +
"\"inventory_fact_1997\" as \"inventory_fact_1997\" " +
"where " +
"\"inventory_fact_1997\".\"store_id\" = \"store\".\"store_id\" " +
"group by \"store\".\"store_country\" " +
"order by 1 ASC";
}
SqlPattern[] patterns1 =
new SqlPattern[] {
new SqlPattern(SqlPattern.Dialect.DERBY, necjSql1, necjSql1)
};
SqlPattern[] patterns2 =
new SqlPattern[] {
new SqlPattern(SqlPattern.Dialect.DERBY, necjSql2, necjSql2)
};
// Run query 1 with cleared cache;
// Make sure NECJ 1 is evaluated natively.
assertQuerySql(query1, patterns1, true);
// Now run query 2 with warm cache;
// Make sure NECJ 2 does not reuse the cache result from NECJ 1, and
// NECJ 2 is evaluated natively.
assertQuerySql(query2, patterns2, false);
}
}
// End VirtualCubeTest.java
|
package com.dumbster.smtp;
import com.dumbster.smtp.SmtpServer;
import com.dumbster.smtp.action.*;
import com.dumbster.smtp.eml.*;
import org.junit.*;
import java.util.Iterator;
import com.dumbster.smtp.MailMessage;
import com.dumbster.smtp.mailstores.EMLMailStore;
import com.dumbster.smtp.mailstores.RollingMailStore;
import com.dumbster.smtp.Response;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Date;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import static org.junit.Assert.*;
public class NewTestCasesTest {
private static final int SMTP_PORT = 1081;
private final String SERVER = "localhost";
private final String FROM = "sender@here.com";
private final String TO = "baker32@illinois.edu";
private final String SUBJECT = "Test Dumbster";
private final String BODY = "Test Body";
private final int WAIT_TICKS = 10000;
private final String text =
"From: \"John\" <baker32@illinois.edu>\n" +
"To: \"PeterShmenos\" <petershmenos@gmail.com>\n" +
"Date: Fri, 8 May 2015 12:16:43 -0500\n" +
"Subject: Test\n" +
"\n" +
"Hello Peter,\n" +
"This is only a test.\n" +
"Sincerely,\n" +
"Baker\n";
private MailMessage message;
private EMLMailMessage emlMessage;
private ServerOptions options;
private MailStore mailStore;
private MailStore mailStore2;
private SmtpServer server;
@Before
public void setup() {
this.message = new MailMessageImpl();
mailStore = new RollingMailStore();
}
/* Message Formatting Utests */
@Test
public void testMaxHeaders() {
message.addHeader("header1", "value1");
message.addHeader("header2", "value2");
message.addHeader("header3", "value3");
message.addHeader("header4", "value4");
message.addHeader("header5", "value5");
message.addHeader("header6", "value6");
message.addHeader("header7", "value7");
message.addHeader("header8", "value8");
message.addHeader("header9", "value9");
message.addHeader("header10", "value10");
Iterator<String> it = message.getHeaderNames();
int i = 0;
while(it.hasNext()) { i++; it.next(); }
assertEquals(10, i);
}
@Test
public void testMaxHeadersPlus1() {
message.addHeader("header1", "value1");
message.addHeader("header2", "value2");
message.addHeader("header3", "value3");
message.addHeader("header4", "value4");
message.addHeader("header5", "value5");
message.addHeader("header6", "value6");
message.addHeader("header7", "value7");
message.addHeader("header8", "value8");
message.addHeader("header9", "value9");
message.addHeader("header10", "value10");
message.addHeader("header11", "value11");
Iterator<String> it = message.getHeaderNames();
int i = 0;
while(it.hasNext()) { i++; it.next(); }
assertEquals(11, i);
}
@Test
public void testAppendBadHeader() {
message.addHeader("foo", "bar");
message.addHeader("tim", "tam");
message.addHeader("zing", "zang");
message.appendHeader("tim", " tum");
assertEquals("tam tum", message.getFirstHeaderValue("tim"));
}
/* Server Options Utests */
@Test
public void testNegativePort() {
String[] args = new String[]{"-1"};
options = new ServerOptions(args);
assertEquals(-1, options.port);
assertEquals(true, options.threaded);
assertEquals(true, options.valid);
assertEquals(RollingMailStore.class, options.mailStore.getClass());
}
/* Request Utests*/
@Test
public void testDataBodyState() {
Request request = Request.createRequest(SmtpState.DATA_BODY, ".");
assertEquals(".", request.getClientAction().toString());
}
@Test
public void testDataFromCreateRequest() {
Request request = Request.createRequest(SmtpState.GREET, "DATA");
assertEquals("DATA", request.getClientAction().toString());
}
@Test
public void testQuitFromCreateRequest() {
Request request = Request.createRequest(SmtpState.GREET, "QUIT");
assertEquals("QUIT", request.getClientAction().toString());
}
@Test
public void testHeloInvalidMessage() {
Request request = Request.createRequest(null, "HELO");
assertEquals("EHLO", request.getClientAction().toString());
}
// This test increases branch coverage
@Test
public void testListFromCreateRequest() {
Request request = Request.createRequest(SmtpState.GREET, "LIST");
assertEquals("LIST", request.getClientAction().toString());
}
/* Action Tests */
// This test increases branch coverage
@Test
public void testListIndexNegative() {
List l = new List("-1");
//This Test passes if there is no exception
//messageIndex is private, no public method to check its value
}
//These two tests increase coverage
@Test
public void testResponseInvalidIndex() {
List l = new List("-1");
Response r = l.response(null, mailStore, null);
assertEquals("There are 0 message(s).", r.getMessage());
}
@Test
public void testResponseValidNoMessages() {
List l = new List("0");
Response r = l.response(null, mailStore, null);
assertEquals("There are 0 message(s).", r.getMessage());
}
/* SMTP Server Tests */
//This test increases coverage
@Test
public void getMessageTest() {
MailMessage[] mm = new MailMessage[10];
ServerOptions options = new ServerOptions();
options.port = SMTP_PORT;
server = SmtpServerFactory.startServer(options);
server.getMessages();
assertEquals(0, server.getEmailCount());
server.stop();
}
/* Advanced Test Cases */
@Test
public void testUniqueMessagesWithClear() {
ServerOptions options = new ServerOptions();
options.port = SMTP_PORT;
server = SmtpServerFactory.startServer(options);
// Message 1
sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO);
server.anticipateMessageCountFor(1, WAIT_TICKS);
assertTrue(server.getEmailCount() == 1);
MailMessage mm = server.getMessage(0);
assertEquals("Test Dumbster", mm.getFirstHeaderValue("Subject"));
// Message 2
sendMessage(SMTP_PORT, FROM, SUBJECT, "HELLO!", TO);
server.anticipateMessageCountFor(1, WAIT_TICKS);
assertTrue(server.getEmailCount() == 2);
mm = server.getMessage(1);
assertEquals("HELLO!", mm.getBody());
// Messages 3-10
int i;
for (i = 3; i <= 10; i++)
{
sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO);
assertTrue(server.getEmailCount() == i);
}
server.clearMessages();
sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO);
assertTrue(server.getEmailCount() == 1);
server.stop();
}
@Test
public void testUniqueMessagesMultipleMailStores() {
ServerOptions options = new ServerOptions();
options.port = SMTP_PORT;
server = SmtpServerFactory.startServer(options);
mailStore2 = new RollingMailStore();
// First rolling Mail Store Message
MailMessage fm = new MailMessageImpl();
mailStore2.addMessage(fm);
// Messages 1-10
int i;
for (i = 1; i <= 10; i++)
{
sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO);
addAMessage();
assertTrue(server.getEmailCount() == i);
}
server.clearMessages();
sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO);
assertTrue(server.getEmailCount() == 1);
server.stop();
}
/* Final Report Tests */
/* Increase Method Coverage */
@Test
public void startServerNoInputs() {
server = SmtpServerFactory.startServer();
server.getMessages();
assertEquals(0, server.getEmailCount());
server.stop();
}
@Test
public void startServerThrowException() {
ServerOptions options = new ServerOptions();
options.port = SMTP_PORT;
server = SmtpServerFactory.startServer(options);
try {
throw new IOException();
}
catch(Exception e) {}
}
@Test
public void appendHeaderEMLmessage(){
emlMessage = new EMLMailMessage(new ByteArrayInputStrem(text.getBytes()));
emlMessage.appendHeader("From", " Baker");
assertEquals("John Baker", emlMessage.getHeaderValues("From"));
}
/* Helpers */
private Properties getMailProperties(int port) {
Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.host", "localhost");
mailProps.setProperty("mail.smtp.port", "" + port);
mailProps.setProperty("mail.smtp.sendpartial", "true");
return mailProps;
}
private void sendMessage(int port, String from, String subject, String body, String to) {
try {
Properties mailProps = getMailProperties(port);
Session session = Session.getInstance(mailProps, null);
MimeMessage msg = createMessage(session, from, to, subject, body);
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected exception: " + e);
}
}
private MimeMessage createMessage(Session session, String from, String to, String subject, String body) throws MessagingException {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(body);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
return msg;
}
private void addAMessage() {
MailMessage message = new MailMessageImpl();
mailStore2.addMessage(message);
}
}
|
package gov.nih.nci.cabig.caaers.dao;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.dao.query.AbstractQuery;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.LoadStatus;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyAgent;
import gov.nih.nci.cabig.caaers.domain.StudyOrganization;
import gov.nih.nci.cabig.caaers.domain.StudyTherapyType;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Sujith Vellat Thayyilthodi
* @author Rhett Sutphin
* @author Priyatam
* @author <a href="mailto:biju.joseph@semanticbits.com">Biju Joseph</a>
*/
@Transactional(readOnly = true)
public class StudyDao extends GridIdentifiableDao<Study> implements MutableDomainObjectDao<Study> {
private static final List<String> SUBSTRING_MATCH_PROPERTIES = Arrays.asList("shortTitle", "longTitle");
private static final List<String> EXACT_MATCH_PROPERTIES = Collections.emptyList();
private static final List<String> EXACT_MATCH_UNIQUE_PROPERTIES = Arrays.asList("longTitle");
private static final List<String> EMPTY_PROPERTIES = Collections.emptyList();
private static final List<String> EXACT_MATCH_TITLE_PROPERTIES = Arrays.asList("shortTitle");
private static final String JOINS = "join o.identifiers as identifier "
+ "join o.studyOrganizations as ss join ss.studyParticipantAssignments as spa join spa.participant as p join p.identifiers as pIdentifier";
private static final String QUERY_BY_SHORT_TITLE = "select s from " + Study.class.getName()
+ " s where shortTitle = :st";
@Override
public Class<Study> domainClass() {
return Study.class;
}
@SuppressWarnings("unchecked")
public List<Study> getAllStudies() {
return getHibernateTemplate().find("from Study");
}
/**
* //TODO - Refactor this code with Hibernate Detached objects !!!
*
* This is a hack to load all collection objects in memory. Useful for editing a Study when you know you will be needing all collections
* To avoid Lazy loading Exception by Hibernate, a call to .size() is done for each collection
* @param id
* @return Fully loaded Study
*/
public Study getStudyDesignById(final int id) {
Study study = (Study) getHibernateTemplate().get(domainClass(), id);
initialize(study);
// now select the therapies types
if (study.getStudyTherapy(StudyTherapyType.DRUG_ADMINISTRATION) != null) {
study.setDrugAdministrationTherapyType(Boolean.TRUE);
}
if (study.getStudyTherapy(StudyTherapyType.DEVICE) != null) {
study.setDeviceTherapyType(Boolean.TRUE);
}
if (study.getStudyTherapy(StudyTherapyType.RADIATION) != null) {
study.setRadiationTherapyType(Boolean.TRUE);
}
if (study.getStudyTherapy(StudyTherapyType.SURGERY) != null) {
study.setSurgeryTherapyType(Boolean.TRUE);
}
if (study.getStudyTherapy(StudyTherapyType.BEHAVIORAL) != null) {
study.setBehavioralTherapyType(Boolean.TRUE);
}
return study;
}
public Study initialize(final Study study) {
HibernateTemplate ht = getHibernateTemplate();
ht.initialize(study.getIdentifiers());
ht.initialize(study.getStudyOrganizations());
for (StudyOrganization studyOrg : study.getStudyOrganizations()) {
if (studyOrg == null) {
continue;
}
ht.initialize(studyOrg.getStudyInvestigatorsInternal());
ht.initialize(studyOrg.getStudyPersonnelsInternal());
}
ht.initialize(study.getMeddraStudyDiseases());
ht.initialize(study.getCtepStudyDiseases());
ht.initialize(study.getStudyAgentsInternal());
ht.initialize(study.getStudyTherapies());
ht.initialize(study.getTreatmentAssignmentsInternal());
for (StudyAgent sa : study.getStudyAgents()) {
ht.initialize(sa.getStudyAgentINDAssociationsInternal());
}
return study;
}
@Transactional(readOnly = false)
public void save(final Study study) {
getHibernateTemplate().saveOrUpdate(study);
}
@Transactional(readOnly = false)
public void batchSave(final List<DomainObjectImportOutcome<Study>> domainObjectImportOutcome){
log.debug("Batch saving start time : " + new java.util.Date());
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
for (DomainObjectImportOutcome<Study> outcome : domainObjectImportOutcome) {
final Study study = outcome.getImportedDomainObject();
session.merge(study);
}
}
public List<Study> getBySubnames(final String[] subnames) {
return findBySubname(subnames, null, null, SUBSTRING_MATCH_PROPERTIES, EXACT_MATCH_PROPERTIES);
}
/*
* Added extraCondition parameter, as a fix for bug 9514
*/
public List<Study> getBySubnamesJoinOnIdentifier(final String[] subnames, String extraConditions) {
String joins = " join o.identifiers as identifier ";
List<String> subStringMatchProperties = Arrays.asList("o.shortTitle", "o.longTitle", "identifier.type",
"identifier.value");
return findBySubname(subnames, extraConditions, null, subStringMatchProperties, EXACT_MATCH_PROPERTIES, joins);
}
/*
* public List<Study> getByCriteria(final String[] subnames, final List<String> subStringMatchProperties) { return
* findBySubname(subnames, null, null, subStringMatchProperties, null, JOINS); }
*/
public List<Study> matchStudyByParticipant(final Integer participantId, final String text, final String extraCondition) {
String joins = " join o.identifiers as identifier join o.studyOrganizations as ss join ss.studyParticipantAssignments as spa join spa.participant as p ";
List<Object> params = new ArrayList<Object>();
StringBuilder queryBuf = new StringBuilder(" select distinct o from ").append(domainClass().getName()).append(
" o ").append(joins);
queryBuf.append(" where ");
queryBuf.append((extraCondition == null)? "" : extraCondition + " and " );
queryBuf.append("p.id = ?");
params.add(participantId);
queryBuf.append(" and ( ");
queryBuf.append("LOWER(").append("o.shortTitle").append(") LIKE ?");
params.add('%' + text.toLowerCase() + '%');
queryBuf.append(" or ");
queryBuf.append("LOWER(").append("identifier.value").append(") LIKE ? ");
params.add('%' + text.toLowerCase() + '%');
queryBuf.append(" or ");
queryBuf.append("LOWER(").append("identifier.type").append(") LIKE ? ");
params.add('%' + text.toLowerCase() + '%');
queryBuf.append(" or ");
queryBuf.append("LOWER(").append("o.longTitle").append(") LIKE ? ) ");
params.add('%' + text.toLowerCase() + '%');
log.debug("matchStudyByParticipant : " + queryBuf.toString());
getHibernateTemplate().setMaxResults(30);
return getHibernateTemplate().find(queryBuf.toString(), params.toArray());
}
public List<Study> searchStudy(final Map props) throws ParseException {
List<Object> params = new ArrayList<Object>();
boolean firstClause = true;
StringBuilder queryBuf = new StringBuilder(" select distinct o from ").append(domainClass().getName()).append(
" o ").append(JOINS);
if (props.get("studyIdentifier") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("identifier.value").append(") LIKE ?");
String p = (String) props.get("studyIdentifier");
params.add('%' + p.toLowerCase() + '%');
firstClause = false;
}
if (props.get("studyShortTitle") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("o.shortTitle").append(") LIKE ?");
String p = (String) props.get("studyShortTitle");
params.add('%' + p.toLowerCase() + '%');
firstClause = false;
}
if (props.get("participantIdentifier") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("pIdentifier.value").append(") LIKE ?");
String p = (String) props.get("participantIdentifier");
params.add('%' + p.toLowerCase() + '%');
firstClause = false;
}
if (props.get("participantFirstName") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("p.firstName").append(") LIKE ?");
String p = (String) props.get("participantFirstName");
params.add('%' + p.toLowerCase() + '%');
firstClause = false;
}
if (props.get("participantLastName") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("p.lastName").append(") LIKE ?");
String p = (String) props.get("participantLastName");
params.add('%' + p.toLowerCase() + '%');
firstClause = false;
}
if (props.get("participantEthnicity") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("p.ethnicity").append(") LIKE ?");
String p = (String) props.get("participantEthnicity");
params.add(p.toLowerCase());
firstClause = false;
}
if (props.get("participantGender") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append("LOWER(").append("p.gender").append(") LIKE ?");
String p = (String) props.get("participantGender");
params.add(p.toLowerCase());
firstClause = false;
}
if (props.get("participantDateOfBirth") != null) {
queryBuf.append(firstClause ? " where " : " and ");
queryBuf.append(" p.dateOfBirth").append(" = ? ");
String p = (String) props.get("participantDateOfBirth");
params.add(stringToDate(p));
firstClause = false;
}
log.debug("::: " + queryBuf.toString());
getHibernateTemplate().setMaxResults(CaaersDao.DEFAULT_MAX_RESULTS_SIZE);
return getHibernateTemplate().find(queryBuf.toString(), params.toArray());
}
/**
* @param subnames a set of substrings to match
* @return a list of participants such that each entry in <code>subnames</code> is a case-insensitive substring match of the
* participant's name or other identifier
*/
@SuppressWarnings("unchecked")
public List<Study> getByUniqueIdentifiers(final String[] subnames) {
return findBySubname(subnames, null, null, EMPTY_PROPERTIES, EXACT_MATCH_UNIQUE_PROPERTIES);
}
public Study getByIdentifier(final Identifier identifier) {
return findByIdentifier(identifier);
}
/**
* This will do an exact match on the <code>shortTitle</code>, and will return the first available Study. Note:- Biz rule should be
* made that short title is unique.
*/
public Study getByShortTitle(final String shortTitle) {
List<Study> studies = findBySubname(new String[] { shortTitle },null, null,null, EXACT_MATCH_TITLE_PROPERTIES);
if (studies != null && studies.size() > 0) {
return studies.get(0);
}
return null;
}
@Override
// TODO - Need to refactor the below into CaaersDao along with identifiers
public List<Study> searchByExample(final Study study, final boolean isWildCard) {
Example example = Example.create(study).excludeZeroes().ignoreCase();
Criteria studyCriteria = getSession().createCriteria(Study.class);
if (isWildCard) {
example.excludeProperty("multiInstitutionIndicator");
example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
studyCriteria.add(example);
if (study.getIdentifiers().size() > 0) {
studyCriteria.createCriteria("identifiers").add(
Restrictions.like("value", study.getIdentifiers().get(0).getValue() + "%"));
}
if (study.getStudyOrganizations().size() > 0) {
studyCriteria.createCriteria("studyOrganizations").add(
Restrictions.eq("organization.id", study.getStudyOrganizations().get(0).getOrganization()
.getId()));
}
return studyCriteria.list();
}
return studyCriteria.add(example).list();
}
@SuppressWarnings( { "unchecked" })
public List<Study> find(final AbstractQuery query) {
String queryString = query.getQueryString();
log.debug("::: " + queryString.toString());
return (List<Study>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(final Session session) throws HibernateException, SQLException {
org.hibernate.Query hiberanteQuery = session.createQuery(query.getQueryString());
Map<String, Object> queryParameterMap = query.getParameterMap();
for (String key : queryParameterMap.keySet()) {
Object value = queryParameterMap.get(key);
hiberanteQuery.setParameter(key, value);
}
return hiberanteQuery.list();
}
});
}
/**
* This will remove a study from the database
* @param study
*/
@Transactional(readOnly=false)
public void deleteInprogressStudy(final Study study){
if(study.getLoadStatus() != LoadStatus.INPROGRESS.getCode()) throw new CaaersSystemException("Only study with INPROGRESS loadStatus can be deleted");
getHibernateTemplate().delete(study);
}
}
|
package gov.nih.nci.cabig.caaers.domain;
import gov.nih.nci.cabig.caaers.utils.ProjectedList;
import gov.nih.nci.cabig.caaers.validation.annotation.UniqueIdentifierForStudy;
import gov.nih.nci.cabig.caaers.validation.annotation.UniqueObjectInCollection;
import gov.nih.nci.cabig.ctms.collections.LazyListHelper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.collections15.functors.InstantiateFactory;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Where;
/**
* Domain object representing Study(Protocol)
*
* @author Sujith Vellat Thayyilthodi
* @author Rhett Sutphin
*/
@Entity
@Table(name = "studies")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "seq_studies_id") })
@Where(clause="load_status > 0")
public class Study extends AbstractIdentifiableDomainObject implements Serializable {
public static final String STATUS_ADMINISTRATIVELY_COMPLETE = "Administratively Complete";
public static final String STATUS_ACTIVE = "Active - Trial is open to accrual";
private String shortTitle;
private String longTitle;
private String description;
private String precis;
private String phaseCode;
private AeTerminology aeTerminology;
private DiseaseTerminology diseaseTerminology;
private String status;
//TODO: Remove
private Boolean blindedIndicator;
private Boolean multiInstitutionIndicator;
private Boolean adeersReporting;
//TODO: Remove
private Boolean randomizedIndicator;
//TODO: Remove
private String diseaseCode;
//TODO: Remove
private String monitorCode;
//TODO: Remove
private Integer targetAccrualNumber;
private List<StudyOrganization> studyOrganizations;
private List<CtepStudyDisease> ctepStudyDiseases = new ArrayList<CtepStudyDisease>();
private List<MeddraStudyDisease> meddraStudyDiseases = new ArrayList<MeddraStudyDisease>();
private final LazyListHelper lazyListHelper;
private OrganizationAssignedIdentifier organizationAssignedIdentifier;
private List<StudyTherapy> studyTherapies = new ArrayList<StudyTherapy>();
// TODO move into Command Object
private String[] diseaseTermIds;
private String diseaseCategoryAsText;
private String diseaseLlt;
private int studySiteIndex = -1; // represents the studysite, selected in the (add Investigators page)
private Boolean drugAdministrationTherapyType = Boolean.FALSE;
private Boolean radiationTherapyType = Boolean.FALSE;
private Boolean deviceTherapyType = Boolean.FALSE;
private Boolean surgeryTherapyType = Boolean.FALSE;
private Boolean behavioralTherapyType = Boolean.FALSE;
private Integer loadStatus = LoadStatus.COMPLETE.getCode();
// Used to facilitate import of a coordinating center / funding sponsor
private FundingSponsor fundingSponsor;
private CoordinatingCenter coordinatingCenter;
public Study() {
lazyListHelper = new LazyListHelper();
// register with lazy list helper study site.
lazyListHelper.add(StudySite.class, new StudyChildInstantiateFactory<StudySite>(this, StudySite.class));
lazyListHelper.add(StudyFundingSponsor.class, new StudyChildInstantiateFactory<StudyFundingSponsor>(this,
StudyFundingSponsor.class));
lazyListHelper.add(Identifier.class, new InstantiateFactory<Identifier>(Identifier.class));
lazyListHelper.add(StudyAgent.class, new StudyChildInstantiateFactory<StudyAgent>(this, StudyAgent.class));
lazyListHelper.add(TreatmentAssignment.class, new InstantiateFactory<TreatmentAssignment>(
TreatmentAssignment.class));
// mandatory, so that the lazy-projected list is created/managed properly.
setStudyOrganizations(new ArrayList<StudyOrganization>());
setStudyAgentsInternal(new ArrayList<StudyAgent>());
}
// / LOGIC
public void addStudyOrganization(final StudyOrganization so) {
getStudyOrganizations().add(so);
so.setStudy(this);
}
public void addTreatmentAssignment(final TreatmentAssignment treatmentAssignment) {
getTreatmentAssignments().add(treatmentAssignment);
treatmentAssignment.setStudy(this);
}
public void removeStudyOrganization(final StudyOrganization so) {
getStudyOrganizations().remove(so);
}
@Transient
public List<StudySite> getStudySites() {
return lazyListHelper.getLazyList(StudySite.class);
}
public void addStudySite(final StudySite studySite) {
getStudySites().add(studySite);
studySite.setStudy(this);
}
public void removeStudySite(final StudySite studySite) {
getStudySites().remove(studySite);
}
public void addStudyFundingSponsor(final StudyFundingSponsor studyFundingSponsor) {
getStudyFundingSponsors().add(studyFundingSponsor);
studyFundingSponsor.setStudy(this);
}
@Transient
public List<StudyFundingSponsor> getStudyFundingSponsors() {
return lazyListHelper.getLazyList(StudyFundingSponsor.class);
}
@Transient
public StudyFundingSponsor getPrimaryFundingSponsor() {
for (StudyFundingSponsor sponsor : getStudyFundingSponsors()) {
if (sponsor.isPrimary()) {
return sponsor;
}
}
return null;
}
@Transient
public Organization getPrimaryFundingSponsorOrganization() {
StudyFundingSponsor primarySponsor = getPrimaryFundingSponsor();
if (primarySponsor == null) {
return null;
}
return primarySponsor.getOrganization();
}
@Transient
public void setPrimaryFundingSponsorOrganization(final Organization org) {
// if already a primary funding sponsor exist, replace that sponor's organization
StudyFundingSponsor xprimarySponsor = getPrimaryFundingSponsor();
if (xprimarySponsor != null) {
xprimarySponsor.setOrganization(org);
}
else {
// no primary funding sponsor yet exist, so create one
List<StudyFundingSponsor> sponsors = getStudyFundingSponsors();
int size = sponsors.size();
StudyFundingSponsor primarySponsor = sponsors.get(size);
primarySponsor.setOrganization(org);
}
}
/**
* Will return the primary identifier associated to this study.
*/
@Transient
public Identifier getPrimaryIdentifier() {
for(Identifier id : getIdentifiersLazy()){
if(id.isPrimary()) return id;
}
return null;
}
public void addStudyAgent(final StudyAgent studyAgent) {
getStudyAgents().add(studyAgent);
studyAgent.setStudy(this);
}
public void addCtepStudyDisease(final CtepStudyDisease ctepStudyDisease) {
ctepStudyDisease.setStudy(this);
ctepStudyDiseases.add(ctepStudyDisease);
}
public void addMeddraStudyDisease(final MeddraStudyDisease meddraStudyDisease) {
meddraStudyDisease.setStudy(this);
meddraStudyDiseases.add(meddraStudyDisease);
}
@Transient
public List<StudyCoordinatingCenter> getStudyCoordinatingCenters() {
return new ProjectedList<StudyCoordinatingCenter>(studyOrganizations, StudyCoordinatingCenter.class);
}
@Transient
public StudyCoordinatingCenter getStudyCoordinatingCenter() {
return getStudyCoordinatingCenters().isEmpty() ? null : getStudyCoordinatingCenters().get(0);
}
@Transient
public OrganizationAssignedIdentifier getOrganizationAssignedIdentifier() {
if (getId() != null) {
for (Identifier identifier : getIdentifiers()) {
if (identifier instanceof OrganizationAssignedIdentifier
&& identifier.getType().equalsIgnoreCase("Co-ordinating Center Identifier")) {
organizationAssignedIdentifier = (OrganizationAssignedIdentifier) identifier;
return organizationAssignedIdentifier;
}
}
}
if (organizationAssignedIdentifier == null) {
organizationAssignedIdentifier = new OrganizationAssignedIdentifier();
organizationAssignedIdentifier.setType("Co-ordinating Center Identifier");
organizationAssignedIdentifier.setPrimaryIndicator(Boolean.FALSE);
}
return organizationAssignedIdentifier;
}
@Transient
public void setOrganizationAssignedIdentifier(final OrganizationAssignedIdentifier organizationAssignedIdentifier) {
this.organizationAssignedIdentifier = organizationAssignedIdentifier;
}
@Transient
public List<StudyAgent> getStudyAgents() {
return lazyListHelper.getLazyList(StudyAgent.class);
}
@Transient
public void setStudyAgents(final List<StudyAgent> studyAgents) {
setStudyAgentsInternal(studyAgents);
}
public boolean hasTherapyOfType(StudyTherapyType therapyType){
if(getStudyTherapies() != null){
for(StudyTherapy therapy : getStudyTherapies()){
if(therapy.getStudyTherapyType().equals(therapyType)) return true;
}
}
return false;
}
// / BEAN PROPERTIES
// TODO: this stuff should really, really not be in here. It's web-view/entry specific.
@Transient
public int getStudySiteIndex() {
return studySiteIndex; // returns the index of the study site selected in investigators page
}
public void setStudySiteIndex(final int studySiteIndex) {
this.studySiteIndex = studySiteIndex;
}
@Transient
public String[] getDiseaseTermIds() {
return diseaseTermIds;
}
public void setDiseaseTermIds(final String[] diseaseTermIds) {
this.diseaseTermIds = diseaseTermIds;
}
@Transient
public String getDiseaseCategoryAsText() {
return diseaseCategoryAsText;
}
public void setDiseaseCategoryAsText(final String diseaseCategoryAsText) {
this.diseaseCategoryAsText = diseaseCategoryAsText;
}
@Transient
public String getDiseaseLlt() {
return diseaseLlt;
}
public void setDiseaseLlt(final String diseaseLlt) {
this.diseaseLlt = diseaseLlt;
}
@Deprecated
@Transient
public Ctc getCtcVersion() {
return getAeTerminology().getCtcVersion();
}
@Deprecated
@Transient
public void setCtcVersion(final Ctc ctcVersion) {
AeTerminology t = getAeTerminology();
t.setTerm(Term.CTC);
t.setCtcVersion(ctcVersion);
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "study")
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public DiseaseTerminology getDiseaseTerminology() {
if (diseaseTerminology == null) {
diseaseTerminology = new DiseaseTerminology();
diseaseTerminology.setStudy(this);
}
return diseaseTerminology;
}
public void setDiseaseTerminology(final DiseaseTerminology diseaseTerminology) {
this.diseaseTerminology = diseaseTerminology;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "study")
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public AeTerminology getAeTerminology() {
if (aeTerminology == null) {
aeTerminology = new AeTerminology();
aeTerminology.setStudy(this);
}
return aeTerminology;
}
public void setAeTerminology(final AeTerminology aeTerminology) {
this.aeTerminology = aeTerminology;
}
@Override
@OneToMany
@Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@JoinColumn(name = "STU_ID")
@OrderBy
public List<Identifier> getIdentifiers() {
return lazyListHelper.getInternalList(Identifier.class);
}
@Override
public void setIdentifiers(final List<Identifier> identifiers) {
lazyListHelper.setInternalList(Identifier.class, identifiers);
}
@Transient
@UniqueIdentifierForStudy(message="Identifier already exist for a different study")
@UniqueObjectInCollection(message="Duplicate Identifier")
public List<Identifier> getIdentifiersLazy() {
return lazyListHelper.getLazyList(Identifier.class);
}
@Transient
public void setIdentifiersLazy(final List<Identifier> identifiers) {
setIdentifiers(identifiers);
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyAgent> getStudyAgentsInternal() {
return lazyListHelper.getInternalList(StudyAgent.class);
}
public void setStudyAgentsInternal(final List<StudyAgent> studyAgents) {
lazyListHelper.setInternalList(StudyAgent.class, studyAgents);
}
@OneToMany
@JoinColumn(name = "study_id", nullable = false)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@Where(clause = "term_type = 'ctep'")
@UniqueObjectInCollection(message = "Duplicate - Same disease is associated to the study more than ones")
// it is pretty lame that this is necessary
public List<CtepStudyDisease> getCtepStudyDiseases() {
return ctepStudyDiseases;
}
public void setCtepStudyDiseases(final List<CtepStudyDisease> ctepStudyDiseases) {
this.ctepStudyDiseases = ctepStudyDiseases;
}
@OneToMany
@JoinColumn(name = "study_id", nullable = false)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@Where(clause = "term_type = 'meddra'")
@UniqueObjectInCollection(message = "Duplicate - Same disease is associated to the study more than ones")
// it is pretty lame that this is necessary
public List<MeddraStudyDisease> getMeddraStudyDiseases() {
return meddraStudyDiseases;
}
public void setMeddraStudyDiseases(final List<MeddraStudyDisease> meddraStudyDiseases) {
this.meddraStudyDiseases = meddraStudyDiseases;
}
public Boolean getBlindedIndicator() {
return blindedIndicator;
}
public void setBlindedIndicator(final Boolean blindedIndicator) {
this.blindedIndicator = blindedIndicator;
}
public Boolean getMultiInstitutionIndicator() {
return multiInstitutionIndicator;
}
public void setMultiInstitutionIndicator(final Boolean multiInstitutionIndicator) {
this.multiInstitutionIndicator = multiInstitutionIndicator;
}
public Boolean getRandomizedIndicator() {
return randomizedIndicator;
}
public void setRandomizedIndicator(final Boolean randomizedIndicator) {
this.randomizedIndicator = randomizedIndicator;
}
public String getDescription() {
return description;
}
public void setDescription(final String descriptionText) {
description = descriptionText;
}
public String getDiseaseCode() {
return diseaseCode;
}
public void setDiseaseCode(final String diseaseCode) {
this.diseaseCode = diseaseCode;
}
public String getLongTitle() {
return longTitle;
}
public void setLongTitle(final String longTitleText) {
longTitle = longTitleText;
}
public String getMonitorCode() {
return monitorCode;
}
public void setMonitorCode(final String monitorCode) {
this.monitorCode = monitorCode;
}
public String getPhaseCode() {
return phaseCode;
}
public void setPhaseCode(final String phaseCode) {
this.phaseCode = phaseCode;
}
public String getPrecis() {
return precis;
}
public void setPrecis(final String precisText) {
precis = precisText;
}
public String getShortTitle() {
return shortTitle;
}
public void setShortTitle(final String shortTitleText) {
shortTitle = shortTitleText;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
public Integer getTargetAccrualNumber() {
return targetAccrualNumber;
}
public void setTargetAccrualNumber(final Integer targetAccrualNumber) {
this.targetAccrualNumber = targetAccrualNumber;
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyOrganization> getStudyOrganizations() {
return studyOrganizations;
}
public void setStudyOrganizations(final List<StudyOrganization> studyOrganizations) {
this.studyOrganizations = studyOrganizations;
// initialize projected list for StudySite, StudyFundingSponsor and StudyCoordinatingCenter
lazyListHelper.setInternalList(StudySite.class, new ProjectedList<StudySite>(this.studyOrganizations,
StudySite.class));
lazyListHelper.setInternalList(StudyFundingSponsor.class, new ProjectedList<StudyFundingSponsor>(
this.studyOrganizations, StudyFundingSponsor.class));
}
@OneToMany(mappedBy = "study", fetch = FetchType.LAZY)
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<TreatmentAssignment> getTreatmentAssignmentsInternal() {
return lazyListHelper.getInternalList(TreatmentAssignment.class);
}
public void setTreatmentAssignmentsInternal(final List<TreatmentAssignment> treatmentAssignments) {
lazyListHelper.setInternalList(TreatmentAssignment.class, treatmentAssignments);
}
@Transient
public List<TreatmentAssignment> getTreatmentAssignments() {
return lazyListHelper.getLazyList(TreatmentAssignment.class);
}
public void setTreatmentAssignments(final List<TreatmentAssignment> treatmentAssignments) {
setTreatmentAssignmentsInternal(treatmentAssignments);
}
// TODO Why rules is still using primarySponsorCode... (check)
@Transient
public String getPrimarySponsorCode() {
Organization sponsorOrg = getPrimaryFundingSponsorOrganization();
if (sponsorOrg != null) {
return sponsorOrg.getNciInstituteCode();
}
return null;
}
public Integer getLoadStatus() {
return loadStatus;
}
public void setLoadStatus(Integer loadStatus) {
this.loadStatus = loadStatus;
}
// TODO Below methods are to be removed.....
// TODO check how to get rid of this???? (Admin module require this method)
public void setPrimarySponsorCode(final String sponsorCode) {
throw new UnsupportedOperationException("'setPrimarySponsorCode', one should not access this method!");
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "study")
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyTherapy> getStudyTherapies() {
return studyTherapies;
}
public void setStudyTherapies(final List<StudyTherapy> studyTherapies) {
this.studyTherapies = studyTherapies;
}
@Transient
public void addStudyTherapy(final StudyTherapy studyTherapy) {
studyTherapies.add(studyTherapy);
}
public void removeIdentifier(final Identifier identifier) {
getIdentifiers().remove(identifier);
}
@Transient
public Boolean getDrugAdministrationTherapyType() {
return drugAdministrationTherapyType;
}
public void setDrugAdministrationTherapyType(final Boolean drugAdministrationTherapyType) {
this.drugAdministrationTherapyType = drugAdministrationTherapyType;
}
@Transient
public Boolean getRadiationTherapyType() {
return radiationTherapyType;
}
public void setRadiationTherapyType(final Boolean radiationTherapyType) {
this.radiationTherapyType = radiationTherapyType;
}
@Transient
public Boolean getDeviceTherapyType() {
return deviceTherapyType;
}
public void setDeviceTherapyType(final Boolean deviceTherapyType) {
this.deviceTherapyType = deviceTherapyType;
}
@Transient
public Boolean getSurgeryTherapyType() {
return surgeryTherapyType;
}
public void setSurgeryTherapyType(final Boolean surgeryTherapyType) {
this.surgeryTherapyType = surgeryTherapyType;
}
@Transient
public Boolean getBehavioralTherapyType(){
return behavioralTherapyType;
}
public void setBehavioralTherapyType(final Boolean behavioralTherapyType){
this.behavioralTherapyType = behavioralTherapyType;
}
@Transient
public StudyTherapy getStudyTherapy(final StudyTherapyType studyTherapyType) {
for (StudyTherapy studyTherapy : studyTherapies) {
if (studyTherapy.getStudyTherapyType().equals(studyTherapyType)) {
return studyTherapy;
}
}
return null;
}
@Transient
public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers(){
return new ProjectedList<SystemAssignedIdentifier>(getIdentifiersLazy(), SystemAssignedIdentifier.class);
}
@Transient
public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers(){
return new ProjectedList<OrganizationAssignedIdentifier>(getIdentifiersLazy(), OrganizationAssignedIdentifier.class);
}
@Transient
public CoordinatingCenter getCoordinatingCenter() {
return coordinatingCenter;
}
@Transient
public FundingSponsor getFundingSponsor() {
return fundingSponsor;
}
public void setCoordinatingCenter(CoordinatingCenter coordinatingCenter) {
this.coordinatingCenter = coordinatingCenter;
}
public void setFundingSponsor(FundingSponsor fundingSponsor) {
this.fundingSponsor = fundingSponsor;
}
public Boolean getAdeersReporting() {
return adeersReporting;
}
public void setAdeersReporting(Boolean adeersSubmission) {
this.adeersReporting = adeersSubmission;
}
}
|
package uk.org.opentrv.test.leafauthenc;
import static org.junit.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.BeforeClass;
import org.junit.Test;
import uk.org.opentrv.comms.util.crc.CRC7_5B;
public class SecureFrameTest
{
public static final int AES_KEY_SIZE = 128; // in bits
public static final int GCM_NONCE_LENGTH = 12; // in bytes
public static final int GCM_TAG_LENGTH = 16; // in bytes (default 16, 12 possible)
public static final byte AES_GCM_ID = (byte)0x80; // used in the trailer to indicate the encryption type
/**Standard text string to compute checksum of, eg as used by pycrc. */
public static final String STD_TEST_ASCII_TEXT = "123456789";
/**Private byte array to clone from as needed. */
private static final byte[] _STD_TEST_ASCII_TEXT_B;
static
{
try { _STD_TEST_ASCII_TEXT_B = STD_TEST_ASCII_TEXT.getBytes("ASCII7"); }
catch(final UnsupportedEncodingException e) { throw new IllegalStateException(); }
}
/**Get STD_TEST_ASCII_TEXT as new private byte array. */
public static byte[] getStdTestASCIITextAsByteArray() { return(_STD_TEST_ASCII_TEXT_B.clone()); }
// Nominal global counters on the TX side for nonce generation
public static final int ResetCounter = 42;
public static final int TxMsgCounter = 793;
// 6 Byte ID of the sensor 4 MSBs are included as the ID. 2 LSBs are pre-shared between rx and tx.
public static byte[] LeafID = {(byte)0xAA,(byte)0xAA,(byte)0xAA,(byte)0xAA,(byte)0x55,(byte)0x55};
// Message definitions ToDO - OFrameStruct into header, body and trailer pointers and define a header struct.
static final class BodyTypeOStruct {
boolean heat; // Call-for-heat flag.
byte valvePos; // Valve % open [0,100] or 0x7f for 'invalid'.
byte flags; // Assorted flags indicating the sate of the nation (ToDo ref spec doc here)
String stats; // Compact JSON object with leading { final } omitted.
}
static final class OFrameStruct {
byte length; // Overall frame length excluding this byte, unsigned [0,255], typically <=64 and filled in automatically
boolean secFlag; // Secure flag (true => secure)
byte frameType; // Frame type.
byte frameSeqNo; // Frame sequence number bits 4-7 [0,15].
byte il; // Length of the ID in bytes [0,15]; 0 implies anonymous, typically 2 bytes.
byte [] id; // ID leading/prefix bytes of length il [0,15].
byte bl; // Length of the body section [0,251].
BodyTypeOStruct body; // Body content.
byte[] trailer; // Trailer - either a 7bit CRC for insecure frame or variable length security
// info in the encrypted case, with the final byte and length determined by encryption method used.
}
// The aad is all the header bytes => 4 fixed plus however many are in the ID
public static byte[] generateAAD (final byte[] msgBuff, final int len){
final byte[] aad = new byte[len];
System.arraycopy(msgBuff,0,aad,0,len);
return(aad);
}
public static byte[] retrieveAAD(final byte[] msgBuff,final OFrameStruct decodedPacket){
final byte [] aad = new byte [decodedPacket.il + 4]; //4 bytes plus the size of the leaf node ID field that was sent.
System.arraycopy(msgBuff,0,aad, 0, decodedPacket.il + 4);
return(aad);
}
// Nonce Generation and Retrieval
public static byte[] generateNonce() {
final byte[] nonce = new byte[GCM_NONCE_LENGTH];
System.arraycopy(LeafID,0,nonce,0,6); // 6MSBs of leaf ID
nonce[6] = (byte)(ResetCounter >> 16); //3 LSB of Reset Counter
nonce[7] = (byte)(ResetCounter >> 8);
nonce[8] = (byte) ResetCounter;
nonce[9] = (byte)(TxMsgCounter >> 16); // 3 LSBs of TXmessage counter
nonce[10] = (byte)(TxMsgCounter >> 8);
nonce[11] = (byte)TxMsgCounter;
return (nonce);
}
static byte[] presharedIdBytes = {LeafID[4],LeafID[5]};
/**Retrieve IV/nonce from raw message and other information.
* <ul>
* <li>4 MSBs of ID</li>
* <li>2 LSBs of ID, that are not sent OTA but magically shared</li>
* <li>3 bytes of resatr counter - retrieved from the trailer</li>
* <li>3 bytes od tx message counter - retrieved from the trailer</li>
* </uL>
*
* @param msgBuff Raw message received from the aether
* @param pos index into msgBuff at the start of the message body
* @param decodedFrame the bits of the frame that have been decoded so far. i,e the header at this point
*/
public static byte[] retrieveNonce(final byte[] msgBuff, int pos, final OFrameStruct decodedFrame ){
final byte[] nonce= new byte[GCM_NONCE_LENGTH];
byte nonceIndx = 0;
pos += decodedFrame.bl; // point pos at the trailer in the msgBuff
if (decodedFrame.il < 4){ // check there are 4 bytes in the ID field in the header
System.out.format("leaf node ID length %d in header too short. should be >=4bytes\r\n",decodedFrame.il);
System.exit(1);
}
System.arraycopy(decodedFrame.id, 0, nonce, 0, decodedFrame.il); // copy the first 4 (MSBs) of the ID from the header
nonceIndx+=decodedFrame.il;
System.arraycopy(presharedIdBytes,0,nonce,nonceIndx,2); // copy the preshared ID bytes
nonceIndx+=2;
System.arraycopy(msgBuff, pos, nonce, nonceIndx, 3); // copy the 3 restart counter bytes out of the trailer
nonceIndx+=3;
pos+=3;
System.arraycopy(msgBuff, pos, nonce, nonceIndx, 3); // copy the 3 tx message counter bytes out of the trailer
return (nonce);
}
public static byte[] removePadding (final byte[] plainText){
//look at the last byte of the array to see how much padding there is
int size = plainText.length;
System.out.println("size ="+ size);
final int padding = plainText[size-1];
size -= padding;
final byte[]unpadded = new byte[size];
//remove padding
for (int i=0;i<size;i++)
{
unpadded[i]=plainText[i];
}
return (unpadded);
}
/*
pads the message body out with 0s to 32 bits. Errors if length > 31
and sticks the number of bytes of padding in the last byte of the padded body.
@param body structure containing the message body for encryption
@param len length (in bytes) of the structure
returns byte array containing the padded message.
*/
public static byte[] addPaddingTo16BTrailing0sAndPadCount(final BodyTypeOStruct body, final byte len){
byte[] paddedMsg;
System.out.println("\r\n Length = "+len);
if(len >=32) {
System.out.format("Body length %d too big. 32 Max",len);
System.exit(1);
}
paddedMsg = new byte[32];
paddedMsg[0]= (body.valvePos |= ((body.heat == true)? (byte)0x80 : (byte)0x00)); //OR in the call for heat bit
paddedMsg[1]= body.flags;
System.arraycopy(body.stats.getBytes(),0,paddedMsg,2,body.stats.getBytes().length);
final int padding =(paddedMsg.length - (len+1));
paddedMsg[paddedMsg.length-1]= (byte)padding; // add the number of bytes of padding to the last byte in the array.
return (paddedMsg);
}
/*
* 23 bytes made up as follows:
* 3 LS Bytess of reset counter
* 3 LS Bytes of message counter
* 16 byte authentication tag from the crypto algorithm
* a 0x80 marker to indicate that AESGCM is the encryption mode.
*
*/
public static int addTrailer (final byte[] msgBuff, int index, final byte[] authTag)
{
msgBuff[index++] = (byte)(ResetCounter >> 16); //3 LSB of Reset Counter
msgBuff[index++] = (byte)(ResetCounter >> 8);
msgBuff[index++] = (byte) ResetCounter;
msgBuff[index++] = (byte)(TxMsgCounter >> 16); // 3 LSBs of TXmessage counter
msgBuff[index++] = (byte)(TxMsgCounter >> 8);
msgBuff[index++] = (byte)TxMsgCounter;
System.arraycopy(authTag,0, msgBuff, index, authTag.length); // copy the authentication tag into the message buffer
msgBuff[index+authTag.length] = AES_GCM_ID; // indicates AESGCM encryption mode - moved to back (byte 23) of trailer.
index++;
return (index+authTag.length); // size of the completed TX packet
}
/*
* @param msgBuff contains a pointer to a 255 byte buffer with partially build packet to send in it
* @param pos points to the start of the body section in msgBuff
* @param body contains the message body to encrypt
*
* returns the number of bytes written to
*/
public static int encryptFrame(final byte[] msgBuff, final int pos, final OFrameStruct frame,final byte[] authTag) throws Exception {
//prepare plain text
final byte[] input = addPaddingTo16BTrailing0sAndPadCount(frame.body, frame.bl); // pad body content out to 16 or 32 bytes.
//Update frame length Header = 4+idLen bytes. Body padded bodylength (input.length). Trailer is fixed 23 bytes
// A better place to do this might be after the trailer has been built. An even better design would be to have separate
// structures for header, body and trailer - this would make the design more extensible and do away with lots of magic numbers.
msgBuff[0] = (byte)(4+frame.il+input.length + 23);
// setup the bodylength now it has been padded
frame.bl = (byte)input.length;
msgBuff[pos-1] = (frame.bl); //Pos -1 is a bit of a hack. This will be fixed with architectural change of body structure to contain the body length.
// Generate IV (nonce)
final byte[] nonce = generateNonce();
final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
// generate AAD
final byte[] aad = generateAAD(msgBuff,(frame.il+4)); // aad = the header - 4 bytes + sizeof ID
// Do the encryption -
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); // JDK 7 breaks here..
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
cipher.updateAAD(aad);
final byte[] cipherText = cipher.doFinal(input); // the authentication tag should end up appended to the cipher text
// print input
System.out.format("%d Byte padded input text\r\n",input.length);
for(final byte element : input)
{
System.out.format("%02x ",element);
}
System.out.format("\r\n\r\n");
// print nonce
System.out.format("%d Byte Nonce\r\n",nonce.length);
for(final byte element : nonce)
{
System.out.format("%02x ",element);
}
System.out.format("\r\n\r\n");
//print aad
System.out.format("%d Byte aad\r\n",aad.length);
for(final byte element : aad)
{
System.out.format("%02x ",element);
}
System.out.format("\r\n\r\n");
//print output
System.out.format("%d Byte cipher text plus authentication tag output from algo\r\n",cipherText.length);
for(final byte element : cipherText)
{
System.out.format("%02x ",element);
}
System.out.format("\r\n\r\n");
// copy cipher text minus authtag to the msgBuff
System.arraycopy(cipherText,0,msgBuff,pos, cipherText.length - GCM_TAG_LENGTH);
// copy the authentication tag appended to the end of cipherText into authTag
System.arraycopy(cipherText,input.length,authTag,0,GCM_TAG_LENGTH);
return (input.length);
}
/*
* @param msgBuff The received message from the aether
* @param index Set to the start of the message body section
* @param decodedPacket The decoded header section of the message.
*
*/
public static void decryptFrame(final byte[] msgBuff, final int index, final OFrameStruct decodedPacket) throws Exception{
// Check we are dealing with AESGCM by looking at the last byte of the packet
if (msgBuff[index + decodedPacket.bl+22] != AES_GCM_ID){ // test trailer last (23rd) byte to make sure we are dealing with the correct algo
System.out.println("unrecognized encryption algorithm");
System.exit(1);
}
// Retrieve Nonce
final byte[] nonce = retrieveNonce (msgBuff, index,decodedPacket);
System.out.println("\r\nRetrieved nonce");
for(final byte element : nonce)
{
System.out.format("%02x ",element);
}
final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
//retrieve AAD
final byte[] aad = retrieveAAD(msgBuff,decodedPacket); // decodedPacket needed to deduce the length of the header.
System.out.println("\r\nRetrieved aad");
for(final byte element : aad)
{
System.out.format("%02x ",element);
}
// copy received ecrypted body text to appropriately sized array
final byte[] cipherText = new byte[decodedPacket.bl + GCM_TAG_LENGTH]; // cipher text has the auth tag appended to it
System.arraycopy(msgBuff, index, cipherText, 0, decodedPacket.bl);
// append the authentication tag to the cipher text - this is a peculiarity of this Java implementation.
// The algo authenticates before decrypting, which is more efficient and less likely to kill the decryption engine with random crap.
// the magic 6 is the offset from the start of the trailer to the auth tag.
System.arraycopy(msgBuff,(index+decodedPacket.bl+6) , cipherText,decodedPacket.bl, GCM_TAG_LENGTH);
System.out.format("\r\nRetrieved %d byte cipher text with auth tag appended\r\n", cipherText.length);
for(final byte element : cipherText)
{
System.out.format("%02x ",element);
}
// Decrypt:
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); // JDK 7 breaks here..
cipher.init(Cipher.DECRYPT_MODE, key, spec);
cipher.updateAAD(aad);
final byte[] plainText = cipher.doFinal(cipherText);
//print out received plain text
System.out.println("\r\nDecrypted plain text");
for(final byte element : plainText)
{
System.out.format("%02x ",element);
}
// copy unpadded plain text into the decoded Packet Structure.
final byte[] unpadded = removePadding (plainText);
System.out.println("unpadded length =" + unpadded.length);
// copy stats string to the structure
final byte[] stats = new byte[unpadded.length-2];
System.arraycopy (unpadded,2,stats,0,unpadded.length-2);
decodedPacket.body.stats = new String(stats);
// set heat flag and valve position
if ((unpadded[0] & 0x80)== 0x80)
{
decodedPacket.body.heat = true;
}
// clear out the top bit and set the valve position
unpadded[0]&= 0x7F;
decodedPacket.body.valvePos = unpadded[0];
//set up the flags
decodedPacket.body.flags = unpadded[1];
}
// Positions in the message byte array of TX buffer
public static final int LENGTH = 0; // Overall frame length, excluding this byte, typically <=64
public static final int TYPE = 1; // bit 7 is secure/insecure flag, bits 6-0 constitute the frame type.
public static final int SEQ_LEN = 2; // Frame Sequence number bits 4-7, id length bits 0-3
public static final int ID = 3; // Start Position of ID
/*
* Takes a 255 byte message buffer and builds the 'O' Frame in it by serialising the OFrame data structure for passing to the physical layer.
*/
public static int buildOFrame (final byte[] msgBuff, final OFrameStruct msg){
byte crc = 0;
int index = ID + msg.il; // set index to the position of body length field
final int bodyPos = index+1; // bodyPos points at the actual body section of the frame
int i;
final int packetLen = 5 + msg.il + msg.bl; // There are 5 fixed bytes in an insecure packet (including the crc)
System.out.println("body len = "+msg.bl);
/*
* Header
*/
if (msg.secFlag == false)
{
msgBuff[LENGTH] = (byte)(packetLen -1); //the frame length byte contains length -1
}
// The packet length for secure packets gets set in the buildOFrame() function
msgBuff[TYPE] = msg.frameType;
if (msg.secFlag == true){
System.out.println("secure flag set");
msgBuff[TYPE] |= 0x80; // bit 7 of the type byte
}
msgBuff[SEQ_LEN] = msg.il; // lower nibble message id length
msgBuff[SEQ_LEN] |= (msg.frameSeqNo << 4); // upper nibble frame sequence number
// build the variable parts of the frame
for (i=0;i<msg.il;i++)
{
msgBuff[ID+i]=msg.id[i]; // copy the message id bytes into the message buffer
}
/*
* Insecure Body and CRC
*/
if (msg.secFlag == false){
// add the message body fixed elements. the assumption here is tha the body length field has been pre-filled in the struct
msgBuff[index++] = msg.bl; // index was initialised to point at the message body length position
if (msg.bl !=0){
msgBuff[index] = msg.body.valvePos; // copy the valve position
if (msg.body.heat == true)
{
msgBuff[index] |= 0x80; // set the call for heat bit.
}
index++;
msgBuff[index++] = msg.body.flags; // copy the flags byte
}
// add the variable length body elements. if there are any
if (msg.bl > 2){ // two is the minimum body length
final byte[] statBody = msg.body.stats.getBytes();
for (i=0;i<(msg.bl-2);i++)
{
msgBuff[index++]=statBody[i];
}
}
// compute the crc
crc = computeInsecureFrameCRC(msgBuff,0,(index));
// add crc to end of packet
msgBuff[index++]= crc;
return (index); //return the number of bytes written
}
/*
* Secure Body and 23 byte Trailer
*/
else {
final byte[] authTag = new byte[GCM_TAG_LENGTH];
byte length=0;
if (msg.il < 4){
System.out.println("Leaf node ID too short. Must be 4 or more bytes");
System.exit(1);
}
try {
length = (byte)encryptFrame (msgBuff,bodyPos,msg,authTag);
//msg.bodyLen is set up in the encryption function, after the padding has been added
index++; // index was initialised to point at the body length field at the top of the function.
index+=length; // move index to point at the start of the trailer
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exception thrown in encrypt frame");
System.exit(1);
}
index = addTrailer (msgBuff,(bodyPos+length),authTag);
return(index);
}
}
/*
* Parses the incoming message and returns an OFrameStruct object populated with the message contents
*/
public static OFrameStruct decodeOFrame (final byte[] msgBuff){
int i=0,j=0;
//allocate memory to build packet in
final OFrameStruct decodedPacket = new OFrameStruct();
final BodyTypeOStruct body = new BodyTypeOStruct();
decodedPacket.body = body;
//Message Header
decodedPacket.length = msgBuff[i++]; // packet length byte
if ((msgBuff[i] & (byte)0x80) == (byte)0x80)
{
decodedPacket.secFlag = true;
}
decodedPacket.frameType |= (byte)(msgBuff[i++] & (byte)0x7F); //set up frame type (after masking out bit 7)
decodedPacket.il = (byte)(msgBuff[i] & (byte)0x0F); // id length is bottom nibble of seq length byte
decodedPacket.frameSeqNo = (byte)(msgBuff[i++] >>> 4); // sequence number is top nibble of seq length byte
final byte[] id = new byte[decodedPacket.il]; // copy id fields
decodedPacket.id = id;
for (j=0;j<decodedPacket.il;j++){
decodedPacket.id[j] = msgBuff[i++];
}
decodedPacket.bl = msgBuff[i++]; // message body length
// Message Body
if (decodedPacket.bl > 0){ // if there is a message body extract it
if (decodedPacket.secFlag == true){ // its secure frame so decrypt it, then return the decoded packet.
System.out.println("decoding secure frame");
try {
decryptFrame (msgBuff,i,decodedPacket); // decrypt the frame
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exceptiom thrown in decrypt frame");
System.exit(1);
}
}
else { // insecure so extract it
System.out.println("decoding insecure frame");
if ((msgBuff[i] & (byte)0x80) == (byte)0x80)
{
decodedPacket.body.heat = true; // set call for heat flag
}
decodedPacket.body.valvePos = (byte)(msgBuff[i++] & (byte)0x7F); // mask out the call for heat flag to get the valve position
decodedPacket.body.flags = msgBuff[i++]; //flags byte
if (decodedPacket.bl > 2) { // test to see if there is a JSON object in the field (first 2 bytes are mandatory)
String json = new String();
json ="";
for (j=0;j<(decodedPacket.bl-2);j++)
{
json += (char)msgBuff[i++];
}
decodedPacket.body.stats = json; //extracted json
}
}
}
else
{
System.out.println("No Message Content found");
}
// Message Trailer
if (decodedPacket.secFlag == false) {
final byte[] crc = new byte[1];
crc[0] = computeInsecureFrameCRC(msgBuff,0,i);
decodedPacket.trailer = crc;
if (crc[0] != msgBuff[i]) {
return (null);
}
}
else { // Extract the 23 byte trailer from the secure message
final byte[] trailer = new byte[23];
// 3 fixed header bytes plus the length of the id plus body length byte plus the actual body length
int trailerPtr = 3+decodedPacket.il + 1 +decodedPacket.bl;
for (i=0;i<23;i++)
{
trailer[i]=msgBuff[trailerPtr++];
}
decodedPacket.trailer = trailer;
}
return (decodedPacket);
}
/**Cryptographically-secure PRNG. */
//private static SecureRandom srnd;
private static SecretKey key;
/**Do some expensive initialisation as lazily as possible... */
@BeforeClass
public static void beforeClass() throws NoSuchAlgorithmException
{
// final SecureRandom srnd;
// srnd = SecureRandom.getInstanceStrong(); // JDK 8.
// Generate Key - needs to be available for the decrypt side too
// final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
// keyGen.init(AES_KEY_SIZE, srnd);
// key = keyGen.generateKey();
key = new SecretKeySpec(new byte[AES_KEY_SIZE/8], 0, AES_KEY_SIZE/8, "AES");
}
public static void printPacket (final OFrameStruct decodedPacket){
byte i=0;
System.out.format("\r\n\r\nDecoded Packet:\r\n");
//header
System.out.format("frame length: %02x\r\n",decodedPacket.length);
System.out.format("secure flag: %b\r\n", decodedPacket.secFlag);
System.out.format("frame type: %02x\r\n",decodedPacket.frameType);
System.out.format("sequence no: %02x\r\n",decodedPacket.frameSeqNo);
System.out.format("idLen: %02x\r\n",decodedPacket.il);
System.out.format("id: ");
for(i=0;i<decodedPacket.il;i++)
{
System.out.format("%02x",decodedPacket.id[i]);
}
System.out.format("\r\n");
System.out.format("body length %02x\r\n",decodedPacket.bl);
//message
System.out.format("\r\n\r\nMessage Body\r\n");
System.out.format("call for heat %b\r\n",decodedPacket.body.heat);
if ( decodedPacket.body.valvePos == 0x7F)
{
System.out.println("no valve present");
}
else
{
System.out.format("valve position %02x\r\n",decodedPacket.body.valvePos);
}
System.out.format("\r\nflags %02x\r\n",decodedPacket.body.flags);
System.out.println(("fault flag: " + (((decodedPacket.body.flags & 0x80)== (byte)0x80)? "set":"clear")));
System.out.println(("low battery: " + (((decodedPacket.body.flags & 0x40)== (byte)0x40)? "set":"clear")));
System.out.println(("tamper flag: " + (((decodedPacket.body.flags & 0x20)== (byte)0x20)? "set":"clear")));
System.out.println(("stats present: " + (((decodedPacket.body.flags & 0x10)== (byte)0x10)? "set":"clear")));
if ((decodedPacket.body.flags & 0x0C) == (byte)0x00)
{
System.out.println("occupancy: unreported");
}
if ((decodedPacket.body.flags & 0x0C) == (byte)0x40)
{
System.out.println("occupancy: none");
}
if ((decodedPacket.body.flags & 0x0C) == (byte)0x08)
{
System.out.println("occupancy: possible");
}
if ((decodedPacket.body.flags & 0x0C) == (byte)0x0C)
{
System.out.println("occupancy: likely");
}
System.out.println("bottom 2 bits reserved value of b01");
System.out.format("\r\njson string %s\r\n",decodedPacket.body.stats);
//Trailer
if (decodedPacket.secFlag == false)
{
System.out.format("CRC: %02x",decodedPacket.trailer[0]);
}
else{
System.out.println("Trailer Bytes");
for(i=0;i<23;i++)
{
System.out.format("%02x ", decodedPacket.trailer[i]);
}
}
}
/**Test non-secure frames. */
@Test
public void testNonSecureFrames()
{
final OFrameStruct packetToSendA = new OFrameStruct();
final byte[] idA = {(byte)0x80,(byte)0x81};
final byte[] idC = new byte[4];
System.arraycopy(LeafID, 0, idC, 0, 4); // 4MSBs of leaf node ID
final BodyTypeOStruct bodyA = new BodyTypeOStruct();
bodyA.heat = false;
bodyA.valvePos=0;
bodyA.flags = 0x01;
packetToSendA.secFlag = false;
packetToSendA.frameType = 0x4F; // Insecure O Frame
packetToSendA.frameSeqNo = 0;
packetToSendA.il = 2;
packetToSendA.id = idA;
packetToSendA.bl = 0x02;
packetToSendA.body = bodyA;
final BodyTypeOStruct bodyB= new BodyTypeOStruct();
bodyB.heat = false;
bodyB.valvePos=0x7f;
bodyB.flags = 0x11;
bodyB.stats = "{\"b\":1";
final OFrameStruct packetToSendB = new OFrameStruct();
packetToSendB.secFlag = false;
packetToSendB.frameType = 0x4F; // Insecure O Frame
packetToSendB.frameSeqNo = 0;
packetToSendB.il = 2;
packetToSendB.id = idA;
packetToSendB.body = bodyB;
packetToSendB.bl = (byte)(bodyB.stats.getBytes().length+2);
}
/**Test secure frames. */
@Test
public void testSecureFrames()
{
final byte[] idC = new byte[4];
System.arraycopy(LeafID, 0, idC, 0, 4); // 4MSBs of leaf node ID
final BodyTypeOStruct bodyC= new BodyTypeOStruct();
bodyC.heat = false;
bodyC.valvePos=0x7f;
bodyC.flags = 0x11;
bodyC.stats = "{\"b\":1";
final OFrameStruct packetToSendC = new OFrameStruct();
packetToSendC.secFlag = true;
packetToSendC.frameType = 0x4F; // secure O Frame
packetToSendC.frameSeqNo = 0;
packetToSendC.il = 4; // needs to be 4 bytes or more. Behaviour undefined if more at the moment
packetToSendC.id = idC;
packetToSendC.body = bodyC; // This must happen before the next line to avoid null pointer exception!!
packetToSendC.bl = (byte)(bodyC.stats.getBytes().length+2); //Number of bytes in the stats string + 2 for the flags
System.out.println("Start Test");
System.out.println("bodyLen ="+ packetToSendC.bl);
//TODO - set up an array of structure pointers and run the whole lot through the encode / decode functions
final byte[] msgBuff = new byte[0xFF];
final int msgLen = buildOFrame(msgBuff, packetToSendC);
System.out.format("Raw data packet from encoder is: %02x bytes long \r\n", msgLen);
for (int i=0;i<msgLen;i++) { System.out.format("%02x ", msgBuff[i]); }
System.out.println(""); // CR LF
// Decode and print out the received packet.
printPacket(decodeOFrame (msgBuff));
}
/**Check expected behaviour of 7-bit '0x5B' CRC. */
@Test public void test_crc7_5B()
{
// Test against standard text string.
// For PYCRC 0.8.1
// Running ./pycrc.py -v --width=7 --poly=0x37 --reflect-in=false --reflect-out=false --xor-in=0 --xor-out=0 --algo=bbb
// Generates: 0x4
// From pycrc-generated reference bit-by-bit code.
byte crcBBB = CRC7_5B.bbb_init();
crcBBB = CRC7_5B.bbb_update(crcBBB, getStdTestASCIITextAsByteArray(), STD_TEST_ASCII_TEXT.length());
crcBBB = CRC7_5B.bbb_finalize(crcBBB);
assertEquals("CRC should match for standard text string", 4, crcBBB);
}
/**Compute (non-secure) CRC over secureable frame content.
* @param buf buffer that included the frame data to have the CRC applied (all of header and body);
* never null
* @param pos starting position of the frame data in the buffer;
* must be valid offset within the buffer
* @param len length of frame data to have the CRC computed over;
* strictly positive and pos+len must be within the buffer
*/
public static byte computeInsecureFrameCRC(final byte buf[], final int pos, final int len)
{
byte crc = (byte)0x7f; // Initialise CRC with 0x7f (protects against extra leading 0x00s).
for(int i = 0; i < len; ++i)
{
crc = CRC7_5B.crc7_5B_update(crc, buf[pos + i]);
}
if(0 == crc) { return((byte)0x80); } // Avoid all-0s and all-1s result values, ie self-whitened.
return(crc);
}
/**Simple minimal test of CRC computations for non-secure 'O' format frame.
* Do a valve frame at 0% open, no stats.
* Do a non-valve frame with minimal representative {"b":1} stats.
*/
@Test
public void testNonSecureCRCs()
{
//Example insecure frame, from valve unit 0% open, no call for heat/flags/stats.
//08 4f 02 80 81 02 | 00 01 | 1c
//08 length of header after length byte 5 + body 2 + trailer 1
//4f 'O' insecure OpenTRV basic frame
//02 0 sequence number, ID length 2
//80 ID byte 1
//81 ID byte 2
//02 body length 2
//00 valve 0%, no call for heat
//01 no flags or stats, unreported occupancy
//23 CRC value
// Check the CRC computation for the simple "valve 0%" frame.
assertEquals((byte)0x23, computeInsecureFrameCRC(new byte[]{8, 'O', 2, (byte)0x80, (byte)0x81, 2, 0, 1}, 0, 8));
//Example insecure frame, no valve, representative minimum stats {"b":1}
//In this case the frame sequence number is zero, and ID is 0x80 0x81.
//0e 4f 02 80 81 08 | 7f 11 7b 22 62 22 3a 31 | 61
//0e length of header (14) after length byte 5 + body 8 + trailer 1
//4f 'O' insecure OpenTRV basic frame
//02 0 sequence number, ID length 2
//80 ID byte 1
//81 ID byte 2
//08 body length 8
//7f no valve, no call for heat
//11 no flags, unreported occupancy, stats present
//7b 22 62 22 3a 31 {"b":1 Stats: note that implicit trailing '}' is not sent.
//61 CRC value
// Check the CRC computation for the simple stats frame.
assertEquals((byte)0x61, computeInsecureFrameCRC(new byte[]{14, 'O', 2, (byte)0x80, (byte)0x81, 8, 0x7f, 0x11, '{', '"', 'b', '"', ':', '1'}, 0, 14));
}
}
|
package gpml;
import giny.view.GraphView;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.pathvisio.debug.Logger;
import org.pathvisio.model.ConverterException;
import org.pathvisio.model.GpmlFormat;
import org.pathvisio.model.GroupStyle;
import org.pathvisio.model.ObjectType;
import org.pathvisio.model.Pathway;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.GraphLink.GraphIdContainer;
import org.pathvisio.model.PathwayElement.MAnchor;
import cytoscape.CyEdge;
import cytoscape.CyNode;
import cytoscape.Cytoscape;
import cytoscape.groups.CyGroup;
import cytoscape.groups.CyGroupManager;
import cytoscape.view.CyNetworkView;
public class GpmlConverter {
List<CyEdge> edges = new ArrayList<CyEdge>();
HashMap<GraphIdContainer, CyNode> nodeMap = new HashMap<GraphIdContainer, CyNode>();
HashMap<PathwayElement, String[]> edgeMap = new HashMap<PathwayElement, String[]>();
GpmlHandler gpmlHandler;
Pathway pathway;
private GpmlConverter(GpmlHandler h) {
gpmlHandler = h;
}
public GpmlConverter(GpmlHandler gpmlHandler, Pathway p) {
this(gpmlHandler);
pathway = p;
convert();
}
public GpmlConverter(GpmlHandler gpmlHandler, String gpml) throws ConverterException {
this(gpmlHandler);
pathway = new Pathway();
GpmlFormat.readFromXml(pathway, new StringReader(gpml), true);
convert();
}
private void convert() {
edgeMap.clear();
edges.clear();
nodeMap.clear();
findNodes();
findEdges();
}
public Pathway getPathway() {
return pathway;
}
private void findNodes() {
for(PathwayElement o : pathway.getDataObjects()) {
int type = o.getObjectType();
if(type == ObjectType.LEGEND || type == ObjectType.INFOBOX || type == ObjectType.MAPPINFO) {
continue;
}
String id = o.getGraphId();
//Get an id if it's not already there
if(id == null) {
id = pathway.getUniqueGraphId();
o.setGraphId(id);
}
CyNode n = null;
switch(type) {
case ObjectType.GROUP:
Logger.log.trace("Creating group: " + id);
n = addGroup(o);
if(n == null) {
Logger.log.error("Group node is null");
} else {
Logger.log.trace("Created group node: " + n.getIdentifier());
}
break;
case ObjectType.LINE:
if(isEdge(o)) {
continue; //Don't add an annotation node for an edge
}
default:
//Create a node for every pathway element
Logger.log.trace("Creating node: " + id + " for " + o.getGraphId() + "@" + o.getObjectType());
n = Cytoscape.getCyNode(id, true);
}
gpmlHandler.addNode(n, o);
nodeMap.put(o, n);
}
processGroups();
}
private boolean isEdge(PathwayElement e) {
GraphIdContainer start = pathway.getGraphIdContainer(e.getMStart().getGraphRef());
GraphIdContainer end = pathway.getGraphIdContainer(e.getMEnd().getGraphRef());
Logger.log.trace("Checking if edge " + e.getGraphId() + ": " +
isNode(start) + ", " + isNode(end)
);
return isNode(start) && isNode(end);
}
private boolean isNode(GraphIdContainer idc) {
if(idc instanceof MAnchor) {
//only valid if the parent line is an edge
return isEdge(((MAnchor)idc).getParent());
} else if(idc instanceof PathwayElement) {
int ot = ((PathwayElement)idc).getObjectType();
return
ot == ObjectType.DATANODE ||
ot == ObjectType.GROUP;
} else {
return false;
}
}
private void findEdges() {
Logger.log.trace("Start finding edges");
//First find edges that contain anchors
//Add an AnchorNode for that line
for(PathwayElement pe : pathway.getDataObjects()) {
if(pe.getObjectType() == ObjectType.LINE) {
if(pe.getMAnchors().size() > 0 && isEdge(pe)) {
CyNode n = Cytoscape.getCyNode(pe.getGraphId(), true);
gpmlHandler.addAnchorNode(n, pe);
for(MAnchor a : pe.getMAnchors()) {
nodeMap.put(a, n);
}
}
}
}
//Create the cytoscape edges for each line for which
//both the start and end points connect to a node
for(PathwayElement pe : pathway.getDataObjects()) {
if(pe.getObjectType() == ObjectType.LINE) {
if(isEdge(pe)) {
//A line without anchors, convert to single edge
if(pe.getMAnchors().size() == 0) {
String source = nodeMap.get(
pathway.getGraphIdContainer(pe.getMStart().getGraphRef())
).getIdentifier();
String target = nodeMap.get(
pathway.getGraphIdContainer(pe.getMEnd().getGraphRef())
).getIdentifier();
Logger.log.trace("Line without anchors ( " + pe.getGraphId() + " ) to edge: " +
source + ", " + target
);
String type = pe.getStartLineType() + ", " + pe.getEndLineType();
CyEdge e = Cytoscape.getCyEdge(
source,
pe.getGraphId(),
target,
type
);
edges.add(e);
gpmlHandler.addEdge(e, pe);
//A line with anchors, split into multiple edges
} else {
String sId = nodeMap.get(
pathway.getGraphIdContainer(pe.getMStart().getGraphRef())
).getIdentifier();
String eId = nodeMap.get(
pathway.getGraphIdContainer(pe.getMEnd().getGraphRef())
).getIdentifier();
Logger.log.trace("Line with anchors ( " + pe.getGraphId() + " ) to edges: " +
sId + ", " + eId
);
CyEdge es = Cytoscape.getCyEdge(
sId,
pe.getGraphId() + "_start",
gpmlHandler.getNode(pe.getGraphId()).getParentIdentifier(),
"start-anchor"
);
edges.add(es);
gpmlHandler.addEdge(es, pe);
CyEdge ee = Cytoscape.getCyEdge(
gpmlHandler.getNode(pe.getGraphId()).getParentIdentifier(),
pe.getGraphId() + "end",
eId,
"anchor-end"
);
edges.add(ee);
gpmlHandler.addEdge(ee, pe);
}
}
}
}
}
public int[] getNodeIndicesArray() {
int[] inodes = new int[nodeMap.size()];
int i = 0;
for(CyNode n : nodeMap.values()) {
inodes[i++] = n.getRootGraphIndex();
}
return inodes;
}
public int[] getEdgeIndicesArray() {
int[] iedges = new int[edges.size()];
for(int i = 0; i< edges.size(); i++) iedges[i] = edges.get(i).getRootGraphIndex();
return iedges;
}
//Add a group node
private CyNode addGroup(PathwayElement group) {
CyGroup cyGroup = CyGroupManager.findGroup(group.getGroupId());
if(cyGroup == null) {
cyGroup = CyGroupManager.createGroup(group.getGroupId(), null);
}
CyNode gn = cyGroup.getGroupNode();
gn.setIdentifier(group.getGraphId());
return gn;
}
//Add all nodes to the group
private void processGroups() {
for(PathwayElement pwElm : pathway.getDataObjects()) {
if(pwElm.getObjectType() == ObjectType.GROUP) {
GpmlNode gpmlNode = gpmlHandler.getNode(pwElm.getGraphId());
CyGroup cyGroup = CyGroupManager.getCyGroup(gpmlNode.getParent());
if(cyGroup == null) {
Logger.log.warn("Couldn't create group: CyGroupManager returned null");
return;
}
//The interaction name
GroupStyle groupStyle = pwElm.getGroupStyle();
String interaction = groupStyle.name();
if(groupStyle == GroupStyle.NONE) {
interaction = "group";
}
PathwayElement[] groupElements = pathway.getGroupElements(
pwElm.getGroupId()
).toArray(new PathwayElement[0]);
//Create the cytoscape parts of the group
for(int i = 0; i < groupElements.length; i++) {
PathwayElement pe_i = groupElements[i];
GpmlNetworkElement<?> ne_i = gpmlHandler.getNetworkElement(pe_i.getGraphId());
//Only add links to nodes, not to annotations
if(ne_i instanceof GpmlNode) {
cyGroup.addNode(((GpmlNode)ne_i).getParent());
edges.add(Cytoscape.getCyEdge(
cyGroup.getGroupNode().getIdentifier(),
"inGroup: " + cyGroup.getGroupName(),
ne_i.getParentIdentifier(), interaction)
);
// //Add links between all elements of the group
// for(int j = i + 1; j < groupElements.length; j++) {
// PathwayElement pe_j = groupElements[j];
// GpmlNetworkElement<?> ne_j = gpmlHandler.getNetworkElement(pe_j.getGraphId());
// if(ne_j instanceof GpmlNode) {
// edges.add(Cytoscape.getCyEdge(
// ne_i.getParentIdentifier(),
// "inGroup: " + cyGroup.getGroupName(),
// ne_j.getParentIdentifier(), interaction)
}
}
}
}
}
private void setGroupViewer(CyNetworkView view, String groupViewer) {
for(GpmlNode gn : gpmlHandler.getNodes()) {
if(gn.getPathwayElement().getObjectType() == ObjectType.GROUP) {
CyGroup group = CyGroupManager.getCyGroup(gn.getParent());
CyGroupManager.setGroupViewer(group, groupViewer, view, true);
}
}
}
public void layout(GraphView view) {
// String viewerName = "metaNode";
// Logger.log.trace(CyGroupManager.getGroupViewers() + "");
// if(CyGroupManager.getGroupViewer(viewerName) != null) {
// setGroupViewer((CyNetworkView)view, viewerName);
gpmlHandler.addAnnotations(view, nodeMap.values());
gpmlHandler.applyGpmlLayout(view, nodeMap.values());
gpmlHandler.applyGpmlVisualStyle();
view.fitContent();
}
}
|
package gov.nih.nci.cabig.caaers.domain;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import java.io.Serializable;
import java.sql.Date;
import java.util.List;
import java.util.LinkedList;
/**
* Domain object representing Study(Protocol)
*
* @author Sujith Vellat Thayyilthodi
* @author Rhett Sutphin
*/
@Entity
@Table(name = "studies")
@GenericGenerator(name = "id-generator", strategy = "native",
parameters = {
@Parameter(name = "sequence", value = "studies_id_seq")
}
)
public class Study extends AbstractDomainObject implements Serializable {
/**
* For Backward compatibility.
*/
private static final long serialVersionUID = -2650610294671313885L;
private Boolean multiInstitutionIndicator;
private String shortTitle;
private String longTitle;
private String description;
private String principalInvestigatorCode;
private String principalInvestigatorName;
private String primarySponsorCode;
private String primarySponsorName;
private String phaseCode;
private Date reviewDate;
private List<StudySite> studySites = new LinkedList<StudySite>();
////// LOGIC
public void addStudySite(StudySite studySite) {
getStudySites().add(studySite);
studySite.setStudy(this);
}
////// BEAN PROPERTIES
public String getShortTitle() {
return shortTitle;
}
public void setShortTitle(String shortTitle) {
this.shortTitle = shortTitle;
}
public String getPrincipalInvestigatorCode() {
return principalInvestigatorCode;
}
public void setPrincipalInvestigatorCode(String investigatorCode) {
this.principalInvestigatorCode = investigatorCode;
}
public String getPrincipalInvestigatorName() {
return principalInvestigatorName;
}
public void setPrincipalInvestigatorName(String investigatorName) {
this.principalInvestigatorName = investigatorName;
}
public String getPrimarySponsorCode() {
return primarySponsorCode;
}
public void setPrimarySponsorCode(String sponsorCode) {
this.primarySponsorCode = sponsorCode;
}
public String getPhaseCode() {
return phaseCode;
}
public void setPhaseCode(String phaseCode) {
this.phaseCode = phaseCode;
}
public String getPrimarySponsorName() {
return primarySponsorName;
}
public void setPrimarySponsorName(String sponsorName) {
this.primarySponsorName = sponsorName;
}
public Boolean isMultiInstitutionIndicator() {
return multiInstitutionIndicator;
}
public void setMultiInstitutionIndicator(Boolean multiInstitutionIndicator) {
this.multiInstitutionIndicator = multiInstitutionIndicator;
}
public Date getReviewDate() {
return reviewDate;
}
public void setReviewDate(Date reviewDate) {
this.reviewDate = reviewDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLongTitle() {
return longTitle;
}
public void setLongTitle(String longTitle) {
this.longTitle = longTitle;
}
@OneToMany(mappedBy = "study", cascade = CascadeType.ALL)
public List<StudySite> getStudySites() {
return studySites;
}
public void setStudySites(List<StudySite> studySites) {
this.studySites = studySites;
}
}
|
package de.aima13.whoami.modules;
import de.aima13.whoami.Analyzable;
import java.io.File;
import java.util.*;
/**
* Spielemodul sucht installierte Spiele, kommentiert diese und liefert Zocker-Score
*
* @author Niko Berkmann
*/
public class Games implements Analyzable {
/**
* Datenstruktur "Spiel"
*/
private static class GameEntry {
public String name;
public Date installed;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getInstalled() {
return installed;
}
public void setInstalled(Date installed) {
this.installed = installed;
}
}
private class GameList extends ArrayList<GameEntry> {
public boolean addUnique(GameEntry game) {
return this.add(game);
}
/**
* Sortiert Spieleliste nach Installationsdatum
*/
public void sortByLatestInstall() {
Collections.sort(this, new Comparator<GameEntry>() {
@Override
public int compare(GameEntry o1, GameEntry o2) {
return o2.getInstalled().compareTo(o1.getInstalled());
}
});
}
}
private LinkedList<File> exeFiles;
private String steamNickname = null;
private File steamAppsFolder = null;
@Override
public List<String> getFilter() {
List<String> filter = new LinkedList<String>();
filter.add("*.exe");
filter.add("SteamApps");
return filter;
}
/**
* Nimmt Suchergebnisse entgegen und legt Executables und SteamApps-Ordner gleich getrennt ab
*
* @param files Suchergebnisse
*/
@Override
public void setFileInputs(List<File> files) {
exeFiles = new LinkedList<>();
for (File currentFile : files) {
if (currentFile.isFile() && currentFile.getAbsolutePath().endsWith(".exe")) {
exeFiles.add(currentFile);
}
else if (currentFile.isDirectory() && currentFile.getName() == "SteamApps") {
steamAppsFolder = currentFile;
}
else {
throw new RuntimeException("Input passt nicht zu Filter: "
+ currentFile.getAbsolutePath());
}
}
}
@Override
public String getHtml() {
return null;
}
@Override
public SortedMap<String, String> getCsvContent() {
return null;
}
@Override
public void run() {
}
}
|
package nallar.nmsprepatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import java.util.regex.*;
// The prepatcher adds method declarations in superclasses,
// so javac can compile the patch classes if they need to use a method/field they
// add on an instance other than this
class PrePatcher {
private static final Logger log = Logger.getLogger("PatchLogger");
private static final Pattern privatePattern = Pattern.compile("^(\\s+?)private", Pattern.MULTILINE);
private static final Pattern extendsPattern = Pattern.compile("^public.*?\\s+?extends\\s+?([\\S^<]+?)(?:<(\\S+)>)?[\\s]+?(?:implements [^}]+?)?\\{", Pattern.MULTILINE);
private static final Pattern declareMethodPattern = Pattern.compile("@Declare\\s+?(public\\s+?(?:(?:synchronized|static) )*(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\([^\\{]*\\)\\s*?\\{)", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern declareFieldPattern = Pattern.compile("@Declare\\s+?(public [^;\r\n]+?)_?( = [^;\r\n]+?)?;", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern packageFieldPattern = Pattern.compile("\n ? ?([^ ]+ ? ?[^ ]+);");
private static final Pattern innerClassPattern = Pattern.compile("[^\n]public (?:static )?class ([^ \n]+)[ \n]", Pattern.MULTILINE);
private static final Pattern importPattern = Pattern.compile("\nimport ([^;]+?);", Pattern.MULTILINE | Pattern.DOTALL);
private static final Splitter spaceSplitter = Splitter.on(' ').omitEmptyStrings();
private static final Splitter commaSplitter = Splitter.on(',').omitEmptyStrings().trimResults();
private static final Map<String, PatchInfo> patchClasses = new HashMap<String, PatchInfo>();
public static void loadPatches(File patchDirectory) {
recursiveSearch(patchDirectory);
}
private static void recursiveSearch(File patchDirectory) {
for (File file : patchDirectory.listFiles()) {
if (!file.getName().equals("annotation") && file.isDirectory()) {
recursiveSearch(file);
continue;
}
if (!file.getName().endsWith(".java")) {
continue;
}
addPatches(file);
}
}
//private static final Pattern methodInfoPattern = Pattern.compile("(?:(public|private|protected) )?(static )?(?:([^ ]+?) )([^\\( ]+?) ?\\((.*?)\\) ?\\{", Pattern.DOTALL);
private static final Pattern methodInfoPattern = Pattern.compile("^(.+) ?\\(([^\\(]*)\\) ?\\{", Pattern.DOTALL);
// TODO - clean up this method. It works, but it's hardly pretty...
private static void addPatches(File file) {
String contents = readFile(file);
if (contents == null) {
log.log(Level.SEVERE, "Failed to read " + file);
return;
}
Matcher extendsMatcher = extendsPattern.matcher(contents);
if (!extendsMatcher.find()) {
if (contents.contains(" extends")) {
log.warning("Didn't match extends matcher for " + file);
}
return;
}
String shortClassName = extendsMatcher.group(1);
String className = null;
Matcher importMatcher = importPattern.matcher(contents);
List<String> imports = new ArrayList<String>();
while (importMatcher.find()) {
imports.add(importMatcher.group(1));
}
for (String import_ : imports) {
if (import_.endsWith('.' + shortClassName)) {
className = import_;
}
}
if (className == null) {
log.warning("Unable to find class " + shortClassName + " for " + file);
return;
}
PatchInfo patchInfo = patchClasses.get(className);
if (patchInfo == null) {
patchInfo = new PatchInfo();
patchClasses.put(className, patchInfo);
}
patchInfo.shortClassName = shortClassName;
Matcher matcher = declareMethodPattern.matcher(contents);
while (matcher.find()) {
Matcher methodInfoMatcher = methodInfoPattern.matcher(matcher.group(1));
if (!methodInfoMatcher.find()) {
log.warning("Failed to match method info matcher to method declaration " + matcher.group(1));
continue;
}
MethodInfo methodInfo = new MethodInfo();
patchInfo.methods.add(methodInfo);
String accessAndNameString = methodInfoMatcher.group(1).replace(", ", ","); // Workaround for multiple argument generics
String paramString = methodInfoMatcher.group(2);
for (String parameter : commaSplitter.split(paramString)) {
Iterator<String> iterator = spaceSplitter.split(parameter).iterator();
String parameterType = null;
while (parameterType == null) {
parameterType = iterator.next();
if (parameterType.equals("final")) {
parameterType = null;
}
}
methodInfo.parameterTypes.add(new Type(parameterType, imports));
}
LinkedList<String> accessAndNames = Lists.newLinkedList(spaceSplitter.split(accessAndNameString));
methodInfo.name = accessAndNames.removeLast();
String rawType = accessAndNames.removeLast();
while (!accessAndNames.isEmpty()) {
String thing = accessAndNames.removeLast();
if (thing.equals("static")) {
methodInfo.static_ = true;
} else if (thing.equals("synchronized")) {
methodInfo.synchronized_ = true;
} else if (thing.equals("final")) {
methodInfo.final_ = true;
} else {
if (methodInfo.access != null) {
log.warning("overwriting access from " + methodInfo.access + " -> " + thing + " in " + matcher.group(1));
}
methodInfo.access = thing;
}
}
String ret = "null";
if ("static".equals(rawType)) {
rawType = matcher.group(3);
}
methodInfo.returnType = new Type(rawType, imports);
if ("boolean".equals(rawType)) {
ret = "false";
} else if ("void".equals(rawType)) {
ret = "";
} else if ("long".equals(rawType)) {
ret = "0L";
} else if ("int".equals(rawType)) {
ret = "0";
} else if ("float".equals(rawType)) {
ret = "0f";
} else if ("double".equals(rawType)) {
ret = "0.0";
}
methodInfo.javaCode = matcher.group(1) + "return " + ret + ";}";
}
Matcher fieldMatcher = declareFieldPattern.matcher(contents);
while (fieldMatcher.find()) {
String var = fieldMatcher.group(1);
FieldInfo fieldInfo = new FieldInfo();
patchInfo.fields.add(fieldInfo);
LinkedList<String> typeAndName = Lists.newLinkedList(spaceSplitter.split(var));
fieldInfo.name = typeAndName.removeLast();
fieldInfo.type = new Type(typeAndName.removeLast(), imports);
while (!typeAndName.isEmpty()) {
String thing = typeAndName.removeLast();
if (thing.equals("static")) {
fieldInfo.static_ = true;
} else if (thing.equals("volatile")) {
fieldInfo.volatile_ = true;
} else if (thing.equals("final")) {
fieldInfo.final_ = true;
} else {
if (fieldInfo.access != null) {
log.severe("overwriting access from " + fieldInfo.access + " -> " + thing + " in " + var);
}
fieldInfo.access = thing;
}
}
fieldInfo.javaCode = var + ';';
}
if (contents.contains("\n@Public")) {
patchInfo.makePublic = true;
}
}
private static int accessStringToInt(String access) {
int a = 0;
if (access.isEmpty()) {
// package-local
} else if (access.equals("public")) {
a |= Opcodes.ACC_PUBLIC;
} else if (access.equals("protected")) {
a |= Opcodes.ACC_PROTECTED;
} else if (access.equals("private")) {
a |= Opcodes.ACC_PRIVATE;
} else {
log.severe("Unknown access string " + access);
}
return a;
}
private static class Type {
public final String clazz;
public final Type generic;
public Type(String raw, List<String> imports) {
String clazz;
if (raw.contains("<")) {
String genericRaw = raw.substring(raw.indexOf("<") + 1, raw.length() - 1);
clazz = raw.substring(0, raw.indexOf("<"));
generic = new Type(genericRaw, imports);
} else {
clazz = raw;
generic = null;
}
this.clazz = fullyQualifiedName(clazz, imports);
}
private static String[] searchPackages = {
"java.lang",
"java.util",
"java.io",
};
private static String fullyQualifiedName(String original, Collection<String> imports) {
if (imports == null || original.contains(".")) {
return original;
}
for (String className : imports) {
String shortClassName = className;
shortClassName = shortClassName.substring(shortClassName.lastIndexOf('.') + 1);
if (shortClassName.equals(original)) {
return className;
}
}
for (String package_ : searchPackages) {
String packagedName = package_ + "." + original;
try {
Class.forName(packagedName, false, PrePatcher.class.getClassLoader());
return packagedName;
} catch (ClassNotFoundException ignored) {
}
}
if (primitiveTypeToDescriptor(original) == null) {
log.severe("Failed to find fully qualified name for '" + original + "'.");
}
return original;
}
private static String primitiveTypeToDescriptor(String primitive) {
switch (primitive) {
case "byte":
return "B";
case "char":
return "C";
case "double":
return "D";
case "float":
return "F";
case "int":
return "I";
case "long":
return "J";
case "short":
return "S";
case "void":
return "V";
case "boolean":
return "Z";
}
return null;
}
public String toString() {
return clazz + (generic == null ? "" : '<' + generic.toString() + '>');
}
private String genericSignatureIfNeeded(boolean useGenerics) {
if (generic == null || !useGenerics) {
return "";
}
return '<' + generic.signature() + '>';
}
private String javaString(boolean useGenerics) {
if (clazz.contains("<") || clazz.contains(">")) {
log.severe("Invalid Type " + this + ", contains broken generics info.");
} else if (clazz.contains("[") || clazz.contains("]")) {
log.severe("Invalid Type " + this + ", contains broken array info.");
} else if (clazz.contains(".")) {
return "L" + clazz.replace(".", "/") + genericSignatureIfNeeded(useGenerics) + ";";
}
String primitiveType = primitiveTypeToDescriptor(clazz);
if (primitiveType != null) {
return primitiveType;
}
log.severe("Unrecognised Type: " + this.toString());
return "Ljava/lang/Object;";
}
public String descriptor() {
return javaString(false);
}
public String signature() {
return javaString(true);
}
}
private static class MethodInfo {
public String name;
public List<Type> parameterTypes = new ArrayList<Type>();
public Type returnType;
public String access;
public boolean static_;
public boolean synchronized_;
public boolean final_;
public String javaCode;
private static final Joiner parameterJoiner = Joiner.on(", ");
public String toString() {
return "method: " + access + ' ' + (static_ ? "static " : "") + (final_ ? "final " : "") + (synchronized_ ? "synchronized " : "") + returnType + ' ' + name + " (" + parameterJoiner.join(parameterTypes) + ')';
}
public int accessAsInt() {
int accessInt = 0;
if (static_) {
accessInt |= Opcodes.ACC_STATIC;
}
if (synchronized_) {
accessInt |= Opcodes.ACC_VOLATILE;
}
if (final_) {
accessInt |= Opcodes.ACC_FINAL;
}
accessInt |= accessStringToInt(access);
return accessInt;
}
public String descriptor() {
StringBuilder sb = new StringBuilder();
sb
.append('(');
for (Type type : parameterTypes) {
sb.append(type.descriptor());
}
sb
.append(')')
.append(returnType.descriptor());
return sb.toString();
}
public String signature() {
StringBuilder sb = new StringBuilder();
sb
.append('(');
for (Type type : parameterTypes) {
sb.append(type.signature());
}
sb
.append(')')
.append(returnType.signature());
return sb.toString();
}
}
private static class FieldInfo {
public String name;
public Type type;
public String access;
public boolean static_;
public boolean volatile_;
public boolean final_;
public String javaCode;
public String toString() {
return "field: " + access + ' ' + (static_ ? "static " : "") + (volatile_ ? "volatile " : "") + type + ' ' + name;
}
public int accessAsInt() {
int accessInt = 0;
if (static_) {
accessInt |= Opcodes.ACC_STATIC;
}
if (volatile_) {
accessInt |= Opcodes.ACC_VOLATILE;
}
if (final_) {
accessInt |= Opcodes.ACC_FINAL;
}
accessInt |= accessStringToInt(access);
return accessInt;
}
}
private static class PatchInfo {
List<MethodInfo> methods = new ArrayList<MethodInfo>();
List<FieldInfo> fields = new ArrayList<FieldInfo>();
boolean makePublic = false;
String shortClassName;
}
private static PatchInfo patchForClass(String className) {
return patchClasses.get(className.replace("/", ".").replace(".java", "").replace(".class", ""));
}
public static String patchSource(String inputSource, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputSource;
}
inputSource = inputSource.trim().replace("\t", " ");
String shortClassName = patchInfo.shortClassName;
StringBuilder sourceBuilder = new StringBuilder(inputSource.substring(0, inputSource.lastIndexOf('}')))
.append("\n// TT Patch Declarations\n");
for (MethodInfo methodInfo : patchInfo.methods) {
if (sourceBuilder.indexOf(methodInfo.javaCode) == -1) {
sourceBuilder.append(methodInfo.javaCode).append('\n');
}
}
for (FieldInfo FieldInfo : patchInfo.fields) {
if (sourceBuilder.indexOf(FieldInfo.javaCode) == -1) {
sourceBuilder.append(FieldInfo.javaCode).append('\n');
}
}
sourceBuilder.append("\n}");
inputSource = sourceBuilder.toString();
/*Matcher genericMatcher = genericMethodPattern.matcher(contents);
while (genericMatcher.find()) {
String original = genericMatcher.group(1);
String withoutGenerics = original.replace(' ' + generic + ' ', " Object ");
int index = inputSource.indexOf(withoutGenerics);
if (index == -1) {
continue;
}
int endIndex = inputSource.indexOf("\n }", index);
String body = inputSource.substring(index, endIndex);
inputSource = inputSource.replace(body, body.replace(withoutGenerics, original).replace("return ", "return (" + generic + ") "));
}*/
inputSource = inputSource.replace("\nfinal ", " ");
inputSource = inputSource.replace(" final ", " ");
inputSource = inputSource.replace("\nclass", "\npublic class");
inputSource = inputSource.replace("\n " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("\n protected " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("private class", "public class");
inputSource = inputSource.replace("protected class", "public class");
inputSource = privatePattern.matcher(inputSource).replaceAll("$1protected");
if (patchInfo.makePublic) {
inputSource = inputSource.replace("protected ", "public ");
}
Matcher packageMatcher = packageFieldPattern.matcher(inputSource);
StringBuffer sb = new StringBuffer();
while (packageMatcher.find()) {
packageMatcher.appendReplacement(sb, "\n public " + packageMatcher.group(1) + ';');
}
packageMatcher.appendTail(sb);
inputSource = sb.toString();
Matcher innerClassMatcher = innerClassPattern.matcher(inputSource);
while (innerClassMatcher.find()) {
String name = innerClassMatcher.group(1);
inputSource = inputSource.replace(" " + name + '(', " public " + name + '(');
}
return inputSource.replace(" ", "\t");
}
private static boolean hasFlag(int access, int flag) {
return (access & flag) != 0;
}
private static int replaceFlag(int in, int from, int to) {
if ((in & from) != 0) {
in &= ~from;
in |= to;
}
return in;
}
private static int makeAccess(int access, boolean makePublic) {
access = makeAtLeastProtected(access);
if (makePublic) {
access = replaceFlag(access, Opcodes.ACC_PROTECTED, Opcodes.ACC_PUBLIC);
}
return access;
}
/**
* Changes access flags to be protected, unless already public.
*
* @return
*/
private static int makeAtLeastProtected(int access) {
if (hasFlag(access, Opcodes.ACC_PUBLIC) || hasFlag(access, Opcodes.ACC_PROTECTED)) {
// already protected or public
return access;
}
if (hasFlag(access, Opcodes.ACC_PRIVATE)) {
// private -> protected
return replaceFlag(access, Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED);
}
// not public, protected or private so must be package-local
// change to public - protected doesn't include package-local.
return access | Opcodes.ACC_PUBLIC;
}
public static byte[] patchCode(byte[] inputCode, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputCode;
}
ClassReader classReader = new ClassReader(inputCode);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
classNode.access = classNode.access & ~Opcodes.ACC_FINAL;
classNode.access = makeAccess(classNode.access, true);
for (FieldNode fieldNode : (Iterable<FieldNode>) classNode.fields) {
fieldNode.access = fieldNode.access & ~Opcodes.ACC_FINAL;
fieldNode.access = makeAccess(fieldNode.access, patchInfo.makePublic);
}
for (MethodNode methodNode : (Iterable<MethodNode>) classNode.methods) {
methodNode.access = methodNode.access & ~Opcodes.ACC_FINAL;
methodNode.access = makeAccess(methodNode.access, patchInfo.makePublic);
}
for (FieldInfo fieldInfo : patchInfo.fields) {
classNode.fields.add(new FieldNode(makeAccess(fieldInfo.accessAsInt(), patchInfo.makePublic), fieldInfo.name, fieldInfo.type.descriptor(), fieldInfo.type.signature(), null));
}
for (MethodInfo methodInfo : patchInfo.methods) {
classNode.methods.add(new MethodNode(makeAccess(methodInfo.accessAsInt() & ~Opcodes.ACC_FINAL, patchInfo.makePublic), methodInfo.name, methodInfo.descriptor(), methodInfo.signature(), null));
}
ClassWriter classWriter = new ClassWriter(classReader, 0);
classNode.accept(classWriter);
return classWriter.toByteArray();
}
private static String readFile(File file) {
Scanner fileReader = null;
try {
fileReader = new Scanner(file, "UTF-8").useDelimiter("\\A");
return fileReader.next().replace("\r\n", "\n");
} catch (FileNotFoundException ignored) {
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return null;
}
}
|
package jodd.util.collection;
import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A Map that accepts int or Integer keys only. The implementation is based on
* <code>java.util.HashMap</code>. IntHashMap is about 25% faster.
*
* @see java.util.HashMap
*/
public class IntHashMap extends AbstractMap implements Cloneable, Serializable {
/**
* The hash table data.
*/
private transient Entry table[];
/**
* The total number of mappings in the hash table.
*/
private transient int count;
/**
* The table is rehashed when its size exceeds this threshold. (The value of
* this field is (int)(capacity * loadFactor).)
*/
private int threshold;
/**
* The load factor for the hashtable.
*/
private float loadFactor;
/**
* The number of times this IntHashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the IntHashMap or otherwise modify its internal structure (e.g., rehash).
* This field is used to make iterators on Collection-views of the IntHashMap
* fail-fast.
*/
private transient int modCount;
public IntHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Initial Capacity: "+ initialCapacity);
}
if (loadFactor <= 0) {
throw new IllegalArgumentException("Illegal Load factor: "+ loadFactor);
}
if (initialCapacity == 0) {
initialCapacity = 1;
}
this.loadFactor = loadFactor;
table = new Entry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);
}
public IntHashMap(int initialCapacity) {
this(initialCapacity, 0.75f);
}
/**
* Constructs a new, empty map with a default capacity and load
* factor, which is 0.75.
*/
public IntHashMap() {
this(101, 0.75f);
}
/**
* Constructs a new map with the same mappings as the given map. The
* map is created with a capacity of twice the number of mappings in
* the given map or 11 (whichever is greater), and a default load factor,
* which is 0.75.
*/
public IntHashMap(Map t) {
this(Math.max(2 * t.size(), 11), 0.75f);
putAll(t);
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map.
*/
@Override
public int size() {
return count;
}
/**
* Returns <code>true</code> if this map contains no key-value mappings.
*
* @return <code>true</code> if this map contains no key-value mappings.
*/
@Override
public boolean isEmpty() {
return count == 0;
}
/**
* Returns <code>true</code> if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested.
*
* @return <code>true</code> if this map maps one or more keys to the
* specified value.
*/
@Override
public boolean containsValue(Object value) {
Entry tab[] = table;
if (value == null) {
for (int i = tab.length; i
for (Entry e = tab[i] ; e != null ; e = e.next) {
if (e.value == null) {
return true;
}
}
}
} else {
for (int i = tab.length; i
for (Entry e = tab[i]; e != null; e = e.next) {
if (value.equals(e.value)) {
return true;
}
}
}
}
return false;
}
/**
* Returns <code>true</code> if this map contains a mapping for the specified
* key.
*
* @param key key whose presence in this Map is to be tested.
*
* @return <code>true</code> if this map contains a mapping for the specified
* key.
*/
@Override
public boolean containsKey(Object key) {
if (key instanceof Number) {
return containsKey( ((Number)key).intValue() );
} else {
return false;
}
}
/**
* Returns <code>true</code> if this map contains a mapping for the specified
* key.
*
* @param key key whose presence in this Map is to be tested.
*
* @return <code>true</code> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(int key) {
Entry tab[] = table;
int index = (key & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next) {
if (e.key == key) {
return true;
}
}
return false;
}
/**
* Returns the value to which this map maps the specified key. Returns
* <code>null</code> if the map contains no mapping for this key. A return
* value of <code>null</code> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <code>null</code>. The <code>containsKey</code>
* operation may be used to distinguish these two cases.
*
* @param key key whose associated value is to be returned.
*
* @return the value to which this map maps the specified key.
*/
@Override
public Object get(Object key) {
if (key instanceof Number) {
return get( ((Number)key).intValue() );
} else {
return null;
}
}
/**
* Returns the value to which this map maps the specified key. Returns
* <code>null</code> if the map contains no mapping for this key. A return
* value of <code>null</code> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <code>null</code>. The <code>containsKey</code>
* operation may be used to distinguish these two cases.
*
* @param key key whose associated value is to be returned.
*
* @return the value to which this map maps the specified key.
*/
public Object get(int key) {
Entry tab[] = table;
int index = (key & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next) {
if (e.key == key) {
return e.value;
}
}
return null;
}
/**
* Rehashes the contents of this map into a new <code>IntHashMap</code>
* instance with a larger capacity. This method is called automatically when
* the number of keys in this map exceeds its capacity and load factor.
*/
private void rehash() {
int oldCapacity = table.length;
Entry oldMap[] = table;
int newCapacity = (oldCapacity << 1) + 1;
Entry newMap[] = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity ; i
for (Entry old = oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.key & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
/**
* Associates the specified value with the specified key in this map. If the
* map previously contained a mapping for this key, the old value is
* replaced.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
*
* @return previous value associated with specified key, or <code>null</code> if
* there was no mapping for key. A <code>null</code> return can also indicate
* that the IntHashMap previously associated <code>null</code> with the
* specified key.
*/
@Override
public Object put(Object key, Object value) {
if (key instanceof Number) {
return put( ((Number)key).intValue(), value );
} else {
throw new UnsupportedOperationException
("IntHashMap key must be a number");
}
}
/**
* Associates the specified value with the specified key in this map. If the
* map previously contained a mapping for this key, the old value is
* replaced.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
*
* @return previous value associated with specified key, or <code>null</code> if
* there was no mapping for key. A <code>null</code> return can also indicate
* that the IntHashMap previously associated <code>null</code> with the
* specified key.
*/
public Object put(int key, Object value) {
// makes sure the key is not already in the IntHashMap.
Entry tab[] = table;
int index = (key & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index] ; e != null ; e = e.next) {
if (e.key == key) {
Object old = e.value;
e.value = value;
return old;
}
}
modCount++;
if (count >= threshold) {
// rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (key & 0x7FFFFFFF) % tab.length;
}
// creates the new entry.
tab[index] = new Entry(key, value, tab[index]);
count++;
return null;
}
/**
* Removes the mapping for this key from this map if present.
*
* @param key key whose mapping is to be removed from the map.
*
* @return previous value associated with specified key, or <code>null</code> if
* there was no mapping for key. A <code>null</code> return can also indicate
* that the map previously associated <code>null</code> with the specified
* key.
*/
@Override
public Object remove(Object key) {
if (key instanceof Number) {
return remove( ((Number)key).intValue() );
} else {
return null;
}
}
/**
* Removes the mapping for this key from this map if present.
*
* @param key key whose mapping is to be removed from the map.
*
* @return previous value associated with specified key, or <code>null</code> if
* there was no mapping for key. A <code>null</code> return can also indicate
* that the map previously associated <code>null</code> with the specified
* key.
*/
public Object remove(int key) {
Entry tab[] = table;
int index = (key & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e.key == key) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count
Object oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
/**
* Copies all of the mappings from the specified map to this one.
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified Map.
*
* @param t Mappings to be stored in this map.
*/
@Override
public void putAll(Map t) {
for (Object o : t.entrySet()) {
Map.Entry e = (Map.Entry) o;
put(e.getKey(), e.getValue());
}
}
/**
* Removes all mappings from this map.
*/
@Override
public void clear() {
Entry tab[] = table;
modCount++;
for (int index = tab.length; --index >= 0; ) {
tab[index] = null;
}
count = 0;
}
/**
* Returns a shallow copy of this <code>IntHashMap</code> instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map.
*/
@Override
public Object clone() {
try {
IntHashMap t = (IntHashMap)super.clone();
t.table = new Entry[table.length];
for (int i = table.length ; i
t.table[i] = (table[i] != null)
? (Entry)table[i].clone() : null;
}
t.keySet = null;
t.entrySet = null;
t.values = null;
t.modCount = 0;
return t;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
// views
private transient Set keySet;
private transient Set entrySet;
private transient Collection values;
/**
* Returns a set view of the keys contained in this map. The set is backed by
* the map, so changes to the map are reflected in the set, and vice-versa.
* The set supports element removal, which removes the corresponding mapping
* from this map, via the <code>Iterator.remove</code>,
* <code>Set.remove</code>, <code>removeAll</code>, <code>retainAll</code>,
* and <code>clear</code> operations. It does not support the
* <code>add</code> or <code>addAll</code> operations.
*
* @return a set view of the keys contained in this map.
*/
@Override
public Set keySet() {
if (keySet == null) {
keySet = new AbstractSet() {
@Override
public Iterator iterator() {
return new IntHashIterator(KEYS);
}
@Override
public int size() {
return count;
}
@Override
public boolean contains(Object o) {
return containsKey(o);
}
@Override
public boolean remove(Object o) {
return IntHashMap.this.remove(o) != null;
}
@Override
public void clear() {
IntHashMap.this.clear();
}
};
}
return keySet;
}
/**
* Returns a collection view of the values contained in this map. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element removal,
* which removes the corresponding mapping from this map, via the
* <code>Iterator.remove</code>, <code>Collection.remove</code>,
* <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code>
* operations. It does not support the <code>add</code> or
* <code>addAll</code> operations.
*
* @return a collection view of the values contained in this map.
*/
@Override
public Collection values() {
if (values==null) {
values = new AbstractCollection() {
@Override
public Iterator iterator() {
return new IntHashIterator(VALUES);
}
@Override
public int size() {
return count;
}
@Override
public boolean contains(Object o) {
return containsValue(o);
}
@Override
public void clear() {
IntHashMap.this.clear();
}
};
}
return values;
}
/**
* Returns a collection view of the mappings contained in this map. Each
* element in the returned collection is a <code>Map.Entry</code>. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element removal,
* which removes the corresponding mapping from the map, via the
* <code>Iterator.remove</code>, <code>Collection.remove</code>,
* <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code>
* operations. It does not support the <code>add</code> or
* <code>addAll</code> operations.
*
* @return a collection view of the mappings contained in this map.
* @see java.util.Map.Entry
*/
@Override
public Set entrySet() {
if (entrySet==null) {
entrySet = new AbstractSet() {
@Override
public Iterator iterator() {
return new IntHashIterator(ENTRIES);
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
int hash = (key==null ? 0 : key.hashCode());
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next) {
if (e.key == hash && e.equals(entry)) {
return true;
}
}
return false;
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
int hash = (key==null ? 0 : key.hashCode());
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e.key == hash && e.equals(entry)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count
e.value = null;
return true;
}
}
return false;
}
@Override
public int size() {
return count;
}
@Override
public void clear() {
IntHashMap.this.clear();
}
};
}
return entrySet;
}
/**
* IntHashMap collision list entry.
*/
private static class Entry implements Map.Entry, Cloneable {
int key;
Object value;
Entry next;
private Integer objectKey;
Entry(int key, Object value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
@Override
protected Object clone() {
return new Entry(key, value,
(next==null ? null : (Entry)next.clone()));
}
// Map.Entry Ops
public Object getKey() {
return(objectKey != null) ? objectKey :
(objectKey = new Integer(key));
}
public Object getValue() {
return value;
}
public Object setValue(Object value) {
Object oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry e = (Map.Entry)o;
return(getKey().equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
@Override
public int hashCode() {
return key ^ (value==null ? 0 : value.hashCode());
}
@Override
public String toString() {
return Integer.toString(key) + '=' + value;
}
}
// types of Iterators
private static final int KEYS = 0;
private static final int VALUES = 1;
private static final int ENTRIES = 2;
private class IntHashIterator implements Iterator {
Entry[] _table = IntHashMap.this.table;
int index = _table.length;
Entry entry;
Entry lastReturned;
int type;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
private int expectedModCount = modCount;
IntHashIterator(int type) {
this.type = type;
}
public boolean hasNext() {
while (entry == null && index > 0) {
entry = _table[--index];
}
return entry != null;
}
public Object next() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
while (entry == null && index > 0) {
entry = _table[--index];
}
if (entry != null) {
Entry e = lastReturned = entry;
entry = e.next;
return type == KEYS ? e.getKey() :
(type == VALUES ? e.value : e);
}
throw new NoSuchElementException();
}
public void remove() {
if (lastReturned == null) {
throw new IllegalStateException();
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
Entry[] tab = IntHashMap.this.table;
int ndx = (lastReturned.key & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[ndx], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null) {
tab[ndx] = e.next;
} else {
prev.next = e.next;
}
count
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
/**
* Save the state of the <code>IntHashMap</code> instance to a stream (i.e.,
* serialize it).
* <p>
* Context The <i>capacity</i> of the IntHashMap (the length of the bucket
* array) is emitted (int), followed by the <i>size</i> of the IntHashMap
* (the number of key-value mappings), followed by the key (Object) and value
* (Object) for each key-value mapping represented by the IntHashMap The
* key-value mappings are emitted in no particular order.
*
* @exception IOException
*/
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
// write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// write out number of buckets
s.writeInt(table.length);
// write out size (number of Mappings)
s.writeInt(count);
// write out keys and values (alternating)
for (int index = table.length-1; index >= 0; index
Entry entry = table[index];
while (entry != null) {
s.writeInt(entry.key);
s.writeObject(entry.value);
entry = entry.next;
}
}
}
/**
* Reconstitutes the <code>IntHashMap</code> instance from a stream (i.e.,
* deserialize it).
*
* @exception IOException
* @exception ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
// read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();
// read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();
table = new Entry[numBuckets];
// read in size (number of Mappings)
int size = s.readInt();
// read the keys and values, and put the mappings in the IntHashMap
for (int i=0; i<size; i++) {
int key = s.readInt();
Object value = s.readObject();
put(key, value);
}
}
int capacity() {
return table.length;
}
float loadFactor() {
return loadFactor;
}
}
|
package replicant;
import arez.Arez;
import arez.ArezContext;
import arez.Disposable;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.Assert;
import org.testng.annotations.Test;
import replicant.spy.AreaOfInterestStatusUpdatedEvent;
import replicant.spy.ConnectFailureEvent;
import replicant.spy.ConnectedEvent;
import replicant.spy.DataLoadStatus;
import replicant.spy.DisconnectFailureEvent;
import replicant.spy.DisconnectedEvent;
import replicant.spy.MessageProcessFailureEvent;
import replicant.spy.MessageProcessedEvent;
import replicant.spy.MessageReadFailureEvent;
import replicant.spy.RestartEvent;
import replicant.spy.SubscribeCompletedEvent;
import replicant.spy.SubscribeFailedEvent;
import replicant.spy.SubscribeRequestQueuedEvent;
import replicant.spy.SubscribeStartedEvent;
import replicant.spy.SubscriptionUpdateCompletedEvent;
import replicant.spy.SubscriptionUpdateFailedEvent;
import replicant.spy.SubscriptionUpdateRequestQueuedEvent;
import replicant.spy.SubscriptionUpdateStartedEvent;
import replicant.spy.UnsubscribeCompletedEvent;
import replicant.spy.UnsubscribeFailedEvent;
import replicant.spy.UnsubscribeRequestQueuedEvent;
import replicant.spy.UnsubscribeStartedEvent;
import static org.testng.Assert.*;
public class ConnectorTest
extends AbstractReplicantTest
{
@Test
public void construct()
throws Exception
{
final Disposable schedulerLock = Arez.context().pauseScheduler();
final ReplicantRuntime runtime = Replicant.context().getRuntime();
Arez.context().safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantRuntime(), runtime );
Arez.context()
.safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
schedulerLock.dispose();
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void dispose()
{
final ReplicantRuntime runtime = Replicant.context().getRuntime();
Arez.context().safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
Disposable.dispose( connector );
Arez.context().safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
}
@Test
public void connect()
{
Arez.context().pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
Arez.context().safeAction( connector::connect );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void connect_causesError()
{
Arez.context().pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
connector.setErrorOnConnect( true );
assertThrows( () -> Arez.context().safeAction( connector::connect ) );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.ERROR ) );
}
@Test
public void disconnect()
{
Arez.context().pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
Arez.context().safeAction( connector::disconnect );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnect_causesError()
{
Arez.context().pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.setErrorOnDisconnect( true );
assertThrows( () -> Arez.context().safeAction( connector::disconnect ) );
Arez.context().safeAction( () -> Assert.assertEquals( connector.getState(), ConnectorState.ERROR ) );
}
@Test
public void onDisconnected()
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( connector::onDisconnected );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.DISCONNECTED ) );
}
@Test
public void onDisconnected_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( connector::onDisconnected );
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectedEvent.class,
e -> assertEquals( e.getSystemType(), connector.getSystemType() ) );
}
@Test
public void onDisconnectFailure()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onDisconnectFailure( error ) );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onDisconnectFailure_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onDisconnectFailure( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectFailureEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onConnected()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( connector::onConnected );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTED ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTED ) );
}
@Test
public void onConnected_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( connector::onConnected );
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectedEvent.class,
e -> assertEquals( e.getSystemType(), connector.getSystemType() ) );
}
@Test
public void onConnectFailure()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onConnectFailure( error ) );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
Arez.context().safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onConnectFailure_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onConnectFailure( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectFailureEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageProcessed_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final DataLoadStatus status =
new DataLoadStatus( ValueUtil.randomInt(),
ValueUtil.randomString(),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 100 ),
ValueUtil.getRandom().nextInt( 100 ),
ValueUtil.getRandom().nextInt( 10 ) );
Arez.context().safeAction( () -> connector.onMessageProcessed( status ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getDataLoadStatus(), status );
} );
}
@Test
public void onMessageProcessFailure()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onMessageProcessFailure( error ) );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageProcessFailure_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
Arez.context().safeAction( () -> connector.onMessageProcessFailure( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void disconnectIfPossible()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
Arez.context().safeAction( () -> connector.disconnectIfPossible( error ) );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnectIfPossible_noActionAsConnecting()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 0 );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void disconnectIfPossible_generatesSpyEvent()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
Arez.context().safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( RestartEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReadFailure()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
Arez.context().pauseScheduler();
Arez.context().safeAction( () -> connector.onMessageReadFailure( error ) );
Arez.context().safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageReadFailure_generatesSpyMessage()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
Arez.context().safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
Arez.context().safeAction( () -> connector.onMessageReadFailure( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageReadFailureEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscribeStarted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscribeStarted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADING ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeCompleted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription =
Arez.context().safeAction( () -> Replicant.context().createSubscription( address, null, true ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscribeCompleted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeFailed()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscribeFailed( address, error ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOAD_FAILED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onUnsubscribeStarted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription =
Arez.context().safeAction( () -> Replicant.context().createSubscription( address, null, true ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onUnsubscribeStarted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADING ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeCompleted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onUnsubscribeCompleted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeFailed()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onUnsubscribeFailed( address, error ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscriptionUpdateStarted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription =
Arez.context().safeAction( () -> Replicant.context().createSubscription( address, null, true ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscriptionUpdateStarted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATING ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateCompleted()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription =
Arez.context().safeAction( () -> Replicant.context().createSubscription( address, null, true ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscriptionUpdateCompleted( address ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateFailed()
throws Exception
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
Arez.context().safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final Subscription subscription =
Arez.context().safeAction( () -> Replicant.context().createSubscription( address, null, true ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
Arez.context().safeAction( () -> connector.onSubscriptionUpdateFailed( address, error ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATE_FAILED ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
Arez.context().safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void areaOfInterestRequestPendingQueries()
{
final TestConnector connector = TestConnector.create( G.class );
final ChannelAddress address = new ChannelAddress( G.G1 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, null ),
-1 );
final Connection connection = new Connection( connector, ValueUtil.randomString() );
connector.setConnection( connection );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, null ),
-1 );
connection.requestSubscribe( address, null );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), true );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, null ),
1 );
}
@Test
public void connection()
{
final TestConnector connector = TestConnector.create( G.class );
assertEquals( connector.getConnection(), null );
final Connection connection = new Connection( connector, ValueUtil.randomString() );
connector.setConnection( connection );
final Subscription subscription1 =
Arez.context()
.safeAction( () -> Replicant.context().createSubscription( new ChannelAddress( G.G1 ), null, true ) );
assertEquals( connector.getConnection(), connection );
assertEquals( connector.ensureConnection(), connection );
assertEquals( Disposable.isDisposed( subscription1 ), false );
connector.setConnection( null );
assertEquals( connector.getConnection(), null );
assertEquals( Disposable.isDisposed( subscription1 ), true );
}
@Test
public void ensureConnection_WhenNoConnection()
{
final TestConnector connector = TestConnector.create( G.class );
final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::ensureConnection );
assertEquals( exception.getMessage(),
"Replicant-0031: Connector.ensureConnection() when no connection is present." );
}
@Test
public void purgeSubscriptions()
{
final TestConnector connector1 = TestConnector.create( G.class );
TestConnector.create( F.class );
final ArezContext context = Arez.context();
final ReplicantContext rContext = Replicant.context();
final Subscription subscription1 =
context.safeAction( () -> rContext.createSubscription( new ChannelAddress( G.G1 ), null, true ) );
final Subscription subscription2 =
context.safeAction( () -> rContext.createSubscription( new ChannelAddress( G.G2, 2 ), null, true ) );
// The next two are from a different Connector
final Subscription subscription3 =
context.safeAction( () -> rContext.createSubscription( new ChannelAddress( F.F2, 1 ), null, true ) );
final Subscription subscription4 =
context.safeAction( () -> rContext.createSubscription( new ChannelAddress( F.F2, 2 ), null, true ) );
assertEquals( Disposable.isDisposed( subscription1 ), false );
assertEquals( Disposable.isDisposed( subscription2 ), false );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
connector1.purgeSubscriptions();
assertEquals( Disposable.isDisposed( subscription1 ), true );
assertEquals( Disposable.isDisposed( subscription2 ), true );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
}
@Test
public void triggerScheduler()
{
final TestConnector connector = TestConnector.create( G.class );
assertEquals( connector.isSchedulerActive(), false );
assertEquals( connector.getActivateSchedulerCount(), 0 );
connector.triggerScheduler();
assertEquals( connector.isSchedulerActive(), true );
assertEquals( connector.getActivateSchedulerCount(), 1 );
connector.triggerScheduler();
assertEquals( connector.isSchedulerActive(), true );
assertEquals( connector.getActivateSchedulerCount(), 1 );
}
@Test
public void scheduleTick()
{
final TestConnector connector = TestConnector.create( G.class );
connector.triggerScheduler();
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 0 );
assertEquals( connector.getProgressResponseProcessingCount(), 0 );
assertNull( connector.getSchedulerLock() );
connector.setProgressAreaOfInterestRequestProcessing( () -> true );
connector.setProgressResponseProcessing( () -> true );
final boolean result1 = connector.scheduleTick();
assertEquals( result1, true );
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 1 );
assertEquals( connector.getProgressResponseProcessingCount(), 1 );
final Disposable schedulerLock1 = connector.getSchedulerLock();
assertNotNull( schedulerLock1 );
final boolean result2 = connector.scheduleTick();
assertEquals( result2, true );
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 2 );
assertEquals( connector.getProgressResponseProcessingCount(), 2 );
assertNotNull( connector.getSchedulerLock() );
connector.setProgressAreaOfInterestRequestProcessing( () -> false );
connector.setProgressResponseProcessing( () -> false );
final boolean result3 = connector.scheduleTick();
assertEquals( result3, false );
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 3 );
assertEquals( connector.getProgressResponseProcessingCount(), 3 );
assertNull( connector.getSchedulerLock() );
assertTrue( Disposable.isDisposed( schedulerLock1 ) );
}
@Test
public void scheduleTick_withError()
{
final TestConnector connector = TestConnector.create( G.class );
connector.triggerScheduler();
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 0 );
assertEquals( connector.getProgressResponseProcessingCount(), 0 );
assertNull( connector.getSchedulerLock() );
connector.setProgressAreaOfInterestRequestProcessing( () -> true );
connector.setProgressResponseProcessing( () -> true );
final boolean result1 = connector.scheduleTick();
assertEquals( result1, true );
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 1 );
assertEquals( connector.getProgressResponseProcessingCount(), 1 );
final Disposable schedulerLock1 = connector.getSchedulerLock();
assertNotNull( schedulerLock1 );
final IllegalStateException error = new IllegalStateException();
connector.setProgressAreaOfInterestRequestProcessing( () -> {
throw error;
} );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final boolean result2 = connector.scheduleTick();
assertEquals( result2, false );
assertEquals( connector.getProgressAreaOfInterestRequestProcessingCount(), 2 );
assertEquals( connector.getProgressResponseProcessingCount(), 1 );
assertNull( connector.getSchedulerLock() );
assertTrue( Disposable.isDisposed( schedulerLock1 ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSystemType(), connector.getSystemType() );
assertEquals( e.getError(), error );
} );
}
@Test
public void requestSubscribe()
{
final TestConnector connector = TestConnector.create( G.class );
connector.setConnection( new Connection( connector, ValueUtil.randomString() ) );
final ChannelAddress address = new ChannelAddress( G.G1 );
assertEquals( connector.getActivateSchedulerCount(), 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscribe( address, null );
assertEquals( connector.getActivateSchedulerCount(), 1 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate()
{
final TestConnector connector = TestConnector.create( G.class );
connector.setConnection( new Connection( connector, ValueUtil.randomString() ) );
final ChannelAddress address = new ChannelAddress( G.G1 );
assertEquals( connector.getActivateSchedulerCount(), 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscriptionUpdate( address, null );
assertEquals( connector.getActivateSchedulerCount(), 1 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestUnsubscribe()
{
final TestConnector connector = TestConnector.create( G.class );
connector.setConnection( new Connection( connector, ValueUtil.randomString() ) );
final ChannelAddress address = new ChannelAddress( G.G1 );
assertEquals( connector.getActivateSchedulerCount(), 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestUnsubscribe( address );
assertEquals( connector.getActivateSchedulerCount(), 1 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void convergeAreaOfInterest()
{
final ArezContext context = Arez.context();
final ReplicantContext rContext = Replicant.context();
// Pause schedule so can manually interact with converger
context.pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
connector.setConnection( new Connection( connector, ValueUtil.randomString() ) );
context.safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
context.safeAction( () -> rContext.createOrUpdateAreaOfInterest( address, null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Converger.Action result = context.safeAction( () -> rContext.getConverger()
.convergeAreaOfInterest( areaOfInterest, null, null, true ) );
assertEquals( result, Converger.Action.SUBMITTED_ADD );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void convergeAreaOfInterest_subscribedButRemovePending()
{
final ArezContext context = Arez.context();
final ReplicantContext rContext = Replicant.context();
// Pause schedule so can manually interact with converger
context.pauseScheduler();
final TestConnector connector = TestConnector.create( G.class );
connector.setConnection( new Connection( connector, ValueUtil.randomString() ) );
context.safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final ChannelAddress address = new ChannelAddress( G.G1 );
final AreaOfInterest areaOfInterest =
context.safeAction( () -> rContext.createOrUpdateAreaOfInterest( address, null ) );
context.safeAction( () -> rContext.createSubscription( address, null, true ) );
connector.requestUnsubscribe( address );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Converger.Action result = context.safeAction( () -> rContext.getConverger()
.convergeAreaOfInterest( areaOfInterest, null, null, true ) );
assertEquals( result, Converger.Action.SUBMITTED_ADD );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
enum G
{
G1, G2
}
enum F
{
F2
}
}
|
package org.jetel.main;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.data.Defaults;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.GraphConfigurationException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.TransformationGraphXMLReaderWriter;
import org.jetel.graph.dictionary.DictionaryEntryFactory;
import org.jetel.graph.dictionary.DictionaryEntryProvider;
import org.jetel.graph.dictionary.IDictionaryValue;
import org.jetel.graph.dictionary.SerializedDictionaryValue;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.graph.runtime.IThreadManager;
import org.jetel.graph.runtime.SimpleThreadManager;
import org.jetel.graph.runtime.WatchDog;
import org.jetel.util.JetelVersion;
import org.jetel.util.file.FileUtils;
/*
* - runGraph.main()
* - runGraph.initEngine()
* - runGraph.loadGraph()
* - ..., Nodes.fromXML(), ...
* - TransformationGraph.init()
* - validate Connections (init(), free())
* - validate Sequences (init(), free())
* - analyze graph topology
* - TransformationGraph.checkConfig()
* - Phases.checkConfig()
* - Nodes.checkConfig()
* - TransfomrationGraph.run()
* - create and start WatchDog thread
* - WatchDog.runPhase()
* - Phase.init()
* - Edges.init()
* - Nodes.init()
* - start all node threads in phase (Nodes.execute())
* - watching them
* - Phase.free()
* - Edges.free()
* - Nodes.free()
*/
/**
* class for executing transformations described in XML layout file<br><br>
* The graph layout is read from specified XML file and the whole transformation is executed.<br>
* <tt><pre>
* Program parameters:
* <table>
* <tr><td nowrap>-v</td><td>be verbose - print even graph layout</td></tr>
* <tr><td nowrap>-P:<i>properyName</i>=<i>propertyValue</i></td><td>add definition of property to global graph's property list</td></tr>
* <tr><td nowrap>-cfg <i>filename</i></td><td>load definitions of properties from specified file</td></tr>
* <tr><td nowrap>-logcfg <i>filename</i></td><td>load log4j properties from specified file; if not specified, \"log4j.properties\" should be in classpath</td></tr>
* <tr><td nowrap>-loglevel <i>ALL | TRACE | DEBUG | INFO | WARN | ERROR | FATAL | OFF</i></td><td>overrides log4j configuration and sets specified logging level for rootLogger</td></tr>
* <tr><td nowrap>-tracking <i>seconds</i></td><td>how frequently output the processing status</td></tr>
* <tr><td nowrap>-info</td><td>print info about Clover library version</td></tr>
* <tr><td nowrap>-plugins <i>filename</i></td><td>directory where to look for plugins/components</td></tr>
* <tr><td nowrap>-pass <i>password</i></td><td>password for decrypting of hidden connections passwords</td></tr>
* <tr><td nowrap>-stdin</td><td>load graph layout from STDIN</td></tr>
* <tr><td nowrap>-loghost</td><td>define host and port number for socket appender of log4j (log4j library is required); i.e. localhost:4445</td></tr>
* <tr><td nowrap>-checkconfig</td><td>only check graph configuration</td></tr>
* <tr><td nowrap>-noJMX</td><td>this switch turns off sending graph tracking information; this switch is recommended if the tracking information are not necessary</td></tr>
* <tr><td nowrap>-config <i>filename</i></td><td>load default engine properties from specified file</td></tr>
* <tr><td nowrap><b>filename</b></td><td>filename or URL of the file (even remote) containing graph's layout in XML (this must be the last parameter passed)</td></tr>
* </table>
* </pre></tt>
* @author dpavlis
* @since 2003/09/09
* @revision $Revision$
*/
public class runGraph {
private static Log logger = LogFactory.getLog(runGraph.class);
//TODO change run graph version
private final static String RUN_GRAPH_VERSION = JetelVersion.MAJOR_VERSION+"."+JetelVersion.MINOR_VERSION;
public final static String VERBOSE_SWITCH = "-v";
public final static String PROPERTY_FILE_SWITCH = "-cfg";
public final static String LOG4J_PROPERTY_FILE_SWITCH = "-logcfg";
public final static String LOG4J_LOG_LEVEL_SWITCH = "-loglevel";
public final static String PROPERTY_DEFINITION_SWITCH = "-P:";
public final static String TRACKING_INTERVAL_SWITCH = "-tracking";
public final static String INFO_SWITCH = "-info";
public final static String PLUGINS_SWITCH = "-plugins";
public final static String PASSWORD_SWITCH = "-pass";
public final static String LOAD_FROM_STDIN_SWITCH = "-stdin";
public final static String LOG_HOST_SWITCH = "-loghost";
public final static String CHECK_CONFIG_SWITCH = "-checkconfig";
public final static String NO_JMX = "-noJMX";
public final static String CONFIG_SWITCH = "-config";
public final static String MBEAN_NAME = "-mbean";
public final static String DICTIONARY_VALUE_DEFINITION_SWITCH = "-V:";
/**
* Description of the Method
*
* @param args Description of the Parameter
*/
public static void main(String args[]) {
boolean loadFromSTDIN = false;
String pluginsRootDirectory = null;
boolean onlyCheckConfig = false;
String logHost = null;
String graphFileName = null;
String configFileName = null;
List<SerializedDictionaryValue> dictionaryValues = new ArrayList<SerializedDictionaryValue>();
logger.info("*** CloverETL framework/transformation graph runner ver "
+ RUN_GRAPH_VERSION
+ ", (c) 2002-06 D.Pavlis, released under GNU Lesser General Public License ***");
logger.info(" Running with framework version: "
+ JetelVersion.MAJOR_VERSION + "." + JetelVersion.MINOR_VERSION
+ " build#" + JetelVersion.BUILD_NUMBER + " compiled "
+ JetelVersion.LIBRARY_BUILD_DATETIME);
Logger.getLogger(runGraph.class); // make log4j to init itself
String log4jPropertiesFile = null;
Level logLevel = null;
// process command line arguments
GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith(VERBOSE_SWITCH)) {
runtimeContext.setVerboseMode(true);
} else if (args[i].startsWith(PROPERTY_FILE_SWITCH)) {
i++;
try {
InputStream inStream = new BufferedInputStream(
new FileInputStream(args[i]));
Properties properties = new Properties();
properties.load(inStream);
runtimeContext.addAdditionalProperties(properties);
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
System.exit(-1);
}
} else if (args[i].startsWith(LOG4J_PROPERTY_FILE_SWITCH)) {
i++;
log4jPropertiesFile = args[i];
File test = new File(log4jPropertiesFile);
if (!test.canRead()){
System.err.println("Cannot read file: \"" + log4jPropertiesFile + "\"");
System.exit(-1);
}
} else if (args[i].startsWith(LOG4J_LOG_LEVEL_SWITCH)){
i++;
String logLevelString = args[i];
logLevel = Level.toLevel(logLevelString, Level.DEBUG);
} else if (args[i].startsWith(PROPERTY_DEFINITION_SWITCH)) {
// String[]
// nameValue=args[i].replaceFirst(PROPERTY_DEFINITION_SWITCH,"").split("=");
// properties.setProperty(nameValue[0],nameValue[1]);
String tmp = args[i].replaceFirst(PROPERTY_DEFINITION_SWITCH, "");
runtimeContext.addAdditionalProperty(tmp.substring(0, tmp.indexOf("=")), tmp.substring(tmp.indexOf("=") + 1));
} else if (args[i].startsWith(TRACKING_INTERVAL_SWITCH)) {
i++;
try {
runtimeContext.setTrackingInterval(Integer.parseInt(args[i]) * 1000);
} catch (NumberFormatException ex) {
System.err.println("Invalid tracking parameter: \"" + args[i] + "\"");
System.exit(-1);
}
} else if (args[i].startsWith(INFO_SWITCH)) {
printInfo();
System.exit(0);
} else if (args[i].startsWith(PLUGINS_SWITCH)) {
i++;
pluginsRootDirectory = args[i];
} else if (args[i].startsWith(PASSWORD_SWITCH)) {
i++;
runtimeContext.setPassword(args[i]);
} else if (args[i].startsWith(LOAD_FROM_STDIN_SWITCH)) {
loadFromSTDIN = true;
} else if (args[i].startsWith(LOG_HOST_SWITCH)) {
i++;
logHost = args[i];
} else if (args[i].startsWith(CHECK_CONFIG_SWITCH)) {
onlyCheckConfig = true;
} else if (args[i].startsWith(MBEAN_NAME)){
i++;
//TODO
//runtimeContext.set --> mbeanName = args[i];
} else if (args[i].startsWith(NO_JMX)){
runtimeContext.setUseJMX(false);
} else if (args[i].startsWith(CONFIG_SWITCH)) {
i++;
configFileName = args[i];
} else if (args[i].startsWith(DICTIONARY_VALUE_DEFINITION_SWITCH)) {
String value = args[i].replaceFirst(DICTIONARY_VALUE_DEFINITION_SWITCH, "");
try {
dictionaryValues.add(SerializedDictionaryValue.fromString(value));
} catch (IllegalArgumentException e) {
System.err.println("Invalid dictionary value format: " + value);
System.exit(-1);
}
} else if (args[i].startsWith("-")) {
System.err.println("Unknown option: " + args[i]);
System.exit(-1);
} else {
graphFileName = args[i];
}
}
if (graphFileName == null) {
printHelp();
System.exit(-1);
}
if (log4jPropertiesFile != null){
PropertyConfigurator.configure( log4jPropertiesFile );
} else {
/*
String wdFile = "./log4j.properties";
File f = new File(wdFile);
if (f.canRead())
PropertyConfigurator.configure( wdFile );
else
BasicConfigurator.configure();
*/
}
if (logLevel != null)
Logger.getRootLogger().setLevel(logLevel);
// engine initialization - should be called only once
EngineInitializer.initEngine(pluginsRootDirectory, configFileName, logHost);
//tohle je nutne odstranit - runtimeContext je potreba vytvorit az po initiazlizaci enginu!!! Kokon
runtimeContext.setTrackingInterval(Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL);
// prepare input stream with XML graph definition
InputStream in = null;
if (loadFromSTDIN) {
System.out.println("Graph definition loaded from STDIN");
in = System.in;
} else {
System.out.println("Graph definition file: " + graphFileName);
try {
in = Channels.newInputStream(FileUtils.getReadableChannel(null, graphFileName));
} catch (IOException e) {
System.err.println("Error - graph definition file can't be read: " + e.getMessage());
System.exit(-1);
}
}
TransformationGraph graph = null;
Future<Result> futureResult = null;;
try {
graph = TransformationGraphXMLReaderWriter.loadGraph(in, runtimeContext.getAdditionalProperties());
initializeDictionary(dictionaryValues, graph);
runGraph(graph, runtimeContext);
} catch (XMLConfigurationException e) {
logger.error("Error in reading graph from XML !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
} catch (GraphConfigurationException e) {
logger.error("Error - graph's configuration invalid !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
}
}
private static void initializeDictionary(List<SerializedDictionaryValue> dictionaryValues, TransformationGraph graph)
throws XMLConfigurationException {
for (SerializedDictionaryValue serializedDictionaryValue : dictionaryValues) {
try {
String type = serializedDictionaryValue.getType() != null ? serializedDictionaryValue.getType() : DictionaryEntryProvider.DEFAULT_TYPE;
DictionaryEntryProvider dictionaryEntryProvider = DictionaryEntryFactory.getDictionaryEntryProvider(type);
IDictionaryValue<?> dictionaryValue = dictionaryEntryProvider.getValue(serializedDictionaryValue.getProperties());
graph.setDefaultDictionaryEntry(serializedDictionaryValue.getKey(), dictionaryValue);
} catch(AttributeNotFoundException ex){
throw new XMLConfigurationException("Dictionary - Attributes missing " + ex.getMessage());
}
}
}
private static void runGraph(TransformationGraph graph, GraphRuntimeContext runtimeContext) {
Future<Result> futureResult = null;
try {
if (!graph.isInitialized()) {
EngineInitializer.initGraph(graph, runtimeContext);
printDictionary("Initial dictionary content:", graph);
}
futureResult = executeGraph(graph, runtimeContext);
} catch (ComponentNotReadyException e) {
logger.error("Error during graph initialization !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
} catch (RuntimeException e) {
logger.error("Error during graph initialization !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
}
Result result = Result.N_A;
try {
result = futureResult.get();
printDictionary("Final dictionary content:", graph);
} catch (InterruptedException e) {
logger.error("Graph was unexpectedly interrupted !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
} catch (ExecutionException e) {
logger.error("Error during graph processing !", e);
if (runtimeContext.isVerboseMode()) {
e.printStackTrace(System.err);
}
System.exit(-1);
}
System.out.println("Freeing graph resources.");
graph.free();
switch (result) {
case FINISHED_OK:
// everything O.K.
System.out.println("Execution of graph successful !");
System.exit(0);
break;
case ABORTED:
// execution was ABORTED !!
System.err.println("Execution of graph aborted !");
System.exit(result.code());
break;
default:
System.err.println("Execution of graph failed !");
System.exit(result.code());
}
}
public static Future<Result> executeGraph(TransformationGraph graph, GraphRuntimeContext runtimeContext) throws ComponentNotReadyException {
if (!graph.isInitialized()) {
EngineInitializer.initGraph(graph, runtimeContext);
}
IThreadManager threadManager = new SimpleThreadManager();
WatchDog watchDog = new WatchDog(graph, runtimeContext);
return threadManager.executeWatchDog(watchDog);
}
private static void printDictionary(String message, TransformationGraph graph) {
if(!graph.getDictionary().isEmpty()) {
logger.info(message);
Set<String> keys = graph.getDictionary().getKeys();
for (String key : keys) {
logger.info(key + ":" + graph.getDictionaryValue(key));
}
}
}
private static void printHelp() {
System.out.println("Usage: runGraph [-(v|cfg|logcfg|loglevel|P:|tracking|info|plugins|pass)] <graph definition file>");
System.out.println("Options:");
System.out.println("-v\t\t\tbe verbose - print even graph layout");
System.out.println("-P:<key>=<value>\tadd definition of property to global graph's property list");
System.out.println("-cfg <filename>\t\tload definitions of properties from specified file");
System.out.println("-logcfg <filename>\tload log4j configuration from specified file; \n\t\t\tif not specified, \"log4j.properties\" should be in classpath");
System.out.println("-loglevel <level>\toverrides log4j configuration and sets specified logging level for rootLogger; \n\t\t\tpossible levels are: ALL | TRACE | DEBUG | INFO | WARN | ERROR | FATAL | OFF");
System.out.println("-tracking <seconds>\thow frequently output the graph processing status");
System.out.println("-info\t\t\tprint info about Clover library version");
System.out.println("-plugins\t\tdirectory where to look for plugins/components");
System.out.println("-pass\t\t\tpassword for decrypting of hidden connections passwords");
System.out.println("-stdin\t\t\tload graph definition from STDIN");
System.out.println("-loghost\t\tdefine host and port number for socket appender of log4j (log4j library is required); i.e. localhost:4445");
System.out.println("-checkconfig\t\tonly check graph configuration");
// System.out.println("-mbean <name>\t\tname under which register Clover's JMXBean");
System.out.println("-noJMX\t\t\tturns off sending graph tracking information");
System.out.println("-config <filename>\t\tload default engine properties from specified file");
System.out.println();
System.out.println("Note: <graph definition file> can be either local filename or URL of local/remote file");
}
private static void printInfo(){
System.out.println("CloverETL library version "+JetelVersion.MAJOR_VERSION+"."+JetelVersion.MINOR_VERSION+" build#"+JetelVersion.BUILD_NUMBER+" compiled "+JetelVersion.LIBRARY_BUILD_DATETIME);
}
}
|
package wycs.builder;
import java.util.*;
import static wybs.lang.SyntaxError.*;
import wybs.lang.Attribute;
import wycs.core.*;
import wycs.syntax.*;
public class CodeGeneration {
private final WycsBuilder builder;
private String filename;
public CodeGeneration(WycsBuilder builder) {
this.builder = builder;
}
public WycsFile generate(WyalFile file) {
this.filename = file.filename();
ArrayList<WycsFile.Declaration> declarations = new ArrayList();
for(WyalFile.Declaration d : file.declarations()) {
declarations.add(generate(d));
}
return new WycsFile(file.id(),file.filename(),declarations);
}
protected WycsFile.Declaration generate(WyalFile.Declaration declaration) {
if(declaration instanceof WyalFile.Define) {
return generate((WyalFile.Define)declaration);
} else if(declaration instanceof WyalFile.Function) {
return generate((WyalFile.Function)declaration);
} else if(declaration instanceof WyalFile.Assert) {
return generate((WyalFile.Assert)declaration);
} else {
internalFailure("unknown declaration encounterd",filename,declaration);
return null;
}
}
protected WycsFile.Declaration generate(WyalFile.Define d) {
return null;
}
protected WycsFile.Declaration generate(WyalFile.Function d) {
return null;
}
protected WycsFile.Declaration generate(WyalFile.Assert d) {
Code condition = generate(d.expr);
return new WycsFile.Assert(d.message, condition, d.attribute(Attribute.Source.class));
}
protected Code generate(Expr e) {
if (e instanceof Expr.Variable) {
return generate((Expr.Variable) e);
} else if (e instanceof Expr.Constant) {
return generate((Expr.Constant) e);
} else if (e instanceof Expr.Unary) {
return generate((Expr.Unary) e);
} else if (e instanceof Expr.Binary) {
return generate((Expr.Binary) e);
} else if (e instanceof Expr.Nary) {
return generate((Expr.Nary) e);
} else if (e instanceof Expr.Quantifier) {
return generate((Expr.Quantifier) e);
} else if (e instanceof Expr.FunCall) {
return generate((Expr.FunCall) e);
} else if (e instanceof Expr.Load) {
return generate((Expr.Load) e);
} else if (e instanceof Expr.IndexOf) {
return generate((Expr.IndexOf) e);
} else {
internalFailure("unknown expression encountered (" + e + ")",
filename, e);
return null;
}
}
protected Code generate(Expr.Variable v) {
}
protected Code generate(Expr.Constant v) {
return Code.Constant(v.value);
}
protected Code generate(Expr.Unary e) {
SemanticType type = e.attribute(TypeAttribute.class).type;
Code operand = generate(e.operand);
Code.Op opcode;
switch(e.op) {
case NEG:
opcode = Code.Op.NEG;
break;
case NOT:
opcode = Code.Op.NOT;
break;
case LENGTHOF:
opcode = Code.Op.LENGTH;
break;
default:
internalFailure("unknown unary opcode encountered (" + e + ")",
filename, e);
return null;
}
return Code.Unary(type, opcode, operand);
}
protected Code generate(Expr.Binary e) {
SemanticType type = e.attribute(TypeAttribute.class).type;
Code lhs = generate(e.leftOperand);
Code rhs = generate(e.rightOperand);
Code.Op opcode;
switch(e.op) {
case ADD:
opcode = Code.Op.ADD;
break;
case SUB:
opcode = Code.Op.SUB;
break;
case MUL:
opcode = Code.Op.MUL;
break;
case DIV:
opcode = Code.Op.DIV;
break;
case REM:
opcode = Code.Op.REM;
break;
case EQ:
opcode = Code.Op.EQ;
break;
case NEQ:
opcode = Code.Op.NEQ;
break;
case IMPLIES:
lhs = Code.Unary(type, Code.Unary.Op.NOT,lhs);
return Code.Nary(type, Code.Op.OR, new Code[]{lhs,rhs});
case IFF:
Code nLhs = Code.Unary(type, Code.Unary.Op.NOT,lhs);
Code nRhs = Code.Unary(type, Code.Unary.Op.NOT,rhs);
lhs = Code.Nary(type, Code.Op.AND, new Code[]{lhs,rhs});
rhs = Code.Nary(type, Code.Op.AND, new Code[]{nLhs,nRhs});
return Code.Nary(type, Code.Op.OR, new Code[]{lhs,rhs});
case LT:
opcode = Code.Op.LT;
break;
case LTEQ:
opcode = Code.Op.LTEQ;
break;
case GT: {
opcode = Code.Op.LT;
Code tmp = lhs;
lhs = rhs;
rhs = tmp;
break;
}
case GTEQ: {
opcode = Code.Op.LTEQ;
Code tmp = lhs;
lhs = rhs;
rhs = tmp;
break;
}
case IN:
opcode = Code.Op.IN;
break;
case SUBSET:
opcode = Code.Op.SUBSET;
break;
case SUBSETEQ:
opcode = Code.Op.SUBSETEQ;
break;
case SUPSET: {
opcode = Code.Op.SUBSET;
Code tmp = lhs;
lhs = rhs;
rhs = tmp;
break;
}
case SUPSETEQ: {
opcode = Code.Op.SUBSETEQ;
Code tmp = lhs;
lhs = rhs;
rhs = tmp;
break;
}
// case SETUNION:
// opcode = Code.Op.NEG;
// break;
// case SETINTERSECTION:
// opcode = Code.Op.NEG;
// break;
// case SETDIFFERENCE:
// opcode = Code.Op.NEG;
// break;
// case LISTAPPEND:
// opcode = Code.Op.NEG;
// break;
default:
internalFailure("unknown unary opcode encountered (" + e + ")",
filename, e);
return null;
}
return Code.Binary(type, opcode, lhs, rhs);
}
}
|
package massim.monitor;
import massim.protocol.WorldData;
import massim.protocol.scenario.city.data.DynamicCityData;
import massim.protocol.scenario.city.data.StaticCityData;
import org.json.JSONObject;
import org.webbitserver.BaseWebSocketHandler;
import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.WebSocketConnection;
import org.webbitserver.handler.HttpToWebSocketHandler;
import org.webbitserver.handler.EmbeddedResourceHandler;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;
/**
* The web monitor for the MASSim server.
*/
public class Monitor {
private String latestStatic;
private String latestDynamic;
private final HashSet<WebSocketConnection> pool = new HashSet<WebSocketConnection>();
private final BaseWebSocketHandler socketHandler = new BaseWebSocketHandler() {
@Override
public void onOpen(WebSocketConnection client) {
pool.add(client);
if (latestStatic != null) client.send(latestStatic);
if (latestDynamic != null) client.send(latestDynamic);
}
@Override
public void onClose(WebSocketConnection client) {
pool.remove(client);
}
};
/**
* Constructor.
* Used by the massim server to create the "live" monitor.
*/
public Monitor() throws ExecutionException, InterruptedException {
WebServer server = WebServers.createWebServer(7777)
.add("/socket", new HttpToWebSocketHandler(this.socketHandler))
.add(new EmbeddedResourceHandler("www"))
.start()
.get();
}
/**
* Creates a new monitor to watch replays with.
* @param replayPath the path to a replay file
*/
Monitor(String replayPath){
// TODO
}
private void broadcast(String message) {
for (WebSocketConnection client: this.pool) {
client.send(message);
}
}
/**
* Updates the current state of the monitor.
* Called by the massim server after each step.
*/
public void updateState(WorldData worldData){
if (worldData instanceof StaticCityData) {
this.latestStatic = staticToJson((StaticCityData) worldData);
this.broadcast(this.latestStatic);
} else if (worldData instanceof DynamicCityData){
this.latestDynamic = dynamicToJson((DynamicCityData) worldData);
this.broadcast(this.latestDynamic);
}
}
private String staticToJson(StaticCityData data) {
JSONObject d = new JSONObject();
d.put("simId", data.simId);
d.put("steps", data.steps);
d.put("map", data.map);
d.put("seedCapital", data.seedCapital);
d.put("teams", data.teams);
d.put("roles", data.roles);
d.put("items", data.items);
return d.toString();
}
private String dynamicToJson(DynamicCityData data) {
JSONObject d = new JSONObject();
d.put("step", data.step);
d.put("workshops", data.workshops);
d.put("chargingStations", data.chargingStations);
d.put("shops", data.shops);
d.put("dumps", data.dumps);
d.put("resourceNodes", data.resourceNodes);
d.put("storages", data.storages);
d.put("entities", data.entities);
d.put("jobs", data.jobs);
d.put("teams", data.teams);
return d.toString();
}
}
|
package mtr.render;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Matrix3f;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
import mtr.MTRClient;
import mtr.block.BlockNode;
import mtr.block.BlockPlatform;
import mtr.block.BlockSignalLightBase;
import mtr.block.BlockSignalSemaphoreBase;
import mtr.client.*;
import mtr.data.*;
import mtr.entity.EntitySeat;
import mtr.item.ItemNodeModifierBase;
import mtr.mappings.EntityRendererMapper;
import mtr.mappings.Utilities;
import mtr.mappings.UtilitiesClient;
import mtr.model.ModelCableCarGrip;
import mtr.path.PathData;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.EntityRenderDispatcher;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.entity.vehicle.Minecart;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.phys.Vec3;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class RenderTrains extends EntityRendererMapper<EntitySeat> implements IGui {
public static int maxTrainRenderDistance;
public static String creatorModelFileName = "";
public static JsonObject creatorModel = new JsonObject();
public static String creatorPropertiesFileName = "";
public static JsonObject creatorProperties = new JsonObject();
public static String creatorTextureFileName = "";
public static ResourceLocation creatorTexture;
private static float lastRenderedTick;
private static int prevPlatformCount;
private static int prevSidingCount;
private static UUID renderedUuid;
public static final int PLAYER_RENDER_OFFSET = 1000;
private static final Set<String> AVAILABLE_TEXTURES = new HashSet<>();
private static final Set<String> UNAVAILABLE_TEXTURES = new HashSet<>();
private static final int DETAIL_RADIUS = 32;
private static final int DETAIL_RADIUS_SQUARED = DETAIL_RADIUS * DETAIL_RADIUS;
private static final int MAX_RADIUS_REPLAY_MOD = 64 * 16;
private static final int TICKS_PER_SECOND = 20;
private static final EntityModel<Minecart> MODEL_MINECART = UtilitiesClient.getMinecartModel();
private static final EntityModel<Boat> MODEL_BOAT = UtilitiesClient.getBoatModel();
private static final Map<Long, FakeBoat> BOATS = new HashMap<>();
private static final ModelCableCarGrip MODEL_CABLE_CAR_GRIP = new ModelCableCarGrip();
public RenderTrains(Object parameter) {
super(parameter);
}
@Override
public void render(EntitySeat entity, float entityYaw, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int entityLight) {
render(entity, tickDelta, matrices, vertexConsumers);
}
@Override
public ResourceLocation getTextureLocation(EntitySeat entity) {
return null;
}
public static void render(EntitySeat entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers) {
final Minecraft client = Minecraft.getInstance();
final boolean backupRendering = entity == null;
final boolean alreadyRendered = renderedUuid != null && (backupRendering || entity.getUUID() != renderedUuid);
if (backupRendering) {
renderedUuid = null;
}
final LocalPlayer player = client.player;
final Level world = client.level;
if (alreadyRendered || player == null || world == null) {
return;
}
if (!backupRendering) {
renderedUuid = entity.getUUID();
}
final int renderDistanceChunks = client.options.renderDistance;
final float lastFrameDuration = MTRClient.getLastFrameDuration();
final boolean useAnnouncements = Config.useTTSAnnouncements() || Config.showAnnouncementMessages();
if (Config.useDynamicFPS()) {
if (lastFrameDuration > 0.5) {
maxTrainRenderDistance = Math.max(maxTrainRenderDistance - (maxTrainRenderDistance - DETAIL_RADIUS) / 2, DETAIL_RADIUS);
} else if (lastFrameDuration < 0.4) {
maxTrainRenderDistance = Math.min(maxTrainRenderDistance + 1, renderDistanceChunks * (Config.trainRenderDistanceRatio() + 1));
}
} else {
maxTrainRenderDistance = renderDistanceChunks * (Config.trainRenderDistanceRatio() + 1);
}
matrices.pushPose();
if (!backupRendering) {
final double entityX = Mth.lerp(tickDelta, entity.xOld, entity.getX());
final double entityY = Mth.lerp(tickDelta, entity.yOld, entity.getY());
final double entityZ = Mth.lerp(tickDelta, entity.zOld, entity.getZ());
matrices.translate(-entityX, -entityY, -entityZ);
}
final Camera camera = client.gameRenderer.getMainCamera();
final float cameraYaw = camera.getYRot();
final Vec3 cameraOffset = camera.isDetached() ? player.getEyePosition(client.getFrameTime()) : camera.getPosition();
final boolean secondF5 = Math.abs(Utilities.getYaw(player) - cameraYaw) > 90;
ClientData.TRAINS.forEach(train -> train.simulateTrain(world, client.isPaused() || lastRenderedTick == MTRClient.getGameTick() ? 0 : lastFrameDuration, (x, y, z, yaw, pitch, trainId, baseTrainType, isEnd1Head, isEnd2Head, head1IsFront, doorLeftValue, doorRightValue, opening, lightsOn, isTranslucent, playerOffset, ridingPositions) -> renderWithLight(world, x, y, z, playerOffset == null, (light, posAverage) -> {
final TrainClientRegistry.TrainProperties trainProperties = TrainClientRegistry.getTrainProperties(trainId, baseTrainType);
if (trainProperties.model == null && isTranslucent) {
return;
}
matrices.pushPose();
if (playerOffset != null) {
matrices.translate(cameraOffset.x, cameraOffset.y, cameraOffset.z);
matrices.mulPose(Vector3f.YP.rotationDegrees(Utilities.getYaw(player) - cameraYaw + (secondF5 ? 180 : 0)));
matrices.translate(-playerOffset.x, -playerOffset.y, -playerOffset.z);
}
matrices.pushPose();
matrices.translate(x, y, z);
matrices.mulPose(Vector3f.YP.rotation((float) Math.PI + yaw));
matrices.mulPose(Vector3f.XP.rotation((float) Math.PI + (baseTrainType.transportMode.hasPitch ? pitch : 0)));
if (trainProperties.model == null || trainProperties.textureId == null) {
final boolean isBoat = baseTrainType.transportMode == TransportMode.BOAT;
matrices.translate(0, isBoat ? 0.875 : 0.5, 0);
matrices.mulPose(Vector3f.YP.rotationDegrees(90));
final EntityModel<? extends Entity> model = isBoat ? MODEL_BOAT : MODEL_MINECART;
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(model.renderType(resolveTexture(trainProperties, textureId -> textureId + ".png")));
if (isBoat) {
if (!BOATS.containsKey(train.id)) {
BOATS.put(train.id, new FakeBoat());
}
MODEL_BOAT.setupAnim(BOATS.get(train.id), (train.getSpeed() + Train.ACCELERATION_DEFAULT) * (doorLeftValue == 0 && doorRightValue == 0 ? lastFrameDuration : 0), 0, -0.1F, 0, 0);
} else {
model.setupAnim(null, 0, 0, -0.1F, 0, 0);
}
model.renderToBuffer(matrices, vertexConsumer, light, OverlayTexture.NO_OVERLAY, 1, 1, 1, 1);
} else {
final boolean renderDetails = MTRClient.isReplayMod() || posAverage.distSqr(camera.getBlockPosition()) <= DETAIL_RADIUS_SQUARED;
trainProperties.model.render(matrices, vertexConsumers, resolveTexture(trainProperties, textureId -> textureId + ".png"), light, doorLeftValue, doorRightValue, opening, isEnd1Head, isEnd2Head, head1IsFront, lightsOn, isTranslucent, renderDetails);
}
if (baseTrainType.transportMode == TransportMode.CABLE_CAR) {
matrices.translate(0, TransportMode.CABLE_CAR.railOffset + 0.5, 0);
if (!baseTrainType.transportMode.hasPitch) {
matrices.mulPose(Vector3f.XP.rotation(pitch));
}
if (baseTrainType.toString().endsWith("_RHT")) {
matrices.mulPose(Vector3f.YP.rotationDegrees(180));
}
MODEL_CABLE_CAR_GRIP.render(matrices, vertexConsumers, light);
}
matrices.popPose();
final EntityRenderDispatcher entityRenderDispatcher = client.getEntityRenderDispatcher();
matrices.pushPose();
matrices.translate(0, PLAYER_RENDER_OFFSET, 0);
ridingPositions.forEach((uuid, offset) -> {
final Player renderPlayer = world.getPlayerByUUID(uuid);
if (renderPlayer != null && (!uuid.equals(player.getUUID()) || camera.isDetached())) {
entityRenderDispatcher.render(renderPlayer, offset.x, offset.y, offset.z, 0, 1, matrices, vertexConsumers, 0xF000F0);
}
});
matrices.popPose();
matrices.popPose();
}), (prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, trainId, baseTrainType, lightsOn, playerOffset) -> renderWithLight(world, x, y, z, playerOffset == null, (light, posAverage) -> {
final TrainClientRegistry.TrainProperties trainProperties = TrainClientRegistry.getTrainProperties(trainId, baseTrainType);
if (trainProperties.textureId == null) {
return;
}
matrices.pushPose();
if (playerOffset != null) {
matrices.translate(cameraOffset.x, cameraOffset.y, cameraOffset.z);
matrices.mulPose(Vector3f.YP.rotationDegrees(Utilities.getYaw(player) - cameraYaw + (secondF5 ? 180 : 0)));
matrices.translate(-playerOffset.x, -playerOffset.y, -playerOffset.z);
}
final VertexConsumer vertexConsumerExterior = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(getConnectorTextureString(trainProperties, "exterior")));
drawTexture(matrices, vertexConsumerExterior, thisPos2, prevPos3, prevPos4, thisPos1, light);
drawTexture(matrices, vertexConsumerExterior, prevPos2, thisPos3, thisPos4, prevPos1, light);
drawTexture(matrices, vertexConsumerExterior, prevPos3, thisPos2, thisPos3, prevPos2, light);
drawTexture(matrices, vertexConsumerExterior, prevPos1, thisPos4, thisPos1, prevPos4, light);
final int lightOnLevel = lightsOn ? MAX_LIGHT_INTERIOR : light;
final VertexConsumer vertexConsumerSide = vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "side")));
drawTexture(matrices, vertexConsumerSide, thisPos3, prevPos2, prevPos1, thisPos4, lightOnLevel);
drawTexture(matrices, vertexConsumerSide, prevPos3, thisPos2, thisPos1, prevPos4, lightOnLevel);
drawTexture(matrices, vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "roof"))), prevPos2, thisPos3, thisPos2, prevPos3, lightOnLevel);
drawTexture(matrices, vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "floor"))), prevPos4, thisPos1, thisPos4, prevPos1, lightOnLevel);
matrices.popPose();
}), (speed, stopIndex, routeIds) -> {
if (!(speed <= 5 && RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
final Component text;
switch ((int) ((System.currentTimeMillis() / 1000) % 3)) {
default:
text = getStationText(thisStation, "this");
break;
case 1:
if (nextStation == null) {
text = getStationText(thisStation, "this");
} else {
text = getStationText(nextStation, "next");
}
break;
case 2:
text = getStationText(lastStation, "last_" + thisRoute.transportMode.toString().toLowerCase());
break;
}
player.displayClientMessage(text, true);
}))) {
player.displayClientMessage(new TranslatableComponent("gui.mtr.vehicle_speed", RailwayData.round(speed, 1), RailwayData.round(speed * 3.6F, 1)), true);
}
}, (stopIndex, routeIds) -> {
if (useAnnouncements) {
RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
final List<String> messages = new ArrayList<>();
final String thisRouteSplit = thisRoute.name.split("\\|\\|")[0];
final String nextRouteSplit = nextRoute == null ? null : nextRoute.name.split("\\|\\|")[0];
if (nextStation != null) {
final boolean isLightRailRoute = thisRoute.isLightRailRoute;
messages.add(IGui.insertTranslation(isLightRailRoute ? "gui.mtr.next_station_light_rail_announcement_cjk" : "gui.mtr.next_station_announcement_cjk", isLightRailRoute ? "gui.mtr.next_station_light_rail_announcement" : "gui.mtr.next_station_announcement", 1, nextStation.name));
final Map<Integer, ClientCache.ColorNameTuple> routesInStation = ClientData.DATA_CACHE.stationIdToRoutes.get(nextStation.id);
if (routesInStation != null) {
final List<String> interchangeRoutes = routesInStation.values().stream().filter(interchangeRoute -> {
final String routeName = interchangeRoute.name.split("\\|\\|")[0];
return !routeName.equals(thisRouteSplit) && (nextRoute == null || !routeName.equals(nextRouteSplit));
}).map(interchangeRoute -> interchangeRoute.name).collect(Collectors.toList());
final String mergedStations = IGui.mergeStations(interchangeRoutes, ", ");
if (!mergedStations.isEmpty()) {
messages.add(IGui.insertTranslation("gui.mtr.interchange_announcement_cjk", "gui.mtr.interchange_announcement", 1, mergedStations));
}
}
if (lastStation != null && nextStation.id == lastStation.id && nextRoute != null && !nextRoute.platformIds.isEmpty() && !nextRouteSplit.equals(thisRouteSplit)) {
final Station nextFinalStation = ClientData.DATA_CACHE.platformIdToStation.get(nextRoute.platformIds.get(nextRoute.platformIds.size() - 1));
if (nextFinalStation != null) {
final String modeString = thisRoute.transportMode.toString().toLowerCase();
if (nextRoute.isLightRailRoute) {
messages.add(IGui.insertTranslation("gui.mtr.next_route_" + modeString + "_light_rail_announcement_cjk", "gui.mtr.next_route_" + modeString + "_light_rail_announcement", nextRoute.lightRailRouteNumber, 1, nextFinalStation.name.split("\\|\\|")[0]));
} else {
messages.add(IGui.insertTranslation("gui.mtr.next_route_" + modeString + "_announcement_cjk", "gui.mtr.next_route_" + modeString + "_announcement", 2, nextRouteSplit, nextFinalStation.name.split("\\|\\|")[0]));
}
}
}
}
IDrawing.narrateOrAnnounce(IGui.mergeStations(messages, " "));
});
}
}, (stopIndex, routeIds) -> {
if (useAnnouncements) {
RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
if (thisRoute.isLightRailRoute && lastStation != null) {
IDrawing.narrateOrAnnounce(IGui.insertTranslation("gui.mtr.light_rail_route_announcement_cjk", "gui.mtr.light_rail_route_announcement", thisRoute.lightRailRouteNumber, 1, lastStation.name));
}
});
}
}));
if (!Config.hideTranslucentParts()) {
ClientData.TRAINS.forEach(TrainClient::renderTranslucent);
}
final boolean renderColors = isHoldingRailRelated(player);
final int maxRailDistance = renderDistanceChunks * 16;
final Map<UUID, RailType> renderedRailMap = new HashMap<>();
ClientData.RAILS.forEach((startPos, railMap) -> railMap.forEach((endPos, rail) -> {
if (!RailwayData.isBetween(player.getX(), startPos.getX(), endPos.getX(), maxRailDistance) || !RailwayData.isBetween(player.getZ(), startPos.getZ(), endPos.getZ(), maxRailDistance)) {
return;
}
final UUID railProduct = PathData.getRailProduct(startPos, endPos);
if (renderedRailMap.containsKey(railProduct)) {
if (renderedRailMap.get(railProduct) == rail.railType) {
return;
}
} else {
renderedRailMap.put(railProduct, rail.railType);
}
switch (rail.transportMode) {
case TRAIN:
renderRailStandard(world, matrices, vertexConsumers, rail, 0.0625F + SMALL_OFFSET, renderColors, 1);
if (renderColors) {
renderSignalsStandard(world, matrices, vertexConsumers, rail, startPos, endPos);
}
break;
case BOAT:
if (renderColors) {
renderRailStandard(world, matrices, vertexConsumers, rail, 0.0625F + SMALL_OFFSET, true, 0.5F);
renderSignalsStandard(world, matrices, vertexConsumers, rail, startPos, endPos);
}
break;
case CABLE_CAR:
if (rail.railType.hasSavedRail || rail.railType == RailType.CABLE_CAR_STATION) {
renderRailStandard(world, matrices, vertexConsumers, rail, 0.25F + SMALL_OFFSET, renderColors, 0.25F, "mtr:textures/block/metal.png", 0.25F, 0, 0.75F, 1);
}
if (renderColors && !rail.railType.hasSavedRail) {
renderRailStandard(world, matrices, vertexConsumers, rail, 0.5F + SMALL_OFFSET, true, 1, "mtr:textures/block/one_way_rail_arrow.png", 0, 0.75F, 1, 0.25F);
}
if (rail.railType != RailType.NONE) {
rail.render((x1, z1, x2, z2, x3, z3, x4, z4, y1, y2) -> {
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lines());
final Matrix4f matrix4f = matrices.last().pose();
final Matrix3f matrix3f = matrices.last().normal();
final int r = renderColors ? (rail.railType.color >> 16) & 0xFF : 0;
final int g = renderColors ? (rail.railType.color >> 8) & 0xFF : 0;
final int b = renderColors ? rail.railType.color & 0xFF : 0;
vertexConsumer.vertex(matrix4f, (float) x1, (float) y1 + 0.5F, (float) z1).color(r, g, b, 0xFF).normal(matrix3f, 0, 1, 0).endVertex();
vertexConsumer.vertex(matrix4f, (float) x3, (float) y2 + 0.5F, (float) z3).color(r, g, b, 0xFF).normal(matrix3f, 0, 1, 0).endVertex();
}, 0, 0);
}
break;
}
}));
matrices.popPose();
lastRenderedTick = MTRClient.getGameTick();
if (prevPlatformCount != ClientData.PLATFORMS.size() || prevSidingCount != ClientData.SIDINGS.size()) {
ClientData.DATA_CACHE.sync();
}
prevPlatformCount = ClientData.PLATFORMS.size();
prevSidingCount = ClientData.SIDINGS.size();
ClientData.DATA_CACHE.clearDataIfNeeded();
}
public static boolean shouldNotRender(BlockPos pos, int maxDistance, Direction facing) {
final Entity camera = Minecraft.getInstance().cameraEntity;
return shouldNotRender(camera == null ? null : camera.position(), pos, maxDistance, facing);
}
public static void clearTextureAvailability() {
AVAILABLE_TEXTURES.clear();
UNAVAILABLE_TEXTURES.clear();
}
public static boolean isHoldingRailRelated(Player player) {
return Utilities.isHolding(player,
item -> item instanceof ItemNodeModifierBase ||
Block.byItem(item) instanceof BlockSignalLightBase ||
Block.byItem(item) instanceof BlockNode ||
Block.byItem(item) instanceof BlockSignalSemaphoreBase ||
Block.byItem(item) instanceof BlockPlatform
);
}
private static double maxDistanceXZ(Vec3 pos1, BlockPos pos2) {
return Math.max(Math.abs(pos1.x - pos2.getX()), Math.abs(pos1.z - pos2.getZ()));
}
private static boolean shouldNotRender(Vec3 cameraPos, BlockPos pos, int maxDistance, Direction facing) {
final boolean playerFacingAway;
if (cameraPos == null || facing == null) {
playerFacingAway = false;
} else {
if (facing.getAxis() == Direction.Axis.X) {
final double playerXOffset = cameraPos.x - pos.getX() - 0.5;
playerFacingAway = Math.signum(playerXOffset) == facing.getStepX() && Math.abs(playerXOffset) >= 0.5;
} else {
final double playerZOffset = cameraPos.z - pos.getZ() - 0.5;
playerFacingAway = Math.signum(playerZOffset) == facing.getStepZ() && Math.abs(playerZOffset) >= 0.5;
}
}
return cameraPos == null || playerFacingAway || maxDistanceXZ(cameraPos, pos) > (MTRClient.isReplayMod() ? MAX_RADIUS_REPLAY_MOD : maxDistance);
}
private static void renderRailStandard(Level world, PoseStack matrices, MultiBufferSource vertexConsumers, Rail rail, float yOffset, boolean renderColors, float railWidth) {
renderRailStandard(world, matrices, vertexConsumers, rail, yOffset, renderColors, railWidth, renderColors && rail.railType == RailType.QUARTZ ? "mtr:textures/block/rail_preview.png" : "textures/block/rail.png", -1, -1, -1, -1);
}
private static void renderRailStandard(Level world, PoseStack matrices, MultiBufferSource vertexConsumers, Rail rail, float yOffset, boolean renderColors, float railWidth, String texture, float u1, float v1, float u2, float v2) {
final int maxRailDistance = Minecraft.getInstance().options.renderDistance * 16;
rail.render((x1, z1, x2, z2, x3, z3, x4, z4, y1, y2) -> {
final BlockPos pos2 = new BlockPos(x1, y1, z1);
if (shouldNotRender(pos2, maxRailDistance, null)) {
return;
}
final int light2 = LightTexture.pack(world.getBrightness(LightLayer.BLOCK, pos2), world.getBrightness(LightLayer.SKY, pos2));
if (rail.railType == RailType.NONE) {
if (rail.transportMode != TransportMode.CABLE_CAR && renderColors) {
final VertexConsumer vertexConsumerArrow = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new ResourceLocation("mtr:textures/block/one_way_rail_arrow.png")));
IDrawing.drawTexture(matrices, vertexConsumerArrow, (float) x1, (float) y1 + yOffset, (float) z1, (float) x2, (float) y1 + yOffset + SMALL_OFFSET, (float) z2, (float) x3, (float) y2 + yOffset, (float) z3, (float) x4, (float) y2 + yOffset + SMALL_OFFSET, (float) z4, 0, 0.25F, 1, 0.75F, Direction.UP, -1, light2);
IDrawing.drawTexture(matrices, vertexConsumerArrow, (float) x2, (float) y1 + yOffset + SMALL_OFFSET, (float) z2, (float) x1, (float) y1 + yOffset, (float) z1, (float) x4, (float) y2 + yOffset + SMALL_OFFSET, (float) z4, (float) x3, (float) y2 + yOffset, (float) z3, 0, 0.25F, 1, 0.75F, Direction.UP, -1, light2);
}
} else {
final float textureOffset = (((int) (x1 + z1)) % 4) * 0.25F + (float) Config.trackTextureOffset() / Config.TRACK_OFFSET_COUNT;
final int color = renderColors || !Config.hideSpecialRailColors() && rail.railType.hasSavedRail ? rail.railType.color : -1;
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new ResourceLocation(texture)));
IDrawing.drawTexture(matrices, vertexConsumer, (float) x1, (float) y1 + yOffset, (float) z1, (float) x2, (float) y1 + yOffset + SMALL_OFFSET, (float) z2, (float) x3, (float) y2 + yOffset, (float) z3, (float) x4, (float) y2 + yOffset + SMALL_OFFSET, (float) z4, u1 < 0 ? 0 : u1, v1 < 0 ? 0.1875F + textureOffset : v1, u2 < 0 ? 1 : u2, v2 < 0 ? 0.3125F + textureOffset : v2, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x2, (float) y1 + yOffset + SMALL_OFFSET, (float) z2, (float) x1, (float) y1 + yOffset, (float) z1, (float) x4, (float) y2 + yOffset + SMALL_OFFSET, (float) z4, (float) x3, (float) y2 + yOffset, (float) z3, u1 < 0 ? 0 : u1, v1 < 0 ? 0.1875F + textureOffset : v1, u2 < 0 ? 1 : u2, v2 < 0 ? 0.3125F + textureOffset : v2, Direction.UP, color, light2);
}
}, -railWidth, railWidth);
}
private static void renderSignalsStandard(Level world, PoseStack matrices, MultiBufferSource vertexConsumers, Rail rail, BlockPos startPos, BlockPos endPos) {
final int maxRailDistance = Minecraft.getInstance().options.renderDistance * 16;
final List<SignalBlocks.SignalBlock> signalBlocks = ClientData.SIGNAL_BLOCKS.getSignalBlocksAtTrack(PathData.getRailProduct(startPos, endPos));
final float width = 1F / DyeColor.values().length;
for (int i = 0; i < signalBlocks.size(); i++) {
final SignalBlocks.SignalBlock signalBlock = signalBlocks.get(i);
final boolean shouldGlow = signalBlock.isOccupied() && (((int) Math.floor(MTRClient.getGameTick())) % TICKS_PER_SECOND) < TICKS_PER_SECOND / 2;
final VertexConsumer vertexConsumer = shouldGlow ? vertexConsumers.getBuffer(MoreRenderLayers.getLight(new ResourceLocation("mtr:textures/block/white.png"), false)) : vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new ResourceLocation("textures/block/white_wool.png")));
final float u1 = width * i + 1 - width * signalBlocks.size() / 2;
final float u2 = u1 + width;
final int color = ARGB_BLACK | signalBlock.color.getMaterialColor().col;
rail.render((x1, z1, x2, z2, x3, z3, x4, z4, y1, y2) -> {
final BlockPos pos2 = new BlockPos(x1, y1, z1);
if (shouldNotRender(pos2, maxRailDistance, null)) {
return;
}
final int light2 = shouldGlow ? MAX_LIGHT_GLOWING : LightTexture.pack(world.getBrightness(LightLayer.BLOCK, pos2), world.getBrightness(LightLayer.SKY, pos2));
IDrawing.drawTexture(matrices, vertexConsumer, (float) x1, (float) y1, (float) z1, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x3, (float) y2, (float) z3, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, u1, 0, u2, 1, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, (float) x3, (float) y2, (float) z3, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x1, (float) y1, (float) z1, u1, 0, u2, 1, Direction.UP, color, light2);
}, u1 - 1, u2 - 1);
}
}
private static void renderWithLight(Level world, double x, double y, double z, boolean noOffset, RenderCallback renderCallback) {
final Entity camera = Minecraft.getInstance().cameraEntity;
final Vec3 cameraPos = camera == null ? null : camera.position();
final BlockPos posAverage = new BlockPos(x + (noOffset || cameraPos == null ? 0 : cameraPos.x), y + (noOffset || cameraPos == null ? 0 : cameraPos.y), z + (noOffset || cameraPos == null ? 0 : cameraPos.z));
if (!shouldNotRender(cameraPos, posAverage, Minecraft.getInstance().options.renderDistance * (Config.trainRenderDistanceRatio() + 1), null)) {
renderCallback.renderCallback(LightTexture.pack(world.getBrightness(LightLayer.BLOCK, posAverage), world.getBrightness(LightLayer.SKY, posAverage)), posAverage);
}
}
private static Component getStationText(Station station, String textKey) {
if (station != null) {
return new TextComponent(IGui.formatStationName(IGui.insertTranslation("gui.mtr." + textKey + "_station_cjk", "gui.mtr." + textKey + "_station", 1, IGui.textOrUntitled(station.name))));
} else {
return new TextComponent("");
}
}
private static void drawTexture(PoseStack matrices, VertexConsumer vertexConsumer, Vec3 pos1, Vec3 pos2, Vec3 pos3, Vec3 pos4, int light) {
IDrawing.drawTexture(matrices, vertexConsumer, (float) pos1.x, (float) pos1.y, (float) pos1.z, (float) pos2.x, (float) pos2.y, (float) pos2.z, (float) pos3.x, (float) pos3.y, (float) pos3.z, (float) pos4.x, (float) pos4.y, (float) pos4.z, 0, 0, 1, 1, Direction.UP, -1, light);
}
private static ResourceLocation resolveTexture(TrainClientRegistry.TrainProperties trainProperties, Function<String, String> formatter) {
final String textureString = formatter.apply(trainProperties.textureId);
final ResourceLocation id = new ResourceLocation(textureString);
final boolean available;
if (!AVAILABLE_TEXTURES.contains(textureString) && !UNAVAILABLE_TEXTURES.contains(textureString)) {
available = Minecraft.getInstance().getResourceManager().hasResource(id);
(available ? AVAILABLE_TEXTURES : UNAVAILABLE_TEXTURES).add(textureString);
if (!available) {
System.out.println("Texture " + textureString + " not found, using default");
}
} else {
available = AVAILABLE_TEXTURES.contains(textureString);
}
if (available) {
return id;
} else {
final String textureId = TrainClientRegistry.getTrainProperties(trainProperties.baseTrainType.toString(), trainProperties.baseTrainType).textureId;
return new ResourceLocation(textureId == null ? "mtr:textures/block/transparent.png" : formatter.apply(textureId));
}
}
private static ResourceLocation getConnectorTextureString(TrainClientRegistry.TrainProperties trainProperties, String connectorPart) {
return resolveTexture(trainProperties, textureId -> textureId + "_connector_" + connectorPart + ".png");
}
private static class FakeBoat extends Boat {
private float progress;
public FakeBoat() {
super(EntityType.BOAT, null);
}
@Override
public float getRowingTime(int paddle, float newProgress) {
progress += newProgress;
return progress;
}
}
@Deprecated // TODO remove
public static float getGameTicks() {
return MTRClient.getGameTick();
}
@FunctionalInterface
private interface RenderCallback {
void renderCallback(int light, BlockPos posAverage);
}
}
|
package com.bls.core.poi;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
// TODO add subcategory
/**
* Categories of Points of Interest
*/
@JsonInclude(Include.NON_EMPTY)
public enum Category {
PERSON("person"),
EVENT("event");
private final String name;
Category(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
|
package ua.com.fielden.platform.web.ioc;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Period;
import com.google.common.base.Charsets;
import com.google.inject.Inject;
import ua.com.fielden.platform.serialisation.api.ISerialiser;
import ua.com.fielden.platform.serialisation.api.SerialiserEngines;
import ua.com.fielden.platform.serialisation.api.impl.TgJackson;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.ResourceLoader;
import ua.com.fielden.platform.web.app.ISourceController;
import ua.com.fielden.platform.web.app.IWebUiConfig;
import ua.com.fielden.platform.web.factories.webui.ResourceFactoryUtils;
import ua.com.fielden.platform.web.resources.webui.FileResource;
/**
* {@link ISourceController} implementation.
*
* @author TG Team
*
*/
public class SourceControllerImpl implements ISourceController {
private static final String COMMENT_END = "
private static final int COMMENT_END_LENGTH = COMMENT_END.length();
private static final String COMMENT_START = "<!
private static final int COMMENT_START_LENGTH = COMMENT_START.length();
private static final String SGL_QUOTED_HREF = "href='";
private static final String DBL_QUOTED_HREF = "href=\"";
private static final int HREF_LENGTH = DBL_QUOTED_HREF.length();
private final IWebUiConfig webUiConfig;
private final ISerialiser serialiser;
private final TgJackson tgJackson;
private static final Logger logger = Logger.getLogger(SourceControllerImpl.class);
/**
* Root URIs, that will be preloaded ('/resources/application-startup-resources.html' defines them) during index.html loading.
*/
private final LinkedHashSet<String> preloadedResources;
/**
* All URIs (including derived ones), that will be preloaded ('/resources/application-startup-resources.html' defines them) during index.html loading.
*/
private final LinkedHashSet<String> allPreloadedResources;
private boolean deploymentMode;
@Inject
public SourceControllerImpl(final IWebUiConfig webUiConfig, final ISerialiser serialiser) {
this.webUiConfig = webUiConfig;
this.serialiser = serialiser;
this.tgJackson = (TgJackson) serialiser.getEngine(SerialiserEngines.JACKSON);
final String startupResources = getSource("/resources/startup-resources.html");
final String startupResourcesOrigin = getSource("/resources/startup-resources-origin.html");
this.deploymentMode = !EntityUtils.equalsEx(startupResources, startupResourcesOrigin);
logger.info(String.format("\t[%s MODE]", this.deploymentMode ? "DEPLOYMENT" : "DEVELOPMENT"));
final LinkedHashSet<String> result = getRootDependenciesFor("/resources/application-startup-resources.html");
if (result == null) {
throw new IllegalStateException("The [/resources/application-startup-resources.html] resource should exist. It is crucial for startup loading of app-specific resources.");
}
this.preloadedResources = result;
if (this.deploymentMode) {
this.allPreloadedResources = calculatePreloadedResources();
} else {
this.allPreloadedResources = null;
}
}
/**
* Returns <code>true</code> in case where the server is in deployment mode, <code>false</code> -- in development mode.
* <p>
* At this stage deployment mode is activated in the case, where /resources/startup-resources.html and /resources/startup-resources-origin.html are different (which means that potentially /resources/startup-resources.html is vulcanized
* version of /resources/startup-resources-origin.html or just changed intentionally to activate the deployment mode for testing purposes).
*
* After the first heavy comparison has been performed -- the flag is cached.
*
* @return
*/
@Override
public boolean isDeploymentMode() {
return deploymentMode;
}
@Override
public void setDeploymentMode(final boolean deploymentMode) {
this.deploymentMode = deploymentMode;
}
/**
* Reads the source and extracts the list of top-level (root) dependency URIs.
*
* @param source
* @return
*/
private static LinkedHashSet<String> getRootDependencies(final String source, final LinkedHashSet<String> currentRootDependencies) {
final int commentStart = source.indexOf(COMMENT_START);
// TODO enhance the logic to support whitespaces etc.?
final int doubleQuotedStart = source.indexOf(DBL_QUOTED_HREF);
final int singleQuotedStart = source.indexOf(SGL_QUOTED_HREF);
final boolean doubleQuotedPresent = doubleQuotedStart >= 0;
final boolean singleQuotedPresent = singleQuotedStart >= 0;
if (doubleQuotedPresent || singleQuotedPresent) {
final boolean bothTypesPresent = doubleQuotedPresent && singleQuotedPresent;
final boolean doubleQuoted = bothTypesPresent ? (doubleQuotedStart < singleQuotedStart) : doubleQuotedPresent;
final int start = doubleQuoted ? doubleQuotedStart : singleQuotedStart;
if (commentStart >= 0) {
if (commentStart < start) {
// remove comment and process the rest of source
final String temp = source.substring(commentStart + COMMENT_START_LENGTH);
final int indexOfUncommentedPart = temp.indexOf(COMMENT_END);
final String sourceWithoutComment = temp.substring(indexOfUncommentedPart + COMMENT_END_LENGTH);
return getRootDependencies(sourceWithoutComment, currentRootDependencies);
} else {
return rootDependencies0(source, currentRootDependencies, start, doubleQuoted);
}
} else {
return rootDependencies0(source, currentRootDependencies, start, doubleQuoted);
}
} else {
return currentRootDependencies;
}
}
private static LinkedHashSet<String> rootDependencies0(final String source, final LinkedHashSet<String> currentRootDependencies, final int start, final boolean doubleQuote) {
// process the rest of source
final int startOfURI = start + HREF_LENGTH;
final String nextCurr = source.substring(startOfURI);
final int endOfURIIndex = doubleQuote ? nextCurr.indexOf("\"") : nextCurr.indexOf("'");
final String importURI = nextCurr.substring(0, endOfURIIndex);
final LinkedHashSet<String> set = new LinkedHashSet<String>(currentRootDependencies);
set.add(importURI);
return getRootDependencies(nextCurr.substring(endOfURIIndex), set);
}
/**
* Returns app-specific preloaded resources.
*
* @return
*/
private LinkedHashSet<String> getApplicationStartupRootDependencies() {
return preloadedResources;
}
/**
* Returns dependent resources URIs for the specified resource's 'resourceURI'.
*
* @return
*/
private LinkedHashSet<String> getRootDependenciesFor(final String resourceURI) {
if (resourceURI.startsWith("/resources/polymer/")) {
// no need to analyze polymer sources!
return new LinkedHashSet<String>();
} else {
final String source = getSource(resourceURI);
if (source == null) {
return null;
} else {
final LinkedHashSet<String> dependentResourceURIs = getRootDependencies(source, new LinkedHashSet<String>());
logger.debug("[" + resourceURI + "]: " + dependentResourceURIs);
return dependentResourceURIs;
}
}
}
/**
* Returns dependent resources URIs including transitive.
*
* @return
*/
private LinkedHashSet<String> getAllDependenciesFor(final String resourceURI) {
final LinkedHashSet<String> roots = getRootDependenciesFor(resourceURI);
if (roots == null) {
return null;
} else {
final LinkedHashSet<String> all = new LinkedHashSet<>();
for (final String root : roots) {
final LinkedHashSet<String> rootDependencies = getAllDependenciesFor(root);
if (rootDependencies != null) {
all.add(root);
all.addAll(rootDependencies);
} else {
// System.out.println("disregarded dependencies of unknown resource [" + root + "]");
}
}
return all;
}
}
@Override
public String loadSource(final String resourceURI) {
final String source = getSource(resourceURI);
return enhanceSource(source, resourceURI);
}
@Override
public String loadSourceWithFilePath(final String filePath) {
final String source = getFileSource(filePath);
return enhanceSource(source, filePath);
}
@Override
public InputStream loadStreamWithFilePath(final String filePath) {
return ResourceLoader.getStream(filePath);
}
private String enhanceSource(final String source, final String path) {
// There is a try to get the resource.
// If this is the deployment mode -- need to calculate all preloaded resources (if not calculated yet)
// and then exclude all preloaded resources from the requested resource file.
// If this is the development mode -- do nothing (no need to calculate all preloaded resources).
if (!isDeploymentMode()) {
return source;
} else {
// System.out.println("SOURCE [" + path + "]: " + source);
final String sourceWithoutPreloadedDependencies = removePrealodedDependencies(source);
// System.out.println("SOURCE WITHOUT PRELOADED [" + path + "]: " + sourceWithoutPreloadedDependencies);
return sourceWithoutPreloadedDependencies;
}
}
/**
* Removes preloaded dependencies from source.
*
* @param source
*
* @return
*/
private String removePrealodedDependencies(final String source) {
String result = source;
for (final String preloaded : allPreloadedResources) {
result = removePrealodedDependency(result, preloaded);
}
return result;
}
/**
* Removes preloaded dependency from source.
*
* @param source
* @param dependency
*
* @return
*/
private String removePrealodedDependency(final String source, final String dependency) {
// TODO VERY FRAGILE APPROACH!
// TODO VERY FRAGILE APPROACH!
// TODO VERY FRAGILE APPROACH! please, provide better implementation (whitespaces, exchanged rel and href, etc.?):
return source.replaceAll("<link rel=\"import\" href=\"" + dependency + "\">", "")
.replaceAll("<link rel='import' href='" + dependency + "'>", "");
}
private LinkedHashSet<String> calculatePreloadedResources() {
logger.info("======== Calculating preloaded resources... ========");
final DateTime start = new DateTime();
final LinkedHashSet<String> all = getAllDependenciesFor("/resources/startup-resources-origin.html");
logger.info("\t ==> " + all + ".");
final Period pd = new Period(start, new DateTime());
logger.info("
return all;
}
private String getSource(final String resourceURI) {
if ("/app/tg-app-config.html".equalsIgnoreCase(resourceURI)) {
return getTgAppConfigSource(webUiConfig);
} else if ("/app/tg-app.html".equalsIgnoreCase(resourceURI)) {
return getTgAppSource(webUiConfig);
} else if ("/app/tg-reflector.html".equalsIgnoreCase(resourceURI)) {
return getReflectorSource(serialiser, tgJackson);
} else if ("/app/tg-element-loader.html".equalsIgnoreCase(resourceURI)) {
return getElementLoaderSource(this, webUiConfig);
} else if (resourceURI.startsWith("/master_ui")) {
return getMasterSource(resourceURI.replaceFirst("/master_ui/", ""), webUiConfig);
} else if (resourceURI.startsWith("/centre_ui")) {
return getCentreSource(resourceURI.replaceFirst("/centre_ui/", ""), webUiConfig);
} else if (resourceURI.startsWith("/resources/")) {
return getFileSource(resourceURI, webUiConfig.resourcePaths());
} else {
logger.error("The URI is not known: [" + resourceURI + "].");
return null;
}
}
private static String getTgAppConfigSource(final IWebUiConfig app) {
return app.genWebUiPreferences();
}
private static String getTgAppSource(final IWebUiConfig app) {
return app.genMainWebUIComponent();
}
private static String getReflectorSource(final ISerialiser serialiser, final TgJackson tgJackson) {
final String typeTableRepresentation = new String(serialiser.serialise(tgJackson.getTypeTable(), SerialiserEngines.JACKSON), Charsets.UTF_8);
final String originalSource = ResourceLoader.getText("ua/com/fielden/platform/web/reflection/tg-reflector.html");
return originalSource.replace("@typeTable", typeTableRepresentation);
}
private static String getElementLoaderSource(final SourceControllerImpl sourceControllerImpl, final IWebUiConfig webUiConfig) {
final String source = getFileSource("/resources/element_loader/tg-element-loader.html", webUiConfig.resourcePaths());
return source.replace("importedURLs = {}", generateImportUrlsFrom(sourceControllerImpl.getApplicationStartupRootDependencies()));
}
/**
* Generates the string of tg-element-loader's 'importedURLs' from 'appSpecificPreloadedResources'.
*
* @param appSpecificPreloadedResources
* @return
*/
private static String generateImportUrlsFrom(final LinkedHashSet<String> appSpecificPreloadedResources) {
final String prepender = "importedURLs = {";
final StringBuilder sb = new StringBuilder("");
final Iterator<String> iter = appSpecificPreloadedResources.iterator();
while (iter.hasNext()) {
final String next = iter.next();
sb.append(",'" + next + "': 'imported'");
}
final String res = sb.toString();
return prepender + (StringUtils.isEmpty(res) ? "" : res.substring(1)) + "}";
}
private static String getMasterSource(final String entityTypeString, final IWebUiConfig webUiConfig) {
return ResourceFactoryUtils.getEntityMaster(entityTypeString, webUiConfig).build().render().toString();
}
private static String getCentreSource(final String mitypeString, final IWebUiConfig webUiConfig) {
return ResourceFactoryUtils.getEntityCentre(mitypeString, webUiConfig).build().render().toString();
}
////////////////////////////////// Getting file source //////////////////////////////////
private static String getFileSource(final String resourceURI, final List<String> resourcePaths) {
final String rest = resourceURI.replaceFirst("/resources/", "");
final int lastDotIndex = rest.lastIndexOf(".");
final String originalPath = rest.substring(0);
final String extension = rest.substring(lastDotIndex + 1);
return getFileSource(originalPath, extension, resourcePaths);
}
private static String getFileSource(final String originalPath, final String extension, final List<String> resourcePaths) {
final String filePath = FileResource.generateFileName(resourcePaths, originalPath);
if (StringUtils.isEmpty(filePath)) {
System.out.println("The requested resource (" + originalPath + " + " + extension + ") wasn't found.");
return null;
} else {
return getFileSource(filePath);
}
}
private static String getFileSource(final String filePath) {
return ResourceLoader.getText(filePath);
}
}
|
package szoftlab4;
public class Map {
/**
* @return Lehet-e a vector helyre Obstacle-t pteni.
*/
public boolean canBuildObstacle(Vector v){
boolean b;
printEnter(this, "vector");
b = printYesNoQuestion("Lehet pteni akadlyt?");
printExit(this);
return b;
}
/**
* @return Lehet-e a vector helyre Tower-t pteni.
*/
public boolean canBuildTower(Vector v){
boolean b;
printEnter(this, "vector");
b = printYesNoQuestion("Lehet pteni akadlyt?");
printExit(this);
return b;
}
}
|
package org.radargun.cachewrappers;
import org.infinispan.Cache;
import org.infinispan.context.Flag;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.remoting.rpc.RpcManager;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.radargun.utils.TypedProperties;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* InfinispanWrapper that queries all the caches defined in the configuration on round robin basis.
*
* @author Ondrej Nevelik <onevelik@redhat.com>
*/
public class InfinispanMultiCacheWrapper extends InfinispanKillableWrapper {
private Map<Integer, Cache<Object, Object>> caches = null;
private static Log log = LogFactory.getLog(InfinispanMultiCacheWrapper.class);
@Override
protected void setUpCache(TypedProperties confAttributes, int nodeIndex) throws Exception {
String configFile = getConfigFile(confAttributes);
cacheManager = new DefaultCacheManager(configFile);
Set<String> cacheNames = cacheManager.getCacheNames();
log.trace("Using config file: " + configFile + " and " + cacheNames.size()
+ " caches defined in it");
int i = 0;
caches = new HashMap<Integer, Cache<Object, Object>>(cacheNames.size());
for (String aCache : cacheNames) {
log.trace(i + " adding cache: " + aCache);
caches.put(i++, cacheManager.getCache(aCache));
}
}
@Override
protected void waitForRehash(TypedProperties confAttributes) throws InterruptedException {
for (Cache<Object, Object> cache : caches.values()) {
blockForRehashing(cache);
injectEvenConsistentHash(cache, confAttributes);
}
}
@Override
public void empty() throws Exception {
for (Cache<Object, Object> aCache : caches.values()) {
empty(aCache);
}
}
private void empty(Cache<Object, Object> cache) {
RpcManager rpcManager = cache.getAdvancedCache().getRpcManager();
int clusterSize = 0;
if (rpcManager != null) {
clusterSize = rpcManager.getTransport().getMembers().size();
}
// use keySet().size() rather than size directly as cache.size might not
// be reliable
log.info("Size of cache " + cache.getName() + " before clear (cluster size= " + clusterSize
+ ")" + cache.keySet().size());
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
log.info("Size of cache " + cache.getName() + " after clear: " + cache.keySet().size());
}
/**
* multiCache test breaks the contract of super.getInfo() method used by bin/dist.sh script!
*/
@Override
public String getInfo() {
return "Running multi cache test!";
}
@Override
public int getLocalSize() {
int size = 0;
for (Cache<Object, Object> aCache : caches.values()) {
size += aCache.keySet().size();
}
return size;
}
@Override
public int getTotalSize() {
int size = 0;
for (Cache<Object, Object> aCache : caches.values()) {
size += aCache.size();
}
return size;
}
@Override
public Cache<Object, Object> getCache(String bucket) {
if (bucket == null) return caches.get(0);
return caches.get(getThreadIdFromBucket(bucket));
}
@Override
public int getNumMembers() {
ComponentRegistry componentRegistry = caches.get(0).getAdvancedCache().getComponentRegistry();
if (componentRegistry.getStatus().startingUp()) {
log.trace("We're in the process of starting up.");
}
if (cacheManager.getMembers() != null) {
log.trace("Members are: " + cacheManager.getMembers());
}
return cacheManager.getMembers() == null ? 0 : cacheManager.getMembers().size();
}
/**
* Following the contract in PutGetSterssor that a bucket for distributed benchmark is in the
* form of: nodeIndex + "_" + threadIndex;
*
* @param bucket
* string to parse the threadIndex from
* @return
*/
private int getThreadIdFromBucket(String bucket) {
if (!bucket.contains("_")) {
return 0;
}
String[] parts = bucket.split("_");
if (parts.length != 2) {
throw new IllegalArgumentException(
"There should be two parts when parsing thread id from bucket string: " + bucket);
}
return Integer.parseInt(parts[1]);
}
}
|
package taskDo;
import commandFactory.CommandType;
public class Parser {
private static final int PARAM_STARTING_INDEX = 1;
enum OptionalCommand {
DUE, FROM, TO, CATEGORY, IMPT, INVALID
}
public static void parserInit() {
}
public static void parseString(String input) {
resetParsedResult();
String commandWord = getCommandWord(input);
CommandType command = identifyCommand(commandWord.toLowerCase());
String remainingInput = removeCommandWord(input, command);
String commandParam = getParam(remainingInput);
remainingInput = removeParam(remainingInput);
updateParsedResult(command,commandParam);
while(remainingInput.isEmpty() == false) {
remainingInput = identifyOptionalCommandAndUpdate(remainingInput);
}
System.out.println(commandWord);
System.out.println(commandParam);
System.out.println(remainingInput);
}
private static String identifyOptionalCommandAndUpdate(String remainingInput) {
String commandWord = getCommandWord(remainingInput);
OptionalCommand command = identifyOptionalCommand(commandWord.toLowerCase());
remainingInput = removeOptionalCommand(remainingInput, command);
String commandParam = getParam(remainingInput);
optionsUpdateParsedResult(command,commandParam);
remainingInput = removeParam(remainingInput);
return remainingInput;
}
private static void optionsUpdateParsedResult(OptionalCommand command,
String commandParam) {
switch(command) {
case DUE:
//do sth
break;
case FROM:
//do sth
break;
case TO:
//do sth
break;
case CATEGORY:
//do sth
break;
case INVALID:
//do sth
break;
default:// do nothing
}
}
private static String removeOptionalCommand(String remainingInput,
OptionalCommand commandWord) {
switch(commandWord) {
case DUE:
return remainingInput.substring(4); //Length of word "due "
case FROM:
return remainingInput.substring(5);
case TO:
return remainingInput.substring(3);
case IMPT:
return remainingInput.substring(5);
case INVALID:
return "INVALID!";
default:
return "";
}
}
private static OptionalCommand identifyOptionalCommand(String commandWord) {
switch(commandWord) {
case "due":
return OptionalCommand.DUE;
case "from":
return OptionalCommand.FROM;
case "to":
return OptionalCommand.TO;
case "category":
return OptionalCommand.CATEGORY;
case "impt":
return OptionalCommand.IMPT;
default:
return OptionalCommand.INVALID;
}
}
private static void updateParsedResult(CommandType command,
String commandParam) {
ParsedResult.setCommandType(command);
Task task = ParsedResult.getTaskDetails();
task.setDescription(commandParam);
//Need to set endDueDate with some constant(No deadline)
}
private static void resetParsedResult() {
ParsedResult.clear();
}
private static String removeParam(String remainingInput) {
int indexEndOfParam = remainingInput.indexOf(']');
//Adjust index to take substring after ']'
indexEndOfParam++;
remainingInput = remainingInput.substring(indexEndOfParam);
return remainingInput.trim();
}
private static String getCommandWord(String input) {
String[] splittedCommand = input.split(" ");
return splittedCommand[0];
}
private static CommandType identifyCommand(String command) {
switch (command) {
case "add":
return CommandType.ADD;
case "display":
return CommandType.DISPLAY;
case "delete":
return CommandType.DELETE;
case "edit":
return CommandType.EDIT;
case "undo":
return CommandType.UNDO;
case "search":
return CommandType.SEARCH;
//not sure if I need init and save to be here
default:
return CommandType.INVALID;
}
}
private static String removeCommandWord(String input,
CommandType commandWord) {
switch (commandWord) {
case ADD:
return input.substring(4); //4 is length of word "add "
case DISPLAY:
return input.substring(8); //8 is length of word "display "
case DELETE:
return input.substring(7); //7 is length of word "delete "
case SEARCH:
return input.substring(7); //7 is length of word "search "
case EDIT:
return input.substring(5);
case INVALID:
return "INVALID!";
default:
return "";
}
}
private static String getParam(String remainingInput) {
int indexEndOfParam = remainingInput.indexOf(']');
remainingInput = remainingInput.substring(PARAM_STARTING_INDEX, indexEndOfParam);
return remainingInput.trim();
}
}
|
package wge3.game.entity.creatures;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Circle;
import static com.badlogic.gdx.math.Intersector.overlaps;
import com.badlogic.gdx.math.MathUtils;
import static com.badlogic.gdx.math.MathUtils.PI;
import static com.badlogic.gdx.math.MathUtils.PI2;
import static com.badlogic.gdx.math.MathUtils.radiansToDegrees;
import static com.badlogic.gdx.math.MathUtils.random;
import com.badlogic.gdx.math.Vector2;
import static com.badlogic.gdx.utils.TimeUtils.millis;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static wge3.game.engine.constants.Direction.*;
import wge3.game.engine.constants.StateFlag;
import wge3.game.engine.constants.Statistic;
import wge3.game.engine.constants.Team;
import static wge3.game.engine.gamestates.PlayState.mStream;
import wge3.game.engine.gui.Drawable;
import static wge3.game.engine.utilities.Math.floatPosToTilePos;
import static wge3.game.engine.utilities.Math.getDiff;
import wge3.game.engine.utilities.StatIndicator;
import wge3.game.engine.utilities.Statistics;
import static wge3.game.engine.utilities.pathfinding.PathFinder.findPath;
import wge3.game.entity.Area;
import wge3.game.entity.Tile;
import wge3.game.entity.creatures.utilities.Inventory;
import wge3.game.entity.tilelayers.grounds.OneWayFloor;
import wge3.game.entity.tilelayers.mapobjects.Item;
import wge3.game.entity.tilelayers.mapobjects.Teleport;
public abstract class Creature implements Drawable {
protected Area area;
protected Statistics statistics;
protected int previousTileX;
protected int previousTileY;
protected Circle bounds;
protected Team team;
protected int size;
protected int defaultSpeed;
protected int currentSpeed;
protected float walkToRunMultiplier;
protected float direction;
protected float turningSpeed;
protected int sight;
protected float FOV;
protected String name;
protected StatIndicator HP;
protected StatIndicator energy;
protected int strength;
protected int defense;
protected int unarmedAttackSize; // radius
// Regen rates: the amount of milliseconds between regenerating 1 unit.
protected int HPRegenRate;
protected int energyRegenRate;
protected int energyConsumptionRate;
protected long lastHPRegen;
protected long lastEnergyRegen;
protected long lastEnergyConsumption;
protected Inventory inventory;
protected Item selectedItem;
protected Texture texture;
protected Sprite sprite;
protected Set<StateFlag> stateFlags;
public Creature() {
texture = new Texture(Gdx.files.internal("graphics/graphics.png"));
size = Tile.size / 3;
defaultSpeed = 75;
currentSpeed = defaultSpeed;
walkToRunMultiplier = 1.35f;
direction = random() * PI2;
turningSpeed = 4;
sight = 12;
FOV = PI;
unarmedAttackSize = Tile.size/2;
HP = new StatIndicator();
energy = new StatIndicator(100);
HPRegenRate = 1000;
lastHPRegen = millis();
lastEnergyRegen = millis();
lastEnergyConsumption = millis();
energyRegenRate = 500;
energyConsumptionRate = 80;
bounds = new Circle(new Vector2(), size);
inventory = new Inventory(this);
selectedItem = null;
stateFlags = EnumSet.noneOf(StateFlag.class);
}
public float getX() {
return bounds.x;
}
public void setX(float x) {
bounds.setX(x);
updateSpritePosition();
}
public float getY() {
return bounds.y;
}
public void setY(float y) {
bounds.setY(y);
updateSpritePosition();
}
public void setPosition(float x, float y) {
bounds.setPosition(x, y);
updateSpritePosition();
}
public void setPosition(int x, int y) {
bounds.setPosition(x * Tile.size + Tile.size/2, y * Tile.size + Tile.size/2);
updateSpritePosition();
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public int getDefaultSpeed() {
return defaultSpeed;
}
public void setDefaultSpeed(int defaultSpeed) {
this.defaultSpeed = defaultSpeed;
}
public void setCurrentSpeed(int speed) {
this.currentSpeed = speed;
}
public float getDirection() {
return direction;
}
public float getTurningSpeed() {
return turningSpeed;
}
public void setTurningSpeed(float turningSpeed) {
this.turningSpeed = turningSpeed;
}
public int getMaxHP() {
return HP.getMaximum();
}
public void setMaxHP(int newMaxHP) {
HP.setMaximum(newMaxHP);
}
public int getEnergy() {
return energy.getCurrent();
}
public int getMaxEnergy() {
return energy.getMaximum();
}
public int getHP() {
return HP.getCurrent();
}
public void setHP(int newHP) {
HP.setCurrent(newHP);
}
public int getSize() {
return size;
}
public int getCurrentSpeed() {
return currentSpeed;
}
public Inventory getInventory() {
return inventory;
}
@Override
public void draw(Batch batch) {
sprite.draw(batch);
}
public void turnLeft(float delta) {
direction += turningSpeed * delta;
if (direction >= PI2) direction -= PI2;
updateSpriteRotation();
}
public void turnRight(float delta) {
direction -= turningSpeed * delta;
if (direction < 0) direction += PI2;
updateSpriteRotation();
}
public void move(float dx, float dy) {
// Apply movement modifiers:
if (!isGhost()) {
float movementModifier = area.getTileAt(getX(), getY()).getMovementModifier();
dx *= movementModifier;
dy *= movementModifier;
}
if (isRunning()) {
long currentTime = millis();
boolean consumeOrTakeDamage = currentTime - lastEnergyConsumption > energyConsumptionRate;
if (canRun()) {
dx *= walkToRunMultiplier;
dy *= walkToRunMultiplier;
if (consumeOrTakeDamage) {
consumeEnergy();
lastEnergyConsumption = currentTime;
}
} else {
dx *= walkToRunMultiplier * HP.getFraction();
dy *= walkToRunMultiplier * HP.getFraction();
if (consumeOrTakeDamage) {
this.dealDamage(1);
lastEnergyConsumption = currentTime;
}
}
}
// Calculate actual movement:
float destX = getX() + dx;
float destY = getY() + dy;
if (canMoveTo(destX, destY)) {
setX(destX);
setY(destY);
} else if (canMoveTo(getX(), destY)) {
setY(destY);
} else if (canMoveTo(destX, getY())) {
setX(destX);
}
// These could be optimized to be checked less than FPS times per second:
if (hasMovedToANewTile()) {
if (getTile().hasTeleport() && !getPreviousTile().hasTeleport()) {
Teleport tele = (Teleport) getTile().getObject();
tele.teleport(this);
}
previousTileX = getTileX();
previousTileY = getTileY();
if (picksUpItems()) pickUpItems();
}
}
public boolean hasMovedToANewTile() {
return getTileX() != previousTileX
|| getTileY() != previousTileY;
}
public void pickUpItems() {
Tile currentTile = getTile();
if (currentTile.hasItem()) {
inventory.addItem((Item) currentTile.getObject());
currentTile.removeObject();
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.ITEMSPICKEDUP, 1);
}
}
}
public boolean canMoveTo(float x, float y) {
if (!area.hasLocation(x, y)) {
return false;
}
if (this.isGhost()) {
return true;
}
Tile destination = area.getTileAt(x, y);
if (this.isFlying()) {
return destination.isPassable();
}
if (destination.isOneWay()) {
OneWayFloor oneWayTile = (OneWayFloor) destination.getGround();
if (oneWayTile.getDirection() == LEFT && x - getX() > 0) {
return false;
}
if (oneWayTile.getDirection() == RIGHT && x - getX() < 0) {
return false;
}
if (oneWayTile.getDirection() == UP && y - getY() < 0) {
return false;
}
if (oneWayTile.getDirection() == DOWN && y - getY() > 0) {
return false;
}
}
if (collisionDetected(x, y)) {
return false;
}
if (!this.isOnPassableObject()) {
return true;
}
return (destination.isPassable());
}
public boolean canMoveTo(Tile dest) {
return findPath(this.getTile(), dest) != null;
}
public void useItem() {
if (this.isInvisible()) {
if (!selectedItem.isPotion()) {
this.setInvisibility(false);
}
}
if (selectedItem == null) attackUnarmed();
else {
selectedItem.use(this);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.ITEMSUSED, 1);
}
}
}
public void changeItem() {
setSelectedItem(inventory.getNextItem());
}
public void setSelectedItem(Item selectedItem) {
this.selectedItem = selectedItem;
}
public Item getSelectedItem() {
return selectedItem;
}
public int getSight() {
return sight;
}
public float getFOV() {
return FOV;
}
public boolean seesEverything() {
return stateFlags.contains(StateFlag.SEES_EVERYTHING);
}
public void toggleSeeEverything() {
if (stateFlags.contains(StateFlag.SEES_EVERYTHING))
stateFlags.remove(StateFlag.SEES_EVERYTHING);
else
stateFlags.add(StateFlag.SEES_EVERYTHING);
}
public boolean isGhost() {
return stateFlags.contains(StateFlag.IS_GHOST);
}
public void toggleGhostMode() {
if (stateFlags.contains(StateFlag.IS_GHOST)) {
stateFlags.remove(StateFlag.IS_GHOST);
mStream.addMessage("Ghost Mode Off");
}
else {
stateFlags.add(StateFlag.IS_GHOST);
mStream.addMessage("Ghost Mode On");
}
}
public boolean isInCenterOfATile() {
float x = (getX() % Tile.size) / Tile.size;
float y = (getY() % Tile.size) / Tile.size;
return (x >= 0.25f && x < 0.75f) && (y >= 0.25f && y < 0.75f);
}
public void dealDamage(int amount) {
int decreaseAmount = max(amount - defense, 1);
HP.decrease(decreaseAmount);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.DAMAGETAKEN, decreaseAmount);
}
}
public boolean isDead() {
return HP.isEmpty();
}
public void regenerate(long currentTime) {
if (currentTime - lastHPRegen > HPRegenRate) {
regenerateHP();
lastHPRegen = currentTime;
}
if (!isRunning() && currentTime - lastEnergyRegen > energyRegenRate) {
regenerateEnergy();
lastEnergyRegen = currentTime;
}
}
public void regenerateEnergy() {
energy.increase();
}
public void regenerateHP() {
HP.increase();
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.HEALTHREGAINED, 1);
}
}
public void updateSpritePosition() {
sprite.setPosition(getX() - Tile.size/2, getY() - Tile.size/2);
}
public void updateSpriteRotation() {
sprite.setRotation(direction * radiansToDegrees);
}
public void attackUnarmed() {
float destX = getX() + MathUtils.cos(direction) * Tile.size;
float destY = getY() + MathUtils.sin(direction) * Tile.size;
Circle dest = new Circle(destX, destY, getUnarmedAttackSize());
for (Creature creature : area.getCreatures()) {
if (dest.contains(creature.getX(), creature.getY())) {
if (creature.getTeam() != getTeam()) {
creature.dealDamage(strength);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.DAMAGEDEALT, strength);
}
}
}
}
area.getTileAt(destX, destY).dealDamage(this.strength);
}
public boolean isPlayer() {
return this.getClass() == Player.class;
}
public void doMovement(float delta) {
if (isGoingForward()) {
stopGoingForward();
float dx = MathUtils.cos(direction) * currentSpeed * delta;
float dy = MathUtils.sin(direction) * currentSpeed * delta;
move(dx, dy);
} else if (isGoingBackward()) {
stopGoingBackward();
float dx = -(MathUtils.cos(direction) * currentSpeed/1.5f * delta);
float dy = -(MathUtils.sin(direction) * currentSpeed/1.5f * delta);
move(dx, dy);
}
if (isTurningLeft()) {
stopTurningLeft();
turnLeft(delta);
} else if (isTurningRight()) {
stopTurningRight();
turnRight(delta);
}
}
public boolean isGoingForward() {
return stateFlags.contains(StateFlag.GOING_FORWARD);
}
public void goForward() {
stateFlags.add(StateFlag.GOING_FORWARD);
}
public void stopGoingForward() {
stateFlags.remove(StateFlag.GOING_FORWARD);
}
public boolean isGoingBackward() {
return stateFlags.contains(StateFlag.GOING_BACKWARD);
}
public void goBackward() {
stateFlags.add(StateFlag.GOING_BACKWARD);
}
public void stopGoingBackward() {
stateFlags.remove(StateFlag.GOING_BACKWARD);
}
public boolean isTurningLeft() {
return stateFlags.contains(StateFlag.TURNING_LEFT);
}
public void turnLeft() {
stateFlags.add(StateFlag.TURNING_LEFT);
}
public void stopTurningLeft() {
stateFlags.remove(StateFlag.TURNING_LEFT);
}
public boolean isTurningRight() {
return stateFlags.contains(StateFlag.TURNING_RIGHT);
}
public void turnRight() {
stateFlags.add(StateFlag.TURNING_RIGHT);
}
public void stopTurningRight() {
stateFlags.remove(StateFlag.TURNING_RIGHT);
}
public boolean canBeSeenBy(Creature creature) {
return getTile().canBeSeenBy(creature) && !this.isInvisible();
}
public boolean canSee(int x, int y) {
if (!getArea().hasLocation(x/Tile.size, y/Tile.size)) {
throw new IllegalArgumentException("Not a valid location!");
}
if (getDistanceTo(x, y) > sight * Tile.size) return false;
for (Tile tile : area.getTilesOnLine(getX(), getY(), x, y)) {
if (tile.blocksVision()) {
return false;
}
}
return true;
}
public void setLighting(Color color) {
sprite.setColor(color);
}
public Tile getTile() {
return area.getTileAt(getX(), getY());
}
public Tile getPreviousTile() {
return area.getTileAt(previousTileX, previousTileY);
}
public Team getTeam() {
return team;
}
public List<Tile> getPossibleMovementDestinations() {
List<Tile> tiles = new ArrayList<Tile>();
for (Tile tile : area.getTiles()) {
if (tile.canBeSeenBy(this) && tile.isAnOKMoveDestinationFor(this)) tiles.add(tile);
}
return tiles;
}
public Tile getNewMovementDestination() {
// Returns a random tile from all the tiles that are
// ok move destinations and can be seen by creature.
List<Tile> tiles = getPossibleMovementDestinations();
return tiles.get(random(tiles.size() - 1));
}
public String getName() {
return name;
}
public int getUnarmedAttackSize() {
return unarmedAttackSize;
}
public boolean isEnemyOf(Creature other) {
return this.getTeam() != other.getTeam();
}
public boolean picksUpItems() {
return stateFlags.contains(StateFlag.PICKS_UP_ITEMS);
}
//SORT THIS, make comparator
public List<Creature> getEnemiesWithinFOV() {
List<Creature> enemiesWithinFOV = new ArrayList<Creature>();
for (Creature creature : getArea().getCreatures()) {
if (creature.isEnemyOf(this) && creature.canBeSeenBy(this)) {
enemiesWithinFOV.add(creature);
}
}
return enemiesWithinFOV;
}
public List<Creature> getFriendliesWithinFOV() {
List<Creature> friendlies = new ArrayList<Creature>();
for (Creature creature : getArea().getCreatures()) {
if (!creature.isEnemyOf(this) && creature.canBeSeenBy(this)) {
friendlies.add(creature);
}
}
return friendlies;
}
public void addHP(int amount) {
HP.increase(amount);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.HEALTHREGAINED, amount);
}
}
public void addEnergy(int amount) {
energy.increase(amount);
}
public float getDistanceTo(float x, float y) {
float dx = x - getX();
float dy = y - getY();
return (float) Math.sqrt(dx*dx + dy*dy);
}
public float getDistance2To(float x, float y) {
float dx = x - getX();
float dy = y - getY();
return (dx * dx) + (dy * dy);
}
public float getDistanceInTilesTo(float x, float y) {
return getDistanceTo(x, y) / Tile.size;
}
public float getDistance2InTilesTo(float x, float y) {
return getDistance2To(x, y) / Tile.size;
}
public float getDistanceTo(Creature other) {
return getDistanceTo(other.getX(), other.getY());
}
public float getDistance2To(Creature other) {
return getDistance2To(other.getX(), other.getY());
}
public float getDistanceTo(Tile tile) {
// Returns distance to middle point of tile
return getDistanceInTilesTo(tile.getMiddleX(), tile.getMiddleY());
}
public float getDistance2To(Tile tile) {
// Returns squared distance to middle point of tile
return getDistance2InTilesTo(tile.getMiddleX(), tile.getMiddleY());
}
public void startRunning() {
stateFlags.add(StateFlag.IS_RUNNING);
}
public void stopRunning() {
stateFlags.remove(StateFlag.IS_RUNNING);
}
public boolean isRunning() {
return stateFlags.contains(StateFlag.IS_RUNNING);
}
public void consumeEnergy() {
energy.decrease();
}
public boolean canRun() {
return !energy.isEmpty();
}
public int getTileX() {
return floatPosToTilePos(getX());
}
public int getTileY() {
return floatPosToTilePos(getY());
}
public void setTeam(Team team) {
this.team = team;
}
public boolean isInSameTileAs(Creature other) {
return this.getTileX() == other.getTileX()
&& this.getTileY() == other.getTileY();
}
public void setInvisibility(boolean truth) {
if (truth) sprite.setAlpha(0.3f);
else sprite.setAlpha(1);
if (truth)
stateFlags.add(StateFlag.IS_INVISIBLE);
else
stateFlags.remove(StateFlag.IS_INVISIBLE);
}
public boolean isInvisible() {
return stateFlags.contains(StateFlag.IS_INVISIBLE);
}
public void removeItem(Item item) {
inventory.removeItem(item);
}
public boolean isFacing(Creature target) {
return abs(getDiff(this.getDirection(), target.direction)) < PI/48;
}
public boolean isFlying() {
return stateFlags.contains(StateFlag.IS_FLYING);
}
public void setFlying(boolean truth) {
if (truth)
stateFlags.add(StateFlag.IS_FLYING);
else
stateFlags.remove(StateFlag.IS_FLYING);
}
public void setSprite(int x, int y) {
sprite = new Sprite(texture, x*Tile.size, y*Tile.size, Tile.size, Tile.size);
updateSpriteRotation();
}
public float getHPAsFraction() {
return HP.getFraction();
}
public float getEnergyAsFraction() {
return energy.getFraction();
}
public void setStatistics(Statistics statistics) {
this.statistics = statistics;
}
public Statistics getStatistics() {
return statistics;
}
public int getDefence() {
return this.defense;
}
public boolean isOnPassableObject() {
return (this.getTile().isPassable());
}
public Circle getBounds() {
return bounds;
}
private boolean collisionDetected(float x, float y) {
Circle newBounds = new Circle(x, y, getSize());
List<Creature> creatures = area.getCreaturesNear(x, y);
creatures.remove(this);
for (Creature other : creatures) {
if (overlaps(newBounds, other.getBounds())) {
return true;
}
}
return false;
}
public List<Creature> getNearbyCreatures() {
List<Creature> creatures = new ArrayList<Creature>();
for (Tile tile : getNearbyTiles(true)) {
creatures.addAll(tile.getCreatures());
}
creatures.addAll(getTile().getCreatures());
creatures.remove(this);
return creatures;
}
public List<Tile> getNearbyTiles(boolean checkForDiagonal) {
return getTile().getNearbyTiles(checkForDiagonal);
}
}
|
package org.eclipse.oomph.p2.internal.core;
import org.eclipse.oomph.p2.P2Exception;
import org.eclipse.oomph.p2.core.Agent;
import org.eclipse.oomph.p2.core.AgentManager;
import org.eclipse.oomph.p2.core.BundlePool;
import org.eclipse.oomph.p2.core.P2Util;
import org.eclipse.oomph.util.IOUtil;
import org.eclipse.oomph.util.PropertiesUtil;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* @author Eike Stepper
*/
public class AgentManagerImpl implements AgentManager
{
public static AgentManager instance;
private final PersistentMap<Agent> agentMap;
private final File defaultsFile;
private Agent currentAgent;
private boolean currentAgentInMap;
public AgentManagerImpl()
{
this(new File(PropertiesUtil.USER_HOME));
}
public AgentManagerImpl(final File userHome)
{
File folder = P2CorePlugin.getUserStateFolder(userHome);
File infoFile = new File(folder, "agents.info");
defaultsFile = new File(folder, "defaults.info");
agentMap = new PersistentMap<Agent>(infoFile)
{
@Override
protected Agent createElement(String key, String extraInfo)
{
return new AgentImpl(AgentManagerImpl.this, new File(key));
}
@Override
protected void initializeFirstTime()
{
File defaultLocation = new File(userHome, ".p2");
initializeFirstTime(defaultLocation);
initializeFirstTime(new File(userHome, "p2"));
initializeFirstTime(new File(userHome, ".eclipse"));
initializeFirstTime(new File(userHome, "eclipse"));
if (getElements().isEmpty())
{
addAgent(defaultLocation);
}
if (getBundlePools().isEmpty())
{
Agent agent = getAgent(defaultLocation);
if (agent == null)
{
agent = getAgents().iterator().next();
}
File poolLocation = new File(agent.getLocation(), "pool");
agent.addBundlePool(poolLocation);
}
}
private void initializeFirstTime(File location)
{
if (location.isDirectory())
{
if (AgentImpl.isValid(location))
{
addAgent(location);
}
else
{
for (File child : location.listFiles())
{
initializeFirstTime(child);
}
}
}
}
};
agentMap.load();
}
public PersistentMap<Agent> getAgentMap()
{
return agentMap;
}
public void dispose()
{
for (Agent agent : getAgents())
{
((AgentImpl)agent).dispose();
}
if (!currentAgentInMap && currentAgent != null)
{
((AgentImpl)currentAgent).dispose();
}
}
public synchronized Agent getCurrentAgent()
{
if (currentAgent == null)
{
BundleContext context = P2CorePlugin.INSTANCE.getBundleContext();
ServiceReference<?> reference = context.getServiceReference(IProvisioningAgent.class);
if (reference == null)
{
throw new P2Exception("Current provisioning agent could not be loaded");
}
try
{
IProvisioningAgent provisioningAgent = (IProvisioningAgent)context.getService(reference);
File agentLocation = P2Util.getAgentLocation(provisioningAgent);
Agent agent = getAgent(agentLocation);
if (agent != null)
{
currentAgent = agent;
currentAgentInMap = true;
}
else
{
currentAgent = new AgentImpl(this, agentLocation);
}
((AgentImpl)currentAgent).initializeProvisioningAgent(provisioningAgent);
}
finally
{
context.ungetService(reference);
}
}
return currentAgent;
}
public Set<File> getAgentLocations()
{
return getLocations(agentMap.getElementKeys());
}
public Collection<Agent> getAgents()
{
return agentMap.getElements();
}
public Agent getAgent(File location)
{
return agentMap.getElement(location.getAbsolutePath());
}
public Agent addAgent(File location)
{
return agentMap.addElement(location.getAbsolutePath(), null);
}
public void deleteAgent(Agent agent)
{
agentMap.removeElement(agent.getLocation().getAbsolutePath());
// TODO Delete artifacts from disk
}
public boolean refreshAgents()
{
return agentMap.refresh();
}
public Collection<BundlePool> getBundlePools()
{
List<BundlePool> bundlePools = new ArrayList<BundlePool>();
for (Agent agent : getAgents())
{
bundlePools.addAll(agent.getBundlePools());
}
return bundlePools;
}
public BundlePool getBundlePool(File location) throws P2Exception
{
if (location.isDirectory())
{
for (Agent agent : getAgents())
{
BundlePool bundlePool = agent.getBundlePool(location);
if (bundlePool != null)
{
return bundlePool;
}
}
}
return null;
}
public BundlePool getDefaultBundlePool(String client) throws P2Exception
{
Properties defaults = loadDefaults();
String location = (String)defaults.get(client);
if (location != null)
{
BundlePool bundlePool = getBundlePool(new File(location));
if (bundlePool != null)
{
return bundlePool;
}
}
for (Object value : defaults.values())
{
BundlePool bundlePool = getBundlePool(new File((String)value));
if (bundlePool != null)
{
return bundlePool;
}
}
Collection<BundlePool> bundlePools = getBundlePools();
if (!bundlePools.isEmpty())
{
return bundlePools.iterator().next();
}
return null;
}
public void setDefaultBundlePool(String client, BundlePool bundlePool)
{
Properties defaults = loadDefaults();
defaults.put(client, bundlePool.getLocation().getAbsolutePath());
saveDefaults(defaults);
}
public Set<String> getClientsFor(String bundlePoolLocation)
{
Set<String> clients = new HashSet<String>();
Properties defaults = loadDefaults();
for (Map.Entry<Object, Object> entry : defaults.entrySet())
{
String client = (String)entry.getKey();
String location = (String)entry.getValue();
if (location.equals(bundlePoolLocation))
{
clients.add(client);
}
}
return clients;
}
private Properties loadDefaults()
{
Properties defaults = new Properties();
if (defaultsFile.exists())
{
InputStream stream = null;
try
{
stream = new FileInputStream(defaultsFile);
defaults.load(stream);
}
catch (IOException ex)
{
throw new P2Exception(ex);
}
finally
{
IOUtil.close(stream);
}
}
return defaults;
}
private void saveDefaults(Properties defaults)
{
OutputStream stream = null;
try
{
stream = new FileOutputStream(defaultsFile);
defaults.store(stream, "P2 clients store their default bundle pool locations here");
}
catch (IOException ex)
{
throw new P2Exception(ex);
}
finally
{
IOUtil.close(stream);
}
}
public static Set<File> getLocations(Set<String> keys)
{
Set<File> locations = new HashSet<File>();
for (String key : keys)
{
locations.add(new File(key));
}
return locations;
}
}
|
package org.eclipse.oomph.p2.internal.core;
import org.eclipse.oomph.p2.P2Exception;
import org.eclipse.oomph.p2.core.Agent;
import org.eclipse.oomph.p2.core.AgentManager;
import org.eclipse.oomph.p2.core.BundlePool;
import org.eclipse.oomph.p2.core.P2Util;
import org.eclipse.oomph.util.IOUtil;
import org.eclipse.oomph.util.PropertiesUtil;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* @author Eike Stepper
*/
public class AgentManagerImpl implements AgentManager
{
private static final String AGENT_PATH = "oomph.p2.agent.path";
private static final String AGENT_SUFFIX = ":agent";
public static AgentManager instance;
private final PersistentMap<Agent> agentMap;
private final File defaultAgentLocation;
private final File defaultsFile;
private Agent currentAgent;
private boolean currentAgentInMap;
public AgentManagerImpl()
{
this(new File(System.getProperty(AGENT_PATH, PropertiesUtil.getOomphHome())));
}
public AgentManagerImpl(final File oomphHome)
{
defaultAgentLocation = new File(PropertiesUtil.getOomphHome(), ".p2");
File folder = P2CorePlugin.getUserStateFolder(oomphHome);
File infoFile = new File(folder, "agents.info");
defaultsFile = new File(folder, "defaults.info");
agentMap = new PersistentMap<Agent>(infoFile)
{
@Override
protected Agent loadElement(String key, String extraInfo)
{
File location = new File(key);
if (AgentImpl.isValid(location))
{
return super.loadElement(key, extraInfo);
}
return null;
}
@Override
protected Agent createElement(String key, String extraInfo)
{
return new AgentImpl(AgentManagerImpl.this, new File(key));
}
@Override
protected void initializeFirstTime()
{
initializeFirstTime(defaultAgentLocation);
initializeFirstTime(new File(oomphHome, "p2"));
initializeFirstTime(new File(oomphHome, ".eclipse"));
initializeFirstTime(new File(oomphHome, "eclipse"));
if (getElements().isEmpty())
{
addAgent(defaultAgentLocation);
}
Collection<BundlePool> bundlePools = getBundlePools();
if (bundlePools.isEmpty())
{
Agent agent = getAgent(defaultAgentLocation);
if (agent == null)
{
Collection<Agent> agents = getAgents(); // Is not null because of addAgent() above.
agent = agents.iterator().next();
}
File poolLocation = new File(agent.getLocation(), BundlePool.DEFAULT_NAME);
agent.addBundlePool(poolLocation);
}
}
private void initializeFirstTime(File location)
{
if (IOUtil.isValidFolder(location))
{
if (AgentImpl.isValid(location))
{
addAgent(location);
}
else
{
for (File child : location.listFiles())
{
initializeFirstTime(child);
}
}
}
}
};
agentMap.load();
}
public PersistentMap<Agent> getAgentMap()
{
return agentMap;
}
public void dispose()
{
for (Agent agent : getAgents())
{
((AgentImpl)agent).dispose();
}
if (!currentAgentInMap && currentAgent != null)
{
((AgentImpl)currentAgent).dispose();
}
}
public synchronized Agent getCurrentAgent()
{
if (currentAgent == null)
{
BundleContext context = P2CorePlugin.INSTANCE.getBundleContext();
ServiceReference<?> reference = context.getServiceReference(IProvisioningAgent.class);
if (reference == null)
{
throw new P2Exception("Current provisioning agent could not be loaded");
}
try
{
IProvisioningAgent provisioningAgent = (IProvisioningAgent)context.getService(reference);
File agentLocation = P2Util.getAgentLocation(provisioningAgent);
Agent agent = getAgent(agentLocation);
if (agent != null)
{
currentAgent = agent;
currentAgentInMap = true;
}
else
{
currentAgent = new AgentImpl(this, agentLocation);
}
((AgentImpl)currentAgent).initializeProvisioningAgent(provisioningAgent);
}
finally
{
context.ungetService(reference);
}
}
return currentAgent;
}
public File getDefaultAgentLocation()
{
return defaultAgentLocation;
}
public Set<File> getAgentLocations()
{
return getLocations(agentMap.getElementKeys());
}
public Collection<Agent> getAgents()
{
return agentMap.getElements();
}
public Agent getAgent(File location)
{
return agentMap.getElement(location.getAbsolutePath());
}
public Agent addAgent(File location)
{
return agentMap.addElement(location.getAbsolutePath(), null);
}
public void deleteAgent(Agent agent)
{
agentMap.removeElement(agent.getLocation().getAbsolutePath());
// TODO Delete artifacts from disk
}
public void refreshAgents(IProgressMonitor monitor)
{
monitor.beginTask("Refreshing agents...", 1 + 20);
try
{
agentMap.refresh();
monitor.worked(1);
Collection<Agent> agents = getAgents();
refreshAgents(agents, new SubProgressMonitor(monitor, 20));
}
finally
{
monitor.done();
}
}
private void refreshAgents(Collection<Agent> agents, IProgressMonitor monitor)
{
monitor.beginTask("", 21 * agents.size());
try
{
for (Agent agent : agents)
{
P2CorePlugin.checkCancelation(monitor);
monitor.subTask("Refreshing " + agent.getLocation());
agent.refreshBundlePools(new SubProgressMonitor(monitor, 1));
agent.refreshProfiles(new SubProgressMonitor(monitor, 20));
}
}
finally
{
monitor.done();
}
}
public Collection<BundlePool> getBundlePools()
{
List<BundlePool> bundlePools = new ArrayList<BundlePool>();
for (Agent agent : getAgents())
{
bundlePools.addAll(agent.getBundlePools());
}
return bundlePools;
}
public BundlePool getBundlePool(File location) throws P2Exception
{
for (Agent agent : getAgents())
{
BundlePool bundlePool = agent.getBundlePool(location);
if (bundlePool != null)
{
return bundlePool;
}
}
return null;
}
private BundlePool getBundlePool(String path) throws P2Exception
{
File location = new File(path);
if (location.isDirectory())
{
return getBundlePool(location);
}
return null;
}
public BundlePool getDefaultBundlePool(String client) throws P2Exception
{
Properties defaults = loadDefaults();
BundlePool bundlePool = restoreBundlePool(client, defaults);
if (bundlePool != null)
{
return bundlePool;
}
for (Object otherClient : defaults.keySet())
{
String clientId = (String)otherClient;
// Skip agent locations.
if (clientId != null && !clientId.equals(client) && !clientId.endsWith(AGENT_SUFFIX))
{
bundlePool = restoreBundlePool(clientId, defaults);
if (bundlePool != null)
{
return bundlePool;
}
}
}
return getDefaultBundlePool();
}
private BundlePool getDefaultBundlePool() throws P2Exception
{
File defaultPoolLocation = new File(defaultAgentLocation, BundlePool.DEFAULT_NAME);
BundlePool bundlePool = getBundlePool(defaultPoolLocation);
if (bundlePool != null)
{
return bundlePool;
}
Agent agent = addAgent(defaultAgentLocation);
Collection<BundlePool> bundlePools = agent.getBundlePools();
if (!bundlePools.isEmpty())
{
return bundlePools.iterator().next();
}
return agent.addBundlePool(defaultPoolLocation);
}
public void setDefaultBundlePool(String client, BundlePool bundlePool)
{
Properties defaults = loadDefaults();
defaults.put(client, bundlePool.getLocation().getAbsolutePath());
defaults.put(client + AGENT_SUFFIX, bundlePool.getAgent().getLocation().getAbsolutePath());
saveDefaults(defaults);
}
private BundlePool restoreBundlePool(String client, Properties defaults)
{
String location = defaults.getProperty(client);
if (location != null)
{
BundlePool bundlePool = getBundlePool(location);
if (bundlePool == null)
{
String agentLocation = defaults.getProperty(client + AGENT_SUFFIX);
if (agentLocation != null)
{
File agentDir = new File(agentLocation);
Agent agent = addAgent(agentDir);
if (agent != null)
{
File poolDir = new File(location);
bundlePool = agent.addBundlePool(poolDir);
}
}
}
return bundlePool;
}
return null;
}
public Set<String> getClientsFor(String bundlePoolLocation)
{
Set<String> clients = new HashSet<String>();
Properties defaults = loadDefaults();
for (Map.Entry<Object, Object> entry : defaults.entrySet())
{
String client = (String)entry.getKey();
// Skip agent locations.
if (client != null && !client.endsWith(AGENT_SUFFIX))
{
String location = (String)entry.getValue();
if (location.equals(bundlePoolLocation))
{
clients.add(client);
}
}
}
return clients;
}
private Properties loadDefaults()
{
Properties defaults = new Properties();
if (defaultsFile.exists())
{
InputStream stream = null;
try
{
stream = new FileInputStream(defaultsFile);
defaults.load(stream);
}
catch (IOException ex)
{
throw new P2Exception(ex);
}
finally
{
IOUtil.close(stream);
}
}
return defaults;
}
private void saveDefaults(Properties defaults)
{
OutputStream stream = null;
try
{
stream = new FileOutputStream(defaultsFile);
defaults.store(stream, "P2 clients store their default bundle pool locations here");
}
catch (IOException ex)
{
throw new P2Exception(ex);
}
finally
{
IOUtil.close(stream);
}
}
public static Set<File> getLocations(Set<String> keys)
{
Set<File> locations = new HashSet<File>();
for (String key : keys)
{
locations.add(new File(key));
}
return locations;
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.DBCStatistics;
import org.jkiss.dbeaver.model.struct.DBSAttributeBase;
import org.jkiss.dbeaver.model.struct.DBSDataManipulator;
import org.jkiss.dbeaver.model.struct.DBSEntity;
import org.jkiss.dbeaver.ui.controls.lightgrid.GridCell;
import org.jkiss.utils.CommonUtils;
import java.util.*;
/**
* Result set model
*/
public class ResultSetModel {
static final Log log = LogFactory.getLog(ResultSetModel.class);
// Columns
private DBDAttributeBinding[] columns = new DBDAttributeBinding[0];
private List<DBDAttributeBinding> visibleColumns = new ArrayList<DBDAttributeBinding>();
private DBDDataFilter dataFilter;
private boolean singleSourceCells;
// Data
private List<RowData> curRows = new ArrayList<RowData>();
private int changesCount = 0;
private volatile boolean hasData = false;
// Flag saying that edited values update is in progress
private volatile boolean updateInProgress = false;
// Edited rows and cells
private DBCStatistics statistics;
public ResultSetModel()
{
dataFilter = createDataFilter();
}
public DBDDataFilter createDataFilter()
{
List<DBDAttributeConstraint> constraints = new ArrayList<DBDAttributeConstraint>(columns.length);
for (DBDAttributeBinding binding : columns) {
addConstraints(constraints, binding);
}
return new DBDDataFilter(constraints);
}
private void addConstraints(List<DBDAttributeConstraint> constraints, DBDAttributeBinding binding) {
DBDAttributeConstraint constraint = new DBDAttributeConstraint(binding);
constraint.setVisible(visibleColumns.contains(binding));
constraints.add(constraint);
List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings();
if (nestedBindings != null) {
for (DBDAttributeBinding nested : nestedBindings) {
addConstraints(constraints, nested);
}
}
}
public boolean isSingleSource()
{
return singleSourceCells;
}
/**
* Returns single source of this result set. Usually it is a table.
* If result set is a result of joins or contains synthetic columns then
* single source is null. If driver doesn't support meta information
* for queries then is will null.
* @return single source entity
*/
@Nullable
public DBSEntity getSingleSource()
{
if (!singleSourceCells) {
return null;
}
return columns[0].getRowIdentifier().getEntity();
}
public void resetCellValue(GridCell cell)
{
RowData row = (RowData) cell.row;
int columnIndex = ((DBDAttributeBinding) cell.col).getTopParent().getAttributeIndex();
if (columnIndex >= 0 && row.oldValues != null && row.changedValues != null && row.changedValues[columnIndex]) {
resetValue(row.values[columnIndex]);
row.values[columnIndex] = row.oldValues[columnIndex];
row.changedValues[columnIndex] = false;
if (row.state == RowData.STATE_NORMAL) {
changesCount
}
}
}
public void refreshChangeCount()
{
changesCount = 0;
for (RowData row : curRows) {
if (row.state != RowData.STATE_NORMAL) {
changesCount++;
} else if (row.changedValues != null) {
for (boolean cv : row.changedValues) {
if (cv) changesCount++;
}
}
}
}
public DBDAttributeBinding[] getColumns()
{
return columns;
}
public int getColumnCount()
{
return columns.length;
}
public DBDAttributeBinding getColumn(int index)
{
return columns[index];
}
public int getVisibleColumnIndex(DBDAttributeBinding column)
{
return visibleColumns.indexOf(column);
}
public List<DBDAttributeBinding> getVisibleColumns()
{
return visibleColumns;
}
public int getVisibleColumnCount()
{
return visibleColumns.size();
}
public DBDAttributeBinding getVisibleColumn(int index)
{
return visibleColumns.get(index);
}
public void setColumnVisibility(DBDAttributeBinding attribute, boolean visible)
{
DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute);
if (constraint.isVisible() != visible) {
constraint.setVisible(visible);
if (visible) {
visibleColumns.add(attribute);
} else {
visibleColumns.remove(attribute);
}
}
}
@Nullable
public DBDAttributeBinding getAttributeBinding(DBSAttributeBase attribute)
{
for (DBDAttributeBinding binding : columns) {
if (binding.getMetaAttribute() == attribute || binding.getEntityAttribute() == attribute) {
return binding;
}
}
return null;
}
@Nullable
DBDAttributeBinding getAttributeBinding(DBSEntity table, String columnName)
{
for (DBDAttributeBinding column : visibleColumns) {
if ((table == null || column.getRowIdentifier().getEntity() == table) &&
column.getAttributeName().equals(columnName)) {
return column;
}
}
return null;
}
public boolean isEmpty()
{
return getRowCount() <= 0 || visibleColumns.size() <= 0;
}
public int getRowCount()
{
return curRows.size();
}
public List<RowData> getAllRows() {
return curRows;
}
public Object[] getRowData(int index)
{
return curRows.get(index).values;
}
public RowData getRow(int index)
{
return curRows.get(index);
}
@Nullable
public Object getCellValue(@NotNull RowData row, @NotNull DBDAttributeBinding column) {
int depth = column.getLevel();
if (depth == 0) {
return row.values[column.getAttributeIndex()];
}
Object curValue = row.values[column.getTopParent().getAttributeIndex()];
for (int i = 0; i < depth; i++) {
if (curValue == null) {
break;
}
DBDAttributeBinding attr = column.getParent(depth - i - 1);
if (curValue instanceof DBDStructure) {
try {
curValue = ((DBDStructure) curValue).getAttributeValue(attr.getAttribute());
} catch (DBCException e) {
log.warn("Error getting field [" + attr.getAttributeName() + "] value", e);
curValue = null;
break;
}
} else {
log.debug("No structure value handler while trying to read nested attribute [" + attr.getAttributeName() + "]");
curValue = null;
break;
}
}
return curValue;
}
/**
* Updates cell value. Saves previous value.
* @param row row index
* @param attr Attribute
* @param value new value
* @return true on success
*/
public boolean updateCellValue(RowData row, DBDAttributeBinding attr, @Nullable Object value)
{
int depth = attr.getLevel();
int rootIndex;
if (depth == 0) {
rootIndex = attr.getAttributeIndex();
} else {
rootIndex = attr.getTopParent().getAttributeIndex();
}
Object rootValue = row.values[rootIndex];
Object ownerValue = depth > 0 ? rootValue : null;
{
// Obtain owner value and create all intermediate values
for (int i = 0; i < depth; i++) {
if (ownerValue == null) {
// Create new owner object
log.warn("Null owner value");
return false;
}
if (i == depth - 1) {
break;
}
DBDAttributeBinding ownerAttr = attr.getParent(depth - i - 1);
if (ownerValue instanceof DBDStructure) {
try {
ownerValue = ((DBDStructure) ownerValue).getAttributeValue(ownerAttr.getAttribute());
} catch (DBCException e) {
log.warn("Error getting field [" + ownerAttr.getAttributeName() + "] value", e);
return false;
}
}
}
}
if (ownerValue != null || (value instanceof DBDValue && value == rootValue) || !CommonUtils.equalObjects(rootValue, value)) {
// If DBDValue was updated (kind of LOB?) or actual value was changed
if (ownerValue == null && DBUtils.isNullValue(rootValue) && DBUtils.isNullValue(value)) {
// Both nulls - nothing to update
return false;
}
// Do not add edited cell for new/deleted rows
if (row.state == RowData.STATE_NORMAL) {
// Save old value
boolean cellWasEdited = row.oldValues != null && row.changedValues != null && row.changedValues[rootIndex];
Object oldOldValue = !cellWasEdited ? null : row.oldValues[rootIndex];
if (cellWasEdited && !CommonUtils.equalObjects(rootValue, oldOldValue)) {
// Value rewrite - release previous stored old value
releaseValue(rootValue);
} else {
if (row.oldValues == null || row.changedValues == null) {
row.oldValues = new Object[row.values.length];
row.changedValues = new boolean[row.values.length];
}
row.oldValues[rootIndex] = rootValue;
row.changedValues[rootIndex] = true;
}
if (row.state == RowData.STATE_NORMAL && !cellWasEdited) {
changesCount++;
}
}
if (ownerValue != null) {
if (ownerValue instanceof DBDStructure) {
try {
((DBDStructure) ownerValue).setAttributeValue(attr.getAttribute(), value);
} catch (DBCException e) {
log.error("Error setting [" + attr.getAttributeName() + "] value", e);
}
} else {
log.warn("Value [" + ownerValue + "] edit is not supported");
}
} else {
row.values[rootIndex] = value;
}
return true;
}
return false;
}
/**
* Sets new metadata of result set
* @param columns columns metadata
* @return true if new metadata differs from old one, false otherwise
*/
public boolean setMetaData(DBDAttributeBinding[] columns)
{
boolean update = false;
if (this.columns == null || this.columns.length != columns.length) {
update = true;
} else {
if (dataFilter != null && dataFilter.hasFilters()) {
// This is a filtered result set so keep old metadata.
// Filtering modifies original query (adds sub-query)
// and it may change metadata (depends on driver)
// but actually it doesn't change any column or table names/types
// so let's keep old info
return false;
}
for (int i = 0; i < this.columns.length; i++) {
if (!this.columns[i].getMetaAttribute().equals(columns[i].getMetaAttribute())) {
update = true;
break;
}
}
}
if (update) {
this.clearData();
this.columns = columns;
this.visibleColumns.clear();
for (DBDAttributeBinding binding : this.columns) {
DBDPseudoAttribute pseudoAttribute = binding.getMetaAttribute().getPseudoAttribute();
if (pseudoAttribute == null) {
// Make visible "real" attributes
this.visibleColumns.add(binding);
}
}
}
return update;
}
public void setData(List<Object[]> rows, boolean updateMetaData)
{
// Clear previous data
this.clearData();
// Add new data
appendData(rows);
if (updateMetaData) {
this.dataFilter = createDataFilter();
// Check single source flag
this.singleSourceCells = true;
DBSEntity sourceTable = null;
for (DBDAttributeBinding column : visibleColumns) {
if (isColumnReadOnly(column)) {
singleSourceCells = false;
break;
}
if (sourceTable == null) {
sourceTable = column.getRowIdentifier().getEntity();
} else if (sourceTable != column.getRowIdentifier().getEntity()) {
singleSourceCells = false;
break;
}
}
}
hasData = true;
}
public void appendData(List<Object[]> rows)
{
int rowCount = rows.size();
List<RowData> newRows = new ArrayList<RowData>(rowCount);
for (int i = 0; i < rowCount; i++) {
newRows.add(
new RowData(curRows.size() + i, rows.get(i), null));
}
curRows.addAll(newRows);
}
void clearData()
{
// Refresh all rows
this.releaseAll();
this.curRows = new ArrayList<RowData>();
hasData = false;
}
public boolean hasData()
{
return hasData;
}
public boolean isDirty()
{
return changesCount != 0;
}
boolean isColumnReadOnly(DBDAttributeBinding column)
{
if (column.getRowIdentifier() == null || !(column.getRowIdentifier().getEntity() instanceof DBSDataManipulator) ||
(column.getValueHandler().getFeatures() & DBDValueHandler.FEATURE_READ_ONLY) != 0) {
return true;
}
DBSDataManipulator dataContainer = (DBSDataManipulator) column.getRowIdentifier().getEntity();
return (dataContainer.getSupportedFeatures() & DBSDataManipulator.DATA_UPDATE) == 0;
}
public boolean isUpdateInProgress()
{
return updateInProgress;
}
void setUpdateInProgress(boolean updateInProgress)
{
this.updateInProgress = updateInProgress;
}
void addNewRow(int rowNum, Object[] data)
{
RowData newRow = new RowData(curRows.size(), data, null);
newRow.visualNumber = rowNum;
newRow.state = RowData.STATE_ADDED;
shiftRows(newRow, 1);
curRows.add(rowNum, newRow);
changesCount++;
}
/**
* Removes row with specified index from data
* @param row row
* @return true if row was physically removed (only in case if this row was previously added)
* or false if it just marked as deleted
*/
boolean deleteRow(RowData row)
{
if (row.state == RowData.STATE_ADDED) {
cleanupRow(row);
return true;
} else {
// Mark row as deleted
row.state = RowData.STATE_REMOVED;
changesCount++;
return false;
}
}
void cleanupRow(RowData row)
{
releaseRow(row);
this.curRows.remove(row.visualNumber);
this.shiftRows(row, -1);
}
boolean cleanupRows(Collection<RowData> rows)
{
if (rows != null && !rows.isEmpty()) {
// Remove rows (in descending order to prevent concurrent modification errors)
List<RowData> rowsToRemove = new ArrayList<RowData>(rows);
Collections.sort(rowsToRemove, new Comparator<RowData>() {
@Override
public int compare(RowData o1, RowData o2) {
return o1.visualNumber - o2.visualNumber;
}
});
for (RowData row : rowsToRemove) {
cleanupRow(row);
}
return true;
} else {
return false;
}
}
private void shiftRows(RowData relative, int delta)
{
for (RowData row : curRows) {
if (row.visualNumber >= relative.visualNumber) {
row.visualNumber += delta;
}
if (row.rowNumber >= relative.rowNumber) {
row.rowNumber += delta;
}
}
}
private void releaseAll()
{
for (RowData row : curRows) {
releaseRow(row);
}
}
private static void releaseRow(RowData row)
{
for (Object value : row.values) {
releaseValue(value);
}
if (row.oldValues != null) {
for (Object oldValue : row.oldValues) {
releaseValue(oldValue);
}
}
}
static void releaseValue(Object value)
{
if (value instanceof DBDValue) {
((DBDValue)value).release();
}
}
static void resetValue(Object value)
{
if (value instanceof DBDContent) {
((DBDContent)value).resetContents();
}
}
public DBDDataFilter getDataFilter()
{
return dataFilter;
}
/**
* Sets new data filter
* @param dataFilter data filter
* @return true if visible columns were changed. Spreadsheet has to be refreshed
*/
boolean setDataFilter(DBDDataFilter dataFilter)
{
this.dataFilter = dataFilter;
List<DBDAttributeBinding> newColumns = this.dataFilter.getOrderedVisibleAttributes();
if (!newColumns.equals(visibleColumns)) {
visibleColumns = newColumns;
return true;
}
return false;
}
void resetOrdering()
{
final boolean hasOrdering = dataFilter.hasOrdering();
// Sort locally
final List<DBDAttributeConstraint> orderConstraints = dataFilter.getOrderConstraints();
Collections.sort(curRows, new Comparator<RowData>() {
@Override
public int compare(RowData row1, RowData row2)
{
if (!hasOrdering) {
return row1.rowNumber - row2.rowNumber;
}
int result = 0;
for (DBDAttributeConstraint co : orderConstraints) {
final DBDAttributeBinding binding = co.getAttribute();
if (binding == null) {
continue;
}
Object cell1 = row1.values[binding.getAttributeIndex()];
Object cell2 = row2.values[binding.getAttributeIndex()];
if (cell1 == cell2) {
result = 0;
} else if (DBUtils.isNullValue(cell1)) {
result = 1;
} else if (DBUtils.isNullValue(cell2)) {
result = -1;
} else if (cell1 instanceof Comparable<?>) {
result = ((Comparable)cell1).compareTo(cell2);
} else {
String str1 = cell1.toString();
String str2 = cell2.toString();
result = str1.compareTo(str2);
}
if (co.isOrderDescending()) {
result = -result;
}
if (result != 0) {
break;
}
}
return result;
}
});
for (int i = 0; i < curRows.size(); i++) {
curRows.get(i).visualNumber = i;
}
}
public DBCStatistics getStatistics()
{
return statistics;
}
public void setStatistics(DBCStatistics statistics)
{
this.statistics = statistics;
}
}
|
package org.lockss.plugin.clockss.eastview;
import org.lockss.daemon.PluginException;
import org.lockss.extractor.ArticleMetadata;
import org.lockss.extractor.FileMetadataExtractor;
import org.lockss.extractor.MetadataField;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.CachedUrl;
import org.lockss.plugin.clockss.SourceXmlMetadataExtractorFactory;
import org.lockss.plugin.clockss.SourceXmlSchemaHelper;
import org.lockss.plugin.clockss.XPathXmlMetadataParser;
import org.lockss.plugin.clockss.XmlFilteringInputStream;
import org.lockss.util.LineRewritingReader;
import org.lockss.util.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.lockss.util.MetadataUtil;
import org.lockss.util.ReaderInputStream;
public class EastviewJournalXmlMetadataExtractorFactory extends SourceXmlMetadataExtractorFactory {
private static final Logger log = Logger.getLogger(EastviewJournalXmlMetadataExtractorFactory.class);
private static SourceXmlSchemaHelper EastviewHelper = null;
public static Map<String, String> issnMap = new HashMap<>();
static {
try {
issnMap = new EastviewNewspaperTitleISSNMappingHelper().getISSNList();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public FileMetadataExtractor createFileMetadataExtractor(MetadataTarget target,
String contentType)
throws PluginException {
return new EastviewXmlMetadataExtractor();
}
public class EastviewXmlMetadataExtractor extends SourceXmlMetadataExtractor {
@Override
protected SourceXmlSchemaHelper setUpSchema(CachedUrl cu) {
String cuBase = cu.getUrl();
log.debug3("Eastview Journal All Version: cuBase = " + cuBase);
if (cuBase.contains("DA-MLT/MTH/2001") || cuBase.contains("DA-MLT/MTH/199")) {
EastviewHelper = new EastviewJournalMetadataXhtmlFormatHelper();
log.debug3("Eastview Journal Early Version(199X - 2001): cuBase = " + cuBase);
} else if (cuBase.contains("DA-MLT/MTH/2002") || cuBase.contains("DA-MLT/MTH/2003")
|| cuBase.contains("DA-MLT/MTH/2004") || cuBase.contains("DA-MLT/MTH/2005")) {
EastviewHelper = new EastviewJournalMetadataXmlFormatHelper();
log.debug3("Eastview Journal Early Version(2002 - 2005): cuBase = " + cuBase);
} else {
EastviewHelper = new EastviewJournalMetadataHelper();
log.debug3("Eastview Journal Later Version: cuBase == " + cuBase);
}
return EastviewHelper;
}
@Override
protected boolean preEmitCheck(SourceXmlSchemaHelper schemaHelper,
CachedUrl cu, ArticleMetadata thisAM) {
log.debug3("Eastview Journal: in SourceXmlMetadataExtractor preEmitCheck");
String url_string = cu.getUrl();
log.debug3("Eastview Journal: preEmitCheck url_string = " + url_string);
List<String> filesToCheck;
// If no files get returned in the list, nothing to check
if ((filesToCheck = getFilenamesAssociatedWithRecord(schemaHelper, cu,thisAM)) == null) {
return true;
}
ArchivalUnit B_au = cu.getArchivalUnit();
CachedUrl fileCu;
for (int i=0; i < filesToCheck.size(); i++)
{
fileCu = B_au.makeCachedUrl(filesToCheck.get(i));
log.debug3("Eastview Journal: Check for existence of " + filesToCheck.get(i));
if(filesToCheck.get(i).contains(".pdf") || filesToCheck.get(i).contains(".xml") || filesToCheck.get(i).contains(".xhtml")) {
// Set a cooked value for an access file. Otherwise it would get set to xml file
log.debug3("Eastview Journal: set access_url to " + filesToCheck.get(i));
return true;
}
}
log.debug3("Eastview Journal: No file exists associated with this record");
return false; //No files found that match this record
}
/*
* a PDF file may or may not exist, but assume the XML is full text
* when it does not
*/
@Override
protected List<String> getFilenamesAssociatedWithRecord(SourceXmlSchemaHelper helper, CachedUrl cu,
ArticleMetadata oneAM) {
String url_string = cu.getUrl();
log.debug3("Eastview Journal: getFilenamesAssociatedWithRecord url_string = " + url_string);
String articlePDFName = url_string.substring(0,url_string.length() - 3) + "pdf";
log.debug3("Eastview Journal: articlePDFName is " + articlePDFName);
List<String> returnList = new ArrayList<String>();
returnList.add(articlePDFName);
returnList.add(url_string); // xml file
//returnList.add(manMadePagePDF); // do not add man-made-pagePDF
return returnList;
}
@Override
protected void postCookProcess(SourceXmlSchemaHelper schemaHelper,
CachedUrl cu, ArticleMetadata thisAM) {
String raw_title = null;
String publisher_shortcut = null;
String publisher_mapped = null;
String volume = null;
String title = null;
String pubdate = null;
if (cu.getUrl().contains(".xml")) {
raw_title = thisAM.getRaw(EastviewSchemaHelper.ART_RAW_TITLE);
log.debug3(String.format("Eastview metadata raw title parsed - xml: %s, cu = %s", raw_title, cu.getUrl()));
} else if (cu.getUrl().contains(".xhtml")) {
raw_title = thisAM.getRaw(EastviewJournalMetadataXmlFormatHelper.ART_RAW_TITLE);
log.debug3(String.format("Eastview metadata raw title parsed - Html: %s, cu = %s, raw_title = %s", raw_title, cu.getUrl(), raw_title));
}
if (raw_title != null) {
Pattern pattern = Pattern.compile("(\\d\\d-\\d\\d-\\d{2,4})\\(([^)]+)-([^(]+)\\)\\s+(.*)");
Matcher m = pattern.matcher(raw_title);
if (m.matches()) {
pubdate = m.group(1);
publisher_shortcut = m.group(2).trim();
publisher_mapped = EastViewPublisherNameMappingHelper.canonical.get(publisher_shortcut);
volume = m.group(3);
title = m.group(4);
}
log.debug3(String.format("Eastview metadata raw title parsed = %s | " +
"publisher_shortcut = %s | publisher_mapped = %s | volume = %s | title = %s",
raw_title,
publisher_shortcut,
publisher_mapped,
volume,
title));
if (publisher_mapped != null) {
thisAM.put(MetadataField.FIELD_PUBLISHER, publisher_mapped);
} else {
log.debug3(String.format("Eastview metadata raw title parsed = %s | " +
"publisher_shortcut = %s | Null publisher_mapped = %s | volume = %s | title = %s",
raw_title,
publisher_shortcut,
publisher_mapped,
volume,
title));
thisAM.put(MetadataField.FIELD_PUBLISHER, publisher_shortcut);
}
}
if (thisAM.get(MetadataField.FIELD_VOLUME) == null || thisAM.get(MetadataField.FIELD_VOLUME).equals("000") || thisAM.get(MetadataField.FIELD_VOLUME).equals('0')) {
if (thisAM.get(MetadataField.FIELD_DATE) != null) {
log.debug3("Eastview Journal: invalid volume, set to " + thisAM.get(MetadataField.FIELD_DATE).substring(0, 4));
thisAM.replace(MetadataField.FIELD_VOLUME, thisAM.get(MetadataField.FIELD_DATE).substring(0, 4));
} else if(volume != null) {
//For early .xhtml data, there is not date field
thisAM.replace(MetadataField.FIELD_VOLUME, volume.replace("No.", ""));
}
}
if (thisAM.get(MetadataField.FIELD_ISSUE) == null || thisAM.get(MetadataField.FIELD_ISSUE).equals("000") || thisAM.get(MetadataField.FIELD_ISSUE).equals('0')) {
if (thisAM.get(MetadataField.FIELD_DATE) != null) {
log.debug3("Eastview Journal: invalid issue, set to " + thisAM.get(MetadataField.FIELD_DATE).replace("-", ""));
thisAM.replace(MetadataField.FIELD_ISSUE, thisAM.get(MetadataField.FIELD_DATE).replace("-", ""));
} else {
thisAM.replace(MetadataField.FIELD_ISSUE, pubdate);
}
}
String publicationTitle = thisAM.getRaw(EastviewJournalMetadataHelper.PUBLICATION_TITLE_PATH);
log.debug3("Eastview Journal: publicationTitle = " + publicationTitle);
if (publicationTitle != null) {
String issn = issnMap.get(publicationTitle);
log.debug3("Eastview Journal: publicationTitle = " + publicationTitle + ", issn = " + issn);
if (MetadataUtil.validateIssn(issn) != null) {
thisAM.put(MetadataField.FIELD_ISSN, MetadataUtil.validateIssn(issn));
}
} else {
log.debug3("Eastview Journal: publicationTitle is null");
}
if (title != null) {
thisAM.put(MetadataField.FIELD_ARTICLE_TITLE, title);
}
thisAM.put(MetadataField.FIELD_ARTICLE_TYPE, MetadataField.ARTICLE_TYPE_JOURNALARTICLE);
thisAM.put(MetadataField.FIELD_PUBLICATION_TYPE, MetadataField.PUBLICATION_TYPE_JOURNAL);
}
/**
* <p>Some IOP XML files contains HTML4 entities, that trip the SAX parser.
* Work around them with Apache Commons Lang3.</p>
*/
@Override
protected XPathXmlMetadataParser createXpathXmlMetadataParser() {
return new XPathXmlMetadataParser(getDoXmlFiltering()) {
@Override
protected InputStream getInputStreamFromCU(CachedUrl cu) {
if (isDoXmlFiltering()) {
return new XmlFilteringInputStream(new ReaderInputStream(new LineRewritingReader(new InputStreamReader(cu.getUnfilteredInputStream())) {
@Override
public String rewriteLine(String line) {
//Sample troubled line:
/*
<head>
<title>
03-31-2003(MTH-No.001) R&D AT THE RUSSIAN DEFENSE MINISTRY: RECOMMENDATIONS ON PLANNING</title>
</head>
log.debug3("Eastview Journal line = " + line + ", unescapeHtml4 line = " + StringEscapeUtils.unescapeHtml4(line)
+ "replaced line = " + line.replace("&", "&"));
*/
//return StringEscapeUtils.unescapeHtml4(line); //this will cause "<xml..." line parsing error.
return line.replaceAll("&", "&");
}
}));
}
else {
return cu.getUnfilteredInputStream();
}
}
};
}
/**
* @see #createXpathXmlMetadataParser()
*/
@Override
public boolean getDoXmlFiltering() {
return true;
}
}
}
|
package net.meisen.general.genmisc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import net.meisen.general.genmisc.types.Streams;
import net.meisen.general.genmisc.types.Streams.ByteResult;
import net.meisen.general.genmisc.types.Strings;
import org.junit.Test;
/**
* The test specified for the <code>Streams</code>
*
* @author pmeisen
*
*/
public class TestStreams {
/**
* Tests the implementation of the
* {@link Streams#writeStringToStream(String, java.io.OutputStream)} method
*/
@Test
public void testWriteStringToStream() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final String content = "This is a Test";
// write it
Streams.writeStringToStream(content, baos);
// test it
assertEquals(baos.toString(), content);
}
/**
* Tests the implementation of the encoding guesses for some files.
*
* @throws IOException
* if the file cannot be accessed
*/
@Test
public void testGuessEncoding() throws IOException {
InputStream is;
String enc;
// EMPTY
is = getClass().getResourceAsStream("encodedFiles/Empty.txt");
enc = Streams.guessEncoding(is, null);
assertEquals(System.getProperty("file.encoding"), enc);
// ASCII
is = getClass().getResourceAsStream("encodedFiles/ASCII.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("US-ASCII", enc);
// Cp1252
is = getClass().getResourceAsStream("encodedFiles/Cp1252.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("Cp1252", enc);
// UTF8 with BOM
is = getClass().getResourceAsStream("encodedFiles/UTF8_BOM.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("UTF-8", enc);
// UTF8 without BOM
is = getClass().getResourceAsStream("encodedFiles/UTF8_noBOM.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("UTF-8", enc);
// UTF16 BigEndian
is = getClass().getResourceAsStream("encodedFiles/UCS-2_BigEndian.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("UTF-16BE", enc);
// UTF16 LittleEndian
is = getClass().getResourceAsStream(
"encodedFiles/UCS-2_LittleEndian.txt");
enc = Streams.guessEncoding(is, null);
assertEquals("UTF-16LE", enc);
}
/**
* Tests the implementation of {@link Streams#combineBytes(byte[][])}.
*/
@Test
public void testCombineBytes() {
// null if null is passed
assertNull(Streams.combineBytes((byte[][]) null));
// if a null array is passed it is ignored
assertTrue(Arrays.equals(new byte[0],
Streams.combineBytes((byte[]) null)));
// test the combination
byte[] input;
input = new byte[] { 0x3, 0x2c };
assertTrue(Arrays.equals(input,
Streams.combineBytes((byte[]) null, input)));
assertTrue(Arrays.equals(
new byte[] { 0x3, 0x2c, 0x3, 0x2c },
Streams.combineBytes(new byte[] { 0x3, 0x2c }, new byte[] {
0x3, 0x2c })));
}
/**
* Tests the implementation of the short mappers, i.e.
* {@link Streams#shortToByte(short)} and
* {@link Streams#byteToShort(byte[])}.
*/
@Test
public void testShortByte() {
byte[] byteArray;
short value;
for (short i = Short.MIN_VALUE;; i++) {
byteArray = Streams.shortToByte((short) i);
value = Streams.byteToShort(byteArray);
assertEquals((short) i, value);
if (i == Short.MAX_VALUE) {
break;
}
}
}
/**
* Tests the implementation of the int mappers, i.e.
* {@link Streams#intToByte(int)} and {@link Streams#byteToInt(byte[])}.
*/
@Test
public void testIntByte() {
byte[] byteArray;
int value;
for (int i = Integer.MIN_VALUE;; i++) {
byteArray = Streams.intToByte(i);
value = Streams.byteToInt(byteArray);
assertEquals(i, value);
if (i == Integer.MAX_VALUE) {
break;
}
}
}
/**
* Tests the implementation of the long mappers, i.e.
* {@link Streams#longToByte(long)} and {@link Streams#byteToLong(byte[])}.
*/
@Test
public void testLongByte() {
byte[] byteArray;
long value;
// test the boundaries
byteArray = Streams.longToByte(Long.MIN_VALUE);
value = Streams.byteToLong(byteArray);
assertEquals(Long.MIN_VALUE, value);
byteArray = Streams.longToByte(Long.MAX_VALUE);
value = Streams.byteToLong(byteArray);
assertEquals(Long.MAX_VALUE, value);
byteArray = Streams.longToByte(0);
value = Streams.byteToLong(byteArray);
assertEquals(0, value);
// pick some random numbers
final Random rnd = new Random();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
final long rndValue = rnd.nextLong();
byteArray = Streams.longToByte(rndValue);
value = Streams.byteToLong(byteArray);
assertEquals(rndValue, value);
}
}
/**
* Tests the implementation of the string mappers, i.e.
* {@link Streams#stringToByte(String)} and
* {@link Streams#byteToString(byte[])}.
*/
@Test
public void testStringByte() {
byte[] byteArray;
String value;
byteArray = Streams.stringToByte("");
value = Streams.byteToString(byteArray);
assertEquals("", value);
byteArray = Streams.stringToByte("Hello");
value = Streams.byteToString(byteArray);
assertEquals("Hello", value);
byteArray = Streams.stringToByte("?\"");
value = Streams.byteToString(byteArray);
assertEquals("?\"", value);
}
/**
* Tests the implementation of the object mappers, i.e.
* {@link Streams#objectToByte(Object)} and
* {@link Streams#byteToObject(byte[])}.
*/
@Test
public void testObjectByte() {
byte[] byteArray;
Object org;
ByteResult value;
// test an empty string
org = "";
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertTrue(Streams.serializeObject(org).length > byteArray.length);
// test a string
org = "A!? ";
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertTrue(Streams.serializeObject(org).length > byteArray.length);
// test a byte
org = Byte.MIN_VALUE;
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertTrue(Streams.serializeObject(org).length > byteArray.length);
// test a short
org = Short.MAX_VALUE;
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertTrue(Streams.serializeObject(org).length > byteArray.length);
// test null
org = null;
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertEquals(1, byteArray.length);
// test some objects
org = new Date();
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertEquals(Streams.serializeObject(org).length + 1
+ Streams.SIZEOF_INT, byteArray.length);
org = UUID.randomUUID();
byteArray = Streams.objectToByte(org);
value = Streams.byteToObject(byteArray);
assertEquals(org, value.object);
assertEquals(byteArray.length, value.nextPos);
assertEquals(Streams.serializeObject(org).length + 1
+ Streams.SIZEOF_INT, byteArray.length);
// test some combination
org = new Date();
byteArray = Streams.combineBytes(Streams.objectToByte(org),
Streams.objectToByte(Byte.MIN_VALUE),
Streams.objectToByte("This is a test!"),
Streams.objectToByte(Integer.MIN_VALUE),
Streams.objectToByte(Long.MAX_VALUE));
// write some objects in an array and read those
final Object[] objects = new Object[5];
int counter = 0;
int offset = 0;
while (offset < byteArray.length) {
value = Streams.byteToObject(byteArray, offset);
offset = value.nextPos;
objects[counter] = value.object;
counter++;
}
assertEquals(org, objects[0]);
assertEquals(Byte.MIN_VALUE, objects[1]);
assertEquals("This is a test!", objects[2]);
assertEquals(Integer.MIN_VALUE, objects[3]);
assertEquals(Long.MAX_VALUE, objects[4]);
}
/**
* Tests the implementation of {@link Streams#writeAllObjects(Object...)}
* and {@link Streams#readAllObjects(byte[])}.
*/
@Test
public void testWriteAndReadAll() {
final List<Object> objects = new ArrayList<Object>();
objects.add(5l);
objects.add(new Date());
objects.add("+\"*");
objects.add((byte) 5);
objects.add(21000);
objects.add(null);
objects.add(UUID.randomUUID());
objects.add(Strings.repeat('A', Short.MAX_VALUE));
// test reading all
final byte[] res = Streams.writeAllObjects(objects);
assertEquals(objects, Streams.readAllObjects(res));
// test the offset
assertEquals(objects.subList(1, objects.size()),
Streams.readAllObjects(res, Streams.objectSize(Long.class)));
}
@Test
public void testReadNextObject() {
// test the reading of three sample objects
final byte[] sampleFile = Streams
.combineBytes(Streams.objectToByte(5),
Streams.objectToByte(500l),
Streams.objectToByte("Hello World"));
final ByteBuffer ret = ByteBuffer.wrap(sampleFile);
final Object o1 = Streams.readNextObject(ret);
assertEquals(new Integer(5), o1);
final Object o2 = Streams.readNextObject(ret);
assertEquals(new Long(500), o2);
final Object o3 = Streams.readNextObject(ret);
assertEquals(new String("Hello World"), o3);
boolean exception = false;
try {
Streams.readNextObject(ByteBuffer.wrap(new byte[0]));
} catch (final IllegalArgumentException e) {
assertTrue(e.getMessage().contains(
"buffer does not contain any object"));
exception = true;
}
assertTrue(exception);
}
}
|
package org.openprovenance.prov.xml;
import java.math.BigInteger;
import java.net.URI;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
public class ValueConverter {
public static QName newXsdQName(String local) {
return new QName(NamespacePrefixMapper.XSD_NS, local, NamespacePrefixMapper.XSD_PREFIX);
}
public static QName newXsdHashQName(String local) {
return new QName(NamespacePrefixMapper.XSD_HASH_NS, local, NamespacePrefixMapper.XSD_PREFIX);
}
public static QName QNAME_XSD_STRING=newXsdQName("string");
public static QName QNAME_XSD_INT=newXsdQName("int");
public static QName QNAME_XSD_LONG=newXsdQName("long");
public static QName QNAME_XSD_SHORT=newXsdQName("short");
public static QName QNAME_XSD_DOUBLE=newXsdQName("double");
public static QName QNAME_XSD_FLOAT=newXsdQName("float");
public static QName QNAME_XSD_DECIMAL=newXsdQName("decimal");
public static QName QNAME_XSD_BOOLEAN=newXsdQName("boolean");
public static QName QNAME_XSD_BYTE=newXsdQName("byte");
public static QName QNAME_XSD_UNSIGNED_INT=newXsdQName("unsignedInt");
public static QName QNAME_XSD_UNSIGNED_LONG=newXsdQName("unsignedLong");
public static QName QNAME_XSD_INTEGER=newXsdQName("integer");
public static QName QNAME_XSD_UNSIGNED_SHORT=newXsdQName("unsignedShort");
public static QName QNAME_XSD_NON_NEGATIVE_INTEGER=newXsdQName("nonNegativeInteger");
public static QName QNAME_XSD_NON_POSITIVE_INTEGER=newXsdQName("nonPositiveInteger");
public static QName QNAME_XSD_POSITIVE_INTEGER=newXsdQName("positiveInteger");
public static QName QNAME_XSD_UNSIGNED_BYTE=newXsdQName("unsignedByte");
public static QName QNAME_XSD_ANY_URI=newXsdQName("anyURI");
public static QName QNAME_XSD_QNAME=newXsdQName("QName");
public static QName QNAME_XSD_DATETIME=newXsdQName("dateTime");
public static QName QNAME_XSD_GYEAR=newXsdQName("gYear");
public static QName QNAME_XSD_HASH_STRING=newXsdHashQName("string");
public static QName QNAME_XSD_HASH_INT=newXsdHashQName("int");
public static QName QNAME_XSD_HASH_LONG=newXsdHashQName("long");
public static QName QNAME_XSD_HASH_SHORT=newXsdHashQName("short");
public static QName QNAME_XSD_HASH_DOUBLE=newXsdHashQName("double");
public static QName QNAME_XSD_HASH_FLOAT=newXsdHashQName("float");
public static QName QNAME_XSD_HASH_DECIMAL=newXsdHashQName("decimal");
public static QName QNAME_XSD_HASH_BOOLEAN=newXsdHashQName("boolean");
public static QName QNAME_XSD_HASH_BYTE=newXsdHashQName("byte");
public static QName QNAME_XSD_HASH_UNSIGNED_INT=newXsdHashQName("unsignedInt");
public static QName QNAME_XSD_HASH_UNSIGNED_LONG=newXsdHashQName("unsignedLong");
public static QName QNAME_XSD_HASH_INTEGER=newXsdHashQName("integer");
public static QName QNAME_XSD_HASH_UNSIGNED_SHORT=newXsdHashQName("unsignedShort");
public static QName QNAME_XSD_HASH_NON_NEGATIVE_INTEGER=newXsdHashQName("nonNegativeInteger");
public static QName QNAME_XSD_HASH_NON_POSITIVE_INTEGER=newXsdHashQName("nonPositiveInteger");
public static QName QNAME_XSD_HASH_POSITIVE_INTEGER=newXsdHashQName("positiveInteger");
public static QName QNAME_XSD_HASH_UNSIGNED_BYTE=newXsdHashQName("unsignedByte");
public static QName QNAME_XSD_HASH_ANY_URI=newXsdHashQName("anyURI");
public static QName QNAME_XSD_HASH_QNAME=newXsdHashQName("QName");
public static QName QNAME_XSD_HASH_DATETIME=newXsdHashQName("dateTime");
public static QName QNAME_XSD_HASH_GYEAR=newXsdQName("gYear");
public static QName QNAME_UNKNOWN=newXsdQName("UNKNOWN");
final private ProvFactory pFactory;
public ValueConverter(ProvFactory pFactory) {
this.pFactory=pFactory;
}
// should be implemented with a hash table of converters
public Object convertToJava(QName datatype, String value) {
if (datatype.equals(QNAME_XSD_STRING) || datatype.equals(QNAME_XSD_HASH_STRING))
return value;
if (datatype.equals(QNAME_XSD_INT) || datatype.equals(QNAME_XSD_HASH_INT))
return Integer.parseInt(value);
if (datatype.equals(QNAME_XSD_LONG) || datatype.equals(QNAME_XSD_HASH_LONG))
return Long.parseLong(value);
if (datatype.equals(QNAME_XSD_SHORT) || datatype.equals(QNAME_XSD_HASH_SHORT))
return Short.parseShort(value);
if (datatype.equals(QNAME_XSD_DOUBLE) || datatype.equals(QNAME_XSD_HASH_DOUBLE))
return Double.parseDouble(value);
if (datatype.equals(QNAME_XSD_FLOAT) || datatype.equals(QNAME_XSD_HASH_FLOAT))
return Float.parseFloat(value);
if (datatype.equals(QNAME_XSD_DECIMAL) || datatype.equals(QNAME_XSD_HASH_DECIMAL))
return new java.math.BigDecimal(value);
if (datatype.equals(QNAME_XSD_BOOLEAN) || datatype.equals(QNAME_XSD_HASH_BOOLEAN))
return Boolean.parseBoolean(value);
if (datatype.equals(QNAME_XSD_BYTE) || datatype.equals(QNAME_XSD_HASH_BYTE))
return Byte.parseByte(value);
if (datatype.equals(QNAME_XSD_UNSIGNED_INT) || datatype.equals(QNAME_XSD_HASH_UNSIGNED_INT))
return Long.parseLong(value);
if (datatype.equals(QNAME_XSD_UNSIGNED_SHORT) || datatype.equals(QNAME_XSD_HASH_UNSIGNED_SHORT))
return Integer.parseInt(value);
if (datatype.equals(QNAME_XSD_UNSIGNED_BYTE) || datatype.equals(QNAME_XSD_HASH_UNSIGNED_BYTE))
return Short.parseShort(value);
if (datatype.equals(QNAME_XSD_UNSIGNED_LONG) || datatype.equals(QNAME_XSD_HASH_UNSIGNED_LONG))
return new java.math.BigInteger(value);
if (datatype.equals(QNAME_XSD_INTEGER) || datatype.equals(QNAME_XSD_HASH_INTEGER))
return new java.math.BigInteger(value);
if (datatype.equals(QNAME_XSD_NON_NEGATIVE_INTEGER) || datatype.equals(QNAME_XSD_HASH_NON_NEGATIVE_INTEGER))
return new java.math.BigInteger(value);
if (datatype.equals(QNAME_XSD_NON_POSITIVE_INTEGER) || datatype.equals(QNAME_XSD_HASH_NON_POSITIVE_INTEGER))
return new java.math.BigInteger(value);
if (datatype.equals(QNAME_XSD_POSITIVE_INTEGER) || datatype.equals(QNAME_XSD_HASH_POSITIVE_INTEGER))
return new java.math.BigInteger(value);
if (datatype.equals(QNAME_XSD_ANY_URI) || datatype.equals(QNAME_XSD_HASH_ANY_URI)) {
URIWrapper u = new URIWrapper();
u.setValue(URI.create(value));
return u;
}
if (datatype.equals(QNAME_XSD_QNAME) || datatype.equals(QNAME_XSD_HASH_QNAME)) {
return pFactory.newQName(value);
}
if (datatype.equals(QNAME_XSD_DATETIME) || datatype.equals(QNAME_XSD_HASH_DATETIME)) {
return pFactory.newISOTime(value);
}
if (datatype.equals(QNAME_XSD_GYEAR) || datatype.equals(QNAME_XSD_HASH_GYEAR)) {
return pFactory.newGYear(value);
}
//transform to qname!!
if ((datatype.equals("rdf:XMLLiteral"))
|| (datatype.equals("xsd:normalizedString"))
|| (datatype.equals("xsd:token"))
|| (datatype.equals("xsd:language"))
|| (datatype.equals("xsd:Name"))
|| (datatype.equals("xsd:NCName"))
|| (datatype.equals("xsd:NMTOKEN"))
|| (datatype.equals("xsd:hexBinary"))
|| (datatype.equals("xsd:base64Binary"))) {
throw new UnsupportedOperationException(
"KNOWN literal type but conversion not supported yet "
+ datatype);
}
throw new UnsupportedOperationException("UNKNOWN literal type "
+ datatype);
}
public QName getXsdType(Object o) {
if (o instanceof Integer)
return QNAME_XSD_INT; //"xsd:int";
if (o instanceof String)
return QNAME_XSD_STRING; //"xsd:string";
if (o instanceof InternationalizedString)
return QNAME_XSD_STRING; //"xsd:string";
if (o instanceof BigInteger)
return QNAME_XSD_INTEGER;
if (o instanceof Long)
return QNAME_XSD_LONG; //"xsd:long";
if (o instanceof Short)
return QNAME_XSD_SHORT; //"xsd:short";
if (o instanceof Double)
return QNAME_XSD_DOUBLE; //"xsd:double";
if (o instanceof Float)
return QNAME_XSD_FLOAT; //"xsd:float";
if (o instanceof java.math.BigDecimal)
return QNAME_XSD_DECIMAL; //"xsd:decimal";
if (o instanceof Boolean)
return QNAME_XSD_BOOLEAN; //"xsd:boolean";
if (o instanceof Byte)
return QNAME_XSD_BYTE; //"xsd:byte";
if (o instanceof URIWrapper)
return QNAME_XSD_ANY_URI; //"xsd:anyURI";
if (o instanceof QName)
return QNAME_XSD_QNAME; //"xsd:QName";
if (o instanceof XMLGregorianCalendar) {
XMLGregorianCalendar cal=(XMLGregorianCalendar)o;
QName t=cal.getXMLSchemaType();
if (t.getLocalPart().equals(QNAME_XSD_GYEAR.getLocalPart())) return QNAME_XSD_GYEAR;
if (t.getLocalPart().equals(QNAME_XSD_DATETIME.getLocalPart())) return QNAME_XSD_DATETIME;
//TODO: need to support all time related xsd types
// default, return xsd:datetime
return QNAME_XSD_DATETIME;
}
//FIXME: see issue #54, value can be an element, when xsi:type was unspecified.
System.out.println("getXsdType() " + o.getClass());
return QNAME_UNKNOWN;
}
}
|
package com.cookpad.puree.outputs;
import com.cookpad.puree.PureeLogger;
import com.cookpad.puree.async.AsyncResult;
import com.cookpad.puree.internal.PureeVerboseRunnable;
import com.cookpad.puree.internal.RetryableTaskRunner;
import com.cookpad.puree.storage.EnhancedPureeStorage;
import com.cookpad.puree.storage.Records;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public abstract class PureeBufferedOutput extends PureeOutput {
RetryableTaskRunner flushTask;
ScheduledExecutorService executor;
public PureeBufferedOutput() {
}
@Override
public void initialize(PureeLogger logger) {
super.initialize(logger);
executor = logger.getExecutor();
flushTask = new RetryableTaskRunner(new Runnable() {
@Override
public void run() {
flush();
}
}, conf.getFlushIntervalMillis(), conf.getMaxRetryCount(), executor);
}
@Override
public void receive(final String jsonLog) {
executor.execute(new PureeVerboseRunnable(new Runnable() {
@Override
public void run() {
String filteredLog = applyFilters(jsonLog);
if (filteredLog != null) {
storage.insert(type(), filteredLog);
}
}
}));
flushTask.tryToStart();
}
@Override
public void flush() {
executor.execute(new PureeVerboseRunnable(new Runnable() {
@Override
public void run() {
flushSync();
}
}));
}
public void flushSync() {
if (!storage.lock()) {
flushTask.retryLater();
return;
}
purgeRecordsFromStorage();
final Records records = getRecordsFromStorage();
if (records.isEmpty()) {
storage.unlock();
flushTask.reset();
return;
}
final List<String> jsonLogs = records.getJsonLogs();
emit(jsonLogs, new AsyncResult() {
@Override
public void success() {
flushTask.reset();
storage.delete(records);
storage.unlock();
}
@Override
public void fail() {
flushTask.retryLater();
storage.unlock();
}
});
}
private Records getRecordsFromStorage() {
return storage.select(type(), conf.getLogsPerRequest());
}
public abstract void emit(List<String> jsonLogs, final AsyncResult result);
private void purgeRecordsFromStorage() {
if (!(storage instanceof EnhancedPureeStorage) || conf.getPurgeAgeMillis() < 0) {
return;
}
((EnhancedPureeStorage) storage).delete(type(), conf.getPurgeAgeMillis());
}
public void emit(String jsonLog) {
// do nothing
}
}
|
package com.jetbrains.python.edu.debugger;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.filters.UrlFilter;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.actions.CloseAction;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.ide.actions.ContextHelpAction;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XDebuggerBundle;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.impl.ui.XDebugSessionTab;
import com.jetbrains.python.console.PythonDebugLanguageConsoleView;
import com.jetbrains.python.debugger.PyDebugProcess;
import com.jetbrains.python.debugger.PyDebugRunner;
import com.jetbrains.python.debugger.PyLineBreakpointType;
import com.jetbrains.python.run.PythonCommandLineState;
import com.jetbrains.python.run.PythonRunConfiguration;
import com.jetbrains.python.run.PythonTracebackFilter;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.net.ServerSocket;
public class PyEduDebugRunner extends PyDebugRunner {
private static final Logger LOG = Logger.getInstance(PyEduDebugRunner.class);
public static final int NO_LINE = -1;
@Override
public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
return executorId.equals(PyEduDebugExecutor.ID);
}
@NotNull
@Override
protected PyDebugProcess createDebugProcess(@NotNull XDebugSession session,
ServerSocket serverSocket,
ExecutionResult result,
PythonCommandLineState pyState) {
ExecutionConsole executionConsole = result.getExecutionConsole();
ProcessHandler processHandler = result.getProcessHandler();
boolean isMultiProcess = pyState.isMultiprocessDebug();
String scriptName = getScriptName(pyState);
if (scriptName != null) {
VirtualFile file = VfsUtil.findFileByIoFile(new File(scriptName), true);
if (file != null) {
int line = getBreakpointLineNumber(file, session.getProject());
if (line != NO_LINE) {
return new PyEduDebugProcess(session, serverSocket,
executionConsole, processHandler,
isMultiProcess, scriptName, line + 1);
}
}
}
LOG.info("Failed to create PyEduDebugProcess. PyDebugProcess created instead.");
return new PyDebugProcess(session, serverSocket, executionConsole,
processHandler, isMultiProcess);
}
@Nullable
private static String getScriptName(PythonCommandLineState pyState) {
ExecutionEnvironment environment = pyState.getEnvironment();
if (environment == null) {
return null;
}
RunProfile runProfile = environment.getRunProfile();
if (runProfile instanceof PythonRunConfiguration) {
return FileUtil.toSystemIndependentName(((PythonRunConfiguration)runProfile).getScriptName());
}
return null;
}
/**
* @return the smallest line (from 0 to line number) suitable to set breakpoint on it, NO_LINE if there is no such line in the file
*/
private static int getBreakpointLineNumber(@NotNull final VirtualFile file, @NotNull final Project project) {
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) {
return NO_LINE;
}
PyLineBreakpointType lineBreakpointType = new PyLineBreakpointType();
for (int line = 0; line < document.getLineCount(); line++) {
if (lineBreakpointType.canPutAt(file, line, project)) {
return line;
}
}
return NO_LINE;
}
@Override
protected void initSession(XDebugSession session, RunProfileState state, Executor executor) {
XDebugSessionTab tab = ((XDebugSessionImpl)session).getSessionTab();
if (tab != null) {
RunnerLayoutUi ui = tab.getUi();
ContentManager contentManager = ui.getContentManager();
Content content = findContent(contentManager, XDebuggerBundle.message("debugger.session.tab.watches.title"));
if (content != null) {
contentManager.removeContent(content, true);
}
content = findContent(contentManager, XDebuggerBundle.message("debugger.session.tab.console.content.name"));
if (content != null) {
contentManager.removeContent(content, true);
}
initEduConsole(session, ui);
}
}
private static void initEduConsole(@NotNull final XDebugSession session,
@NotNull final RunnerLayoutUi ui) {
Project project = session.getProject();
final Sdk sdk = PythonSdkType.findPythonSdk(ModuleManager.getInstance(project).getModules()[0]);
final PythonDebugLanguageConsoleView view = new PythonDebugLanguageConsoleView(project, sdk);
final ProcessHandler processHandler = session.getDebugProcess().getProcessHandler();
view.attachToProcess(processHandler);
view.addMessageFilter(new PythonTracebackFilter(project));
view.addMessageFilter(new UrlFilter());
view.enableConsole(false);
Content eduConsole =
ui.createContent("EduConsole", view.getComponent(),
XDebuggerBundle.message("debugger.session.tab.console.content.name"),
AllIcons.Debugger.ToolConsole, view.getPreferredFocusableComponent());
eduConsole.setCloseable(false);
ui.addContent(eduConsole, 0, PlaceInGrid.right, false);
PyDebugProcess process = (PyDebugProcess)session.getDebugProcess();
PyDebugRunner.initDebugConsoleView(project, process, view, processHandler, session);
patchLeftToolbar(session, ui);
}
private static void patchLeftToolbar(@NotNull XDebugSession session, @NotNull RunnerLayoutUi ui) {
DefaultActionGroup newLeftToolbar = new DefaultActionGroup();
DefaultActionGroup firstGroup = new DefaultActionGroup();
addActionToGroup(firstGroup, XDebuggerActions.RESUME);
addActionToGroup(firstGroup, IdeActions.ACTION_STOP_PROGRAM);
newLeftToolbar.addAll(firstGroup);
newLeftToolbar.addSeparator();
Executor executor = PyEduDebugExecutor.getInstance();
newLeftToolbar.add(new CloseAction(executor, session.getRunContentDescriptor(), session.getProject()));
//TODO: return proper helpID
newLeftToolbar.add(new ContextHelpAction(executor.getHelpId()));
ui.getOptions().setLeftToolbar(newLeftToolbar, ActionPlaces.DEBUGGER_TOOLBAR);
}
private static void addActionToGroup(DefaultActionGroup group, String actionId) {
AnAction action = ActionManager.getInstance().getAction(actionId);
if (action != null) {
action.getTemplatePresentation().setEnabled(true);
group.add(action, Constraints.LAST);
}
}
@Nullable
private static Content findContent(ContentManager manager, String name) {
for (Content content : manager.getContents()) {
if (content.getDisplayName().equals(name)) {
return content;
}
}
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.