answer
stringlengths 17
10.2M
|
|---|
package org.csstudio.display.builder.editor.util;
import static org.csstudio.display.builder.editor.Plugin.logger;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.csstudio.display.builder.editor.DisplayEditor;
import org.csstudio.display.builder.editor.EditorUtil;
import org.csstudio.display.builder.editor.Messages;
import org.csstudio.display.builder.editor.palette.Palette;
import org.csstudio.display.builder.editor.tracker.SelectedWidgetUITracker;
import org.csstudio.display.builder.model.DisplayModel;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetDescriptor;
import org.csstudio.display.builder.model.WidgetFactory;
import org.csstudio.display.builder.model.persist.ModelReader;
import org.csstudio.display.builder.model.persist.ModelWriter;
import org.csstudio.display.builder.model.persist.WidgetClassesService;
import org.csstudio.display.builder.model.util.ModelResourceUtil;
import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget;
import org.csstudio.display.builder.model.widgets.LabelWidget;
import org.csstudio.display.builder.model.widgets.PVWidget;
import org.csstudio.display.builder.model.widgets.PictureWidget;
import org.csstudio.display.builder.model.widgets.WebBrowserWidget;
import org.csstudio.display.builder.representation.ToolkitRepresentation;
import org.eclipse.osgi.util.NLS;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
/** Helper for widget drag/drop
*
* <h3>Handling New File/URL Extensions</h3>
* To add the support for a new set of file/URL extensions do the following:
* <ul>
* <li>Create a new static list of extensions (see {@link #IMAGE_FILE_EXTENSIONS});</li>
* <li>Update {@link #SUPPORTED_EXTENSIONS} to include the new list;</li>
* <li>Update {@link #installWidgetsFromFiles(List,SelectedWidgetUITracker,List)
* to handle files having the new extensions;</li>
* <li>Update {@link #installWidgetsFromURL(DragEvent,List)
* to handle URLs having the new extensions.</li>
* </ul>
*
* @author Kay Kasemir
* @author Claudio Rosati
*/
@SuppressWarnings("nls")
public class WidgetTransfer
{
private static Color TRANSPARENT = new Color(0, 0, 0, 24);
private static Stroke OUTLINE_STROKE = new BasicStroke(2.2F);
// The extensions listed here MUST BE ALL UPPERCASE.
private static List<String> IMAGE_FILE_EXTENSIONS = Arrays.asList("BMP", "GIF", "JPEG", "JPG", "PNG", "SVG");
private static List<String> EMBEDDED_FILE_EXTENSIONS = Arrays.asList("BOB", "OPI");
private static List<String> SUPPORTED_EXTENSIONS = Stream.concat(IMAGE_FILE_EXTENSIONS.stream(), EMBEDDED_FILE_EXTENSIONS.stream()).collect(Collectors.toList());
// Lazily initialized list of widgets that have a PV
private static List<WidgetDescriptor> pvWidgetDescriptors = null;
// Could create custom data format, or use "application/xml".
// Transferring as DataFormat("text/plain"), however, allows exchange
// with basic text editor, which can be very convenient.
/** Add support for 'dragging' a widget out of a node
*
* @param source Source {@link Node}
* @param selection
* @param desc Description of widget type to drag
* @param image Image to represent the widget, or <code>null</code>
*/
public static void addDragSupport(final Node source, final DisplayEditor editor,
final Palette palette, final WidgetDescriptor descriptor, final Image image)
{
source.setOnDragDetected( ( MouseEvent event ) ->
{
logger.log(Level.FINE, "Starting drag for {0}", descriptor);
editor.getWidgetSelectionHandler().clear();
final Widget widget = descriptor.createWidget();
// In class editor mode, create widget with some class name.
// In display editor mode, apply the class settings.
final DisplayModel model = editor.getModel();
if (model != null && model.isClassModel())
widget.propName().setValue("MY_CLASS");
else
WidgetClassesService.getWidgetClasses().apply(widget);
final String xml;
try
{
xml = ModelWriter.getXML(Arrays.asList(widget));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot drag-serialize", ex);
return;
}
final Dragboard db = source.startDragAndDrop(TransferMode.COPY);
final ClipboardContent content = new ClipboardContent();
content.putString(xml);
db.setContent(content);
final int width = widget.propWidth().getValue();
final int height = widget.propHeight().getValue();
db.setDragView(createDragImage(widget, image, width, height), width / 2, -height / 2);
event.consume();
});
source.setOnDragDone(event ->
{ // Widget was dropped
// -> Stop scrolling, clear the selected palette entry
editor.getAutoScrollHandler().canceTimeline();
palette.clearSelectedWidgetType();
});
}
/** Add support for dropping widgets
*
* @param node Node that will receive the widgets
* @param group_handler Group handler
* @param selection_tracker The selection tracker.
* @param handleDroppedModel Callback for handling the dropped widgets
*/
public static void addDropSupport(
final Node node,
final ParentHandler group_handler,
final SelectedWidgetUITracker selection_tracker,
final Consumer<List<Widget>> handleDroppedModel)
{
node.setOnDragOver( ( DragEvent event ) ->
{
final Dragboard db = event.getDragboard();
if (db.hasString() || db.hasUrl() || db.hasRtf() || db.hasHtml() || db.hasImage() || db.hasFiles())
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
group_handler.locateParent(event.getX(), event.getY(), 10, 10);
event.consume();
});
node.setOnDragDropped( (DragEvent event) ->
{
final Dragboard db = event.getDragboard();
final Point2D location = selection_tracker.gridConstrain(event.getX(), event.getY());
final List<Widget> widgets = new ArrayList<>();
final List<Runnable> updates = new ArrayList<>();
if (db.hasFiles() && canAcceptFiles(db.getFiles()))
installWidgetsFromFiles(db, selection_tracker, widgets, updates);
else if (db.hasImage() && db.getImage() != null)
installWidgetsFromImage(db, selection_tracker, widgets);
else if (db.hasUrl() && db.getUrl() != null)
installWidgetsFromURL(event, widgets, updates);
else if (db.hasHtml() && db.getHtml() != null)
installWidgetsFromHTML(event, selection_tracker, widgets);
else if (db.hasRtf() && db.getRtf() != null)
installWidgetsFromRTF(event, selection_tracker, widgets);
else if (db.hasString() && db.getString() != null)
installWidgetsFromString(event, selection_tracker, widgets);
if (widgets.isEmpty())
event.setDropCompleted(false);
else
{
logger.log(Level.FINE, "Dropped {0} widgets.", widgets.size());
GeometryTools.moveWidgets((int) location.getX(), (int) location.getY(), widgets);
handleDroppedModel.accept(widgets);
// Now that model holds the widgets, perform updates that for example check an image size
for (Runnable update : updates)
EditorUtil.getExecutor().execute(update);
event.setDropCompleted(true);
}
event.consume();
});
}
/** Return {@code true} if there is a {@link File} in {@code files}
* whose extension is one of the {@link #SUPPORTED_EXTENSIONS}.
*
* <P>
* <B>Note:<B> only one file will be accepted: the first one
* matching the above condition.
*
* @param files The {@link List} of {@link File}s to be checked.
* Can be {@code null} or empty.
* @return {@code true} if a file existing whose extension is
* contained in {@link #SUPPORTED_EXTENSIONS}.
*/
private static boolean canAcceptFiles(final List<File> files)
{
if (files != null && !files.isEmpty())
return files.stream().anyMatch(f -> SUPPORTED_EXTENSIONS.contains(FilenameUtils.getExtension(f.toString()).toUpperCase()));
return false;
}
/** Create a image representing the dragged widget.
*
* @param widget The {@link Widget} being dragged.
* @param image The widget's type image. Can be {@code null}.
* @return An {@link Image} instance.
*/
private static Image createDragImage (final Widget widget, final Image image, final int width, final int height)
{
final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = bImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setBackground(TRANSPARENT);
g2d.clearRect(0, 0, width, height);
g2d.setColor(Color.ORANGE);
g2d.setStroke(OUTLINE_STROKE);
g2d.drawRect(0, 0, width, height);
if ( image != null )
{
int w = (int) image.getWidth();
int h = (int) image.getHeight();
BufferedImage bbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
SwingFXUtils.fromFXImage(image, bbImage);
g2d.drawImage(bbImage, (int) ( ( width - w ) / 2.0 ), (int) ( ( height - h ) / 2.0 ), null);
}
final WritableImage dImage = new WritableImage(width, height);
SwingFXUtils.toFXImage(bImage, dImage);
return dImage;
}
/** @param image_file The image file used to create and preset a {@link PictureWidget}.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void imageFileAcceptor(final String image_file, final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
logger.log(Level.FINE, "Creating PictureWidget for dropped image {0}", image_file);
final DisplayModel model = selection_tracker.getModel();
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(image_file);
final int index = widgets.size();
widget.propX().setValue(model.propGridStepX().getValue() * index);
widget.propY().setValue(model.propGridStepY().getValue() * index);
widgets.add(widget);
updates.add(() -> updatePictureWidget(widget));
}
/** Update a picture widget's size from image file
* @param widget {@link PictureWidget}
*/
private static void updatePictureWidget(final PictureWidget widget)
{
final String image_file = widget.propFile().getValue();
try
{
final String filename = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), image_file);
final BufferedImage image = ImageIO.read(ModelResourceUtil.openResourceStream(filename));
widget.propWidth().setValue(image.getWidth());
widget.propHeight().setValue(image.getHeight());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot obtain image size for " + image_file, ex);
}
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void installWidgetsFromFiles(final Dragboard db, final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
final List<File> files = db.getFiles();
for (int i = 0; i < files.size(); i++)
{
String filename = files.get(i).toString();
// If running under RCP, try to convert dropped files which are always
// absolute file system locations into workspace resource
final String workspace_file = ModelResourceUtil.getWorkspacePath(filename);
if (workspace_file != null)
filename = workspace_file;
// Attempt to turn into relative path
final DisplayModel model = selection_tracker.getModel();
filename = ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename);
final String extension = FilenameUtils.getExtension(filename).toUpperCase();
if (IMAGE_FILE_EXTENSIONS.contains(extension))
imageFileAcceptor(filename, selection_tracker, widgets, updates);
else if (EMBEDDED_FILE_EXTENSIONS.contains(extension) )
displayFileAcceptor(filename, selection_tracker, widgets, updates);
}
}
/** @param event The {@link DragEvent} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromHTML(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
String html = db.getHtml();
HTMLEditorKit htmlParser = new HTMLEditorKit();
Document document = htmlParser.createDefaultDocument();
try
{
htmlParser.read(new ByteArrayInputStream(html.getBytes()), document, 0);
installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Invalid HTML string", ex);
}
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the display model.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromImage(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
logger.log(Level.FINE, "Dropped image: creating PictureWidget");
final DisplayModel model = selection_tracker.getModel();
final ToolkitRepresentation<?, ?> toolkit = ToolkitRepresentation.getToolkit(selection_tracker.getModel());
final String filename = toolkit.showSaveAsDialog(model, null);
if (filename == null)
return;
final Image image = db.getImage();
if (image == null)
return;
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propWidth().setValue((int) image.getWidth());
widget.propHeight().setValue((int) image.getHeight());
widgets.add(widget);
// File access should not be on UI thread,
// but we need to return the widget right away.
// -> Return the widget now,
// create the image file later,
// and then update the widget's file property
EditorUtil.getExecutor().execute(() ->
{
try
{
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bImage, "png", new File(filename));
widget.propFile().setValue(ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot save image as " + filename, ex);
}
});
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromRTF(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
final String rtf = db.getRtf();
final RTFEditorKit rtfParser = new RTFEditorKit();
final Document document = rtfParser.createDefaultDocument();
try
{
rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document, 0);
installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Invalid RTF string", ex);
}
}
/** @param event The {@link DragEvent} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromString(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
final String xmlOrText = db.getString();
try
{
final DisplayModel model = ModelReader.parseXML(xmlOrText);
widgets.addAll(model.getChildren());
}
catch (Exception ex)
{
installWidgetsFromString(event, xmlOrText, selection_tracker, widgets);
}
}
private static void installWidgetsFromString(final DragEvent event, final String text, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
// Consider each word a separate PV
final String[] words = text.split("[ \n]+");
final boolean multiple = words.length > 1;
final List<WidgetDescriptor> descriptors = getPVWidgetDescriptors();
final List<String> choices = new ArrayList<>(descriptors.size() + ( multiple ? 1 : 0 ));
final String format = multiple ? Messages.WT_FromString_multipleFMT : Messages.WT_FromString_singleFMT;
// Always offer a single LabelWidget for the complete text
final String defaultChoice = NLS.bind(Messages.WT_FromString_singleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName());
choices.add(defaultChoice);
// When multiple words were dropped, offer multiple label widgets
if (multiple)
choices.add(NLS.bind(Messages.WT_FromString_multipleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName()));
choices.addAll(descriptors.stream().map(d -> NLS.bind(format, d.getName())).collect(Collectors.toList()));
Collections.sort(choices);
final ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, choices);
dialog.setX(event.getScreenX()-100);
dialog.setY(event.getScreenY()-200);
dialog.setTitle(Messages.WT_FromString_dialog_title);
dialog.setHeaderText(NLS.bind(Messages.WT_FromString_dialog_headerFMT, reduceStrings(words)));
dialog.setContentText(Messages.WT_FromString_dialog_content);
final Optional<String> result = dialog.showAndWait();
if (! result.isPresent())
return;
final String choice = result.get();
if (defaultChoice.equals(choice))
{
logger.log(Level.FINE, "Dropped text: created LabelWidget [{0}].", text);
// Not a valid XML. Instantiate a Label object.
final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propText().setValue(text);
widgets.add(widget);
}
else
{ // Parse choice back into widget descriptor
final MessageFormat msgf = new MessageFormat(format);
final String descriptorName;
try
{
descriptorName = msgf.parse(choice)[0].toString();
}
catch (Exception ex)
{
logger.log(Level.SEVERE, "Cannot parse selected widget type " + choice, ex);
return;
}
WidgetDescriptor descriptor = null;
if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(descriptorName))
descriptor = LabelWidget.WIDGET_DESCRIPTOR;
else
descriptor = descriptors.stream().filter(d -> descriptorName.equals(d.getName())).findFirst().orElse(null);
if (descriptor == null)
{
logger.log(Level.SEVERE, "Cannot obtain widget for " + descriptorName);
return;
}
for (String word : words)
{
final Widget widget = descriptor.createWidget();
logger.log(Level.FINE, "Dropped text: created {0} [{1}].", new Object[] { widget.getClass().getSimpleName(), word });
if (widget instanceof PVWidget)
((PVWidget) widget).propPVName().setValue(word);
else if (widget instanceof LabelWidget)
((LabelWidget) widget).propText().setValue(word);
else
logger.log(Level.WARNING, "Unexpected widget type [{0}].", widget.getClass().getSimpleName());
final int index = widgets.size();
if (index > 0)
{ // Place widgets below each other
final Widget previous = widgets.get(index - 1);
int x = previous.propX().getValue();
int y = previous.propY().getValue() + previous.propHeight().getValue();
// Align (if enabled)
final Point2D pos = selection_tracker.gridConstrain(x, y);
widget.propX().setValue((int)pos.getX());
widget.propY().setValue((int)pos.getY());
}
widgets.add(widget);
}
}
}
/** @return Widgets that have a PV */
private static List<WidgetDescriptor> getPVWidgetDescriptors()
{
if (pvWidgetDescriptors == null)
pvWidgetDescriptors = WidgetFactory.getInstance().getWidgetDescriptions()
.stream()
.filter(d -> d.createWidget() instanceof PVWidget)
.collect(Collectors.toList());
return pvWidgetDescriptors;
}
private static void installWidgetsFromURL(final DragEvent event, final List<Widget> widgets, final List<Runnable> updates)
{
final String choice;
final Dragboard db = event.getDragboard();
String url = db.getUrl();
// Fix URL, which on linux can contain the file name twice:
int sep = url.indexOf('\n');
if (sep > 0)
url = url.substring(0, sep);
// Check URL's extension
sep = url.lastIndexOf('.');
final String ext = sep > 0 ? url.substring(1 + sep).toUpperCase() : null;
if (EMBEDDED_FILE_EXTENSIONS.contains(ext))
choice = EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName();
else if (IMAGE_FILE_EXTENSIONS.contains(ext))
choice = PictureWidget.WIDGET_DESCRIPTOR.getName();
else
{ // Prompt user
final List<String> choices = Arrays.asList(LabelWidget.WIDGET_DESCRIPTOR.getName(),
EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(),
PictureWidget.WIDGET_DESCRIPTOR.getName(),
WebBrowserWidget.WIDGET_DESCRIPTOR.getName());
final ChoiceDialog<String> dialog = new ChoiceDialog<>(choices.get(3), choices);
// Position dialog
dialog.setX(event.getScreenX());
dialog.setY(event.getScreenY());
dialog.setTitle(Messages.WT_FromURL_dialog_title);
dialog.setHeaderText(NLS.bind(Messages.WT_FromURL_dialog_headerFMT, reduceURL(url)));
dialog.setContentText(Messages.WT_FromURL_dialog_content);
final Optional<String> result = dialog.showAndWait();
if (result.isPresent())
choice = result.get();
else
return;
}
if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating LabelWidget for {0}", url);
final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propText().setValue(url);
widgets.add(widget);
}
else if (WebBrowserWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating WebBrowserWidget for {0}", url);
final WebBrowserWidget widget = (WebBrowserWidget) WebBrowserWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propWidgetURL().setValue(url);
widgets.add(widget);
}
else if (PictureWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating PictureWidget for {0}", url);
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(url);
widgets.add(widget);
updates.add(() -> updatePictureWidget(widget));
}
else if (EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", url);
EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(url);
widgets.add(widget);
updates.add(() -> updateEmbeddedWidget(widget));
}
}
/** @param display_file Display file for which to create an {@link EmbeddedDisplayWidget}.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void displayFileAcceptor(final String display_file,
final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", display_file);
final DisplayModel model = selection_tracker.getModel();
final EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(display_file);
// Offset multiple widgets by grid size
final int index = widgets.size();
widget.propX().setValue(model.propGridStepX().getValue() * index);
widget.propY().setValue(model.propGridStepY().getValue() * index);
widgets.add(widget);
updates.add(() -> updateEmbeddedWidget(widget));
}
/** Update an embedded widget's name and size from its input
* @param widget {@link EmbeddedDisplayWidget}
*/
private static void updateEmbeddedWidget(final EmbeddedDisplayWidget widget)
{
final String display_file = widget.propFile().getValue();
final String resolved;
try
{
resolved = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), display_file);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot resolve resource " + display_file, ex);
return;
}
try
(
final InputStream bis = ModelResourceUtil.openResourceStream(resolved);
)
{
final ModelReader reader = new ModelReader(bis);
final DisplayModel embedded_model = reader.readModel();
final String name = embedded_model.getName();
if (! name.isEmpty())
widget.propName().setValue(name);
widget.propWidth().setValue(embedded_model.propWidth().getValue());
widget.propHeight().setValue(embedded_model.propHeight().getValue());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error updating embedded widget", ex);
}
}
private static String reduceString(String text)
{
if (text.length() <= 64)
return text;
else
return StringUtils.join(StringUtils.left(text, 32), "...", StringUtils.right(text, 32));
}
private static String reduceStrings(String[] lines)
{
final int ALLOWED_LINES = 16; // Should be a even number.
List<String> validLines = new ArrayList<>(1 + ALLOWED_LINES);
if ( lines.length <= ALLOWED_LINES )
Arrays.asList(lines).stream().forEach(l -> validLines.add(reduceString(l)));
else
{
for ( int i = 0; i < ALLOWED_LINES / 2; i++ )
validLines.add(reduceString(lines[i]));
validLines.add("...");
for ( int i = lines.length - ALLOWED_LINES / 2; i < lines.length; i++ )
validLines.add(reduceString(lines[i]));
}
StringBuilder builder = new StringBuilder();
validLines.stream().forEach(l -> builder.append(l).append("\n"));
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/** Return a reduced version of the given {@code url}.
*
* @param url An URL string that, if long, must be reduced
* to a shorter version to be displayed.
* @return A reduced version of the given {@code url}.
*/
private static String reduceURL(String url)
{
if (url.length() > 64)
{
String shortURL = url;
int leftSlash = 2;
int rightSlash = 2;
if (url.contains(":
leftSlash += 2;
else if (url.startsWith("/"))
leftSlash += 1;
if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash))
{
shortURL = reduceURL(url, leftSlash, rightSlash);
if (shortURL.length() <= 80)
return shortURL;
}
if (shortURL.length() > 64)
{
leftSlash
rightSlash
if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash))
{
shortURL = reduceURL(url, leftSlash, rightSlash);
if (shortURL.length() <= 80)
return shortURL;
}
}
if (shortURL.length() > 64)
return StringUtils.join(StringUtils.left(url, 32), "...", StringUtils.right(url, 32));
}
return url;
}
private static String reduceURL(String url, int leftSlash, int rightSlash)
{
int leftSlashIndex = StringUtils.ordinalIndexOf(url, "/", leftSlash);
int rightSlashIndex = StringUtils.ordinalIndexOf(StringUtils.reverse(url), "/", rightSlash);
return StringUtils.join(StringUtils.left(url, leftSlashIndex + 1), "...", StringUtils.right(url, rightSlashIndex + 1));
}
}
|
package org.csstudio.display.builder.editor.util;
import static org.csstudio.display.builder.editor.DisplayEditor.logger;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.csstudio.display.builder.editor.DisplayEditor;
import org.csstudio.display.builder.editor.EditorUtil;
import org.csstudio.display.builder.editor.Messages;
import org.csstudio.display.builder.editor.tracker.SelectedWidgetUITracker;
import org.csstudio.display.builder.model.DisplayModel;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetDescriptor;
import org.csstudio.display.builder.model.WidgetFactory;
import org.csstudio.display.builder.model.persist.ModelReader;
import org.csstudio.display.builder.model.persist.ModelWriter;
import org.csstudio.display.builder.model.util.ModelResourceUtil;
import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget;
import org.csstudio.display.builder.model.widgets.LabelWidget;
import org.csstudio.display.builder.model.widgets.PVWidget;
import org.csstudio.display.builder.model.widgets.PictureWidget;
import org.csstudio.display.builder.model.widgets.WebBrowserWidget;
import org.csstudio.display.builder.representation.ToolkitRepresentation;
import org.eclipse.osgi.util.NLS;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
/** Helper for widget drag/drop
*
* <h3>Handling New File/URL Extensions</h3>
* To add the support for a new set of file/URL extensions do the following:
* <ul>
* <li>Create a new static list of extensions (see {@link #IMAGE_FILE_EXTENSIONS});</li>
* <li>Update {@link #SUPPORTED_EXTENSIONS} to include the new list;</li>
* <li>Update {@link #installWidgetsFromFiles(List,SelectedWidgetUITracker,List)
* to handle files having the new extensions;</li>
* <li>Update {@link #installWidgetsFromURL(DragEvent,List)
* to handle URLs having the new extensions.</li>
* </ul>
*
* @author Kay Kasemir
* @author Claudio Rosati
*/
@SuppressWarnings("nls")
public class WidgetTransfer
{
private static Color TRANSPARENT = new Color(0, 0, 0, 24);
private static Stroke OUTLINE_STROKE = new BasicStroke(2.2F);
// The extensions listed here MUST BE ALL UPPERCASE.
private static List<String> IMAGE_FILE_EXTENSIONS = Arrays.asList("BMP", "GIF", "JPEG", "JPG", "PNG");
private static List<String> EMBEDDED_FILE_EXTENSIONS = Arrays.asList("BOB", "OPI");
private static List<String> SUPPORTED_EXTENSIONS = Stream.concat(IMAGE_FILE_EXTENSIONS.stream(), EMBEDDED_FILE_EXTENSIONS.stream()).collect(Collectors.toList());
// Lazily initialized list of widgets that have a PV
private static List<WidgetDescriptor> pvWidgetDescriptors = null;
// Could create custom data format, or use "application/xml".
// Transferring as DataFormat("text/plain"), however, allows exchange
// with basic text editor, which can be very convenient.
/** Add support for 'dragging' a widget out of a node
*
* @param source Source {@link Node}
* @param selection
* @param desc Description of widget type to drag
* @param image Image to represent the widget, or <code>null</code>
*/
public static void addDragSupport(final Node source, final DisplayEditor editor, final WidgetDescriptor descriptor, final Image image)
{
source.setOnDragDetected( ( MouseEvent event ) ->
{
logger.log(Level.FINE, "Starting drag for {0}", descriptor);
editor.getWidgetSelectionHandler().clear();
final Widget widget = descriptor.createWidget();
final String xml;
try
{
xml = ModelWriter.getXML(Arrays.asList(widget));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot drag-serialize", ex);
return;
}
final Dragboard db = source.startDragAndDrop(TransferMode.COPY);
final ClipboardContent content = new ClipboardContent();
content.putString(xml);
db.setContent(content);
final int width = widget.propWidth().getValue();
final int height = widget.propHeight().getValue();
db.setDragView(createDragImage(widget, image, width, height), width / 2, -height / 2);
event.consume();
});
source.setOnDragDone(event -> editor.getAutoScrollHandler().canceTimeline());
}
/** Add support for dropping widgets
*
* @param node Node that will receive the widgets
* @param group_handler Group handler
* @param selection_tracker The selection tracker.
* @param handleDroppedModel Callback for handling the dropped widgets
*/
public static void addDropSupport(
final Node node,
final ParentHandler group_handler,
final SelectedWidgetUITracker selection_tracker,
final Consumer<List<Widget>> handleDroppedModel)
{
node.setOnDragOver( ( DragEvent event ) ->
{
final Dragboard db = event.getDragboard();
if (db.hasString() || db.hasUrl() || db.hasRtf() || db.hasHtml() || db.hasImage() || db.hasFiles())
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
group_handler.locateParent(event.getX(), event.getY(), 10, 10);
event.consume();
});
node.setOnDragDropped( (DragEvent event) ->
{
final Dragboard db = event.getDragboard();
final Point2D location = selection_tracker.gridConstrain(event.getX(), event.getY());
final List<Widget> widgets = new ArrayList<>();
final List<Runnable> updates = new ArrayList<>();
if (db.hasFiles() && canAcceptFiles(db.getFiles()))
installWidgetsFromFiles(db, selection_tracker, widgets, updates);
else if (db.hasImage() && db.getImage() != null)
installWidgetsFromImage(db, selection_tracker, widgets);
else if (db.hasUrl() && db.getUrl() != null)
installWidgetsFromURL(event, widgets, updates);
else if (db.hasHtml() && db.getHtml() != null)
installWidgetsFromHTML(event, selection_tracker, widgets);
else if (db.hasRtf() && db.getRtf() != null)
installWidgetsFromRTF(event, selection_tracker, widgets);
else if (db.hasString() && db.getString() != null)
installWidgetsFromString(event, selection_tracker, widgets);
if (widgets.isEmpty())
event.setDropCompleted(false);
else
{
logger.log(Level.FINE, "Dropped {0} widgets.", widgets.size());
GeometryTools.moveWidgets((int) location.getX(), (int) location.getY(), widgets);
handleDroppedModel.accept(widgets);
// Now that model holds the widgets, perform updates that for example check an image size
for (Runnable update : updates)
EditorUtil.getExecutor().execute(update);
event.setDropCompleted(true);
}
event.consume();
});
}
/** Return {@code true} if there is a {@link File} in {@code files}
* whose extension is one of the {@link #SUPPORTED_EXTENSIONS}.
*
* <P>
* <B>Note:<B> only one file will be accepted: the first one
* matching the above condition.
*
* @param files The {@link List} of {@link File}s to be checked.
* Can be {@code null} or empty.
* @return {@code true} if a file existing whose extension is
* contained in {@link #SUPPORTED_EXTENSIONS}.
*/
private static boolean canAcceptFiles(final List<File> files)
{
if (files != null && !files.isEmpty())
return files.stream().anyMatch(f -> SUPPORTED_EXTENSIONS.contains(FilenameUtils.getExtension(f.toString()).toUpperCase()));
return false;
}
/** Create a image representing the dragged widget.
*
* @param widget The {@link Widget} being dragged.
* @param image The widget's type image. Can be {@code null}.
* @return An {@link Image} instance.
*/
private static Image createDragImage (final Widget widget, final Image image, final int width, final int height)
{
final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = bImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setBackground(TRANSPARENT);
g2d.clearRect(0, 0, width, height);
g2d.setColor(Color.ORANGE);
g2d.setStroke(OUTLINE_STROKE);
g2d.drawRect(0, 0, width, height);
if ( image != null )
{
int w = (int) image.getWidth();
int h = (int) image.getHeight();
BufferedImage bbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
SwingFXUtils.fromFXImage(image, bbImage);
g2d.drawImage(bbImage, (int) ( ( width - w ) / 2.0 ), (int) ( ( height - h ) / 2.0 ), null);
}
WritableImage dImage = new WritableImage(width, height);
SwingFXUtils.toFXImage(bImage, dImage);
return dImage;
}
/** @param image_file The image file used to create and preset a {@link PictureWidget}.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void imageFileAcceptor(final String image_file, final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
logger.log(Level.FINE, "Creating PictureWidget for dropped image {0}", image_file);
final DisplayModel model = selection_tracker.getModel();
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(image_file);
final int index = widgets.size();
widget.propX().setValue(model.propGridStepX().getValue() * index);
widget.propY().setValue(model.propGridStepY().getValue() * index);
widgets.add(widget);
updates.add(() -> updatePictureWidget(widget));
}
/** Update a picture widget's size from image file
* @param widget {@link PictureWidget}
*/
private static void updatePictureWidget(final PictureWidget widget)
{
final String image_file = widget.propFile().getValue();
try
{
final String filename = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), image_file);
final BufferedImage image = ImageIO.read(ModelResourceUtil.openResourceStream(filename));
widget.propWidth().setValue(image.getWidth());
widget.propHeight().setValue(image.getHeight());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot obtain image size for " + image_file, ex);
}
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void installWidgetsFromFiles(final Dragboard db, final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
final List<File> files = db.getFiles();
for (int i = 0; i < files.size(); i++)
{
String filename = files.get(i).toString();
// If running under RCP, try to convert dropped files which are always
// absolute file system locations into workspace resource
final String workspace_file = ModelResourceUtil.getWorkspacePath(filename);
if (workspace_file != null)
filename = workspace_file;
// Attempt to turn into relative path
final DisplayModel model = selection_tracker.getModel();
filename = ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename);
final String extension = FilenameUtils.getExtension(filename).toUpperCase();
if (IMAGE_FILE_EXTENSIONS.contains(extension))
imageFileAcceptor(filename, selection_tracker, widgets, updates);
else if (EMBEDDED_FILE_EXTENSIONS.contains(extension) )
displayFileAcceptor(filename, selection_tracker, widgets, updates);
}
}
/** @param event The {@link DragEvent} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromHTML(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
String html = db.getHtml();
HTMLEditorKit htmlParser = new HTMLEditorKit();
Document document = htmlParser.createDefaultDocument();
try
{
htmlParser.read(new ByteArrayInputStream(html.getBytes()), document, 0);
installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Invalid HTML string", ex);
}
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the display model.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromImage(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
logger.log(Level.FINE, "Dropped image: creating PictureWidget");
final DisplayModel model = selection_tracker.getModel();
final ToolkitRepresentation<?, ?> toolkit = ToolkitRepresentation.getToolkit(selection_tracker.getModel());
final String filename = toolkit.showSaveAsDialog(model, null);
if (filename == null)
return;
final Image image = db.getImage();
if (image == null)
return;
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propWidth().setValue((int) image.getWidth());
widget.propHeight().setValue((int) image.getHeight());
widgets.add(widget);
// File access should not be on UI thread,
// but we need to return the widget right away.
// -> Return the widget now,
// create the image file later,
// and then update the widget's file property
EditorUtil.getExecutor().execute(() ->
{
try
{
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bImage, "png", new File(filename));
widget.propFile().setValue(ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot save image as " + filename, ex);
}
});
}
/** @param db The {@link Dragboard} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromRTF(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
final String rtf = db.getRtf();
final RTFEditorKit rtfParser = new RTFEditorKit();
final Document document = rtfParser.createDefaultDocument();
try
{
rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document, 0);
installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Invalid RTF string", ex);
}
}
/** @param event The {@link DragEvent} containing the dragged data.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
*/
private static void installWidgetsFromString(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
final Dragboard db = event.getDragboard();
final String xmlOrText = db.getString();
try
{
final DisplayModel model = ModelReader.parseXML(xmlOrText);
widgets.addAll(model.getChildren());
}
catch (Exception ex)
{
installWidgetsFromString(event, xmlOrText, selection_tracker, widgets);
}
}
private static void installWidgetsFromString(final DragEvent event, final String text, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets)
{
// Consider each word a separate PV
final String[] words = text.split("[ \n]+");
final boolean multiple = words.length > 1;
final List<WidgetDescriptor> descriptors = getPVWidgetDescriptors();
final List<String> choices = new ArrayList<>(descriptors.size() + ( multiple ? 1 : 0 ));
final String format = multiple ? Messages.WT_FromString_multipleFMT : Messages.WT_FromString_singleFMT;
// Always offer a single LabelWidget for the complete text
final String defaultChoice = NLS.bind(Messages.WT_FromString_singleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName());
choices.add(defaultChoice);
// When multiple words were dropped, offer multiple label widgets
if (multiple)
choices.add(NLS.bind(Messages.WT_FromString_multipleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName()));
choices.addAll(descriptors.stream().map(d -> NLS.bind(format, d.getName())).collect(Collectors.toList()));
Collections.sort(choices);
final ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, choices);
dialog.setX(event.getScreenX()-100);
dialog.setY(event.getScreenY()-200);
dialog.setTitle(Messages.WT_FromString_dialog_title);
dialog.setHeaderText(NLS.bind(Messages.WT_FromString_dialog_headerFMT, reduceStrings(words)));
dialog.setContentText(Messages.WT_FromString_dialog_content);
final Optional<String> result = dialog.showAndWait();
if (! result.isPresent())
return;
final String choice = result.get();
if (defaultChoice.equals(choice))
{
logger.log(Level.FINE, "Dropped text: created LabelWidget [{0}].", text);
// Not a valid XML. Instantiate a Label object.
final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propText().setValue(text);
widgets.add(widget);
}
else
{ // Parse choice back into widget descriptor
final MessageFormat msgf = new MessageFormat(format);
final String descriptorName;
try
{
descriptorName = msgf.parse(choice)[0].toString();
}
catch (Exception ex)
{
logger.log(Level.SEVERE, "Cannot parse selected widget type " + choice, ex);
return;
}
WidgetDescriptor descriptor = null;
if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(descriptorName))
descriptor = LabelWidget.WIDGET_DESCRIPTOR;
else
descriptor = descriptors.stream().filter(d -> descriptorName.equals(d.getName())).findFirst().orElse(null);
if (descriptor == null)
{
logger.log(Level.SEVERE, "Cannot obtain widget for " + descriptorName);
return;
}
for (String word : words)
{
final Widget widget = descriptor.createWidget();
logger.log(Level.FINE, "Dropped text: created {0} [{1}].", new Object[] { widget.getClass().getSimpleName(), word });
if (widget instanceof PVWidget)
((PVWidget) widget).propPVName().setValue(word);
else if (widget instanceof LabelWidget)
((LabelWidget) widget).propText().setValue(word);
else
logger.log(Level.WARNING, "Unexpected widget type [{0}].", widget.getClass().getSimpleName());
final int index = widgets.size();
if (index > 0)
{ // Place widgets below each other
final Widget previous = widgets.get(index - 1);
int x = previous.propX().getValue();
int y = previous.propY().getValue() + previous.propHeight().getValue();
// Align (if enabled)
final Point2D pos = selection_tracker.gridConstrain(x, y);
widget.propX().setValue((int)pos.getX());
widget.propY().setValue((int)pos.getY());
}
widgets.add(widget);
}
}
}
/** @return Widgets that have a PV */
private static List<WidgetDescriptor> getPVWidgetDescriptors()
{
if (pvWidgetDescriptors == null)
pvWidgetDescriptors = WidgetFactory.getInstance().getWidgetDescriptions()
.stream()
.filter(d -> d.createWidget() instanceof PVWidget)
.collect(Collectors.toList());
return pvWidgetDescriptors;
}
private static void installWidgetsFromURL(final DragEvent event, final List<Widget> widgets, final List<Runnable> updates)
{
final String choice;
final Dragboard db = event.getDragboard();
String url = db.getUrl();
// Fix URL, which on linux can contain the file name twice:
int sep = url.indexOf('\n');
if (sep > 0)
url = url.substring(0, sep);
// Check URL's extension
sep = url.lastIndexOf('.');
final String ext = sep > 0 ? url.substring(1 + sep).toUpperCase() : null;
if (EMBEDDED_FILE_EXTENSIONS.contains(ext))
choice = EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName();
else if (IMAGE_FILE_EXTENSIONS.contains(ext))
choice = PictureWidget.WIDGET_DESCRIPTOR.getName();
else
{ // Prompt user
final List<String> choices = Arrays.asList(LabelWidget.WIDGET_DESCRIPTOR.getName(),
EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(),
PictureWidget.WIDGET_DESCRIPTOR.getName(),
WebBrowserWidget.WIDGET_DESCRIPTOR.getName());
final ChoiceDialog<String> dialog = new ChoiceDialog<>(choices.get(3), choices);
// Position dialog
dialog.setX(event.getScreenX());
dialog.setY(event.getScreenY());
dialog.setTitle(Messages.WT_FromURL_dialog_title);
dialog.setHeaderText(NLS.bind(Messages.WT_FromURL_dialog_headerFMT, reduceURL(url)));
dialog.setContentText(Messages.WT_FromURL_dialog_content);
final Optional<String> result = dialog.showAndWait();
if (result.isPresent())
choice = result.get();
else
return;
}
if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating LabelWidget for {0}", url);
final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propText().setValue(url);
widgets.add(widget);
}
else if (WebBrowserWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating WebBrowserWidget for {0}", url);
final WebBrowserWidget widget = (WebBrowserWidget) WebBrowserWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propWidgetURL().setValue(url);
widgets.add(widget);
}
else if (PictureWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating PictureWidget for {0}", url);
final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(url);
widgets.add(widget);
updates.add(() -> updatePictureWidget(widget));
}
else if (EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName().equals(choice))
{
logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", url);
EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(url);
widgets.add(widget);
updates.add(() -> updateEmbeddedWidget(widget));
}
}
/** @param display_file Display file for which to create an {@link EmbeddedDisplayWidget}.
* @param selection_tracker Used to get the grid steps from its model to be used
* in offsetting multiple widgets.
* @param widgets The container of the created widgets.
* @param updates Updates to perform on widgets
*/
private static void displayFileAcceptor(final String display_file,
final SelectedWidgetUITracker selection_tracker,
final List<Widget> widgets, final List<Runnable> updates)
{
logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", display_file);
final DisplayModel model = selection_tracker.getModel();
final EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget();
widget.propFile().setValue(display_file);
// Offset multiple widgets by grid size
final int index = widgets.size();
widget.propX().setValue(model.propGridStepX().getValue() * index);
widget.propY().setValue(model.propGridStepY().getValue() * index);
widgets.add(widget);
updates.add(() -> updateEmbeddedWidget(widget));
}
/** Update an embedded widget's name and size from its input
* @param widget {@link EmbeddedDisplayWidget}
*/
private static void updateEmbeddedWidget(final EmbeddedDisplayWidget widget)
{
final String display_file = widget.propFile().getValue();
final String resolved;
try
{
resolved = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), display_file);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot resolve resource " + display_file, ex);
return;
}
try
(
final InputStream bis = ModelResourceUtil.openResourceStream(resolved);
)
{
final ModelReader reader = new ModelReader(bis);
final DisplayModel embedded_model = reader.readModel();
final String name = embedded_model.getName();
if (! name.isEmpty())
widget.propName().setValue(name);
widget.propWidth().setValue(embedded_model.propWidth().getValue());
widget.propHeight().setValue(embedded_model.propHeight().getValue());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error updating embedded widget", ex);
}
}
private static String reduceString(String text)
{
if (text.length() <= 64)
return text;
else
return StringUtils.join(StringUtils.left(text, 32), "...", StringUtils.right(text, 32));
}
private static String reduceStrings(String[] lines)
{
final int ALLOWED_LINES = 16; // Should be a even number.
List<String> validLines = new ArrayList<>(1 + ALLOWED_LINES);
if ( lines.length <= ALLOWED_LINES )
Arrays.asList(lines).stream().forEach(l -> validLines.add(reduceString(l)));
else
{
for ( int i = 0; i < ALLOWED_LINES / 2; i++ )
validLines.add(reduceString(lines[i]));
validLines.add("...");
for ( int i = lines.length - ALLOWED_LINES / 2; i < lines.length; i++ )
validLines.add(reduceString(lines[i]));
}
StringBuilder builder = new StringBuilder();
validLines.stream().forEach(l -> builder.append(l).append("\n"));
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/** Return a reduced version of the given {@code url}.
*
* @param url An URL string that, if long, must be reduced
* to a shorter version to be displayed.
* @return A reduced version of the given {@code url}.
*/
private static String reduceURL(String url)
{
if (url.length() > 64)
{
String shortURL = url;
int leftSlash = 2;
int rightSlash = 2;
if (url.contains(":
leftSlash += 2;
else if (url.startsWith("/"))
leftSlash += 1;
if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash))
{
shortURL = reduceURL(url, leftSlash, rightSlash);
if (shortURL.length() <= 80)
return shortURL;
}
if (shortURL.length() > 64)
{
leftSlash
rightSlash
if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash))
{
shortURL = reduceURL(url, leftSlash, rightSlash);
if (shortURL.length() <= 80)
return shortURL;
}
}
if (shortURL.length() > 64)
return StringUtils.join(StringUtils.left(url, 32), "...", StringUtils.right(url, 32));
}
return url;
}
private static String reduceURL(String url, int leftSlash, int rightSlash)
{
int leftSlashIndex = StringUtils.ordinalIndexOf(url, "/", leftSlash);
int rightSlashIndex = StringUtils.ordinalIndexOf(StringUtils.reverse(url), "/", rightSlash);
return StringUtils.join(StringUtils.left(url, leftSlashIndex + 1), "...", StringUtils.right(url, rightSlashIndex + 1));
}
}
|
package org.eclipse.emf.emfstore.jaxrs.client;
import java.util.List;
import org.eclipse.emf.emfstore.internal.server.model.ProjectInfo;
import org.eclipse.emf.emfstore.internal.server.model.impl.ProjectInfoImpl;
import org.eclipse.emf.emfstore.internal.server.model.versioning.LogMessage;
/**
* @author Pascal
*
*/
public class JaxrsConnectionManager {
public List<ProjectInfo> getProjectList() {
// TODO: implement!
return null;
}
public ProjectInfo createEmptyProject(String name, String description, LogMessage logMessage) {
// TODO: implement!!!
return new ProjectInfoImpl();
}
}
|
package org.jcryptool.analysis.freqanalysis.ui;
import java.util.Arrays;
import java.util.Comparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisCalc;
import org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisData;
import org.jcryptool.analysis.graphtools.derivates.LabelBar;
import org.jcryptool.analysis.graphtools.derivates.OverlayLabelBar;
/**
* @author SLeischnig
*
*/
public class CustomFreqCanvas extends Canvas implements PaintListener, MouseMoveListener, MouseTrackListener {
private Composite mycomp;
private FreqAnalysisCalc myAnalysis, myOverlayAnalysis;
// Flag if mouseover shows details for a single bar...
private boolean overlay = false;
// Class for drawing calculations
private FreqAnalysisGraph frequencyGraph = new FreqAnalysisGraph(null, this.getSize().x, this.getSize().y);
// graph dragging variables
private boolean draggingEnabled = true;
private boolean dragging = false;
private int dragBeginX;
public final void setOverlayActivated(final boolean isOverlay) {
overlay = isOverlay;
buildBars();
}
public CustomFreqCanvas(final org.eclipse.swt.widgets.Composite parent, final int style) {
super(parent, SWT.DOUBLE_BUFFERED);
mycomp = parent;
// myAnalysis = analysis;
setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
int width = 0, height = 0;
width = mycomp.getSize().x;
height = mycomp.getSize().y;
setSize(width, height);
myAnalysis = new FreqAnalysisCalc("", 1, 0, null); //$NON-NLS-1$
myOverlayAnalysis = new FreqAnalysisCalc("", 1, 0, null); //$NON-NLS-1$
addPaintListener(this);
this.addPaintListener(this);
this.addMouseMoveListener(this);
this.addMouseTrackListener(this);
this.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(final MouseEvent evt) {
dragging = false;
if (getFrequencyGraph().setDraggedPixels(0, false)) {
redraw(); // reset the drag
}
}
});
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(final MouseEvent evt) {
if (dragging && draggingEnabled) {
int myPixelsDifference = evt.x - dragBeginX;
getFrequencyGraph().setDraggedPixels(myPixelsDifference, false);
}
dragging = false;
}
@Override
public void mouseDown(final MouseEvent evt) {
dragging = true;
dragBeginX = evt.x;
}
@Override
public void mouseDoubleClick(final MouseEvent evt) {
getFrequencyGraph().resetDrag();
redraw();
}
});
}
/**
* sets the Frequency analysis
*/
public final void setAnalysis(final FreqAnalysisCalc in) {
myAnalysis = in;
buildBars();
}
/**
* Sets the overlay Analysis
*/
public final void setOverlayAnalysis(final FreqAnalysisCalc in) {
myOverlayAnalysis = in;
buildBars();
}
/**
* Generates the bars for the drawing procedures
*/
private void buildBars() {
class CustomFreqAnalysisData extends FreqAnalysisData {
boolean isOverlayBar;
public CustomFreqAnalysisData() {
super();
}
public void copySuper(final FreqAnalysisData in) {
this.absOcc = in.absOcc;
this.ch = in.ch;
this.charPrinted = in.charPrinted;
this.relOcc = in.relOcc;
}
}
/**
* @author SLeischnig comparates two frequency analysis data sets for sorting
*/
class MyComparator implements Comparator<FreqAnalysisData> {
@Override
public int compare(final FreqAnalysisData a, final FreqAnalysisData b) {
if ((a.ch) > (b.ch)) {
return 1;
}
if ((a.ch) == (b.ch)) {
return 0;
}
return -1;
}
// No need to override equals.
}
// Copy all Analysis Data in one Array
CustomFreqAnalysisData[] allData = new CustomFreqAnalysisData[myAnalysis.getAnalysisArray().length
+ myOverlayAnalysis.getAnalysisArray().length];
for (int i = 0; i < myAnalysis.getAnalysisArray().length; i++) {
allData[i] = new CustomFreqAnalysisData();
allData[i].copySuper(myAnalysis.getAnalysisArray()[i]);
allData[i].isOverlayBar = false;
}
for (int i = 0; i < myOverlayAnalysis.getAnalysisArray().length; i++) {
allData[myAnalysis.getAnalysisArray().length + i] = new CustomFreqAnalysisData();
allData[myAnalysis.getAnalysisArray().length + i].copySuper(myOverlayAnalysis.getAnalysisArray()[i]);
allData[myAnalysis.getAnalysisArray().length + i].isOverlayBar = true;
}
// sort all Analysis Data in view of its character values (see comparator class)
Arrays.sort(allData, new MyComparator());
char actualChar = (char) 0;
int actualIndex = -1;
double maxValue = Math.max(max(myAnalysis.getAnalysisArray()), max(myOverlayAnalysis.getAnalysisArray()));
double barHeight = 0;
// generate Bars
getFrequencyGraph().resetBars();
for (int i = 0; i < allData.length; i++) {
// Only draw overlay bars when it's activated
if (overlay || (!allData[i].isOverlayBar)) {
if (allData[i].ch != actualChar) {
actualChar = allData[i].ch;
actualIndex++;
}
barHeight = (allData[i].relOcc) / (maxValue);
LabelBar myBar;
if (!allData[i].isOverlayBar) {
myBar = new LabelBar(barHeight, actualIndex, 10, "" + allData[i].absOcc, allData[i].charPrinted);
} else {
myBar = new OverlayLabelBar(barHeight, actualIndex, 11, "" + allData[i].absOcc,
allData[i].charPrinted);
}
myBar.attachedData.add(allData[i]);
getFrequencyGraph().addBar(myBar);
}
}
}
/**
* returns the maximum relative occurence in the frequency analysis set.
*
* @param t the frequency analysis set
* @return the highest relative occurence in the set
*/
private static double max(final FreqAnalysisData[] t) {
double maximum = -9999; // start with the first value
for (int i = 0; i < t.length; i++) {
if (t[i].relOcc > maximum) {
maximum = t[i].relOcc; // new maximum
}
}
return maximum;
}
@Override
public final void paintControl(final PaintEvent e) {
GC gc = e.gc;
int width = 0, height = 0;
width = this.getSize().x;
height = this.getSize().y;
getFrequencyGraph().setGC(gc);
getFrequencyGraph().updateBounds(width, height);
getFrequencyGraph().paintArea();
}
public final void setDraggingEnabled(final boolean dragEnabled) {
this.draggingEnabled = dragEnabled;
}
public final boolean isDraggingEnabled() {
return draggingEnabled;
}
public final void setFrequencyGraph(final FreqAnalysisGraph frequencyGraph) {
this.frequencyGraph = frequencyGraph;
}
public final FreqAnalysisGraph getFrequencyGraph() {
return frequencyGraph;
}
@Override
public final void mouseMove(final MouseEvent e) {
if (dragging && draggingEnabled) {
int myPixelsDifference = e.x - dragBeginX;
if (getFrequencyGraph().setDraggedPixels(myPixelsDifference, true)) {
redraw();
}
}
if (this.frequencyGraph != null) {
frequencyGraph.mouseMove(e);
}
}
@Override
public void mouseEnter(MouseEvent e) {
if (this.frequencyGraph != null) {
frequencyGraph.mouseEnter(e);
this.redraw();
}
}
@Override
public void mouseExit(MouseEvent e) {
if (this.frequencyGraph != null) {
frequencyGraph.mouseExit(e);
this.redraw();
}
}
@Override
public void mouseHover(MouseEvent e) {
if (this.frequencyGraph != null) {
frequencyGraph.mouseHover(e);
this.redraw();
}
}
}
|
package com.gurkensalat.osm.mosques.jobs;
import com.gurkensalat.osm.entity.DitibPlace;
import com.gurkensalat.osm.mosques.service.GeocodingService;
import com.gurkensalat.osm.repository.DitibPlaceRepository;
import com.tandogan.geostuff.opencagedata.entity.GeocodeResponse;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.List;
@Configuration
@Component
public class DitibForwardGeocoderHandler
{
private final static Logger LOGGER = LoggerFactory.getLogger(DitibForwardGeocoderHandler.class);
@Value("${mq.queue.forward-geocode-ditib.minsleep}")
private Integer minsleep;
@Value("${mq.queue.forward-geocode-ditib.randomsleep}")
private Integer randomsleep;
@Autowired
private GeocodingService geocodingService;
@Autowired
private DitibPlaceRepository ditibPlaceRepository;
@Autowired
private SlackNotifier slackNotifier;
@RabbitListener(queues = "${mq.queue.forward-geocode-ditib.name}")
public void handleMessage(TaskMessage message)
{
LOGGER.info(" received <{}>", message);
String ditibCode = message.getMessage();
List<DitibPlace> places = ditibPlaceRepository.findByKey(ditibCode);
if (places != null)
{
for (DitibPlace place : places)
{
LOGGER.info(" have to handle: {}", place);
if (!(place.isGeocoded()))
{
// Do some magic... Maybe the service should not write directly to the database...
GeocodeResponse response = geocodingService.ditibForward(ditibCode);
// Reload the place, it might have been changed by the geocodingService
place = ditibPlaceRepository.findOne(place.getId());
// did what we had to, now mark this place as "touched"
place.setLastGeocodeAttempt(DateTime.now());
place = ditibPlaceRepository.save(place);
long sleeptime = (long) (minsleep + (Math.random() * (double) randomsleep));
LOGGER.debug("Processing finished, sleeping a while ({} seconds)...", sleeptime);
try
{
Thread.sleep(sleeptime * 1000);
}
catch (InterruptedException ie)
{
// Not really important...
}
if (response.getRate() != null)
{
if (response.getRate().getRemaining() < 100)
{
slackNotifier.notify(SlackNotifier.CHANNEL_GEOCODING, "Too little attempts left (" + response.getRate().getRemaining() + " out of " + response.getRate().getLimit() + "), sleeping for half an hour");
try
{
Thread.sleep(30 * 60 * 1000);
}
catch (InterruptedException ie)
{
// Not really important...
}
}
}
}
}
}
LOGGER.info(" done with handleMessage <{}>", message);
}
}
|
package org.opendaylight.protocol.pcep.impl.object;
import org.opendaylight.protocol.pcep.spi.ObjectParser;
import org.opendaylight.protocol.pcep.spi.ObjectSerializer;
import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
import org.opendaylight.protocol.pcep.spi.TlvHandlerRegistry;
import org.opendaylight.protocol.pcep.spi.TlvParser;
import org.opendaylight.protocol.pcep.spi.TlvSerializer;
import org.opendaylight.protocol.util.ByteArray;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
public abstract class AbstractObjectWithTlvsParser<T> implements ObjectParser, ObjectSerializer {
private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectWithTlvsParser.class);
private static final int TLV_TYPE_F_LENGTH = 2;
private static final int TLV_LENGTH_F_LENGTH = 2;
private static final int TLV_HEADER_LENGTH = TLV_LENGTH_F_LENGTH + TLV_TYPE_F_LENGTH;
protected static final int PADDED_TO = 4;
private final TlvHandlerRegistry tlvReg;
protected AbstractObjectWithTlvsParser(final TlvHandlerRegistry tlvReg) {
this.tlvReg = Preconditions.checkNotNull(tlvReg);
}
protected final void parseTlvs(final T builder, final byte[] bytes) throws PCEPDeserializerException {
if (bytes == null) {
throw new IllegalArgumentException("Byte array is mandatory.");
}
if (bytes.length == 0) {
return;
}
int length;
int byteOffset = 0;
int type = 0;
while (byteOffset < bytes.length) {
type = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_TYPE_F_LENGTH));
byteOffset += TLV_TYPE_F_LENGTH;
length = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_LENGTH_F_LENGTH));
byteOffset += TLV_LENGTH_F_LENGTH;
if (TLV_HEADER_LENGTH + length > bytes.length) {
throw new PCEPDeserializerException("Wrong length specified. Passed: " + (TLV_HEADER_LENGTH + length) + "; Expected: <= "
+ (bytes.length - byteOffset) + ".");
}
final byte[] tlvBytes = ByteArray.subByte(bytes, byteOffset, length);
LOG.trace("Attempt to parse tlv from bytes: {}", ByteArray.bytesToHexString(tlvBytes));
final TlvParser parser = this.tlvReg.getTlvParser(type);
if (parser != null) {
final Tlv tlv = parser.parseTlv(tlvBytes);
LOG.trace("Tlv was parsed. {}", tlv);
addTlv(builder, tlv);
} else {
LOG.warn("Unknown TLV received. Type {}. Ignoring it.", type);
}
byteOffset += length + getPadding(TLV_HEADER_LENGTH + length, PADDED_TO);
}
}
protected final byte[] serializeTlv(final Tlv tlv) {
final TlvSerializer serializer = this.tlvReg.getTlvSerializer(tlv);
final byte[] typeBytes = ByteArray.intToBytes(serializer.getType(), TLV_TYPE_F_LENGTH);
final byte[] valueBytes = serializer.serializeTlv(tlv);
final byte[] lengthBytes = ByteArray.intToBytes(valueBytes.length, TLV_LENGTH_F_LENGTH);
final byte[] bytes = new byte[TLV_HEADER_LENGTH + valueBytes.length + getPadding(TLV_HEADER_LENGTH + valueBytes.length, PADDED_TO)];
int byteOffset = 0;
System.arraycopy(typeBytes, 0, bytes, byteOffset, TLV_TYPE_F_LENGTH);
byteOffset += TLV_TYPE_F_LENGTH;
System.arraycopy(lengthBytes, 0, bytes, byteOffset, TLV_LENGTH_F_LENGTH);
byteOffset += TLV_LENGTH_F_LENGTH;
System.arraycopy(valueBytes, 0, bytes, byteOffset, valueBytes.length);
return bytes;
}
public abstract void addTlv(final T builder, final Tlv tlv);
protected static int getPadding(final int length, final int padding) {
return (padding - (length % padding)) % padding;
}
}
|
package uk.org.cinquin.mutinack;
import static contrib.uk.org.lidalia.slf4jext.Level.TRACE;
import static uk.org.cinquin.mutinack.MutationType.INSERTION;
import static uk.org.cinquin.mutinack.MutationType.SUBSTITUTION;
import static uk.org.cinquin.mutinack.MutationType.WILDTYPE;
import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.DISAGREEMENT;
import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.MISSING_STRAND;
import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.N_READS_PER_STRAND;
import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.QUALITY_AT_POSITION;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.FRACTION_WRONG_PAIRS_AT_POS;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_DPLX_Q_IGNORING_DISAG;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_Q_FOR_ALL_DUPLEXES;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_CANDIDATE_PHRED;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_PHRED_AT_POS;
import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.NO_DUPLEXES;
import static uk.org.cinquin.mutinack.misc_util.DebugLogControl.NONTRIVIAL_ASSERTIONS;
import static uk.org.cinquin.mutinack.misc_util.Util.basesEqual;
import static uk.org.cinquin.mutinack.qualities.Quality.ATROCIOUS;
import static uk.org.cinquin.mutinack.qualities.Quality.DUBIOUS;
import static uk.org.cinquin.mutinack.qualities.Quality.GOOD;
import static uk.org.cinquin.mutinack.qualities.Quality.MINIMUM;
import static uk.org.cinquin.mutinack.qualities.Quality.POOR;
import static uk.org.cinquin.mutinack.qualities.Quality.max;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.list.primitive.MutableFloatList;
import org.eclipse.collections.api.multimap.set.MutableSetMultimap;
import org.eclipse.collections.api.set.ImmutableSet;
import org.eclipse.collections.api.set.MutableSet;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.factory.Sets;
import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import contrib.net.sf.picard.reference.ReferenceSequence;
import contrib.net.sf.samtools.CigarOperator;
import contrib.net.sf.samtools.SAMRecord;
import contrib.net.sf.samtools.SamPairUtil;
import contrib.net.sf.samtools.SamPairUtil.PairOrientation;
import contrib.net.sf.samtools.util.StringUtil;
import contrib.uk.org.lidalia.slf4jext.Logger;
import contrib.uk.org.lidalia.slf4jext.LoggerFactory;
import gnu.trove.list.array.TByteArrayList;
import gnu.trove.map.TByteObjectMap;
import gnu.trove.map.hash.TByteObjectHashMap;
import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.set.hash.TCustomHashSet;
import gnu.trove.set.hash.THashSet;
import uk.org.cinquin.mutinack.candidate_sequences.CandidateBuilder;
import uk.org.cinquin.mutinack.candidate_sequences.CandidateCounter;
import uk.org.cinquin.mutinack.candidate_sequences.CandidateDeletion;
import uk.org.cinquin.mutinack.candidate_sequences.CandidateSequence;
import uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay;
import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock;
import uk.org.cinquin.mutinack.candidate_sequences.PositionAssay;
import uk.org.cinquin.mutinack.misc_util.Assert;
import uk.org.cinquin.mutinack.misc_util.ComparablePair;
import uk.org.cinquin.mutinack.misc_util.DebugLogControl;
import uk.org.cinquin.mutinack.misc_util.Handle;
import uk.org.cinquin.mutinack.misc_util.Pair;
import uk.org.cinquin.mutinack.misc_util.SettableDouble;
import uk.org.cinquin.mutinack.misc_util.SettableInteger;
import uk.org.cinquin.mutinack.misc_util.Util;
import uk.org.cinquin.mutinack.misc_util.collections.HashingStrategies;
import uk.org.cinquin.mutinack.misc_util.collections.InterningSet;
import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException;
import uk.org.cinquin.mutinack.output.LocationExaminationResults;
import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities;
import uk.org.cinquin.mutinack.qualities.DetailedQualities;
import uk.org.cinquin.mutinack.qualities.Quality;
import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter;
import uk.org.cinquin.mutinack.statistics.Histogram;
public final class SubAnalyzer {
private static final Logger logger = LoggerFactory.getLogger(SubAnalyzer.class);
public final @NonNull Mutinack analyzer;
@NonNull Parameters param;
@NonNull AnalysisStats stats;//Will in fact be null until set in SubAnalyzerPhaser but that's OK
final @NonNull SettableInteger lastProcessablePosition = new SettableInteger(-1);
final @NonNull THashMap<SequenceLocation, THashSet<CandidateSequence>> candidateSequences =
new THashMap<>(1_000);
int truncateProcessingAt = Integer.MAX_VALUE;
int startProcessingAt = 0;
MutableList<@NonNull DuplexRead> analyzedDuplexes;
float[] averageClipping;
int averageClippingOffset = Integer.MAX_VALUE;
final @NonNull THashMap<String, @NonNull ExtendedSAMRecord> extSAMCache =
new THashMap<>(10_000, 0.5f);
private final AtomicInteger threadCount = new AtomicInteger();
@NonNull Map<@NonNull ExtendedSAMRecord, @NonNull SAMRecord> readsToWrite
= new THashMap<>();
private final Random random;
private static final @NonNull Set<DuplexAssay>
assaysToIgnoreForDisagreementQuality
= Collections.unmodifiableSet(EnumSet.copyOf(Collections.singletonList(DISAGREEMENT))),
assaysToIgnoreForDuplexNStrands
= Collections.unmodifiableSet(EnumSet.copyOf(Arrays.asList(N_READS_PER_STRAND, MISSING_STRAND)));
static final @NonNull TByteObjectMap<@NonNull String> byteMap;
static {
byteMap = new TByteObjectHashMap<>();
byteMap.put((byte) 'A', "A");
byteMap.put((byte) 'a', "A");
byteMap.put((byte) 'T', "T");
byteMap.put((byte) 't', "T");
byteMap.put((byte) 'G', "G");
byteMap.put((byte) 'g', "G");
byteMap.put((byte) 'C', "C");
byteMap.put((byte) 'c', "C");
byteMap.put((byte) 'N', "N");
byteMap.put((byte) 'n', "N");
}
static final @NonNull TByteObjectMap<byte @NonNull[]> byteArrayMap;
static {
byteArrayMap = new TByteObjectHashMap<>();
byteArrayMap.put((byte) 'A', new byte[] {'A'});
byteArrayMap.put((byte) 'a', new byte[] {'a'});
byteArrayMap.put((byte) 'T', new byte[] {'T'});
byteArrayMap.put((byte) 't', new byte[] {'t'});
byteArrayMap.put((byte) 'G', new byte[] {'G'});
byteArrayMap.put((byte) 'g', new byte[] {'g'});
byteArrayMap.put((byte) 'C', new byte[] {'C'});
byteArrayMap.put((byte) 'c', new byte[] {'c'});
byteArrayMap.put((byte) 'N', new byte[] {'N'});
byteArrayMap.put((byte) 'n', new byte[] {'n'});
}
private volatile boolean writing = false;
synchronized void queueOutputRead(@NonNull ExtendedSAMRecord e, @NonNull SAMRecord r, boolean mayAlreadyBeQueued) {
Assert.isFalse(writing);
final SAMRecord previous;
if ((previous = readsToWrite.put(e, r)) != null && !mayAlreadyBeQueued) {
throw new IllegalStateException("Read " + e.getFullName() + " already queued for writing; new: " +
r.toString() + "; previous: " + previous.toString());
}
}
void writeOutputReads() {
writing = true;
try {
synchronized(analyzer.outputAlignmentWriter) {
for (SAMRecord samRecord: readsToWrite.values()) {
Objects.requireNonNull(analyzer.outputAlignmentWriter).addAlignment(samRecord);
}
}
readsToWrite.clear();
} finally {
writing = false;
}
}
@SuppressWarnings("null")//Stats not initialized straight away
SubAnalyzer(@NonNull Mutinack analyzer) {
this.analyzer = analyzer;
this.param = analyzer.param;
useHashMap = param.alignmentPositionMismatchAllowed == 0;
random = new Random(param.randomSeed);
}
private boolean meetsQ2Thresholds(@NonNull ExtendedSAMRecord extendedRec) {
return !extendedRec.formsWrongPair() &&
extendedRec.getnClipped() <= param.maxAverageBasesClipped &&
extendedRec.getMappingQuality() >= param.minMappingQualityQ2 &&
Math.abs(extendedRec.getInsertSize()) <= param.maxInsertSize;
}
/**
* Make sure that concurring reads get associated with a unique candidate.
* We should *not* insert candidates directly into candidateSequences.
* Get interning as a small, beneficial side effect.
* @param candidate
* @param location
* @return
*/
private @NonNull CandidateSequence insertCandidateAtPosition(@NonNull CandidateSequence candidate,
@NonNull SequenceLocation location) {
//No need for synchronization since we should not be
//concurrently inserting two candidates at the same position
THashSet<CandidateSequence> candidates = candidateSequences.computeIfAbsent(location, k -> new THashSet<>(2));
CandidateSequence candidateMapValue = candidates.get(candidate);
if (candidateMapValue == null) {
boolean added = candidates.add(candidate);
Assert.isTrue(added);
} else {
candidateMapValue.mergeWith(candidate);
candidate = candidateMapValue;
}
return candidate;
}
/**
* Load all reads currently referred to by candidate sequences and group them into DuplexReads
* @param toPosition
* @param fromPosition
*/
void load(int fromPosition, int toPosition) {
Assert.isFalse(threadCount.incrementAndGet() > 1);
try {
if (toPosition < fromPosition) {
throw new IllegalArgumentException("Going from " + fromPosition + " to " + toPosition);
}
final List<@NonNull DuplexRead> resultDuplexes = new ArrayList<>(3_000);
loadAll(fromPosition, toPosition, resultDuplexes);
analyzedDuplexes = Lists.mutable.withAll(resultDuplexes);
} finally {
if (NONTRIVIAL_ASSERTIONS) {
threadCount.decrementAndGet();
}
}
}
void checkAllDone() {
if (!candidateSequences.isEmpty()) {
final SettableInteger nLeftBehind = new SettableInteger(-1);
candidateSequences.forEach((k,v) -> {
Assert.isTrue(v.isEmpty() || (v.iterator().next().getLocation().equals(k)),
"Mismatched locations");
String s = v.stream().
filter(c -> c.getLocation().position > truncateProcessingAt + param.maxInsertSize &&
c.getLocation().position < startProcessingAt - param.maxInsertSize).
flatMap(v0 -> v0.getNonMutableConcurringReads().keySet().stream()).
map(read -> {
if (nLeftBehind.incrementAndGet() == 0) {
logger.error("Sequences left behind before " + truncateProcessingAt);
}
return Integer.toString(read.getAlignmentStart()) + '-' +
Integer.toString(read.getAlignmentEnd()); })
.collect(Collectors.joining("; "));
if (!s.equals("")) {
logger.error(s);
}
});
Assert.isFalse(nLeftBehind.get() > 0);
}
}
private final boolean useHashMap;
private @NonNull DuplexKeeper getDuplexKeeper(boolean fallBackOnIntervalTree) {
final @NonNull DuplexKeeper result;
if (MutinackGroup.forceKeeperType != null) {
switch(MutinackGroup.forceKeeperType) {
case "DuplexHashMapKeeper":
if (useHashMap) {
result = new DuplexHashMapKeeper();
} else {
result = new DuplexArrayListKeeper(5_000);
}
break;
//case "DuplexITKeeper":
// result = new DuplexITKeeper();
// break;
case "DuplexArrayListKeeper":
result = new DuplexArrayListKeeper(5_000);
break;
default:
throw new AssertionFailedException();
}
} else {
if (useHashMap) {
result = new DuplexHashMapKeeper();
} else /*if (fallBackOnIntervalTree) {
result = new DuplexITKeeper();
} else */{
result = new DuplexArrayListKeeper(5_000);
}
}
return result;
}
/**
* Group reads into duplexes.
* @param toPosition
* @param fromPosition
* @param finalResult
*/
private void loadAll(
final int fromPosition,
final int toPosition,
final @NonNull List<DuplexRead> finalResult) {
/**
* Use a custom hash map type to keep track of duplexes when
* alignmentPositionMismatchAllowed is 0.
* This provides by far the highest performance.
* When alignmentPositionMismatchAllowed is greater than 0, use
* either an interval tree or a plain list. The use of an interval
* tree instead of a plain list provides a speed benefit only when
* there is large number of local duplexes, so switch dynamically
* based on that number. The threshold was optimized empirically
* and at a gross level.
*/
final boolean fallBackOnIntervalTree = extSAMCache.size() > 5_000;
@NonNull DuplexKeeper duplexKeeper =
getDuplexKeeper(fallBackOnIntervalTree);
InterningSet<SequenceLocation> sequenceLocationCache =
new InterningSet<>(500);
final AlignmentExtremetiesDistance ed = new AlignmentExtremetiesDistance(
analyzer.groupSettings, param);
final SettableInteger nReadsExcludedFromDuplexes = new SettableInteger(0);
final TObjectProcedure<@NonNull ExtendedSAMRecord> callLoadRead = rExtended -> {
loadRead(rExtended, duplexKeeper, ed, sequenceLocationCache, nReadsExcludedFromDuplexes);
return true;
};
if (param.jiggle) {
List<@NonNull ExtendedSAMRecord> reorderedReads = new ArrayList<>(extSAMCache.values());
Collections.shuffle(reorderedReads, random);
reorderedReads.forEach(e -> callLoadRead.execute(e));
} else {
extSAMCache.forEachValue(callLoadRead);
}
sequenceLocationCache.clear();//Not strictly necessary, but might as well release the
//memory now
if (param.randomizeStrand) {
duplexKeeper.forEach(dr -> dr.randomizeStrands(random));
}
duplexKeeper.forEach(DuplexRead::computeGlobalProperties);
Pair<DuplexRead, DuplexRead> pair;
if (param.enableCostlyAssertions &&
(pair =
DuplexRead.checkNoEqualDuplexes(duplexKeeper.getIterable())) != null) {
throw new AssertionFailedException("Equal duplexes: " +
pair.fst + " and " + pair.snd);
}
if (param.enableCostlyAssertions) {
Assert.isTrue(checkReadsOccurOnceInDuplexes(extSAMCache.values(),
duplexKeeper.getIterable(), nReadsExcludedFromDuplexes.get()));
}
//Group duplexes that have alignment positions that differ by at most
//param.alignmentPositionMismatchAllowed
//and left/right consensus that differ by at most
//param.nVariableBarcodeMismatchesAllowed
final DuplexKeeper cleanedUpDuplexes =
param.nVariableBarcodeMismatchesAllowed > 0 ?
DuplexRead.groupDuplexes(
duplexKeeper,
duplex -> duplex.computeConsensus(false, param.variableBarcodeLength),
() -> getDuplexKeeper(fallBackOnIntervalTree),
param,
stats,
0)
:
duplexKeeper;
if (param.nVariableBarcodeMismatchesAllowed == 0) {
cleanedUpDuplexes.forEach(d -> d.computeConsensus(true,
param.variableBarcodeLength));
}
//Group duplexes by alignment start (or equivalent)
TIntObjectHashMap<List<DuplexRead>> duplexPositions = new TIntObjectHashMap<>
(1_000, 0.5f, -999);
cleanedUpDuplexes.forEach(dr -> {
List<DuplexRead> list = duplexPositions.computeIfAbsent(dr.position0,
(Supplier<List<DuplexRead>>) ArrayList::new);
list.add(dr);
});
if (param.variableBarcodeLength == 0) {
final double @NonNull[] insertSizeProb =
Objects.requireNonNull(analyzer.insertSizeProbSmooth);
duplexPositions.forEachValue(list -> {
for (DuplexRead dr: list) {
double sizeP = insertSizeProb[
Math.min(insertSizeProb.length - 1, dr.maxInsertSize)];
Assert.isTrue(Double.isNaN(sizeP) || sizeP >= 0,
() -> "Insert size problem: " + Arrays.toString(insertSizeProb));
dr.probAtLeastOneCollision = 1 - Math.pow(1 - sizeP, list.size());
}
return true;
});
}
cleanedUpDuplexes.forEach(duplexRead -> duplexRead.analyzeForStats(param, stats));
cleanedUpDuplexes.forEach(finalResult::add);
averageClippingOffset = fromPosition;
final int arrayLength = toPosition - fromPosition + 1;
averageClipping = new float[arrayLength];
int[] duplexNumber = new int[arrayLength];
cleanedUpDuplexes.forEach(duplexRead -> {
int start = duplexRead.getUnclippedAlignmentStart() - fromPosition;
int stop = duplexRead.getUnclippedAlignmentEnd() - fromPosition;
start = Math.min(Math.max(0, start), toPosition - fromPosition);
stop = Math.min(Math.max(0, stop), toPosition - fromPosition);
for (int i = start; i <= stop; i++) {
averageClipping[i] += duplexRead.averageNClipped;
duplexNumber[i]++;
}
});
for (int i = 0; i < averageClipping.length; i++) {
int n = duplexNumber[i];
if (n == 0) {
Assert.isTrue(averageClipping[i] == 0);
} else {
averageClipping[i] /= n;
}
}
}//End loadAll
private void loadRead(@NonNull ExtendedSAMRecord rExtended, @NonNull DuplexKeeper duplexKeeper,
AlignmentExtremetiesDistance ed, InterningSet<SequenceLocation> sequenceLocationCache,
SettableInteger nReadsExcludedFromDuplexes) {
final @NonNull SequenceLocation location = rExtended.getLocation();
final byte @NonNull[] barcode = rExtended.variableBarcode;
final byte @NonNull[] mateBarcode = rExtended.getMateVariableBarcode();
final @NonNull SAMRecord r = rExtended.record;
if (rExtended.getMate() == null) {
stats.nMateOutOfReach.add(location, 1);
}
if (r.getMateUnmappedFlag()) {
//It is not trivial to tell whether the mate is unmapped because
//e.g. it did not sequence properly, or because all of the reads
//from the duplex just do not map to the genome. To avoid
//artificially inflating local duplex number, do not allow the
//read to contribute to computed duplexes. Note that the rest of
//the duplex-handling code could technically handle an unmapped
//mate, and that the read will still be able to contribute to
//local statistics such as average clipping.
nReadsExcludedFromDuplexes.incrementAndGet();
return;
}
boolean foundDuplexRead = false;
final boolean matchToLeft = rExtended.duplexLeft();
ed.set(rExtended);
for (final DuplexRead duplexRead: duplexKeeper.getOverlapping(ed.temp)) {
//stats.nVariableBarcodeCandidateExaminations.increment(location);
ed.set(duplexRead);
if (ed.getMaxDistance() > param.alignmentPositionMismatchAllowed) {
continue;
}
final boolean barcodeMatch;
//During first pass, do not allow any barcode mismatches
if (matchToLeft) {
barcodeMatch = basesEqual(duplexRead.leftBarcode, barcode,
param.acceptNInBarCode) &&
basesEqual(duplexRead.rightBarcode, mateBarcode,
param.acceptNInBarCode);
} else {
barcodeMatch = basesEqual(duplexRead.leftBarcode, mateBarcode,
param.acceptNInBarCode) &&
basesEqual(duplexRead.rightBarcode, barcode,
param.acceptNInBarCode);
}
if (barcodeMatch) {
if (r.getInferredInsertSize() >= 0) {
if (r.getFirstOfPairFlag()) {
if (param.enableCostlyAssertions) {
Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended));
}
duplexRead.topStrandRecords.add(rExtended);
} else {
if (param.enableCostlyAssertions) {
Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended));
}
duplexRead.bottomStrandRecords.add(rExtended);
}
} else {
if (r.getFirstOfPairFlag()) {
if (param.enableCostlyAssertions) {
Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended));
}
duplexRead.bottomStrandRecords.add(rExtended);
} else {
if (param.enableCostlyAssertions) {
Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended));
}
duplexRead.topStrandRecords.add(rExtended);
}
}
if (param.enableCostlyAssertions) {
Assert.noException(duplexRead::assertAllBarcodesEqual);
}
rExtended.duplexRead = duplexRead;
//stats.nVariableBarcodeMatchAfterPositionCheck.increment(location);
foundDuplexRead = true;
break;
} else {//left and/or right barcodes do not match
/*
leftEqual = basesEqual(duplexRead.leftBarcode, barcode, true, 1);
rightEqual = basesEqual(duplexRead.rightBarcode, barcode, true, 1);
if (leftEqual || rightEqual) {
stats.nVariableBarcodesCloseMisses.increment(location);
}*/
}
}//End loop over duplexReads
if (!foundDuplexRead) {
final DuplexRead duplexRead = matchToLeft ?
new DuplexRead(analyzer.groupSettings, barcode, mateBarcode, !r.getReadNegativeStrandFlag(), r.getReadNegativeStrandFlag()) :
new DuplexRead(analyzer.groupSettings, mateBarcode, barcode, r.getReadNegativeStrandFlag(), !r.getReadNegativeStrandFlag());
if (matchToLeft) {
duplexRead.setPositions(
rExtended.getOffsetUnclippedStart(),
rExtended.getMateOffsetUnclippedEnd());
} else {
duplexRead.setPositions(
rExtended.getMateOffsetUnclippedStart(),
rExtended.getOffsetUnclippedEnd());
}
duplexKeeper.add(duplexRead);
duplexRead.roughLocation = location;
rExtended.duplexRead = duplexRead;
if (!matchToLeft) {
if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) {
//Reads that completely overlap because of short insert size
stats.nPosDuplexCompletePairOverlap.increment(location);
}
//Arbitrarily choose top strand as the one associated with
//first of pair that maps to the lowest position in the contig
if (!r.getFirstOfPairFlag()) {
duplexRead.topStrandRecords.add(rExtended);
} else {
duplexRead.bottomStrandRecords.add(rExtended);
}
if (param.enableCostlyAssertions) {
Assert.noException(duplexRead::assertAllBarcodesEqual);
}
duplexRead.rightAlignmentStart = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
rExtended.getReferenceName(), rExtended.getOffsetUnclippedStart()));
duplexRead.rightAlignmentEnd = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
rExtended.getReferenceName(), rExtended.getOffsetUnclippedEnd()));
duplexRead.leftAlignmentStart = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedStart()));
duplexRead.leftAlignmentEnd = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedEnd()));
} else {//Read on positive strand
if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) {
//Reads that completely overlap because of short insert size?
stats.nPosDuplexCompletePairOverlap.increment(location);
}
//Arbitrarily choose top strand as the one associated with
//first of pair that maps to the lowest position in the contig
if (r.getFirstOfPairFlag()) {
duplexRead.topStrandRecords.add(rExtended);
} else {
duplexRead.bottomStrandRecords.add(rExtended);
}
if (param.enableCostlyAssertions) {
Assert.noException(duplexRead::assertAllBarcodesEqual);
}
duplexRead.leftAlignmentStart = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
r.getReferenceName(), rExtended.getOffsetUnclippedStart()));
duplexRead.leftAlignmentEnd = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
r.getReferenceName(), rExtended.getOffsetUnclippedEnd()));
duplexRead.rightAlignmentStart = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
r.getReferenceName(), rExtended.getMateOffsetUnclippedStart()));
duplexRead.rightAlignmentEnd = sequenceLocationCache.intern(
new SequenceLocation(rExtended.getReferenceIndex(),
r.getReferenceName(), rExtended.getMateOffsetUnclippedEnd()));
}
Assert.isFalse(
duplexRead.leftAlignmentEnd.compareTo(duplexRead.leftAlignmentStart) < 0,
(Supplier<Object>) duplexRead.leftAlignmentStart::toString,
(Supplier<Object>) duplexRead.leftAlignmentEnd::toString,
(Supplier<Object>) duplexRead::toString,
(Supplier<Object>) rExtended::getFullName,
"Misordered duplex: %s -- %s %s %s");
}//End new duplex creation
}
private static boolean checkReadsOccurOnceInDuplexes(
Collection<@NonNull ExtendedSAMRecord> reads,
@NonNull Iterable<DuplexRead> duplexes,
int nReadsExcludedFromDuplexes) {
ExtendedSAMRecord lostRead = null;
int nUnfoundReads = 0;
for (final @NonNull ExtendedSAMRecord rExtended: reads) {
boolean found = false;
for (DuplexRead dr: duplexes) {
if (dr.topStrandRecords.contains(rExtended)) {
if (found) {
throw new AssertionFailedException("Two occurrences of read " + rExtended);
}
found = true;
}
if (dr.bottomStrandRecords.contains(rExtended)) {
if (found) {
throw new AssertionFailedException("Two occurrences of read " + rExtended);
}
found = true;
}
}
if (!found) {
nUnfoundReads++;
lostRead = rExtended;
}
}
if (nUnfoundReads != nReadsExcludedFromDuplexes) {
throw new AssertionFailedException("Lost " + nUnfoundReads +
" but expected " + nReadsExcludedFromDuplexes + "; see perhaps " + lostRead);
}
return true;
}
@NonNull LocationExaminationResults examineLocation(final @NonNull SequenceLocation location) {
Assert.isFalse(threadCount.incrementAndGet() > 1);
try {
return examineLocation0(location);
} finally {
threadCount.decrementAndGet();
}
}
@SuppressWarnings({"null", "ReferenceEquality"})
/**
* This method is *NOT* thread-safe (it modifies DuplexReads associated with location retrieved
* from field candidateSequences)
* @param location
* @return
*/
@NonNull
private LocationExaminationResults examineLocation0(final @NonNull SequenceLocation location) {
final LocationExaminationResults result = new LocationExaminationResults();
final THashSet<CandidateSequence> candidateSet0 = candidateSequences.get(location);
if (candidateSet0 == null) {
stats.nPosUncovered.increment(location);
result.analyzedCandidateSequences = Sets.immutable.empty();
return result;
}
final ImmutableSet<CandidateSequence> candidateSet =
// DebugLogControl.COSTLY_ASSERTIONS ?
// Collections.unmodifiableSet(candidateSet0)
Sets.immutable.ofAll(candidateSet0);
//Retrieve relevant duplex reads
//It is necessary not to duplicate the duplex reads, hence the use of a set
//Identity should be good enough (and is faster) because no two different duplex read
//objects we use in this method should be equal according to the equals() method
//(although when grouping duplexes we don't check equality for the inner ends of
//the reads since they depend on read length)
final TCustomHashSet<DuplexRead> duplexReads =
new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200);
candidateSet.forEach(candidate -> {
candidate.getQuality().reset();
candidate.getDuplexes().clear();//Should have no effect
candidate.restoreConcurringReads();
final Set<DuplexRead> candidateDuplexReads =
new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200);
candidate.getNonMutableConcurringReads().forEachEntry((r, c) -> {
@Nullable DuplexRead d = r.duplexRead;
if (d != null) {
candidateDuplexReads.add(d);
} else {
//throw new AssertionFailedException("Read without a duplex :" + r);
}
return true;
});
duplexReads.addAll(candidateDuplexReads);
});
//Allocate here to avoid repeated allocation in DuplexRead::examineAtLoc
final CandidateCounter topCounter = new CandidateCounter(candidateSet, location);
final CandidateCounter bottomCounter = new CandidateCounter(candidateSet, location);
int[] insertSizes = new int [duplexReads.size()];
SettableDouble averageCollisionProbS = new SettableDouble(0d);
SettableInteger index = new SettableInteger(0);
duplexReads.forEach(duplexRead -> {
Assert.isFalse(duplexRead.invalid);
Assert.isTrue(duplexRead.averageNClipped >= 0);
Assert.isTrue(param.variableBarcodeLength > 0 ||
Double.isNaN(duplexRead.probAtLeastOneCollision) ||
duplexRead.probAtLeastOneCollision >= 0);
duplexRead.examineAtLoc(
location,
result,
candidateSet,
assaysToIgnoreForDisagreementQuality,
topCounter,
bottomCounter,
analyzer,
param,
stats);
if (index.get() < insertSizes.length) {
//Check in case array size was capped (for future use; it is
//never capped currently)
insertSizes[index.get()] = duplexRead.maxInsertSize;
index.incrementAndGet();
}
averageCollisionProbS.addAndGet(duplexRead.probAtLeastOneCollision);
if (param.variableBarcodeLength == 0 && !duplexRead.missingStrand) {
stats.duplexCollisionProbabilityWhen2Strands.insert((int)
(1_000f * duplexRead.probAtLeastOneCollision));
}
});
if (param.enableCostlyAssertions) {
Assert.noException(() -> checkDuplexAndCandidates(duplexReads, candidateSet));
}
if (index.get() > 0) {
Arrays.parallelSort(insertSizes, 0, index.get());
result.duplexInsertSize10thP = insertSizes[(int) (index.get() * 0.1f)];
result.duplexInsertSize90thP = insertSizes[(int) (index.get() * 0.9f)];
}
double averageCollisionProb = averageCollisionProbS.get();
averageCollisionProb /= duplexReads.size();
if (param.variableBarcodeLength == 0) {
stats.duplexCollisionProbability.insert((int) (1_000d * averageCollisionProb));
}
result.probAtLeastOneCollision = averageCollisionProb;
final DetailedQualities<PositionAssay> positionQualities = new DetailedPositionQualities();
if (averageClipping[location.position - averageClippingOffset] >
param.maxAverageClippingOfAllCoveringDuplexes) {
positionQualities.addUnique(
MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS, DUBIOUS);
}
if (param.enableCostlyAssertions) {
Assert.noException(() -> duplexReads.forEach(duplexRead -> {
for (int i = duplexRead.topStrandRecords.size() - 1; i >= 0; --i) {
ExtendedSAMRecord r = duplexRead.topStrandRecords.get(i);
if (r.duplexRead != duplexRead) {
throw new AssertionFailedException();
}
if (duplexRead.bottomStrandRecords.contains(r)) {
throw new AssertionFailedException();
}
}
for (int i = duplexRead.bottomStrandRecords.size() - 1; i >= 0; --i) {
ExtendedSAMRecord r = duplexRead.bottomStrandRecords.get(i);
if (r.duplexRead != duplexRead) {
throw new AssertionFailedException();
}
if (duplexRead.topStrandRecords.contains(r)) {
throw new AssertionFailedException();
}
}
return true;
}));
}
final int totalReadsAtPosition = (int) candidateSet.sumOfInt(
c -> c.getNonMutableConcurringReads().size());
final TByteArrayList allPhredQualitiesAtPosition = new TByteArrayList(500);
final SettableInteger nWrongPairsAtPosition = new SettableInteger(0);
final SettableInteger nPairsAtPosition = new SettableInteger(0);
candidateSet.forEach(candidate -> {
candidate.addPhredScoresToList(allPhredQualitiesAtPosition);
nPairsAtPosition.addAndGet(candidate.getNonMutableConcurringReads().size());
SettableInteger count = new SettableInteger(0);
candidate.getNonMutableConcurringReads().forEachKey(r -> {
if (r.formsWrongPair()) {
count.incrementAndGet();
}
return true;
});
candidate.setnWrongPairs(count.get());
nWrongPairsAtPosition.addAndGet(candidate.getnWrongPairs());
});
final int nPhredQualities = allPhredQualitiesAtPosition.size();
allPhredQualitiesAtPosition.sort();
final byte positionMedianPhred = nPhredQualities == 0 ? 127 :
allPhredQualitiesAtPosition.get(nPhredQualities / 2);
if (positionMedianPhred < param.minMedianPhredScoreAtPosition) {
positionQualities.addUnique(MEDIAN_PHRED_AT_POS, DUBIOUS);
stats.nMedianPhredAtPositionTooLow.increment(location);
}
stats.medianPositionPhredQuality.insert(positionMedianPhred);
if (nWrongPairsAtPosition.get() / ((float) nPairsAtPosition.get()) > param.maxFractionWrongPairsAtPosition) {
positionQualities.addUnique(FRACTION_WRONG_PAIRS_AT_POS, DUBIOUS);
stats.nFractionWrongPairsAtPositionTooHigh.increment(location);
}
Quality maxQuality;
int totalGoodDuplexes, totalGoodOrDubiousDuplexes,
totalGoodDuplexesIgnoringDisag, totalAllDuplexes;
Handle<Byte> wildtypeBase = new Handle<>((byte) 'X');
candidateSet.forEach(candidate -> {
candidate.getQuality().addAllUnique(positionQualities);
processCandidateQualityStep1(candidate, location, result, positionMedianPhred, positionQualities);
if (candidate.getMutationType().isWildtype()) {
wildtypeBase.set(candidate.getWildtypeSequence());
}
});
boolean leave = false;
final boolean qualityOKBeforeTopAllele =
Quality.nullableMax(positionQualities.getValue(true), GOOD).atLeast(GOOD);
Quality topAlleleQuality = null;
do {
maxQuality = MINIMUM;
totalAllDuplexes = 0;
totalGoodDuplexes = 0;
totalGoodOrDubiousDuplexes = 0;
totalGoodDuplexesIgnoringDisag = 0;
for (CandidateSequence candidate: candidateSet) {
if (leave) {
candidate.getQuality().addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, DUBIOUS);
}
@NonNull MutableSetMultimap<Quality, DuplexRead> map = candidate.getDuplexes().
groupBy(dr -> dr.localAndGlobalQuality.getValue());
if (param.enableCostlyAssertions) {
map.forEachKeyMultiValues((k, v) -> Assert.isTrue(Util.getDuplicates(v).isEmpty()));
Assert.isTrue(map.multiValuesView().collectInt(v -> v.size()).sum() == candidate.getDuplexes().size());
}
@Nullable MutableSet<DuplexRead> gd = map.get(GOOD);
candidate.setnGoodDuplexes(gd == null ? 0 : gd.size());
@Nullable MutableSet<DuplexRead> db = map.get(DUBIOUS);
candidate.setnGoodOrDubiousDuplexes(candidate.getnGoodDuplexes() + (db == null ? 0 : db.size()));
candidate.setnGoodDuplexesIgnoringDisag(candidate.getDuplexes().
count(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality).atLeast(GOOD)));
maxQuality = max(candidate.getQuality().getValue(), maxQuality);
totalAllDuplexes += candidate.getnDuplexes();
totalGoodDuplexes += candidate.getnGoodDuplexes();
totalGoodOrDubiousDuplexes += candidate.getnGoodOrDubiousDuplexes();
totalGoodDuplexesIgnoringDisag += candidate.getnGoodDuplexesIgnoringDisag();
processCandidateQualityStep2(candidate, location, result, positionMedianPhred, positionQualities);
}
if (leave) {
break;
} else {
result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes;
topAlleleQuality = getAlleleFrequencyQuality(candidateSet, result);
if (topAlleleQuality == null) {
break;
}
Assert.isTrue(topAlleleQuality == DUBIOUS);
positionQualities.addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, topAlleleQuality);
leave = true;//Just one more iteration
continue;
}
} while(Boolean.valueOf(null));//Assert never reached
if (qualityOKBeforeTopAllele) {
registerDuplexMinFracTopCandidate(param, duplexReads,
topAlleleQuality == null ?
stats.minTopCandFreqQ2PosTopAlleleFreqOK
:
stats.minTopCandFreqQ2PosTopAlleleFreqKO,
location);
}
if (positionQualities.getValue(true) != null && positionQualities.getValue(true).lowerThan(GOOD)) {
result.disagreements.clear();
} else {
if (param.maxMutFreqForDisag < 1f) {
final int finalTotalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes;
result.disagreements.forEachKey(disag -> {
Mutation m = disag.getSnd();
if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) {
disag.quality = Quality.min(disag.quality, POOR);
}
m = disag.getFst();
if (m != null && m.mutationType != WILDTYPE) {
if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) {
disag.quality = Quality.min(disag.quality, POOR);
}
}
return true;
});
}
stats.nPosDuplexCandidatesForDisagreementQ2.acceptSkip0(location, result.disagQ2Coverage);
stats.nPosDuplexCandidatesForDisagreementQ1.acceptSkip0(location, result.disagOneStrandedCoverage);
if (param.computeRawMismatches) {
candidateSet.forEach(c -> c.getRawMismatchesQ2().forEach(result.rawMismatchesQ2::add));
candidateSet.forEach(c -> c.getRawInsertionsQ2().forEach(result.rawInsertionsQ2::add));
candidateSet.forEach(c -> c.getRawDeletionsQ2().forEach(result.rawDeletionsQ2::add));
}
}
for (CandidateSequence candidate: candidateSet) {
candidate.setTotalAllDuplexes(totalAllDuplexes);
candidate.setTotalGoodDuplexes(totalGoodDuplexes);
candidate.setTotalGoodOrDubiousDuplexes(totalGoodOrDubiousDuplexes);
candidate.setTotalReadsAtPosition(totalReadsAtPosition);
}
result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes;
result.nGoodDuplexes = totalGoodDuplexes;
result.nGoodDuplexesIgnoringDisag = totalGoodDuplexesIgnoringDisag;
stats.Q1Q2DuplexCoverage.insert(result.nGoodOrDubiousDuplexes);
stats.Q2DuplexCoverage.insert(result.nGoodDuplexes);
if (result.nGoodOrDubiousDuplexes == 0) {
stats.missingStrandsWhenNoUsableDuplex.insert(result.nMissingStrands);
stats.strandCoverageImbalanceWhenNoUsableDuplex.insert(result.strandCoverageImbalance);
}
if (maxQuality.atMost(POOR)) {
stats.nPosQualityPoor.increment(location);
switch (wildtypeBase.get()) {
case 'A' : stats.nPosQualityPoorA.increment(location); break;
case 'T' : stats.nPosQualityPoorT.increment(location); break;
case 'G' : stats.nPosQualityPoorG.increment(location); break;
case 'C' : stats.nPosQualityPoorC.increment(location); break;
case 'X' :
case 'N' :
break;//Ignore because we do not have a record of wildtype sequence
default : throw new AssertionFailedException();
}
} else if (maxQuality == DUBIOUS) {
stats.nPosQualityQ1.increment(location);
} else if (maxQuality == GOOD) {
stats.nPosQualityQ2.increment(location);
} else {
throw new AssertionFailedException();
}
result.analyzedCandidateSequences = candidateSet;
return result;
}//End examineLocation
private static void registerDuplexMinFracTopCandidate(Parameters param,
TCustomHashSet<DuplexRead> duplexReads, Histogram hist, SequenceLocation location) {
duplexReads.forEach(dr -> {
Assert.isFalse(dr.totalNRecords == -1);
if (dr.totalNRecords < 2 || dr.minFracTopCandidate == Float.MAX_VALUE) {
return true;
}
hist.insert((int) (dr.minFracTopCandidate * 10));
return true;
});
}
private boolean lowMutFreq(Mutation mut, ImmutableSet<CandidateSequence> candidateSet, int nGOrDDuplexes) {
Objects.requireNonNull(mut);
Handle<Boolean> result = new Handle<>(true);
candidateSet.detect((CandidateSequence c) -> {
Mutation cMut = c.getMutation();
if (cMut.equals(mut)) {
if (c.getnGoodOrDubiousDuplexes() > param.maxMutFreqForDisag * nGOrDDuplexes) {
result.set(false);
}
return true;
}
return false;
});
return result.get();
}
private static float divideWithNanToZero(float f1, float f2) {
return f2 == 0f ? 0 : f1 / f2;
}
private @Nullable Quality getAlleleFrequencyQuality(
ImmutableSet<CandidateSequence> candidateSet,
LocationExaminationResults result) {
MutableFloatList frequencyList = candidateSet.collectFloat(c ->
divideWithNanToZero(c.getnGoodOrDubiousDuplexes(), result.nGoodOrDubiousDuplexes),
new FloatArrayList(Math.max(2, candidateSet.size()))).//Need second argument to collectInt
//to avoid collecting into a set
sortThis();
result.alleleFrequencies = frequencyList;
while (frequencyList.size() < 2) {
frequencyList.addAtIndex(0, Float.NaN);
}
float topAlleleFrequency = frequencyList.getLast();
if (!(topAlleleFrequency >= param.minTopAlleleFreqQ2 &&
topAlleleFrequency <= param.maxTopAlleleFreqQ2)) {
return DUBIOUS;
}
return null;
}
@SuppressWarnings("null")
private void processCandidateQualityStep1(
final CandidateSequence candidate,
final @NonNull SequenceLocation location,
final LocationExaminationResults result,
final byte positionMedianPhred,
final @NonNull DetailedQualities<PositionAssay> positionQualities) {
candidate.setMedianPhredAtPosition(positionMedianPhred);
final byte candidateMedianPhred = candidate.getMedianPhredScore();//Will be -1 for insertions and deletions
if (candidateMedianPhred != -1 && candidateMedianPhred < param.minCandidateMedianPhredScore) {
candidate.getQuality().addUnique(MEDIAN_CANDIDATE_PHRED, DUBIOUS);
}
//TODO Should report min rather than average collision probability?
candidate.setProbCollision((float) result.probAtLeastOneCollision);
candidate.setInsertSizeAtPos10thP(result.duplexInsertSize10thP);
candidate.setInsertSizeAtPos90thP(result.duplexInsertSize90thP);
final MutableSet<DuplexRead> candidateDuplexes = Sets.mutable.empty();
candidate.getNonMutableConcurringReads().forEachKey(r -> {
DuplexRead dr = r.duplexRead;
if (dr != null) {
Assert.isFalse(dr.invalid);
candidateDuplexes.add(dr);
}
return true;
});
candidate.setDuplexes(candidateDuplexes);
candidate.setnDuplexes(candidateDuplexes.size());
if (candidate.getnDuplexes() == 0) {
candidate.getQuality().addUnique(NO_DUPLEXES, ATROCIOUS);
}
if (param.verbosity > 2) {
candidate.getIssues().clear();//This *must* be done to avoid interference
//between parameter sets, in parameter exploration runs
candidateDuplexes.forEach(d -> {
candidate.getIssues().put(d, d.localAndGlobalQuality.toLong());
});
}
final Quality posQMin = positionQualities.getValue(true);
Handle<Quality> maxDuplexQHandle = new Handle<>(ATROCIOUS);
candidateDuplexes.each(dr -> {
if (posQMin != null) {
dr.localAndGlobalQuality.addUnique(QUALITY_AT_POSITION, posQMin);
}
maxDuplexQHandle.set(Quality.max(maxDuplexQHandle.get(), dr.localAndGlobalQuality.getValue()));
});
final @NonNull Quality maxDuplexQ = maxDuplexQHandle.get();
switch(param.candidateQ2Criterion) {
case "1Q2Duplex":
candidate.getQuality().addUnique(MAX_Q_FOR_ALL_DUPLEXES, maxDuplexQ);
break;
case "NQ1Duplexes":
SettableInteger countQ1Duplexes = new SettableInteger(0);
candidateDuplexes.forEach(d -> {
if (d.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDuplexNStrands).
atLeast(GOOD)) {
countQ1Duplexes.incrementAndGet();
}
});
if (countQ1Duplexes.get() >= param.minQ1Duplexes) {
candidate.getQuality().addUnique(PositionAssay.N_Q1_DUPLEXES, GOOD);
}
break;
default:
throw new AssertionFailedException();
}
if (PositionAssay.COMPUTE_MAX_DPLX_Q_IGNORING_DISAG) {
candidateDuplexes.stream().
map(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality, true)).
max(Quality::compareTo).ifPresent(q -> candidate.getQuality().addUnique(MAX_DPLX_Q_IGNORING_DISAG, q));
}
candidate.resetLigSiteDistances();
if (maxDuplexQ.atLeast(DUBIOUS)) {
candidateDuplexes.forEach(dr -> {
if (dr.localAndGlobalQuality.getValue().atLeast(maxDuplexQ)) {
candidate.acceptLigSiteDistance(dr.getMaxDistanceToLigSite());
}
});
}
}
private void processCandidateQualityStep2(
final CandidateSequence candidate,
final @NonNull SequenceLocation location,
final LocationExaminationResults result,
final byte positionMedianPhred,
final @NonNull DetailedQualities<PositionAssay> positionQualities
) {
if (!param.rnaSeq) {
candidate.getNonMutableConcurringReads().forEachKey(r -> {
final int refPosition = location.position;
final int readPosition = r.referencePositionToReadPosition(refPosition);
if (!r.formsWrongPair()) {
final int distance = r.tooCloseToBarcode(readPosition, 0);
if (Math.abs(distance) > 160) {
throw new AssertionFailedException("Distance problem with candidate " + candidate +
" read at read position " + readPosition + " and refPosition " +
refPosition + ' ' + r.toString() + " in analyzer" +
analyzer.inputBam.getAbsolutePath() + "; distance is " + distance);
}
if (distance >= 0) {
stats.singleAnalyzerQ2CandidateDistanceToLigationSite.insert(distance);
} else {
stats.Q2CandidateDistanceToLigationSiteN.insert(-distance);
}
}
return true;
});
}
if (candidate.getMutationType().isWildtype()) {
candidate.setSupplementalMessage(null);
} else if (candidate.getQuality().getNonNullValue().greaterThan(POOR)) {
final StringBuilder supplementalMessage = new StringBuilder();
final Map<String, Integer> stringCounts = new HashMap<>(100);
candidate.getNonMutableConcurringReads().forEachKey(er -> {
String other = er.record.getMateReferenceName();
if (!er.record.getReferenceName().equals(other)) {
String s = other + ':' + er.getMateAlignmentStart();
Integer found = stringCounts.get(s);
if (found == null){
stringCounts.put(s, 1);
} else {
stringCounts.put(s, found + 1);
}
}
return true;
});
final Optional<String> mates = stringCounts.entrySet().stream().map(entry -> entry.getKey() +
((entry.getValue() == 1) ? "" : (" (" + entry.getValue() + " repeats)")) + "; ").
sorted().reduce(String::concat);
final String hasMateOnOtherChromosome = mates.isPresent() ? mates.get() : "";
final IntSummaryStatistics insertSizeStats = candidate.getNonMutableConcurringReads().keySet().stream().
mapToInt(er -> Math.abs(er.getInsertSize())).summaryStatistics();
final int localMaxInsertSize = insertSizeStats.getMax();
final int localMinInsertSize = insertSizeStats.getMin();
candidate.setMinInsertSize(localMinInsertSize);
candidate.setMaxInsertSize(localMaxInsertSize);
if (localMaxInsertSize < param.minInsertSize || localMinInsertSize > param.maxInsertSize) {
candidate.getQuality().add(PositionAssay.INSERT_SIZE, DUBIOUS);
}
final boolean has0PredictedInsertSize = localMinInsertSize == 0;
final NumberFormat nf = DoubleAdderFormatter.nf.get();
@SuppressWarnings("null")
final boolean hasNoMate = candidate.getNonMutableConcurringReads().forEachKey(
er -> er.record.getMateReferenceName() != null);
if (localMaxInsertSize > param.maxInsertSize) {
supplementalMessage.append("one predicted insert size is " +
nf.format(localMaxInsertSize)).append("; ");
}
if (localMinInsertSize < param.minInsertSize) {
supplementalMessage.append("one predicted insert size is " +
nf.format(localMinInsertSize)).append("; ");
}
candidate.setAverageMappingQuality((int) candidate.getNonMutableConcurringReads().keySet().stream().
mapToInt(r -> r.record.getMappingQuality()).summaryStatistics().getAverage());
if (!"".equals(hasMateOnOtherChromosome)) {
supplementalMessage.append("pair elements map to other chromosomes: " + hasMateOnOtherChromosome).append("; ");
}
if (hasNoMate) {
supplementalMessage.append("at least one read has no mate; ");
}
if ("".equals(hasMateOnOtherChromosome) && !hasNoMate && has0PredictedInsertSize) {
supplementalMessage.append("at least one insert has 0 predicted size; ");
}
if (candidate.getnWrongPairs() > 0) {
supplementalMessage.append(candidate.getnWrongPairs() + " wrong pairs; ");
}
candidate.setSupplementalMessage(supplementalMessage);
}
}
@SuppressWarnings("ReferenceEquality")
private static Runnable checkDuplexAndCandidates(Set<DuplexRead> duplexReads,
ImmutableSet<CandidateSequence> candidateSet) {
for (DuplexRead duplexRead: duplexReads) {
duplexRead.allDuplexRecords.each(r -> {
if (r.duplexRead != duplexRead) {
throw new AssertionFailedException("Read " + r + " associated with duplexes " +
r.duplexRead + " and " + duplexRead);
}
});
}
candidateSet.each(c -> {
Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals(
c.getMutableConcurringReads().keySet()));
Set<DuplexRead> duplexesSupportingC = new UnifiedSet<>(30);
c.getNonMutableConcurringReads().forEachKey(r -> {
DuplexRead d = r.duplexRead;
if (d != null) {
Assert.isFalse(d.invalid);
duplexesSupportingC.add(d);
}
return true;
});//Collect *unique* duplexes
candidateSet.each(c2 -> {
Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals(
c.getMutableConcurringReads().keySet()));
if (c2 == c) {
return;
}
if (c2.equals(c)) {
throw new AssertionFailedException();
}
c2.getNonMutableConcurringReads().keySet().forEach(r -> {
if (r.isOpticalDuplicate()) {
return;
}
DuplexRead d = r.duplexRead;
if (d != null && duplexesSupportingC.contains(d)) {
boolean disowned = !d.allDuplexRecords.contains(r);
throw new AssertionFailedException(disowned + " Duplex " + d +
" associated with candidates " + c + " and " + c2);
}
});
});
});
return null;
}
private boolean checkConstantBarcode(byte[] bases, boolean allowN, int nAllowableMismatches) {
if (nAllowableMismatches == 0 && !allowN) {
return bases == analyzer.constantBarcode;//OK because of interning
}
int nMismatches = 0;
for (int i = 0; i < analyzer.constantBarcode.length; i++) {
if (!basesEqual(analyzer.constantBarcode[i], bases[i], allowN)) {
nMismatches ++;
if (nMismatches > nAllowableMismatches)
return false;
}
}
return true;
}
@SuppressWarnings("null")
ExtendedSAMRecord getExtended(@NonNull SAMRecord record, @NonNull SequenceLocation location) {
final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false);
return extSAMCache.computeIfAbsent(readFullName, s ->
new ExtendedSAMRecord(record, readFullName, analyzer.groupSettings, analyzer, location, extSAMCache));
}
/**
*
* @return the furthest position in the contig covered by the read
*/
int processRead(
final @NonNull SequenceLocation location,
final @NonNull InterningSet<SequenceLocation> locationInterningSet,
final @NonNull ExtendedSAMRecord extendedRec,
final @NonNull ReferenceSequence ref) {
Assert.isFalse(extendedRec.processed, "Double processing of record %s"/*,
extendedRec.getFullName()*/);
extendedRec.processed = true;
final SAMRecord rec = extendedRec.record;
final byte[] readBases = rec.getReadBases();
final byte[] refBases = ref.getBases();
final byte[] baseQualities = rec.getBaseQualities();
final int effectiveReadLength = extendedRec.effectiveLength;
if (effectiveReadLength == 0) {
return -1;
}
final CandidateBuilder readLocalCandidates = new CandidateBuilder(rec.getReadNegativeStrandFlag(),
param.enableCostlyAssertions ? null : (k, v) -> insertCandidateAtPosition(v, k));
final int insertSize = extendedRec.getInsertSize();
final int insertSizeAbs = Math.abs(insertSize);
if (insertSizeAbs > param.maxInsertSize) {
stats.nReadsInsertSizeAboveMaximum.increment(location);
if (param.ignoreSizeOutOfRangeInserts) {
return -1;
}
}
if (insertSizeAbs < param.minInsertSize) {
stats.nReadsInsertSizeBelowMinimum.increment(location);
if (param.ignoreSizeOutOfRangeInserts) {
return -1;
}
}
final PairOrientation pairOrientation;
if (rec.getReadPairedFlag() && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() &&
rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) &&
((pairOrientation = SamPairUtil.getPairOrientation(rec)) == PairOrientation.TANDEM ||
pairOrientation == PairOrientation.RF)) {
if (pairOrientation == PairOrientation.TANDEM) {
stats.nReadsPairTandem.increment(location);
} else if (pairOrientation == PairOrientation.RF) {
stats.nReadsPairRF.increment(location);
}
if (param.ignoreTandemRFPairs) {
return -1;
}
}
final boolean readOnNegativeStrand = rec.getReadNegativeStrandFlag();
if (!checkConstantBarcode(extendedRec.constantBarcode, false, param.nConstantBarcodeMismatchesAllowed)) {
if (checkConstantBarcode(extendedRec.constantBarcode, true, param.nConstantBarcodeMismatchesAllowed)) {
if (readOnNegativeStrand)
stats.nConstantBarcodeDodgyNStrand.increment(location);
else
stats.nConstantBarcodeDodgy.increment(location);
if (!param.acceptNInBarCode)
return -1;
} else {
stats.nConstantBarcodeMissing.increment(location);
return -1;
}
}
stats.nReadsConstantBarcodeOK.increment(location);
if (extendedRec.medianPhred < param.minReadMedianPhredScore) {
stats.nReadMedianPhredBelowThreshold.accept(location);
return -1;
}
stats.mappingQualityKeptRecords.insert(rec.getMappingQuality());
SettableInteger refEndOfPreviousAlignment = new SettableInteger(-1);
SettableInteger readEndOfPreviousAlignment = new SettableInteger(-1);
SettableInteger returnValue = new SettableInteger(-1);
if (insertSize == 0) {
stats.nReadsInsertNoSize.increment(location);
if (param.ignoreZeroInsertSizeReads) {
return -1;
}
}
for (ExtendedAlignmentBlock block: extendedRec.getAlignmentBlocks()) {
processAlignmentBlock(location,
locationInterningSet,
readLocalCandidates,
ref,
!param.rnaSeq,
block,
extendedRec,
rec,
insertSize,
readOnNegativeStrand,
readBases,
refBases,
baseQualities,
effectiveReadLength,
refEndOfPreviousAlignment,
readEndOfPreviousAlignment,
returnValue);
}
if (param.enableCostlyAssertions) {
readLocalCandidates.build().forEach((k, v) -> insertCandidateAtPosition(v, k));
}
return returnValue.get();
}
private void processAlignmentBlock(@NonNull SequenceLocation location,
InterningSet<@NonNull SequenceLocation> locationInterningSet,
final CandidateBuilder readLocalCandidates,
final @NonNull ReferenceSequence ref,
final boolean notRnaSeq,
final ExtendedAlignmentBlock block,
final @NonNull ExtendedSAMRecord extendedRec,
final SAMRecord rec,
final int insertSize,
final boolean readOnNegativeStrand,
final byte[] readBases,
final byte[] refBases,
final byte[] baseQualities,
final int effectiveReadLength,
final SettableInteger refEndOfPreviousAlignment0,
final SettableInteger readEndOfPreviousAlignment0,
final SettableInteger returnValue) {
int refPosition = block.getReferenceStart() - 1;
int readPosition = block.getReadStart() - 1;
final int nBlockBases = block.getLength();
final int refEndOfPreviousAlignment = refEndOfPreviousAlignment0.get();
final int readEndOfPreviousAlignment = readEndOfPreviousAlignment0.get();
returnValue.set(Math.max(returnValue.get(), refPosition + nBlockBases));
/**
* When adding an insertion candidate, make sure that a wildtype or
* mismatch candidate is also inserted at the same position, even
* if it normally would not have been (for example because of low Phred
* quality). This should avoid awkward comparisons between e.g. an
* insertion candidate and a combo insertion + wildtype candidate.
*/
boolean forceCandidateInsertion = false;
if (refEndOfPreviousAlignment != -1) {
final boolean insertion = refPosition == refEndOfPreviousAlignment + 1;
final boolean tooLate = (readOnNegativeStrand ?
(insertion ? readPosition <= param.ignoreLastNBases : readPosition < param.ignoreLastNBases) :
readPosition > rec.getReadLength() - param.ignoreLastNBases) && notRnaSeq;
if (tooLate) {
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Ignoring indel too close to end " + readPosition + (readOnNegativeStrand ? " neg strand " : " pos strand ") + readPosition + ' ' + (rec.getReadLength() - 1) + ' ' + extendedRec.getFullName());
}
stats.nCandidateIndelAfterLastNBases.increment(location);
} else {
if (insertion) {
stats.nCandidateInsertions.increment(location);
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Insertion at position " + readPosition + " for read " + rec.getReadName() +
" (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand +
"; insert size: " + insertSize + ')');
}
forceCandidateInsertion = processInsertion(
readPosition,
refPosition,
readEndOfPreviousAlignment,
refEndOfPreviousAlignment,
locationInterningSet,
readLocalCandidates,
extendedRec,
rec,
insertSize,
readOnNegativeStrand,
readBases,
baseQualities,
effectiveReadLength);
}
else if (refPosition < refEndOfPreviousAlignment + 1) {
throw new AssertionFailedException("Alignment block misordering");
} else {
processDeletion(location,
ref,
block,
readPosition,
refPosition,
readEndOfPreviousAlignment,
refEndOfPreviousAlignment,
locationInterningSet,
readLocalCandidates,
extendedRec,
rec,
insertSize,
readOnNegativeStrand,
readBases,
refBases,
baseQualities,
effectiveReadLength);
}//End of deletion case
}//End of case with accepted indel
}//End of case where there was a previous alignment block
refEndOfPreviousAlignment0.set(refPosition + (nBlockBases - 1));
readEndOfPreviousAlignment0.set(readPosition + (nBlockBases - 1));
for (int i = 0; i < nBlockBases; i++, readPosition++, refPosition++) {
if (i == 1) {
forceCandidateInsertion = false;
}
boolean insertCandidateAtRegularPosition = true;
final SequenceLocation locationPH = notRnaSeq && i < nBlockBases - 1 ? //No insertion or deletion; make a note of it
SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refPosition, true)
: null;
location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refPosition);
if (baseQualities[readPosition] < param.minBasePhredScoreQ1) {
stats.nBasesBelowPhredScore.increment(location);
if (forceCandidateInsertion) {
insertCandidateAtRegularPosition = false;
} else {
continue;
}
}
if (refPosition > refBases.length - 1) {
logger.warn("Ignoring base mapped at " + refPosition + ", beyond the end of " + ref.getName());
continue;
}
stats.nCandidateSubstitutionsConsidered.increment(location);
if (readBases[readPosition] != StringUtil.toUpperCase(refBases[refPosition]) /*Mismatch*/) {
final boolean tooLate = readOnNegativeStrand ? readPosition < param.ignoreLastNBases :
readPosition > (rec.getReadLength() - 1) - param.ignoreLastNBases;
int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1);
boolean goodToInsert = distance < 0 && !tooLate;
if (distance >= 0) {
if (!extendedRec.formsWrongPair()) {
distance = extendedRec.tooCloseToBarcode(readPosition, 0);
if (distance <= 0 && insertCandidateAtRegularPosition) {
stats.rejectedSubstDistanceToLigationSite.insert(-distance);
stats.nCandidateSubstitutionsBeforeFirstNBases.increment(location);
}
}
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Ignoring subst too close to barcode for read " + rec.getReadName());
}
insertCandidateAtRegularPosition = false;
} else if (tooLate && insertCandidateAtRegularPosition) {
stats.nCandidateSubstitutionsAfterLastNBases.increment(location);
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Ignoring subst too close to read end for read " + rec.getReadName());
}
insertCandidateAtRegularPosition = false;
}
if (goodToInsert || forceCandidateInsertion) {
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Substitution at position " + readPosition + " for read " + rec.getReadName() +
" (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand +
"; insert size: " + insertSize + ')');
}
final byte wildType = StringUtil.toUpperCase(refBases[refPosition]);
final byte mutation = StringUtil.toUpperCase(readBases[readPosition]);
switch (mutation) {
case 'A':
stats.nCandidateSubstitutionsToA.increment(location); break;
case 'T':
stats.nCandidateSubstitutionsToT.increment(location); break;
case 'G':
stats.nCandidateSubstitutionsToG.increment(location); break;
case 'C':
stats.nCandidateSubstitutionsToC.increment(location); break;
case 'N':
stats.nNs.increment(location);
if (!forceCandidateInsertion) {
continue;
} else {
insertCandidateAtRegularPosition = false;
}
break;
default:
throw new AssertionFailedException("Unexpected letter: " + StringUtil.toUpperCase(readBases[readPosition]));
}
distance = -extendedRec.tooCloseToBarcode(readPosition, 0);
final byte[] mutSequence = byteArrayMap.get(readBases[readPosition]);
CandidateSequence candidate = new CandidateSequence(this,
SUBSTITUTION, mutSequence, location, extendedRec, distance);
if (!extendedRec.formsWrongPair()) {
candidate.acceptLigSiteDistance(distance);
}
candidate.setInsertSize(insertSize);
candidate.setInsertSizeNoBarcodeAccounting(false);
candidate.setPositionInRead(readPosition);
candidate.setReadEL(effectiveReadLength);
candidate.setReadName(extendedRec.getFullName());
candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart());
candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart());
candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd());
candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd());
candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite());
candidate.setWildtypeSequence(wildType);
candidate.addBasePhredScore(baseQualities[readPosition]);
extendedRec.nReferenceDisagreements++;
if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) !=
ExtendedSAMRecord.PHRED_NO_ENTRY) {
logger.warn("Recording Phred score multiple times at same position " + location);
}
if (param.computeRawMismatches && insertCandidateAtRegularPosition) {
final ComparablePair<String, String> mutationPair = readOnNegativeStrand ?
new ComparablePair<>(byteMap.get(Mutation.complement(wildType)),
byteMap.get(Mutation.complement(mutation))) :
new ComparablePair<>(byteMap.get(wildType),
byteMap.get(mutation));
stats.rawMismatchesQ1.accept(location, mutationPair);
if (meetsQ2Thresholds(extendedRec) &&
baseQualities[readPosition] >= param.minBasePhredScoreQ2 &&
!extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) {
candidate.getMutableRawMismatchesQ2().add(mutationPair);
}
}
if (insertCandidateAtRegularPosition) {
candidate = readLocalCandidates.add(candidate, location);
candidate = null;
}
if (locationPH != null) {
CandidateSequence candidate2 = new CandidateSequence(this,
WILDTYPE, null, locationPH, extendedRec, distance);
if (!extendedRec.formsWrongPair()) {
candidate2.acceptLigSiteDistance(distance);
}
candidate2.setWildtypeSequence(wildType);
candidate2 = readLocalCandidates.add(candidate2, locationPH);
candidate2 = null;
}
}//End of mismatched read case
} else {
//Wildtype read
int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1);
if (distance >= 0) {
if (!extendedRec.formsWrongPair()) {
distance = extendedRec.tooCloseToBarcode(readPosition, 0);
if (distance <= 0 && insertCandidateAtRegularPosition) {
stats.wtRejectedDistanceToLigationSite.insert(-distance);
}
}
if (!forceCandidateInsertion) {
continue;
} else {
insertCandidateAtRegularPosition = false;
}
} else {
if (!extendedRec.formsWrongPair() && distance < -150) {
throw new AssertionFailedException("Distance problem 1 at read position " + readPosition +
" and refPosition " + refPosition + ' ' + extendedRec.toString() +
" in analyzer" + analyzer.inputBam.getAbsolutePath() +
"; distance is " + distance + "");
}
distance = extendedRec.tooCloseToBarcode(readPosition, 0);
if (!extendedRec.formsWrongPair() && insertCandidateAtRegularPosition) {
stats.wtAcceptedBaseDistanceToLigationSite.insert(-distance);
}
}
if (((!readOnNegativeStrand && readPosition > readBases.length - 1 - param.ignoreLastNBases) ||
(readOnNegativeStrand && readPosition < param.ignoreLastNBases))) {
if (insertCandidateAtRegularPosition) {
stats.nCandidateWildtypeAfterLastNBases.increment(location);
}
if (!forceCandidateInsertion) {
continue;
} else {
insertCandidateAtRegularPosition = false;
}
}
CandidateSequence candidate = new CandidateSequence(this,
WILDTYPE, null, location, extendedRec, -distance);
if (!extendedRec.formsWrongPair()) {
candidate.acceptLigSiteDistance(-distance);
}
candidate.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition]));
candidate.addBasePhredScore(baseQualities[readPosition]);
if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) !=
ExtendedSAMRecord.PHRED_NO_ENTRY) {
logger.warn("Recording Phred score multiple times at same position " + location);
}
if (insertCandidateAtRegularPosition) {
candidate = readLocalCandidates.add(candidate, location);
candidate = null;
}
if (locationPH != null) {
CandidateSequence candidate2 = new CandidateSequence(this,
WILDTYPE, null, locationPH, extendedRec, -distance);
if (!extendedRec.formsWrongPair()) {
candidate2.acceptLigSiteDistance(-distance);
}
candidate2.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition]));
candidate2 = readLocalCandidates.add(candidate2, locationPH);
candidate2 = null;
}
}//End of wildtype case
}//End of loop over alignment bases
}
private void processDeletion(
final @NonNull SequenceLocation location,
final @NonNull ReferenceSequence ref,
final ExtendedAlignmentBlock block,
final int readPosition,
final int refPosition,
final int readEndOfPreviousAlignment,
final int refEndOfPreviousAlignment,
InterningSet<@NonNull SequenceLocation> locationInterningSet,
final CandidateBuilder readLocalCandidates,
final @NonNull ExtendedSAMRecord extendedRec,
final SAMRecord rec,
final int insertSize,
final boolean readOnNegativeStrand,
final byte[] readBases,
final byte[] refBases,
final byte[] baseQualities,
final int effectiveReadLength) {
//Deletion or skipped region ("N" in Cigar)
if (refPosition > refBases.length - 1) {
logger.warn("Ignoring rest of read after base mapped at " + refPosition +
", beyond the end of " + ref.getName());
return;
}
int distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, param.ignoreFirstNBasesQ1);
int distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, param.ignoreFirstNBasesQ1);
int distance = Math.min(distance0, distance1) + 1;
final boolean isIntron = block.previousCigarOperator == CigarOperator.N;
final boolean Q1reject = distance < 0;
if (!isIntron && Q1reject) {
if (!extendedRec.formsWrongPair()) {
stats.rejectedIndelDistanceToLigationSite.insert(-distance);
stats.nCandidateIndelBeforeFirstNBases.increment(location);
}
logger.trace("Ignoring deletion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName());
} else {
distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, 0);
distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, 0);
distance = Math.min(distance0, distance1) + 1;
if (!isIntron) stats.nCandidateDeletions.increment(location);
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Deletion or intron at position " + readPosition + " for read " + rec.getReadName() +
" (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand +
"; insert size: " + insertSize + ')');
}
final int deletionLength = refPosition - (refEndOfPreviousAlignment + 1);
final @NonNull SequenceLocation newLocation =
SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1);
final @NonNull SequenceLocation deletionEnd = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), newLocation.position + deletionLength);
final byte @Nullable[] deletedSequence = isIntron ? null :
Arrays.copyOfRange(ref.getBases(), refEndOfPreviousAlignment + 1, refPosition);
//Add hidden mutations to all locations covered by deletion
//So disagreements between deletions that have only overlapping
//spans are detected.
if (!isIntron) {
for (int i = 1; i < deletionLength; i++) {
SequenceLocation location2 = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1 + i);
CandidateSequence hiddenCandidate = new CandidateDeletion(
this, deletedSequence, location2, extendedRec, Integer.MAX_VALUE, MutationType.DELETION,
newLocation, deletionEnd);
hiddenCandidate.setHidden(true);
hiddenCandidate.setInsertSize(insertSize);
hiddenCandidate.setInsertSizeNoBarcodeAccounting(false);
hiddenCandidate.setPositionInRead(readPosition);
hiddenCandidate.setReadEL(effectiveReadLength);
hiddenCandidate.setReadName(extendedRec.getFullName());
hiddenCandidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart());
hiddenCandidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart());
hiddenCandidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd());
hiddenCandidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd());
hiddenCandidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite());
hiddenCandidate = readLocalCandidates.add(hiddenCandidate, location2);
hiddenCandidate = null;
}
}
CandidateSequence candidate = new CandidateDeletion(this,
deletedSequence, newLocation, extendedRec, distance, isIntron ? MutationType.INTRON : MutationType.DELETION,
newLocation, SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refPosition));
if (!extendedRec.formsWrongPair()) {
candidate.acceptLigSiteDistance(distance);
}
candidate.setInsertSize(insertSize);
candidate.setInsertSizeNoBarcodeAccounting(false);
candidate.setPositionInRead(readPosition);
candidate.setReadEL(effectiveReadLength);
candidate.setReadName(extendedRec.getFullName());
candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart());
candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart());
candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd());
candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd());
candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite());
if (!isIntron) extendedRec.nReferenceDisagreements++;
if (!isIntron && param.computeRawMismatches) {
Objects.requireNonNull(deletedSequence);
final ComparablePair<String, String> mutationPair = readOnNegativeStrand ?
new ComparablePair<>(byteMap.get(Mutation.complement(deletedSequence[0])),
new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase())
:
new ComparablePair<>(byteMap.get(deletedSequence[0]),
new String(deletedSequence).toUpperCase());
stats.rawDeletionsQ1.accept(newLocation, mutationPair);
stats.rawDeletionLengthQ1.insert(deletedSequence.length);
if (meetsQ2Thresholds(extendedRec) &&
baseQualities[readPosition] >= param.minBasePhredScoreQ2 &&
!extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) {
candidate.getMutableRawDeletionsQ2().add(mutationPair);
}
}
candidate = readLocalCandidates.add(candidate, newLocation);
candidate = null;
}
}
private boolean processInsertion(
final int readPosition,
final int refPosition,
final int readEndOfPreviousAlignment,
final int refEndOfPreviousAlignment,
InterningSet<@NonNull SequenceLocation> locationInterningSet,
final CandidateBuilder readLocalCandidates,
final @NonNull ExtendedSAMRecord extendedRec,
final SAMRecord rec,
final int insertSize,
final boolean readOnNegativeStrand,
final byte[] readBases,
final byte[] baseQualities,
final int effectiveReadLength) {
boolean forceCandidateInsertion = false;
final @NonNull SequenceLocation location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex,
extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment, true);
int distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, param.ignoreFirstNBasesQ1);
int distance1 = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1);
int distance = Math.max(distance0, distance1);
distance = -distance + 1;
final boolean Q1reject = distance < 0;
if (Q1reject) {
if (!extendedRec.formsWrongPair()) {
stats.rejectedIndelDistanceToLigationSite.insert(-distance);
stats.nCandidateIndelBeforeFirstNBases.increment(location);
}
logger.trace("Ignoring insertion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName());
} else {
distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, 0);
distance1 = extendedRec.tooCloseToBarcode(readPosition, 0);
distance = Math.max(distance0, distance1);
distance = -distance + 1;
final byte [] insertedSequence = Arrays.copyOfRange(readBases,
readEndOfPreviousAlignment + 1, readPosition);
CandidateSequence candidate = new CandidateSequence(
this,
INSERTION,
insertedSequence,
location,
extendedRec,
distance);
if (!extendedRec.formsWrongPair()) {
candidate.acceptLigSiteDistance(distance);
}
candidate.setInsertSize(insertSize);
candidate.setPositionInRead(readPosition);
candidate.setReadEL(effectiveReadLength);
candidate.setReadName(extendedRec.getFullName());
candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart());
candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart());
candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd());
candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd());
candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite());
candidate.setInsertSizeNoBarcodeAccounting(false);
if (param.computeRawMismatches) {
final byte wildType = readBases[readEndOfPreviousAlignment];
final ComparablePair<String, String> mutationPair = readOnNegativeStrand ?
new ComparablePair<>(byteMap.get(Mutation.complement(wildType)),
new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase())
:
new ComparablePair<>(byteMap.get(wildType),
new String(insertedSequence).toUpperCase());
stats.rawInsertionsQ1.accept(location, mutationPair);
stats.rawInsertionLengthQ1.insert(insertedSequence.length);
if (meetsQ2Thresholds(extendedRec) &&
baseQualities[readPosition] >= param.minBasePhredScoreQ2 &&
!extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) {
candidate.getMutableRawInsertionsQ2().add(mutationPair);
}
}
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Insertion of " + new String(candidate.getSequence()) + " at ref " + refPosition + " and read position " + readPosition + " for read " + extendedRec.getFullName());
}
candidate = readLocalCandidates.add(candidate, location);
candidate = null;
forceCandidateInsertion = true;
if (DebugLogControl.shouldLog(TRACE, logger, param, location)) {
logger.info("Added candidate at " + location /*+ "; readLocalCandidates now " + readLocalCandidates.build()*/);
}
extendedRec.nReferenceDisagreements++;
}
return forceCandidateInsertion;
}
public @NonNull Mutinack getAnalyzer() {
return analyzer;
}
}
|
package launcher.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
/**
* SolidLeon #4 20150227
*
* Simple display for showing current progress
* @author SolidLeon
*
*/
public class StatusDisplay extends JFrame implements IStatusListener, ActionListener {
private JProgressBar overallProgress;
private JProgressBar currentProgress;
private JTextArea text;
/** OutputStream redirecting output to JTextArea 'text' */
private OutputStream textOut;
private JButton closeButton;
/** Runnable object to 'run' close button is pressed and before disposing */
private Runnable exitRunner;
public StatusDisplay() {
setPreferredSize(new Dimension(800, 600));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("Launcher Status");
overallProgress = new JProgressBar();
overallProgress.setStringPainted(true);
currentProgress = new JProgressBar();
currentProgress.setStringPainted(true);
JPanel progressPanel = new JPanel(new BorderLayout());
JPanel progressLabelPanel = new JPanel(new GridLayout(2, 1));
JPanel progressBarPanel = new JPanel(new GridLayout(2, 1));
progressLabelPanel.add(new JLabel("Overall Progress:"));
progressLabelPanel.add(new JLabel("Current Progress:"));
progressBarPanel.add(overallProgress);
progressBarPanel.add(currentProgress);
progressPanel.add(progressLabelPanel, BorderLayout.WEST);
progressPanel.add(progressBarPanel, BorderLayout.CENTER);
add(progressPanel, BorderLayout.NORTH);
text = new JTextArea();
text.setFont(new Font("Monospaced", Font.PLAIN, 12));
DefaultCaret caret = (DefaultCaret)text.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
add(new JScrollPane(text), BorderLayout.CENTER);
closeButton = new JButton("Close");
closeButton.addActionListener(this);
add(closeButton, BorderLayout.SOUTH);
textOut = new OutputStream() {
@Override
public void write(int b) throws IOException {
text.append(String.valueOf((char) b));
}
};
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (closeButton.isEnabled()) {
closeButton.doClick();
} else {
JOptionPane.showMessageDialog(StatusDisplay.this, "Cannot close the window right now!");
}
}
});
pack();
setLocationRelativeTo(null);
closeButton.setEnabled(false);
}
@Override
public OutputStream getOutputStream() {
return textOut;
}
public void setProgress(JProgressBar bar, int value, int min, int max, String text) {
bar.setMinimum(min);
bar.setMaximum(max);
bar.setValue(value);
bar.setString(text);
}
@Override
public void setCurrentProgress(int value, int min, int max, String text) {
setProgress(currentProgress, value, min, max, text);
}
@Override
public void setCurrentProgress(int value) {
currentProgress.setValue(value);
}
@Override
public void setCurrentProgressToMax() {
currentProgress.setValue(currentProgress.getMaximum());
}
@Override
public void setCurrentProgress(String text) {
currentProgress.setString(text);
}
@Override
public int getCurrentProgress() {
return currentProgress.getValue();
}
@Override
public void setOverallProgress(int value, int min, int max) {
setProgress(overallProgress, value, min, max, null);
}
@Override
public void setOverallProgress(int value) {
overallProgress.setValue(value);
}
@Override
public void setOverallProgress(String text) {
overallProgress.setString(text);
}
@Override
public int getOverallProgress() {
return overallProgress.getValue();
}
@Override
public void addOverallProgress(int i) {
setOverallProgress(getOverallProgress() + i);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == closeButton) {
if (exitRunner != null)
exitRunner.run();
dispose();
}
}
/**
* - Sets a runner being executed after close button has been pressed.
* - Enabled the close button
* - Sets a fancy text for the close button
* - Sets overall progress to max
* - Sets current progress max to 100 (for cases where the max is 0)
* - Sets current progress to max
* - Sets 'Done!' as curren progress text
*/
@Override
public void setStatusCompletedExecCommandOnExit(Runnable runner) {
this.exitRunner = runner;
closeButton.setEnabled(true);
closeButton.setText("Completed! Close me!");
overallProgress.setValue(overallProgress.getMaximum());
currentProgress.setMaximum(100);
setCurrentProgressToMax();
setCurrentProgress("Done!");
}
}
|
package org.eclipse.xtext.resource.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.naming.IQualifiedNameProvider;
import org.eclipse.xtext.resource.DescriptionUtils;
import org.eclipse.xtext.resource.IContainer;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.IResourceDescription.Delta;
import org.eclipse.xtext.util.IResourceScopeCache;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author Sebastian Zarnekow - Initial contribution and API
* @author Sven Efftinge
*/
public class DefaultResourceDescriptionManager implements IResourceDescription.Manager {
@Inject
private IQualifiedNameProvider nameProvider;
@Inject
private IContainer.Manager containerManager;
@Inject
private IResourceScopeCache cache = IResourceScopeCache.NullImpl.INSTANCE;
@Inject
private DescriptionUtils descriptionUtils;
private static final String CACHE_KEY = DefaultResourceDescriptionManager.class.getName() + "#getResourceDescription";
public IResourceDescription getResourceDescription(final Resource resource) {
return cache.get(CACHE_KEY, resource, new Provider<IResourceDescription>() {
public IResourceDescription get() {
return internalGetResourceDescription(resource, nameProvider);
}
});
}
protected IResourceDescription internalGetResourceDescription(Resource resource, IQualifiedNameProvider nameProvider) {
return new DefaultResourceDescription(resource, nameProvider);
}
public void setNameProvider(IQualifiedNameProvider nameProvider) {
this.nameProvider = nameProvider;
}
public IQualifiedNameProvider getNameProvider() {
return nameProvider;
}
public IContainer.Manager getContainerManager() {
return containerManager;
}
public void setContainerManager(IContainer.Manager containerManager) {
this.containerManager = containerManager;
}
public void setCache(IResourceScopeCache cache) {
this.cache = cache;
}
public IResourceScopeCache getCache() {
return cache;
}
public boolean isAffected(Delta delta, IResourceDescription candidate) throws IllegalArgumentException {
if (!delta.haveEObjectDescriptionsChanged())
return false;
Set<String> names = Sets.newHashSet();
addExportedNames(names,delta.getOld());
addExportedNames(names,delta.getNew());
return !Collections.disjoint(names, getImportedNames(candidate));
}
protected Collection<String> getImportedNames(IResourceDescription candidate) {
return Collections2.forIterable(candidate.getImportedNames());
}
protected void addExportedNames(Set<String> names, IResourceDescription resourceDescriptor) {
if (resourceDescriptor==null)
return;
Iterable<IEObjectDescription> iterable = resourceDescriptor.getExportedObjects();
for (IEObjectDescription ieObjectDescription : iterable) {
names.add(ieObjectDescription.getName());
}
}
public boolean isAffected(Collection<IResourceDescription.Delta> deltas,
IResourceDescription candidate,
IResourceDescriptions context) {
Set<URI> outgoingReferences = descriptionUtils.collectOutgoingReferences(candidate);
Set<URI> interestingResources = Sets.newHashSet();
// deleted resources are no longer visible resources
// so we collect them pessimistic up-front
for (IResourceDescription.Delta delta : deltas) {
if (delta.getNew() == null)
interestingResources.add(delta.getUri());
}
Set<URI> visibleResources = collectVisibleResources(candidate, context);
interestingResources.addAll(visibleResources);
if (interestingResources.isEmpty()) // should at least contain the resource itself
return true;
for (IResourceDescription.Delta delta : deltas) {
if (delta.haveEObjectDescriptionsChanged()) {
URI deltaURI = delta.getUri();
if (outgoingReferences.contains(deltaURI)) {
return true;
}
if (interestingResources.contains(deltaURI)) {
if (isAffected(delta, candidate)) {
return true;
}
}
}
}
return false;
}
protected Set<URI> collectVisibleResources(IResourceDescription description, IResourceDescriptions allDescriptions) {
Set<URI> result = null;
List<IContainer> containers = containerManager.getVisibleContainers(description, allDescriptions);
for (IContainer container: containers) {
for(IResourceDescription resourceDescription: container.getResourceDescriptions()) {
if (result == null)
result = Sets.newHashSet();
result.add(resourceDescription.getURI());
}
}
if (result == null)
return Collections.emptySet();
return result;
}
public DescriptionUtils getDescriptionUtils() {
return descriptionUtils;
}
public void setDescriptionUtils(DescriptionUtils descriptionUtils) {
this.descriptionUtils = descriptionUtils;
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPImage;
import org.jkiss.dbeaver.model.DBPImageProvider;
import org.jkiss.dbeaver.model.data.DBDDataFilter;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCStatistics;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.model.struct.DBSEntity;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.StringEditorInput;
import org.jkiss.dbeaver.ui.editors.SubEditorSite;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.CommonUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ResultSetFilterPanel
*/
class ResultSetFilterPanel extends Composite
{
static final Log log = Log.getLog(ResultSetFilterPanel.class);
public static final int MIN_FILTER_TEXT_WIDTH = 50;
public static final int MIN_FILTER_TEXT_HEIGHT = 20;
public static final int MAX_HISTORY_PANEL_HEIGHT = 200;
private static final String DEFAULT_QUERY_TEXT = "<empty>";
private final ResultSetViewer viewer;
private final ActiveObjectPanel activeObjectPanel;
private final RefreshPanel refreshPanel;
private final HistoryPanel historyPanel;
private StyledText filtersText;
private ToolItem filtersApplyButton;
private ToolItem filtersClearButton;
private ToolItem historyBackButton;
private ToolItem historyForwardButton;
private ControlEnableState filtersEnableState;
private final Composite filterComposite;
private final Color hoverBgColor;
private final Color shadowColor;
private final GC sizingGC;
private final Font hintFont;
private String activeDisplayName = DEFAULT_QUERY_TEXT;
private String prevQuery = null;
private final List<String> filtersHistory = new ArrayList<>();
public ResultSetFilterPanel(ResultSetViewer rsv) {
super(rsv.getControl(), SWT.NONE);
this.viewer = rsv;
this.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
sizingGC = new GC(this);
GridLayout gl = new GridLayout(4, false);
gl.marginHeight = 3;
gl.marginWidth = 3;
this.setLayout(gl);
hoverBgColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
shadowColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
hintFont = UIUtils.modifyFont(getFont(), SWT.ITALIC);
{
this.filterComposite = new Composite(this, SWT.BORDER);
gl = new GridLayout(4, false);
gl.marginHeight = 0;
gl.marginWidth = 0;
gl.horizontalSpacing = 0;
gl.verticalSpacing = 0;
filterComposite.setLayout(gl);
filterComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
activeObjectPanel = new ActiveObjectPanel(filterComposite);
this.filtersText = new StyledText(filterComposite, SWT.SINGLE);
this.filtersText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createFiltersContextMenu();
this.historyPanel = new HistoryPanel(filterComposite);
this.refreshPanel = new RefreshPanel(filterComposite);
// Register filters text in focus service
UIUtils.addFocusTracker(viewer.getSite(), UIUtils.INLINE_WIDGET_EDITOR_ID, this.filtersText);
this.filtersText.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e)
{
// Unregister from focus service
UIUtils.removeFocusTracker(viewer.getSite(), filtersText);
}
});
this.filtersText.addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
if (filtersText.isEnabled() && filtersText.getCharCount() == 0) {
e.gc.setForeground(shadowColor);
e.gc.setFont(hintFont);
e.gc.drawText("Enter an SQL expression to filter results", 2, 0);
e.gc.setFont(null);
}
}
});
this.filtersText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e)
{
if (filtersEnableState == null) {
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
}
}
});
this.filtersText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN) {
historyPanel.showFilterHistoryPopup();
}
}
});
/*
this.filtersText.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
}
});
*/
}
// Handle all shortcuts by filters editor, not by host editor
UIUtils.enableHostEditorKeyBindingsSupport(viewer.getSite(), this.filtersText);
{
ToolBar filterToolbar = new ToolBar(this, SWT.HORIZONTAL | SWT.RIGHT);
filtersApplyButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersApplyButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_APPLY));
//filtersApplyButton.setText("Apply");
filtersApplyButton.setToolTipText("Apply filter criteria");
filtersApplyButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setCustomDataFilter();
}
});
filtersApplyButton.setEnabled(false);
filtersClearButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersClearButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_RESET));
filtersClearButton.setToolTipText("Remove all filters");
filtersClearButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.resetDataFilter(true);
}
});
filtersClearButton.setEnabled(false);
ToolItem filtersCustomButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersCustomButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER));
filtersCustomButton.setToolTipText("Custom Filters");
filtersCustomButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new FilterSettingsDialog(viewer).open();
}
});
filtersCustomButton.setEnabled(true);
new ToolItem(filterToolbar, SWT.SEPARATOR).setControl(new Label(filterToolbar, SWT.SEPARATOR | SWT.VERTICAL));
historyBackButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyBackButton.setImage(DBeaverIcons.getImage(UIIcon.RS_BACK));
historyBackButton.setEnabled(false);
historyBackButton.addSelectionListener(new HistoryMenuListener(historyBackButton, true));
historyForwardButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyForwardButton.setImage(DBeaverIcons.getImage(UIIcon.RS_FORWARD));
historyForwardButton.setEnabled(false);
historyForwardButton.addSelectionListener(new HistoryMenuListener(historyForwardButton, false));
}
this.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e)
{
if (e.detail == SWT.TRAVERSE_RETURN) {
setCustomDataFilter();
e.doit = false;
e.detail = SWT.TRAVERSE_NONE;
}
}
});
this.addControlListener(new ControlListener() {
@Override
public void controlMoved(ControlEvent e) {
redrawPanels();
}
@Override
public void controlResized(ControlEvent e) {
redrawPanels();
}
});
filtersEnableState = ControlEnableState.disable(this);
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
UIUtils.dispose(sizingGC);
UIUtils.dispose(hintFont);
}
});
}
private void createFiltersContextMenu() {
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(filtersText);
menuMgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager)
{
UIUtils.fillDefaultStyledTextContextMenu(manager, filtersText);
}
});
menuMgr.setRemoveAllWhenShown(true);
filtersText.setMenu(menu);
}
private void redrawPanels() {
if (activeObjectPanel != null && !activeObjectPanel.isDisposed()) {
activeObjectPanel.redraw();
}
if (historyPanel != null && !historyPanel.isDisposed()) {
historyPanel.redraw();
}
if (refreshPanel != null && !refreshPanel.isDisposed()) {
refreshPanel.redraw();
}
}
@NotNull
private String getActiveQueryText() {
DBCStatistics statistics = viewer.getModel().getStatistics();
String queryText = statistics == null ? null : statistics.getQueryText();
if (queryText == null || queryText.isEmpty()) {
DBSDataContainer dataContainer = viewer.getDataContainer();
if (dataContainer != null) {
return dataContainer.getName();
}
queryText = DEFAULT_QUERY_TEXT;
}
return queryText;
}
@Nullable
private DBPImage getActiveObjectImage() {
DBSDataContainer dataContainer = viewer.getDataContainer();
if (dataContainer instanceof DBSEntity) {
DBNDatabaseNode dcNode = viewer.getDataContainer().getDataSource().getContainer().getApplication().getNavigatorModel().findNode(dataContainer);
if (dcNode != null) {
return dcNode.getNodeIcon();
}
}
if (dataContainer instanceof DBPImageProvider) {
return ((DBPImageProvider) dataContainer).getObjectImage();
} else if (dataContainer instanceof DBSEntity) {
return DBIcon.TREE_TABLE;
} else {
return UIIcon.SQL_TEXT;
}
}
void enableFilters(boolean enableFilters) {
if (enableFilters) {
if (filtersEnableState != null) {
filtersEnableState.restore();
filtersEnableState = null;
}
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
// Update history buttons
if (historyPosition > 0) {
historyBackButton.setEnabled(true);
historyBackButton.setToolTipText(
stateHistory.get(historyPosition - 1).describeState() +
" (" + ActionUtils.findCommandDescription(IWorkbenchCommandConstants.NAVIGATE_BACKWARD_HISTORY, viewer.getSite(), true) + ")");
} else {
historyBackButton.setEnabled(false);
}
if (historyPosition < stateHistory.size() - 1) {
historyForwardButton.setEnabled(true);
historyForwardButton.setToolTipText(
stateHistory.get(historyPosition + 1).describeState() +
" (" + ActionUtils.findCommandDescription(IWorkbenchCommandConstants.NAVIGATE_FORWARD_HISTORY, viewer.getSite(), true) + ")");
} else {
historyForwardButton.setEnabled(false);
}
} else if (filtersEnableState == null) {
filtersEnableState = ControlEnableState.disable(this);
}
filtersText.getParent().setBackground(filtersText.getBackground());
{
String displayName = getActiveSourceQuery();
if (prevQuery == null || !prevQuery.equals(displayName)) {
loadFiltersHistory(displayName);
prevQuery = displayName;
}
Pattern mlCommentsPattern = Pattern.compile("/\\*.*\\*/", Pattern.DOTALL);
Matcher m = mlCommentsPattern.matcher(displayName);
if (m.find()) {
displayName = m.replaceAll("");
}
displayName = displayName.replaceAll("--.+", "").replaceAll("\\s+", " ");
activeDisplayName = CommonUtils.notEmpty(CommonUtils.truncateString(displayName, 200));
if (CommonUtils.isEmpty(activeDisplayName)) {
activeDisplayName = DEFAULT_QUERY_TEXT;
}
}
filterComposite.layout();
redrawPanels();
}
@NotNull
private String getActiveSourceQuery() {
String displayName;
DBSDataContainer dataContainer = viewer.getDataContainer();
if (dataContainer != null) {
displayName = dataContainer.getName();
} else {
displayName = getActiveQueryText();
}
return displayName;
}
private void loadFiltersHistory(String query) {
filtersHistory.clear();
try {
final Collection<String> history = viewer.getFilterManager().getQueryFilterHistory(query);
filtersHistory.addAll(history);
} catch (Throwable e) {
log.debug("Error reading history", e);
}
}
private void setCustomDataFilter()
{
DBCExecutionContext context = viewer.getExecutionContext();
if (context == null) {
return;
}
String condition = filtersText.getText();
StringBuilder currentCondition = new StringBuilder();
SQLUtils.appendConditionString(viewer.getModel().getDataFilter(), context.getDataSource(), null, currentCondition, true);
if (currentCondition.toString().trim().equals(condition.trim())) {
// The same
return;
}
DBDDataFilter newFilter = viewer.getModel().createDataFilter();
newFilter.setWhere(condition);
viewer.setDataFilter(newFilter, true);
//viewer.getControl().setFocus();
}
void addFiltersHistory(String whereCondition)
{
final boolean oldFilter = filtersHistory.remove(whereCondition);
filtersHistory.add(whereCondition);
if (!oldFilter) {
try {
viewer.getFilterManager().saveQueryFilterValue(getActiveSourceQuery(), whereCondition);
} catch (Throwable e) {
log.debug("Error saving filter", e);
}
}
filtersText.setText(whereCondition);
}
Control getEditControl() {
return filtersText;
}
void setFilterValue(String whereCondition) {
filtersText.setText(whereCondition);
}
@NotNull
private Control createObjectPanel(Shell popup) throws PartInitException {
Composite panel = new Composite(popup, SWT.NONE);
GridLayout gl = new GridLayout(2, false);
// gl.marginWidth = 0;
gl.marginHeight = 0;
// gl.horizontalSpacing = 0;
panel.setLayout(gl);
Label iconLabel = new Label(panel, SWT.NONE);
iconLabel.setImage(DBeaverIcons.getImage(getActiveObjectImage()));
iconLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
Composite editorPH = new Composite(panel, SWT.NONE);
editorPH.setLayoutData(new GridData(GridData.FILL_BOTH));
editorPH.setLayout(new FillLayout());
final SQLEditorBase editor = new SQLEditorBase() {
@Nullable
@Override
public DBCExecutionContext getExecutionContext() {
return viewer.getExecutionContext();
}
@Override
public void createPartControl(Composite parent) {
super.createPartControl(parent);
getAction(ITextEditorActionConstants.CONTEXT_PREFERENCES).setEnabled(false);
}
};
editor.setHasVerticalRuler(false);
editor.init(new SubEditorSite(viewer.getSite()), new StringEditorInput("SQL", getActiveQueryText(), true, GeneralUtils.getDefaultConsoleEncoding()));
editor.createPartControl(editorPH);
editor.reloadSyntaxRules();
StyledText textWidget = editor.getTextViewer().getTextWidget();
textWidget.setAlwaysShowScrollBars(false);
panel.setBackground(textWidget.getBackground());
panel.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
editor.dispose();
}
});
return textWidget;
}
private class FilterPanel extends Canvas {
protected boolean hover = false;
public FilterPanel(Composite parent, int style) {
super(parent, style);
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
paintPanel(e);
}
});
addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseEnter(MouseEvent e) {
hover = true;
redraw();
}
@Override
public void mouseExit(MouseEvent e) {
hover = false;
redraw();
}
});
}
protected void paintPanel(PaintEvent e) {
}
}
private class ActiveObjectPanel extends FilterPanel {
public static final int MIN_INFO_PANEL_WIDTH = 300;
public static final int MIN_INFO_PANEL_HEIGHT = 100;
public static final int MAX_INFO_PANEL_HEIGHT = 400;
private Shell popup;
public ActiveObjectPanel(Composite addressBar) {
super(addressBar, SWT.NONE);
setLayoutData(new GridData(GridData.FILL_VERTICAL));
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
showObjectInfoPopup(e);
}
});
}
private void showObjectInfoPopup(MouseEvent e) {
if (popup != null) {
popup.dispose();
}
popup = new Shell(getShell(), SWT.ON_TOP | SWT.RESIZE);
popup.setLayout(new FillLayout());
Control editControl;
try {
editControl = createObjectPanel(popup);
} catch (PartInitException e1) {
UIUtils.showErrorDialog(getShell(), "Object info", "Error opening object info", e1);
popup.dispose();
return;
}
Point controlRect = editControl.computeSize(-1, -1);
Rectangle parentRect = getDisplay().map(activeObjectPanel, null, getBounds());
Rectangle displayRect = getMonitor().getClientArea();
int width = Math.min(filterComposite.getSize().x, Math.max(MIN_INFO_PANEL_WIDTH, controlRect.x + 30));
int height = Math.min(MAX_INFO_PANEL_HEIGHT, Math.max(MIN_INFO_PANEL_HEIGHT, controlRect.y + 30));
int x = parentRect.x + e.x + 1;
int y = parentRect.y + e.y + 1;
if (y + height > displayRect.y + displayRect.height) {
y = parentRect.y - height;
}
popup.setBounds(x, y, width, height);
popup.setVisible(true);
editControl.setFocus();
editControl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
popup.dispose();
}
});
}
@Override
public Point computeSize(int wHint, int hHint, boolean changed) {
int maxWidth = viewer.getControl().getParent().getSize().x / 4;
Point textSize = sizingGC.textExtent(activeDisplayName);
Image image = DBeaverIcons.getImage(getActiveObjectImage());
if (image != null) {
textSize.x += image.getBounds().width + 4;
}
return new Point(
Math.max(MIN_FILTER_TEXT_WIDTH, Math.min(textSize.x + 10, maxWidth)),
Math.min(textSize.y + 6, MIN_FILTER_TEXT_HEIGHT));
}
@Override
protected void paintPanel(PaintEvent e) {
e.gc.setForeground(shadowColor);
if (hover) {
e.gc.setBackground(hoverBgColor);
e.gc.fillRectangle(e.x, e.y, e.width - 3, e.height);
e.gc.drawLine(
e.x + e.width - 4, e.y,
e.x + e.width - 4, e.y + e.height);
} else {
e.gc.drawLine(
e.x + e.width - 4, e.y + 2,
e.x + e.width - 4, e.y + e.height - 4);
}
e.gc.setForeground(e.gc.getDevice().getSystemColor(SWT.COLOR_DARK_GREEN));
e.gc.setClipping(e.x, e.y, e.width - 8, e.height);
int textOffset = 2;
Image icon = DBeaverIcons.getImage(getActiveObjectImage());
if (icon != null) {
e.gc.drawImage(icon, 2, 3);
textOffset += icon.getBounds().width + 2;
}
e.gc.drawText(activeDisplayName, textOffset, 3);
e.gc.setClipping((Rectangle) null);
}
}
private class HistoryPanel extends FilterPanel {
private final Image dropImageE, dropImageD;
private TableItem hoverItem;
private Shell popup;
public HistoryPanel(Composite addressBar) {
super(addressBar, SWT.NONE);
dropImageE = DBeaverIcons.getImage(UIIcon.DROP_DOWN);
dropImageD = new Image(dropImageE.getDevice(), dropImageE, SWT.IMAGE_GRAY);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.heightHint = MIN_FILTER_TEXT_HEIGHT;
gd.widthHint = dropImageE.getBounds().width;
setLayoutData(gd);
addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
UIUtils.dispose(dropImageD);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
showFilterHistoryPopup();
}
});
}
@Override
protected void paintPanel(PaintEvent e) {
e.gc.setForeground(shadowColor);
if (hover) {
e.gc.drawImage(dropImageE, e.x, e.y + 2);
} else {
e.gc.drawImage(dropImageD, e.x, e.y + 2);
}
}
private void showFilterHistoryPopup() {
if (popup != null) {
popup.dispose();
}
popup = new Shell(getShell(), SWT.NO_TRIM | SWT.ON_TOP | SWT.RESIZE);
popup.setLayout(new FillLayout());
Table editControl = createFilterHistoryPanel(popup);
Point parentRect = getDisplay().map(filtersText, null, new Point(0, 0));
Rectangle displayRect = getMonitor().getClientArea();
final Point filterTextSize = filtersText.getSize();
int width = filterTextSize.x + historyPanel.getSize().x + refreshPanel.getSize().x;
int height = Math.min(MAX_HISTORY_PANEL_HEIGHT, editControl.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
int x = parentRect.x;
int y = parentRect.y + getSize().y;
if (y + height > displayRect.y + displayRect.height) {
y = parentRect.y - height;
}
popup.setBounds(x, y, width, height);
int tableWidth = editControl.getSize().x - editControl.getBorderWidth() * 2;
final ScrollBar vsb = editControl.getVerticalBar();
if (vsb != null) {
tableWidth -= vsb.getSize().x;
}
editControl.getColumn(0).setWidth(tableWidth);
popup.setVisible(true);
editControl.setFocus();
editControl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
popup.dispose();
}
});
}
@NotNull
private Table createFilterHistoryPanel(final Shell popup) {
final Table historyTable = new Table(popup, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE);
new TableColumn(historyTable, SWT.NONE);
if (filtersHistory.isEmpty()) {
// nothing
} else {
String curFilterValue = filtersText.getText();
for (int i = filtersHistory.size(); i > 0; i
String hi = filtersHistory.get(i - 1);
if (!CommonUtils.equalObjects(hi, curFilterValue)) {
new TableItem(historyTable, SWT.NONE).setText(hi);
}
}
historyTable.deselectAll();
}
historyTable.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseHover(MouseEvent e) {
//hoverItem = historyTable.getItem(new Point(e.x, e.y));
}
@Override
public void mouseExit(MouseEvent e) {
hoverItem = null;
}
});
historyTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
TableItem item = hoverItem;
if (item == null) {
final int selectionIndex = historyTable.getSelectionIndex();
if (selectionIndex != -1) {
item = historyTable.getItem(selectionIndex);
}
}
if (item != null) {
if (e.keyCode == SWT.DEL) {
final String filterValue = item.getText();
try {
viewer.getFilterManager().deleteQueryFilterValue(getActiveSourceQuery(), filterValue);
} catch (DBException e1) {
log.warn("Error deleting filter value [" + filterValue + "]", e1);
}
filtersHistory.remove(filterValue);
item.dispose();
hoverItem = null;
} else if (e.keyCode == SWT.CR || e.keyCode == SWT.SPACE) {
final String newFilter = item.getText();
popup.dispose();
setFilterValue(newFilter);
setCustomDataFilter();
}
}
}
});
historyTable.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent e) {
hoverItem = historyTable.getItem(new Point(e.x, e.y));
}
});
historyTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
if (hoverItem != null) {
final String newFilter = hoverItem.getText();
popup.dispose();
setFilterValue(newFilter);
setCustomDataFilter();
}
}
});
return historyTable;
}
}
private class RefreshPanel extends FilterPanel {
private final Image enabledImage, disabledImage;
public RefreshPanel(Composite addressBar) {
super(addressBar, SWT.NONE);
setToolTipText(CoreMessages.controls_resultset_viewer_action_refresh);
enabledImage = DBeaverIcons.getImage(UIIcon.RS_REFRESH);
disabledImage = new Image(enabledImage.getDevice(), enabledImage, SWT.IMAGE_GRAY);
addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
UIUtils.dispose(disabledImage);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (!viewer.isRefreshInProgress() && e.x > 8) {
viewer.refresh();
redraw();
}
}
});
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.heightHint = MIN_FILTER_TEXT_HEIGHT;
gd.widthHint = 10 + enabledImage.getBounds().width + 6;
setLayoutData(gd);
}
@Override
protected void paintPanel(PaintEvent e) {
e.gc.setForeground(shadowColor);
e.gc.drawLine(
e.x + 4, e.y + 2,
e.x + 4, e.y + e.height - 4);
if (viewer.isRefreshInProgress()) {
e.gc.drawImage(DBeaverIcons.getImage(UIIcon.CLOSE), e.x + 10, e.y + 2);
} else if (hover) {
e.gc.drawImage(enabledImage, e.x + 10, e.y + 2);
} else {
e.gc.drawImage(disabledImage, e.x + 10, e.y + 2);
}
}
}
private class HistoryMenuListener extends SelectionAdapter {
private final ToolItem dropdown;
private final boolean back;
public HistoryMenuListener(ToolItem item, boolean back) {
this.dropdown = item;
this.back = back;
}
@Override
public void widgetSelected(SelectionEvent e) {
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
if (e.detail == SWT.ARROW) {
ToolItem item = (ToolItem) e.widget;
Rectangle rect = item.getBounds();
Point pt = item.getParent().toDisplay(new Point(rect.x, rect.y));
Menu menu = new Menu(dropdown.getParent().getShell());
menu.setLocation(pt.x, pt.y + rect.height);
menu.setVisible(true);
for (int i = historyPosition + (back ? -1 : 1); i >= 0 && i < stateHistory.size(); i += back ? -1 : 1) {
MenuItem mi = new MenuItem(menu, SWT.NONE);
ResultSetViewer.StateItem state = stateHistory.get(i);
mi.setText(state.describeState());
final int statePosition = i;
mi.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.navigateHistory(statePosition);
}
});
}
} else {
int newPosition = back ? historyPosition - 1 : historyPosition + 1;
viewer.navigateHistory(newPosition);
}
}
}
}
|
package com.indeed.proctor.webapp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.indeed.proctor.common.ProctorSpecification;
import com.indeed.proctor.common.ProctorUtils;
import com.indeed.proctor.common.Serializers;
import com.indeed.proctor.common.SpecificationResult;
import com.indeed.proctor.common.dynamic.DynamicFilters;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import com.indeed.proctor.common.model.TestDefinition;
import com.indeed.proctor.common.model.TestMatrixArtifact;
import com.indeed.proctor.common.model.TestMatrixVersion;
import com.indeed.proctor.store.ProctorReader;
import com.indeed.proctor.store.StoreException;
import com.indeed.proctor.webapp.db.Environment;
import com.indeed.proctor.webapp.model.AppVersion;
import com.indeed.proctor.webapp.model.ProctorClientApplication;
import com.indeed.proctor.webapp.model.RemoteSpecificationResult;
import com.indeed.proctor.webapp.util.threads.LogOnUncaughtExceptionHandler;
import com.indeed.util.core.DataLoadingTimerTask;
import com.indeed.util.core.Pair;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
/**
* Regularly reloads specifications from applications where proctor client is deployed.
*/
public class RemoteProctorSpecificationSource extends DataLoadingTimerTask implements ProctorSpecificationSource {
private static final Logger LOGGER = Logger.getLogger(RemoteProctorSpecificationSource.class);
private static final ObjectMapper OBJECT_MAPPER = Serializers.strict();
@Autowired(required = false)
private final ProctorClientSource clientSource = new DefaultClientSource();
private final int httpTimeout;
private final ExecutorService httpExecutor;
private final Map<Environment, ImmutableMap<AppVersion, RemoteSpecificationResult>> cache_ = Maps.newConcurrentMap();
private final Map<Environment, ProctorReader> proctorReaderMap;
public RemoteProctorSpecificationSource(final int httpTimeout,
final int executorThreads,
final ProctorReader trunk,
final ProctorReader qa,
final ProctorReader production) {
super(RemoteProctorSpecificationSource.class.getSimpleName());
this.httpTimeout = httpTimeout;
Preconditions.checkArgument(httpTimeout > 0, "verificationTimeout > 0");
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("proctor-specification-source-Thread-%d")
.setUncaughtExceptionHandler(new LogOnUncaughtExceptionHandler())
.build();
this.httpExecutor = Executors.newFixedThreadPool(executorThreads, threadFactory);
this.proctorReaderMap = ImmutableMap.of(
Environment.WORKING, trunk,
Environment.QA, qa,
Environment.PRODUCTION, production
);
}
@Override
public RemoteSpecificationResult getRemoteResult(final Environment environment,
final AppVersion version) {
final ImmutableMap<AppVersion, RemoteSpecificationResult> results = cache_.get(environment);
if (results != null && results.containsKey(version)) {
return results.get(version);
}
return RemoteSpecificationResult.newBuilder(version).build(Collections.<ProctorClientApplication>emptyList());
}
@Override
public Map<AppVersion, RemoteSpecificationResult> loadAllSpecifications(final Environment environment) {
final ImmutableMap<AppVersion, RemoteSpecificationResult> cache = cache_.get(environment);
if (cache == null) {
return Collections.emptyMap();
} else {
return cache;
}
}
@Override
public Map<AppVersion, ProctorSpecification> loadAllSuccessfulSpecifications(final Environment environment) {
final ImmutableMap<AppVersion, RemoteSpecificationResult> cache = cache_.get(environment);
if (cache == null) {
return Collections.emptyMap();
} else {
final Map<AppVersion, RemoteSpecificationResult> success = Maps.filterEntries(cache, input -> input.getValue().isSuccess());
return Maps.transformValues(success, input -> input.getSpecificationResult().getSpecification());
}
}
@Override
public Set<AppVersion> activeClients(final Environment environment, final String testName) {
final Map<AppVersion, RemoteSpecificationResult> specifications = cache_.get(environment);
if (specifications == null) {
return Collections.emptySet();
}
final Set<AppVersion> clients = Sets.newHashSet();
final ConsumableTestDefinition testDefinition = getCurrentConsumableTestDefinition(environment, testName);
for (final Map.Entry<AppVersion, RemoteSpecificationResult> entry : specifications.entrySet()) {
final AppVersion version = entry.getKey();
final RemoteSpecificationResult rr = entry.getValue();
if (rr.isSuccess()) {
final ProctorSpecification specification = rr.getSpecificationResult().getSpecification();
final DynamicFilters filters = specification.getDynamicFilters();
if (containsTest(specification, testName) || willResolveTest(filters, testName, testDefinition)) {
clients.add(version);
}
}
}
return clients;
}
@Override
public Set<String> activeTests(final Environment environment) {
final Map<AppVersion, RemoteSpecificationResult> specifications = cache_.get(environment);
if (specifications == null) {
return Collections.emptySet();
}
final TestMatrixArtifact testMatrixArtifact = getCurrentTestMatrixArtifact(environment);
Preconditions.checkNotNull(testMatrixArtifact, "Failed to get the current test matrix artifact");
final Map<String, ConsumableTestDefinition> definedTests = testMatrixArtifact.getTests();
final Set<String> tests = Sets.newHashSet();
for (final Map.Entry<AppVersion, RemoteSpecificationResult> entry : specifications.entrySet()) {
final RemoteSpecificationResult remoteResult = entry.getValue();
if (remoteResult.isSuccess()) {
final ProctorSpecification specification = remoteResult.getSpecificationResult().getSpecification();
final Set<String> requiredTests = specification.getTests().keySet();
final Set<String> dynamicTests = specification.getDynamicFilters()
.determineTests(definedTests, requiredTests);
tests.addAll(requiredTests);
tests.addAll(dynamicTests);
}
}
return tests;
}
@Override
public boolean load() {
final boolean success = refreshInternalCache();
if (success) {
setDataVersion(new Date().toString());
}
return success;
}
private boolean refreshInternalCache() {
// TODO (parker) 9/6/12 - run all of these in parallel instead of in series
final boolean devSuccess = refreshInternalCache(Environment.WORKING);
final boolean qaSuccess = refreshInternalCache(Environment.QA);
final boolean productionSuccess = refreshInternalCache(Environment.PRODUCTION);
return devSuccess && qaSuccess && productionSuccess;
}
private boolean refreshInternalCache(final Environment environment) {
LOGGER.info("Refreshing internal list of ProctorSpecifications");
final List<ProctorClientApplication> clients = clientSource.loadClients(environment);
final Map<AppVersion, Future<RemoteSpecificationResult>> futures = Maps.newLinkedHashMap();
final ImmutableMap.Builder<AppVersion, RemoteSpecificationResult> allResults = ImmutableMap.builder();
final Set<AppVersion> appVersionsToCheck = Sets.newLinkedHashSet();
final Set<AppVersion> skippedAppVersions = Sets.newLinkedHashSet();
// Accumulate all clients that have equivalent AppVersion (APPLICATION_COMPARATOR)
final ImmutableListMultimap.Builder<AppVersion, ProctorClientApplication> builder = ImmutableListMultimap.builder();
for (final ProctorClientApplication client : clients) {
final AppVersion appVersion = new AppVersion(client.getApplication(), client.getVersion());
builder.put(appVersion, client);
}
final ImmutableListMultimap<AppVersion, ProctorClientApplication> apps = builder.build();
for (final AppVersion appVersion : apps.keySet()) {
appVersionsToCheck.add(appVersion);
final List<ProctorClientApplication> callableClients = apps.get(appVersion);
assert !callableClients.isEmpty();
futures.put(appVersion, httpExecutor.submit(
() -> internalGet(appVersion, callableClients, httpTimeout)));
}
while (!futures.isEmpty()) {
try {
Thread.sleep(10);
} catch (final InterruptedException e) {
LOGGER.error("Oh heavens", e);
}
for (final Iterator<Map.Entry<AppVersion, Future<RemoteSpecificationResult>>> iterator = futures.entrySet().iterator(); iterator.hasNext(); ) {
final Map.Entry<AppVersion, Future<RemoteSpecificationResult>> entry = iterator.next();
final AppVersion appVersion = entry.getKey();
final Future<RemoteSpecificationResult> future = entry.getValue();
if (future.isDone()) {
iterator.remove();
try {
final RemoteSpecificationResult result = future.get();
allResults.put(appVersion, result);
if (result.isSkipped()) {
skippedAppVersions.add(result.getVersion());
appVersionsToCheck.remove(result.getVersion());
} else if (result.isSuccess()) {
appVersionsToCheck.remove(result.getVersion());
}
} catch (final InterruptedException e) {
LOGGER.error("Interrupted getting " + appVersion, e);
} catch (final ExecutionException e) {
final Throwable cause = e.getCause();
LOGGER.error("Unable to fetch " + appVersion, cause);
}
}
}
}
synchronized (cache_) {
cache_.put(environment, allResults.build());
}
// TODO (parker) 9/6/12 - Fail if we do not have 1 specification for each <Application>.<Version>
// should we update the cache?
if (!appVersionsToCheck.isEmpty()) {
LOGGER.warn("Failed to load any specification for the following AppVersions: " + Joiner.on(",").join(appVersionsToCheck));
}
if (!skippedAppVersions.isEmpty()) {
LOGGER.info("Skipped checking specification for the following AppVersions (/private/proctor/specification returned 404): " + Joiner.on(",").join(skippedAppVersions));
}
LOGGER.info("Finish refreshing internal list of ProctorSpecifications");
return appVersionsToCheck.isEmpty();
}
public void shutdown() {
httpExecutor.shutdownNow();
}
private static RemoteSpecificationResult internalGet(final AppVersion version, final List<ProctorClientApplication> clients, final int timeout) {
// TODO (parker) 2/7/13 - priority queue them based on AUS datacenter, US DC, etc
final LinkedList<ProctorClientApplication> remaining = Lists.newLinkedList(clients);
final RemoteSpecificationResult.Builder results = RemoteSpecificationResult.newBuilder(version);
while (remaining.peek() != null) {
final ProctorClientApplication client = remaining.poll();
// really stupid method of pinging 1 of the applications.
final Pair<Integer, SpecificationResult> result = fetchSpecification(client, timeout);
final int statusCode = result.getFirst();
final SpecificationResult specificationResult = result.getSecond();
if (fetchSpecificationFailed(specificationResult)) {
if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
LOGGER.info("Client " + client.getBaseApplicationUrl() + " /private/proctor/specification returned 404 - skipping");
results.skipped(client, specificationResult);
break;
}
// Don't yell too load, the error is handled
LOGGER.info("Failed to read specification from: " + client.getBaseApplicationUrl() + " : " + specificationResult.getError());
results.failed(client, specificationResult);
} else {
results.success(client, specificationResult);
break;
}
}
return results.build(remaining);
}
/**
* Firstly try visiting specification API end point. If it's not exported, fetch from private/v instead.
*
* @param client
* @param timeout
* @return
*/
private static Pair<Integer, SpecificationResult> fetchSpecification(final ProctorClientApplication client, final int timeout) {
final Pair<Integer, SpecificationResult> apiSpec = fetchSpecificationFromApi(client, timeout);
if (fetchSpecificationFailed(apiSpec.getSecond())) {
return fetchSpecificationFromExportedVariable(client, timeout);
}
return apiSpec;
}
// @Nonnull
private static Pair<Integer, SpecificationResult> fetchSpecification(final String urlString, final int timeout, final SpecificationParser parser) {
int statusCode = -1;
InputStream inputStream = null;
try {
final URL url = new URL(urlString);
LOGGER.debug("Trying to read specification from " + url.toString() + " using timeout " + timeout + " ms");
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(timeout);
urlConnection.setConnectTimeout(timeout);
statusCode = urlConnection.getResponseCode();
inputStream = urlConnection.getInputStream();
// map from testName => list of bucket names
final SpecificationResult result = parser.parse(inputStream);
return new Pair<>(statusCode, result);
} catch (final Throwable e) {
final SpecificationResult errorResult = createErrorResult(e);
return new Pair<>(statusCode, errorResult);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (final IOException e) {
LOGGER.error("Unable to close stream to " + urlString, e);
}
}
}
private static SpecificationResult createErrorResult(final Throwable t) {
final SpecificationResult result = new SpecificationResult();
final StringWriter sw = new StringWriter();
final PrintWriter writer = new PrintWriter(sw);
t.printStackTrace(writer);
result.setError(t.getMessage());
result.setException(sw.toString());
return result;
}
// Check if this test is defined in a specification by a client.
private static boolean containsTest(final ProctorSpecification specification, final String testName) {
return specification.getTests().containsKey(testName);
}
// Check if this test will be resolved by defined filters in a client.
private static boolean willResolveTest(final DynamicFilters filters, final String testName, final ConsumableTestDefinition testDefinition) {
return (filters != null) && StringUtils.isNotEmpty(testName) && (testDefinition != null) &&
filters.determineTests(ImmutableMap.of(testName, testDefinition), Collections.emptySet()).contains(testName);
}
@Nullable
private ConsumableTestDefinition getCurrentConsumableTestDefinition(final Environment environment, final String testName) {
try {
final TestDefinition testDefinition = proctorReaderMap.get(environment).getCurrentTestDefinition(testName);
if (testDefinition != null) {
return ProctorUtils.convertToConsumableTestDefinition(testDefinition);
}
} catch (final StoreException e) {
LOGGER.warn("Failed to get current consumable test definition for " + testName + " in " + environment, e);
}
return null;
}
@Nullable
private TestMatrixArtifact getCurrentTestMatrixArtifact(final Environment environment) {
try {
final TestMatrixVersion testMatrix = proctorReaderMap.get(environment).getCurrentTestMatrix();
if (testMatrix != null) {
return ProctorUtils.convertToConsumableArtifact(testMatrix);
}
} catch (final StoreException e) {
LOGGER.warn("Failed to get current test matrix artifact in " + environment, e);
}
return null;
}
private static Pair<Integer, SpecificationResult> fetchSpecificationFromApi(final ProctorClientApplication client, final int timeout) {
/*
* This needs to be moved to a separate checker class implementing some interface
*/
final String apiUrl = client.getBaseApplicationUrl() + "/private/proctor/specification";
return fetchSpecification(apiUrl, timeout, new SpecificationParser() {
@Override
public SpecificationResult parse(final InputStream inputStream) throws IOException {
return OBJECT_MAPPER.readValue(inputStream, SpecificationResult.class);
}
});
}
private static Pair<Integer, SpecificationResult> fetchSpecificationFromExportedVariable(final ProctorClientApplication client, final int timeout) {
/*
* This needs to be moved to a separate checker class implementing some interface
*/
final String urlStr = client.getBaseApplicationUrl() + "/private/v?ns=JsonProctorLoaderFactory&v=specification";
return fetchSpecification(urlStr, timeout, EXPORTED_VARIABLE_PARSER);
}
@VisibleForTesting
static final SpecificationParser EXPORTED_VARIABLE_PARSER = new SpecificationParser() {
@Override
public SpecificationResult parse(final InputStream inputStream) throws IOException {
final String json = IOUtils.toString(inputStream).replace("\\:", ":").trim();
final ProctorSpecification proctorSpecification = OBJECT_MAPPER.readValue(json, ProctorSpecification.class);
final SpecificationResult specificationResult = new SpecificationResult();
specificationResult.setSpecification(proctorSpecification);
return specificationResult;
}
};
interface SpecificationParser {
SpecificationResult parse(final InputStream inputStream) throws IOException;
}
private static boolean fetchSpecificationFailed(final SpecificationResult result) {
return result.getSpecification() == null;
}
}
|
package com.opengamma.financial.functiondoc;
import java.util.HashMap;
import java.util.Map;
import com.opengamma.financial.security.bond.BondSecurity;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.cash.CashSecurity;
import com.opengamma.financial.security.cds.CreditDefaultSwapSecurity;
import com.opengamma.financial.security.deposit.PeriodicZeroDepositSecurity;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;
import com.opengamma.financial.security.forward.CommodityForwardSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity;
import com.opengamma.financial.security.future.FutureSecurity;
import com.opengamma.financial.security.fx.FXForwardSecurity;
import com.opengamma.financial.security.fx.NonDeliverableFXForwardSecurity;
import com.opengamma.financial.security.option.BondFutureOptionSecurity;
import com.opengamma.financial.security.option.CommodityFutureOptionSecurity;
import com.opengamma.financial.security.option.EquityBarrierOptionSecurity;
import com.opengamma.financial.security.option.EquityIndexOptionSecurity;
import com.opengamma.financial.security.option.EquityOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.IRFutureOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXDigitalOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.SwapSecurity;
/**
* Temporary measure for formatting an internal security type string into a
* form that can be displayed in the documentation. Note that the web gui
* requires the same behaviour and will get a proper implementation. When that
* happens, use that and delete this class.
*/
public final class PrettyPrintSecurityType {
private static final Map<String, String> s_data;
static {
s_data = new HashMap<String, String>();
s_data.put(BondSecurity.SECURITY_TYPE, "Bond");
s_data.put(BondFutureOptionSecurity.SECURITY_TYPE, "Bond Future Option");
s_data.put(CapFloorSecurity.SECURITY_TYPE, "Cap/Floor");
s_data.put(CapFloorCMSSpreadSecurity.SECURITY_TYPE, "Cap/Floor CMS Spread");
s_data.put(CashSecurity.SECURITY_TYPE, "Cash");
s_data.put(CommodityForwardSecurity.SECURITY_TYPE, "Commodity Forward");
s_data.put(CommodityFutureOptionSecurity.SECURITY_TYPE, "Commodity Future Option");
s_data.put(CreditDefaultSwapSecurity.SECURITY_TYPE, "CDS");
s_data.put(EquitySecurity.SECURITY_TYPE, "Equity");
s_data.put(EquityBarrierOptionSecurity.SECURITY_TYPE, "Equity Barrier Option");
s_data.put(EquityIndexOptionSecurity.SECURITY_TYPE, "Equity Index Option");
s_data.put(EquityIndexDividendFutureSecurity.SECURITY_TYPE, "Equity Index Future");
s_data.put(EquityVarianceSwapSecurity.SECURITY_TYPE, "Equity Variance Swap");
s_data.put(EquityOptionSecurity.SECURITY_TYPE, "Equity Option");
s_data.put("EXTERNAL_SENSITIVITIES_SECURITY", "Externally Calculated Sensitivities");
s_data.put(FRASecurity.SECURITY_TYPE, "FRA");
s_data.put(FutureSecurity.SECURITY_TYPE, "Future");
s_data.put(FXBarrierOptionSecurity.SECURITY_TYPE, "FX Barrier Option");
s_data.put(FXDigitalOptionSecurity.SECURITY_TYPE, "FX Digital Option");
s_data.put(FXForwardSecurity.SECURITY_TYPE, "FX Forward");
s_data.put(FXOptionSecurity.SECURITY_TYPE, "FX Option");
s_data.put(IRFutureOptionSecurity.SECURITY_TYPE, "IR Future Option");
s_data.put(NonDeliverableFXDigitalOptionSecurity.SECURITY_TYPE, "Non-deliverable FX Digital Option");
s_data.put(NonDeliverableFXOptionSecurity.SECURITY_TYPE, "Non-deliverable FX Option");
s_data.put(NonDeliverableFXForwardSecurity.SECURITY_TYPE, "Non-deliverable FX Forward");
s_data.put(PeriodicZeroDepositSecurity.SECURITY_TYPE, "Periodic Zero Deposit");
s_data.put(SwapSecurity.SECURITY_TYPE, "Swap");
s_data.put(SwaptionSecurity.SECURITY_TYPE, "Swaption");
}
private PrettyPrintSecurityType() {
}
public static String getTypeString(final String type) {
final String value = s_data.get(type);
if (value != null) {
return value;
}
return type;
}
}
|
package gov.nih.nci.cabig.caaers.service.migrator;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao;
import gov.nih.nci.cabig.caaers.dao.SiteInvestigatorDao;
import gov.nih.nci.cabig.caaers.dao.query.OrganizationQuery;
import gov.nih.nci.cabig.caaers.domain.CoordinatingCenter;
import gov.nih.nci.cabig.caaers.domain.FundingSponsor;
import gov.nih.nci.cabig.caaers.domain.Investigator;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.SiteInvestigator;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter;
import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor;
import gov.nih.nci.cabig.caaers.domain.StudyInvestigator;
import gov.nih.nci.cabig.caaers.domain.StudyOrganization;
import gov.nih.nci.cabig.caaers.domain.StudyPersonnel;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;
public class StudyOrganizationMigrator implements Migrator<Study>{
private OrganizationDao organizationDao;
private SiteInvestigatorDao siteInvestigatorDao;
private ResearchStaffDao researchStaffDao;
/**
* This method will copy the {@link StudyOrganization}s from source to destination
*/
public void migrate(Study source, Study destination,DomainObjectImportOutcome<Study> outcome) {
//migrate funding sponsor
migrateFundingSponsor(source, destination, outcome);
//migrate coordinating center
migrateCoordinatingCenter(source, destination, outcome);
//migrate studyOrganization.
migrateStudySite(source, destination, outcome);
}
private void migrateStudySite(Study source, Study destination,DomainObjectImportOutcome<Study> outcome) {
if(source.getStudyOrganizations() != null && source.getStudyOrganizations().size() > 0){
for (StudyOrganization studyOrganization : source.getStudyOrganizations()) {
Organization organization = null;
if(studyOrganization.getOrganization().getNciInstituteCode() != null && studyOrganization.getOrganization().getNciInstituteCode().length() > 0){
String nciInstituteCode = studyOrganization.getOrganization().getNciInstituteCode();
organization = fetchOrganization(nciInstituteCode);
}else{
String orgName = studyOrganization.getOrganization().getName();
organization = organizationDao.getByName(orgName);
}
outcome.ifNullObject(organization, DomainObjectImportOutcome.Severity.ERROR,
"The organization specified in studySite is invalid");
studyOrganization.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studyOrganization, organization, outcome);
migrateStudyPersonnels(studyOrganization, organization, outcome);
destination.addStudySite((StudySite) studyOrganization);
}
}
}
private void migrateFundingSponsor(Study source, Study destination, DomainObjectImportOutcome<Study> outcome ){
FundingSponsor sponsor = source.getFundingSponsor();
if(sponsor == null) return;
StudyFundingSponsor studySponsor = sponsor.getStudyFundingSponsor();
Organization organization = null;
if(studySponsor.getOrganization().getNciInstituteCode() != null && studySponsor.getOrganization().getNciInstituteCode().length() > 0){
String nciInstituteCode = studySponsor.getOrganization().getNciInstituteCode();
organization = fetchOrganization(nciInstituteCode);
}else{
String orgName = studySponsor.getOrganization().getName();
organization = organizationDao.getByName(orgName);
}
outcome.ifNullObject(organization, DomainObjectImportOutcome.Severity.ERROR,
"The organization specified in fundingSponsor is invalid");
studySponsor.setOrganization(organization);
OrganizationAssignedIdentifier orgIdentifier = sponsor.getOrganizationAssignedIdentifier();
orgIdentifier.setType(OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE);
orgIdentifier.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studySponsor, organization, outcome);
migrateStudyPersonnels(studySponsor, organization, outcome);
destination.getIdentifiers().add(orgIdentifier);
destination.addStudyFundingSponsor(studySponsor);
}
private void migrateCoordinatingCenter(Study source, Study destination, DomainObjectImportOutcome<Study> outcome ){
CoordinatingCenter coCenter = source.getCoordinatingCenter();
if(coCenter == null) return;
StudyCoordinatingCenter studyCoordinatingCenter = coCenter.getStudyCoordinatingCenter();
Organization organization = null;
if(studyCoordinatingCenter.getOrganization().getNciInstituteCode() != null && studyCoordinatingCenter.getOrganization().getNciInstituteCode().length() > 0){
String nciInstituteCode = studyCoordinatingCenter.getOrganization().getNciInstituteCode();
organization = fetchOrganization(nciInstituteCode);
}else{
String orgName = studyCoordinatingCenter.getOrganization().getName();
organization = organizationDao.getByName(orgName);
}
outcome.ifNullObject(organization, DomainObjectImportOutcome.Severity.ERROR, "The organization specified in coordinatingCenter is invalid");
studyCoordinatingCenter.setOrganization(organization);
OrganizationAssignedIdentifier orgIdentifier = coCenter.getOrganizationAssignedIdentifier();
orgIdentifier.setType(OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE);
orgIdentifier.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studyCoordinatingCenter, organization, outcome);
migrateStudyPersonnels(studyCoordinatingCenter, organization, outcome);
destination.getIdentifiers().add(orgIdentifier);
destination.addStudyOrganization(studyCoordinatingCenter);
}
private void migrateStudyInvestigators(StudyOrganization studyOrganization, Organization organization, DomainObjectImportOutcome studyImportOutcome) {
for (StudyInvestigator studyInvestigator : studyOrganization.getStudyInvestigators()) {
Investigator investigator = studyInvestigator.getSiteInvestigator().getInvestigator();
List<SiteInvestigator> siteInvestigators = null;
if(investigator.getNciIdentifier() != null && investigator.getNciIdentifier().length() > 0){
String[] nciIdentifier = {investigator.getNciIdentifier()};
siteInvestigators = siteInvestigatorDao.getByNciIdentifier(nciIdentifier, organization.getId());
}else{
String[] investigatorFirstAndLast = {investigator.getFirstName(), investigator.getLastName()};
siteInvestigators = siteInvestigatorDao.getBySubnames(investigatorFirstAndLast, organization.getId());
}
if (siteInvestigators.size() > 0) {
studyInvestigator.setSiteInvestigator(siteInvestigators.get(0));
studyInvestigator.setStudyOrganization(studyOrganization);
} else {
studyImportOutcome.ifNullObject(null, DomainObjectImportOutcome.Severity.ERROR, "The selected investigator " +
investigator.getFirstName() + " " + investigator.getLastName() + " is not Valid ");
}
}
}
private void migrateStudyPersonnels(StudyOrganization studyOrganization,
Organization organization, DomainObjectImportOutcome<Study> studyImportOutcome) {
for (StudyPersonnel studyPersonnel : studyOrganization.getStudyPersonnels()) {
ResearchStaff researchStaffer = studyPersonnel.getResearchStaff();
List<ResearchStaff> researchStaffs = null;
if(researchStaffer.getNciIdentifier() != null && researchStaffer.getNciIdentifier().length() > 0){
String[] nciIdentifier = {researchStaffer.getNciIdentifier()};
researchStaffs = researchStaffDao.getByNciIdentifier(nciIdentifier, organization.getId());
}else{
String[] investigatorFirstAndLast = {researchStaffer.getFirstName(), researchStaffer.getLastName()};
researchStaffs = researchStaffDao.getBySubnames(investigatorFirstAndLast, organization.getId());
}
if (researchStaffs.size() > 0) {
ResearchStaff researchStaff = researchStaffs.get(0);
studyPersonnel.setResearchStaff(researchStaff);
studyPersonnel.setStudyOrganization(studyOrganization);
} else {
studyImportOutcome.ifNullObject(null, DomainObjectImportOutcome.Severity.ERROR, "The selected personnel " +
researchStaffer.getFirstName() + " " + researchStaffer.getLastName() + " is not Valid ");
}
}
}
/**
* Fetches the organization from the DB
*
* @param nciCode
* @return
*/
private Organization fetchOrganization(String nciInstituteCode) {
OrganizationQuery orgQuery = new OrganizationQuery();
if (StringUtils.isNotEmpty(nciInstituteCode)) {
orgQuery.filterByNciCodeExactMatch(nciInstituteCode);
}
List<Organization> orgList = organizationDao.searchOrganization(orgQuery);
if (orgList == null || orgList.isEmpty()) {
return null;
}
if (orgList.size() > 1) {
//("Multiple organizations exist with same NCI Institute Code :" + nciInstituteCode);
}
return orgList.get(0);
}
@Required
public void setSiteInvestigatorDao(final SiteInvestigatorDao siteInvestigatorDao) {
this.siteInvestigatorDao = siteInvestigatorDao;
}
@Required
public void setResearchStaffDao(final ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
@Required
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
}
|
package gov.nih.nci.cabig.caaers.rules.jsr94.jbossrules.runtime;
import gov.nih.nci.cabig.caaers.rules.brxml.RuleSet;
import java.util.Hashtable;
import javax.rules.admin.RuleExecutionSet;
public class RulesCache implements RuleSetModificationListener,RuleExecutionSetModificationListener{
private static RulesCache instance = null;
private Hashtable<String,RuleSet> ruleSetCache = null;
//private Hashtable<String,RuleExecutionSet> ruleExecutionSetCache = null;
public static synchronized RulesCache getInstance(){
if(instance==null){
instance = new RulesCache();
}
return instance;
}
private RulesCache(){
ruleSetCache = new Hashtable<String,RuleSet>();
//ruleExecutionSetCache = new Hashtable<String,RuleExecutionSet>();
}
public void ruleSetModified(String uri) {
// TODO Auto-generated method stub
this.removeRuleSet(uri);
}
public void putRuleSet(String uri, RuleSet ruleSet){
if(!ruleSetCache.containsKey(uri)){
System.out.println ("put in map "+uri);
ruleSetCache.put(uri, ruleSet);
}
}
public RuleSet getRuleSet(String uri){
return ruleSetCache.get(uri);
}
private void removeRuleSet(String uri){
if(ruleSetCache.containsKey(uri)){
ruleSetCache.remove(uri);
}
}
//public void putRuleExecutionSet(String uri, RuleExecutionSet ruleExecutionSet){
// System.out.println ("put in exec map "+uri);
// ruleExecutionSetCache.put(uri, ruleExecutionSet);
//public RuleExecutionSet getRuleExecutionSet(String uri){
// return ruleExecutionSetCache.get(uri);
public void ruleSetDeployed(String uri) {
// TODO Auto-generated method stub
//if(ruleExecutionSetCache.containsKey(uri)){
/// ruleExecutionSetCache.remove(uri);
}
}
|
package org.jnosql.diana.ravendb.document;
import net.ravendb.client.documents.DocumentStore;
import net.ravendb.client.documents.session.IDocumentSession;
import net.ravendb.client.documents.session.IMetadataDictionary;
import org.jnosql.diana.api.document.DocumentCollectionManager;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static net.ravendb.client.Constants.Documents.Metadata.COLLECTION;
import static net.ravendb.client.Constants.Documents.Metadata.ID;
/**
* The mongodb implementation to {@link DocumentCollectionManager} that does not support TTL methods
* <p>{@link RavenDBDocumentCollectionManager#insert(DocumentEntity, Duration)}</p>
*/
public class RavenDBDocumentCollectionManager implements DocumentCollectionManager {
private final DocumentStore store;
RavenDBDocumentCollectionManager(DocumentStore store) {
this.store = store;
this.store.initialize();
}
@Override
public DocumentEntity insert(DocumentEntity entity) {
Objects.requireNonNull(entity, "entity is required");
try (IDocumentSession session = store.openSession()) {
String collection = entity.getName();
Map<String, Object> entityMap = EntityConverter.getMap(entity);
session.store(entityMap, collection + "/1231231");
IMetadataDictionary metadata = session.advanced().getMetadataFor(entityMap);
metadata.put(COLLECTION, collection);
metadata.put(ID, collection + "/");
session.saveChanges();
}
return entity;
}
@Override
public DocumentEntity insert(DocumentEntity entity, Duration ttl) {
throw new UnsupportedOperationException("MongoDB does not support save with TTL");
}
@Override
public DocumentEntity update(DocumentEntity entity) {
return null;
}
@Override
public void delete(DocumentDeleteQuery query) {
}
@Override
public List<DocumentEntity> select(DocumentQuery query) {
return null;
}
@Override
public void close() {
store.close();
}
}
|
package net.runelite.client.plugins.itemidentification;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import net.runelite.api.ItemID;
enum ItemIdentification
{
//Seeds
GUAM_SEED(Type.SEED, "Guam", "G", ItemID.GUAM_SEED),
MARRENTILL_SEED(Type.SEED, "Marren", "M", ItemID.MARRENTILL_SEED),
TARROMIN_SEED(Type.SEED, "Tarro", "TAR", ItemID.TARROMIN_SEED),
HARRALANDER_SEED(Type.SEED, "Harra", "H", ItemID.HARRALANDER_SEED),
RANARR_SEED(Type.SEED, "Ranarr", "R", ItemID.RANARR_SEED),
TOADFLAX_SEED(Type.SEED, "Toad", "TOA", ItemID.TOADFLAX_SEED),
IRIT_SEED(Type.SEED, "Irit", "I", ItemID.IRIT_SEED),
AVANTOE_SEED(Type.SEED, "Avan", "A", ItemID.AVANTOE_SEED),
KWUARM_SEED(Type.SEED, "Kwuarm", "K", ItemID.KWUARM_SEED),
SNAPDRAGON_SEED(Type.SEED, "Snap", "S", ItemID.SNAPDRAGON_SEED),
CADANTINE_SEED(Type.SEED, "Cadan", "C", ItemID.CADANTINE_SEED),
LANTADYME_SEED(Type.SEED, "Lanta", "L", ItemID.LANTADYME_SEED),
DWARF_WEED_SEED(Type.SEED, "Dwarf", "D", ItemID.DWARF_WEED_SEED),
TORSTOL_SEED(Type.SEED, "Torstol", "TOR", ItemID.TORSTOL_SEED),
POISON_IVY_SEED(Type.SEED, "Ivy", "I", ItemID.POISON_IVY_SEED),
WHITEBERRY_SEED(Type.SEED, "White", "W", ItemID.WHITEBERRY_SEED),
SEAWEED_SPORE(Type.SEED, "Seaweed", "SW", ItemID.SEAWEED_SPORE),
HESPORI_SEED(Type.SEED, "Hespori", "HES", ItemID.HESPORI_SEED),
KRONOS_SEED(Type.SEED, "Kronos", "KRO", ItemID.KRONOS_SEED),
IASOR_SEED(Type.SEED, "Iasor", "IA", ItemID.IASOR_SEED),
ATTAS_SEED(Type.SEED, "Attas", "AT", ItemID.ATTAS_SEED),
CELASTRUS_SEED(Type.SEED, "Celas", "CEL", ItemID.CELASTRUS_SEED),
SPIRIT_SEED(Type.SEED, "Spirit", "SPI", ItemID.SPIRIT_SEED),
CALQUAT_SEED(Type.SEED, "Calquat", "CAL", ItemID.CALQUAT_TREE_SEED),
ACORN(Type.SEED, "Oak", "OAK", ItemID.ACORN),
WILLOW_SEED(Type.SEED, "Willow", "WIL", ItemID.WILLOW_SEED),
MAPLE_SEED(Type.SEED, "Maple", "MAP", ItemID.MAPLE_SEED),
YEW_SEED(Type.SEED, "Yew", "YEW", ItemID.SPIRIT_SEED),
MAGIC_SEED(Type.SEED, "Magic", "MAG", ItemID.SPIRIT_SEED),
REDWOOD_SEED(Type.SEED, "Red", "RED", ItemID.REDWOOD_TREE_SEED),
TEAK_SEED(Type.SEED, "Teak", "TEAK", ItemID.TEAK_SEED),
MAHOGANY_SEED(Type.SEED, "Mahog", "MAH", ItemID.MAHOGANY_SEED),
CRYSTAL_ACORN(Type.SEED, "Crystal", "CRY", ItemID.CRYSTAL_ACORN),
//Sacks
SACK(Type.SACK, "Empty", "EMP", ItemID.EMPTY_SACK),
CABBAGE_SACK(Type.SACK, "Cabbage", "CAB", ItemID.CABBAGES1, ItemID.CABBAGES2, ItemID.CABBAGES3, ItemID.CABBAGES4, ItemID.CABBAGES5, ItemID.CABBAGES6, ItemID.CABBAGES7, ItemID.CABBAGES8, ItemID.CABBAGES9, ItemID.CABBAGES10),
ONION_SACK(Type.SACK, "Onion", "ONI", ItemID.ONIONS1, ItemID.ONIONS2, ItemID.ONIONS3, ItemID.ONIONS4, ItemID.ONIONS5, ItemID.ONIONS6, ItemID.ONIONS7, ItemID.ONIONS8, ItemID.ONIONS9, ItemID.ONIONS10),
POTATO_SACK(Type.SACK, "Potato", "POT", ItemID.POTATOES1, ItemID.POTATOES2, ItemID.POTATOES3, ItemID.POTATOES4, ItemID.POTATOES5, ItemID.POTATOES6, ItemID.POTATOES7, ItemID.POTATOES8, ItemID.POTATOES9, ItemID.POTATOES10),
//Herbs
GUAM(Type.HERB, "Guam", "G", ItemID.GUAM_LEAF, ItemID.GRIMY_GUAM_LEAF),
MARRENTILL(Type.HERB, "Marren", "M", ItemID.MARRENTILL, ItemID.GRIMY_MARRENTILL),
TARROMIN(Type.HERB, "Tarro", "TAR", ItemID.TARROMIN, ItemID.GRIMY_TARROMIN),
HARRALANDER(Type.HERB, "Harra", "H", ItemID.HARRALANDER, ItemID.GRIMY_HARRALANDER),
RANARR(Type.HERB, "Ranarr", "R", ItemID.RANARR_WEED, ItemID.GRIMY_RANARR_WEED),
TOADFLAX(Type.HERB, "Toad", "TOA", ItemID.TOADFLAX, ItemID.GRIMY_TOADFLAX),
IRIT(Type.HERB, "Irit", "I", ItemID.IRIT_LEAF, ItemID.GRIMY_IRIT_LEAF),
AVANTOE(Type.HERB, "Avan", "A", ItemID.AVANTOE, ItemID.GRIMY_AVANTOE),
KWUARM(Type.HERB, "Kwuarm", "K", ItemID.KWUARM, ItemID.GRIMY_KWUARM),
SNAPDRAGON(Type.HERB, "Snap", "S", ItemID.SNAPDRAGON, ItemID.GRIMY_SNAPDRAGON),
CADANTINE(Type.HERB, "Cadan", "C", ItemID.CADANTINE, ItemID.GRIMY_CADANTINE),
LANTADYME(Type.HERB, "Lanta", "L", ItemID.LANTADYME, ItemID.GRIMY_LANTADYME),
DWARF_WEED(Type.HERB, "Dwarf", "D", ItemID.DWARF_WEED, ItemID.GRIMY_DWARF_WEED),
TORSTOL(Type.HERB, "Torstol", "TOR", ItemID.TORSTOL, ItemID.GRIMY_TORSTOL),
ARDRIGAL(Type.HERB, "Ardrig", "ARD", ItemID.ARDRIGAL, ItemID.GRIMY_ARDRIGAL),
ROGUES_PURSE(Type.HERB, "Rogue", "ROG", ItemID.ROGUES_PURSE, ItemID.GRIMY_ROGUES_PURSE),
SITO_FOIL(Type.HERB, "Sito", "SF", ItemID.SITO_FOIL, ItemID.GRIMY_SITO_FOIL),
SNAKE_WEED(Type.HERB, "Snake", "SW", ItemID.SNAKE_WEED, ItemID.GRIMY_SNAKE_WEED),
VOLENCIA_MOSS(Type.HERB, "Volenc", "V", ItemID.VOLENCIA_MOSS, ItemID.GRIMY_VOLENCIA_MOSS),
//Saplings
OAK_SAPLING(Type.SAPLING, "Oak", "OAK", ItemID.OAK_SAPLING, ItemID.OAK_SEEDLING, ItemID.OAK_SEEDLING_W),
WILLOW_SAPLING(Type.SAPLING, "Willow", "WIL", ItemID.WILLOW_SAPLING, ItemID.WILLOW_SEEDLING, ItemID.WILLOW_SEEDLING_W),
MAPLE_SAPLING(Type.SAPLING, "Maple", "MAP", ItemID.MAPLE_SAPLING, ItemID.MAPLE_SEEDLING, ItemID.MAPLE_SEEDLING_W),
YEW_SAPLING(Type.SAPLING, "Yew", "YEW", ItemID.YEW_SAPLING, ItemID.YEW_SEEDLING, ItemID.YEW_SEEDLING_W),
MAGIC_SAPLING(Type.SAPLING, "Magic", "MAG", ItemID.MAGIC_SAPLING, ItemID.MAGIC_SEEDLING, ItemID.MAGIC_SEEDLING_W),
REDWOOD_SAPLING(Type.SAPLING, "Red", "RED", ItemID.REDWOOD_SAPLING, ItemID.REDWOOD_SEEDLING, ItemID.REDWOOD_SEEDLING_W),
SPIRIT_SAPLING(Type.SAPLING, "Spirit", "SPI", ItemID.SPIRIT_SAPLING, ItemID.SPIRIT_SEEDLING, ItemID.SPIRIT_SEEDLING_W),
CRYSTAL_SAPLING(Type.SAPLING, "Crystal", "CRY", ItemID.CRYSTAL_SAPLING, ItemID.CRYSTAL_SEEDLING, ItemID.CRYSTAL_SEEDLING_W),
APPLE_SAPLING(Type.SAPLING, "Apple", "APP", ItemID.APPLE_SAPLING, ItemID.APPLE_SEEDLING, ItemID.APPLE_SEEDLING_W),
BANANA_SAPLING(Type.SAPLING, "Banana", "BAN", ItemID.BANANA_SAPLING, ItemID.BANANA_SEEDLING, ItemID.BANANA_SEEDLING_W),
ORANGE_SAPLING(Type.SAPLING, "Orange", "ORA", ItemID.ORANGE_SAPLING, ItemID.ORANGE_SEEDLING, ItemID.ORANGE_SEEDLING_W),
CURRY_SAPLING(Type.SAPLING, "Curry", "CUR", ItemID.CURRY_SAPLING, ItemID.CURRY_SEEDLING, ItemID.CURRY_SEEDLING_W),
PINEAPPLE_SAPLING(Type.SAPLING, "Pine", "PINE", ItemID.PINEAPPLE_SAPLING, ItemID.PINEAPPLE_SEEDLING, ItemID.PINEAPPLE_SEEDLING_W),
PAPAYA_SAPLING(Type.SAPLING, "Papaya", "PAP", ItemID.PAPAYA_SAPLING, ItemID.PAPAYA_SEEDLING, ItemID.PAPAYA_SEEDLING_W),
PALM_SAPLING(Type.SAPLING, "Palm", "PALM", ItemID.PALM_SAPLING, ItemID.PALM_SEEDLING, ItemID.PALM_SEEDLING_W),
DRAGONFRUIT_SAPLING(Type.SAPLING, "Dragon", "DRAG", ItemID.DRAGONFRUIT_SAPLING, ItemID.DRAGONFRUIT_SEEDLING, ItemID.DRAGONFRUIT_SEEDLING_W),
TEAK_SAPLING(Type.SAPLING, "Teak", "TEAK", ItemID.TEAK_SAPLING, ItemID.TEAK_SEEDLING, ItemID.TEAK_SEEDLING_W),
MAHOGANY_SAPLING(Type.SAPLING, "Mahog", "MAHOG", ItemID.MAHOGANY_SAPLING, ItemID.MAHOGANY_SEEDLING, ItemID.MAHOGANY_SEEDLING_W),
CALQUAT_SAPLING(Type.SAPLING, "Calquat", "CALQ", ItemID.CALQUAT_SAPLING, ItemID.CALQUAT_SEEDLING, ItemID.CALQUAT_SEEDLING_W),
CELASTRUS_SAPLING(Type.SAPLING, "Celas", "CEL", ItemID.CELASTRUS_SAPLING, ItemID.CELASTRUS_SEEDLING, ItemID.CELASTRUS_SEEDLING_W),
//Ores
COPPER_ORE(Type.ORE, "Copper", "COP", ItemID.COPPER_ORE),
TIN_ORE(Type.ORE, "Tin", "TIN", ItemID.TIN_ORE),
IRON_ORE(Type.ORE, "Iron", "IRO", ItemID.IRON_ORE),
SILVER_ORE(Type.ORE, "Silver", "SIL", ItemID.SILVER_ORE),
COAL_ORE(Type.ORE, "Coal", "COA", ItemID.COAL),
GOLD_ORE(Type.ORE, "Gold", "GOL", ItemID.GOLD_ORE),
MITHRIL_ORE(Type.ORE, "Mithril", "MIT", ItemID.MITHRIL_ORE),
ADAMANTITE_ORE(Type.ORE, "Adaman", "ADA", ItemID.ADAMANTITE_ORE),
RUNITE_ORE(Type.ORE, "Runite", "RUN", ItemID.RUNITE_ORE),
RUNE_ESSENCE(Type.ORE, "R.Ess", "R.E.", ItemID.RUNE_ESSENCE),
PURE_ESSENCE(Type.ORE, "P.Ess", "P.E.", ItemID.PURE_ESSENCE),
PAYDIRT(Type.ORE, "Paydirt", "PAY", ItemID.PAYDIRT),
AMETHYST(Type.ORE, "Amethy", "AME", ItemID.AMETHYST),
LOVAKITE_ORE(Type.ORE, "Lovakit", "LOV", ItemID.LOVAKITE_ORE),
BLURITE_ORE(Type.ORE, "Blurite", "BLU", ItemID.BLURITE_ORE),
ELEMENTAL_ORE(Type.ORE, "Element", "ELE", ItemID.ELEMENTAL_ORE),
DAEYALT_ORE(Type.ORE, "Daeyalt", "DAE", ItemID.DAEYALT_ORE),
LUNAR_ORE(Type.ORE, "Lunar", "LUN", ItemID.LUNAR_ORE),
//Gems
SAPPHIRE(Type.GEM, "Sapphir", "S", ItemID.UNCUT_SAPPHIRE, ItemID.SAPPHIRE),
EMERALD(Type.GEM, "Emerald", "E", ItemID.UNCUT_EMERALD, ItemID.EMERALD),
RUBY(Type.GEM, "Ruby", "R", ItemID.UNCUT_RUBY, ItemID.RUBY),
DIAMOND(Type.GEM, "Diamon", "DI", ItemID.UNCUT_DIAMOND, ItemID.DIAMOND),
OPAL(Type.GEM, "Opal", "OP", ItemID.UNCUT_OPAL, ItemID.OPAL),
JADE(Type.GEM, "Jade", "J", ItemID.UNCUT_JADE, ItemID.JADE),
RED_TOPAZ(Type.GEM, "Topaz", "T", ItemID.UNCUT_RED_TOPAZ, ItemID.RED_TOPAZ),
DRAGONSTONE(Type.GEM, "Dragon", "DR", ItemID.UNCUT_DRAGONSTONE, ItemID.DRAGONSTONE),
ONYX(Type.GEM, "Onyx", "ON", ItemID.UNCUT_ONYX, ItemID.ONYX),
ZENYTE(Type.GEM, "Zenyte", "Z", ItemID.UNCUT_ZENYTE, ItemID.ZENYTE),
// Potions
ATTACK(Type.POTION, "Att", "A", ItemID.ATTACK_POTION4, ItemID.ATTACK_POTION3, ItemID.ATTACK_POTION2, ItemID.ATTACK_POTION1),
STRENGTH(Type.POTION, "Str", "S", ItemID.STRENGTH_POTION4, ItemID.STRENGTH_POTION3, ItemID.STRENGTH_POTION2, ItemID.STRENGTH_POTION1),
DEFENCE(Type.POTION, "Def", "D", ItemID.DEFENCE_POTION4, ItemID.DEFENCE_POTION3, ItemID.DEFENCE_POTION2, ItemID.DEFENCE_POTION1),
COMBAT(Type.POTION, "Com", "C", ItemID.COMBAT_POTION4, ItemID.COMBAT_POTION3, ItemID.COMBAT_POTION2, ItemID.COMBAT_POTION1),
MAGIC(Type.POTION, "Magic", "M", ItemID.MAGIC_POTION4, ItemID.MAGIC_POTION3, ItemID.MAGIC_POTION2, ItemID.MAGIC_POTION1),
RANGING(Type.POTION, "Range", "R", ItemID.RANGING_POTION4, ItemID.RANGING_POTION3, ItemID.RANGING_POTION2, ItemID.RANGING_POTION1),
BASTION(Type.POTION, "Bastion", "B", ItemID.BASTION_POTION4, ItemID.BASTION_POTION3, ItemID.BASTION_POTION2, ItemID.BASTION_POTION1),
BATTLEMAGE(Type.POTION, "BatMage", "B.M", ItemID.BATTLEMAGE_POTION4, ItemID.BATTLEMAGE_POTION3, ItemID.BATTLEMAGE_POTION2, ItemID.BATTLEMAGE_POTION1),
SUPER_ATTACK(Type.POTION, "S.Att", "S.A", ItemID.SUPER_ATTACK4, ItemID.SUPER_ATTACK3, ItemID.SUPER_ATTACK2, ItemID.SUPER_ATTACK1),
SUPER_STRENGTH(Type.POTION, "S.Str", "S.S", ItemID.SUPER_STRENGTH4, ItemID.SUPER_STRENGTH3, ItemID.SUPER_STRENGTH2, ItemID.SUPER_STRENGTH1),
SUPER_DEFENCE(Type.POTION, "S.Def", "S.D", ItemID.SUPER_DEFENCE4, ItemID.SUPER_DEFENCE3, ItemID.SUPER_DEFENCE2, ItemID.SUPER_DEFENCE1),
SUPER_COMBAT(Type.POTION, "S.Com", "S.C", ItemID.SUPER_COMBAT_POTION4, ItemID.SUPER_COMBAT_POTION3, ItemID.SUPER_COMBAT_POTION2, ItemID.SUPER_COMBAT_POTION1),
SUPER_RANGING(Type.POTION, "S.Range", "S.Ra", ItemID.SUPER_RANGING_4, ItemID.SUPER_RANGING_3, ItemID.SUPER_RANGING_2, ItemID.SUPER_RANGING_1),
SUPER_MAGIC(Type.POTION, "S.Magic", "S.M", ItemID.SUPER_MAGIC_POTION_4, ItemID.SUPER_MAGIC_POTION_3, ItemID.SUPER_MAGIC_POTION_2, ItemID.SUPER_MAGIC_POTION_1),
DIVINE_SUPER_ATTACK(Type.POTION, "S.Att", "S.A", ItemID.DIVINE_SUPER_ATTACK_POTION4, ItemID.DIVINE_SUPER_ATTACK_POTION3, ItemID.DIVINE_SUPER_ATTACK_POTION2, ItemID.DIVINE_SUPER_ATTACK_POTION1),
DIVINE_SUPER_DEFENCE(Type.POTION, "S.Def", "S.D", ItemID.DIVINE_SUPER_DEFENCE_POTION4, ItemID.DIVINE_SUPER_DEFENCE_POTION3, ItemID.DIVINE_SUPER_DEFENCE_POTION2, ItemID.DIVINE_SUPER_DEFENCE_POTION1),
DIVINE_SUPER_STRENGTH(Type.POTION, "S.Str", "S.S", ItemID.DIVINE_SUPER_STRENGTH_POTION4, ItemID.DIVINE_SUPER_STRENGTH_POTION3, ItemID.DIVINE_SUPER_STRENGTH_POTION2, ItemID.DIVINE_SUPER_STRENGTH_POTION1),
DIVINE_SUPER_COMBAT(Type.POTION, "S.Com", "S.C", ItemID.DIVINE_SUPER_COMBAT_POTION4, ItemID.DIVINE_SUPER_COMBAT_POTION3, ItemID.DIVINE_SUPER_COMBAT_POTION2, ItemID.DIVINE_SUPER_COMBAT_POTION1),
DIVINE_RANGING(Type.POTION, "Range", "R", ItemID.DIVINE_RANGING_POTION4, ItemID.DIVINE_RANGING_POTION3, ItemID.DIVINE_RANGING_POTION2, ItemID.DIVINE_RANGING_POTION1),
DIVINE_MAGIC(Type.POTION, "Magic", "M", ItemID.DIVINE_MAGIC_POTION4, ItemID.DIVINE_MAGIC_POTION3, ItemID.DIVINE_MAGIC_POTION2, ItemID.DIVINE_MAGIC_POTION1),
DIVINE_BASTION(Type.POTION, "Bastion", "B", ItemID.DIVINE_BASTION_POTION4, ItemID.DIVINE_BASTION_POTION3, ItemID.DIVINE_BASTION_POTION2, ItemID.DIVINE_BASTION_POTION1),
DIVINE_BATTLEMAGE(Type.POTION, "BatMage", "B.M", ItemID.DIVINE_BATTLEMAGE_POTION4, ItemID.DIVINE_BATTLEMAGE_POTION3, ItemID.DIVINE_BATTLEMAGE_POTION2, ItemID.DIVINE_BATTLEMAGE_POTION1),
RESTORE(Type.POTION, "Restore", "Re", ItemID.RESTORE_POTION4, ItemID.RESTORE_POTION3, ItemID.RESTORE_POTION2, ItemID.RESTORE_POTION1),
GUTHIX_BALANCE(Type.POTION, "GuthBal", "G.B.", ItemID.GUTHIX_BALANCE4, ItemID.GUTHIX_BALANCE3, ItemID.GUTHIX_BALANCE2, ItemID.GUTHIX_BALANCE1),
SUPER_RESTORE(Type.POTION, "S.Rest", "S.Re", ItemID.SUPER_RESTORE4, ItemID.SUPER_RESTORE3, ItemID.SUPER_RESTORE2, ItemID.SUPER_RESTORE1),
PRAYER(Type.POTION, "Prayer", "P", ItemID.PRAYER_POTION4, ItemID.PRAYER_POTION3, ItemID.PRAYER_POTION2, ItemID.PRAYER_POTION1),
ENERGY(Type.POTION, "Energy", "En", ItemID.ENERGY_POTION4, ItemID.ENERGY_POTION3, ItemID.ENERGY_POTION2, ItemID.ENERGY_POTION1),
SUPER_ENERGY(Type.POTION, "S.Energ", "S.En", ItemID.SUPER_ENERGY4, ItemID.SUPER_ENERGY3, ItemID.SUPER_ENERGY2, ItemID.SUPER_ENERGY1),
STAMINA(Type.POTION, "Stamina", "St", ItemID.STAMINA_POTION4, ItemID.STAMINA_POTION3, ItemID.STAMINA_POTION2, ItemID.STAMINA_POTION1),
OVERLOAD(Type.POTION, "Overloa", "OL", ItemID.OVERLOAD_4, ItemID.OVERLOAD_3, ItemID.OVERLOAD_2, ItemID.OVERLOAD_1),
ABSORPTION(Type.POTION, "Absorb", "Ab", ItemID.ABSORPTION_4, ItemID.ABSORPTION_3, ItemID.ABSORPTION_2, ItemID.ABSORPTION_1),
ZAMORAK_BREW(Type.POTION, "ZammyBr", "Za", ItemID.ZAMORAK_BREW4, ItemID.ZAMORAK_BREW3, ItemID.ZAMORAK_BREW2, ItemID.ZAMORAK_BREW1),
SARADOMIN_BREW(Type.POTION, "SaraBr", "Sa", ItemID.SARADOMIN_BREW4, ItemID.SARADOMIN_BREW3, ItemID.SARADOMIN_BREW2, ItemID.SARADOMIN_BREW1),
ANTIPOISON(Type.POTION, "AntiP", "AP", ItemID.ANTIPOISON4, ItemID.ANTIPOISON3, ItemID.ANTIPOISON2, ItemID.ANTIPOISON1),
SUPERANTIPOISON(Type.POTION, "S.AntiP", "S.AP", ItemID.SUPERANTIPOISON4, ItemID.SUPERANTIPOISON3, ItemID.SUPERANTIPOISON2, ItemID.SUPERANTIPOISON1),
ANTIDOTE_P(Type.POTION, "Antid+", "A+", ItemID.ANTIDOTE4, ItemID.ANTIDOTE3, ItemID.ANTIDOTE2, ItemID.ANTIDOTE1),
ANTIDOTE_PP(Type.POTION, "Antid++", "A++", ItemID.ANTIDOTE4_5952, ItemID.ANTIDOTE3_5954, ItemID.ANTIDOTE2_5956, ItemID.ANTIDOTE1_5958),
ANTIVENOM(Type.POTION, "Anti-V", "AV", ItemID.ANTIVENOM4, ItemID.ANTIVENOM3, ItemID.ANTIVENOM2, ItemID.ANTIVENOM1),
ANTIVENOM_P(Type.POTION, "Anti-V+", "AV+", ItemID.ANTIVENOM4_12913, ItemID.ANTIVENOM3_12915, ItemID.ANTIVENOM2_12917, ItemID.ANTIVENOM1_12919),
RELICYMS_BALM(Type.POTION, "Relicym", "R.B", ItemID.RELICYMS_BALM4, ItemID.RELICYMS_BALM3, ItemID.RELICYMS_BALM2, ItemID.RELICYMS_BALM1),
SANFEW_SERUM(Type.POTION, "Sanfew", "Sf", ItemID.SANFEW_SERUM4, ItemID.SANFEW_SERUM3, ItemID.SANFEW_SERUM2, ItemID.SANFEW_SERUM1),
ANTIFIRE(Type.POTION, "Antif", "Af", ItemID.ANTIFIRE_POTION4, ItemID.ANTIFIRE_POTION3, ItemID.ANTIFIRE_POTION2, ItemID.ANTIFIRE_POTION1),
EXTENDED_ANTIFIRE(Type.POTION, "E.Antif", "E.Af", ItemID.EXTENDED_ANTIFIRE4, ItemID.EXTENDED_ANTIFIRE3, ItemID.EXTENDED_ANTIFIRE2, ItemID.EXTENDED_ANTIFIRE1),
SUPER_ANTIFIRE(Type.POTION, "S.Antif", "S.Af", ItemID.SUPER_ANTIFIRE_POTION4, ItemID.SUPER_ANTIFIRE_POTION3, ItemID.SUPER_ANTIFIRE_POTION2, ItemID.SUPER_ANTIFIRE_POTION1),
EXTENDED_SUPER_ANTIFIRE(Type.POTION, "ES.Antif", "ES.Af", ItemID.EXTENDED_SUPER_ANTIFIRE4, ItemID.EXTENDED_SUPER_ANTIFIRE3, ItemID.EXTENDED_SUPER_ANTIFIRE2, ItemID.EXTENDED_SUPER_ANTIFIRE1),
SERUM_207(Type.POTION, "Ser207", "S7", ItemID.SERUM_207_4, ItemID.SERUM_207_3, ItemID.SERUM_207_2, ItemID.SERUM_207_1),
SERUM_208(Type.POTION, "Ser208", "S8", ItemID.SERUM_208_4, ItemID.SERUM_208_3, ItemID.SERUM_208_2, ItemID.SERUM_208_1),
COMPOST(Type.POTION, "Compost", "Cp", ItemID.COMPOST_POTION4, ItemID.COMPOST_POTION3, ItemID.COMPOST_POTION2, ItemID.COMPOST_POTION1),
AGILITY(Type.POTION, "Agility", "Ag", ItemID.AGILITY_POTION4, ItemID.AGILITY_POTION3, ItemID.AGILITY_POTION2, ItemID.AGILITY_POTION1),
FISHING(Type.POTION, "Fishing", "Fi", ItemID.FISHING_POTION4, ItemID.FISHING_POTION3, ItemID.FISHING_POTION2, ItemID.FISHING_POTION1),
HUNTER(Type.POTION, "Hunter", "Hu", ItemID.HUNTER_POTION4, ItemID.HUNTER_POTION3, ItemID.HUNTER_POTION2, ItemID.HUNTER_POTION1),
// Unfinished Potions
GUAM_POTION(Type.POTION, "Guam", "G", ItemID.GUAM_POTION_UNF),
MARRENTILL_POTION(Type.POTION, "Marren", "M", ItemID.MARRENTILL_POTION_UNF),
TARROMIN_POTION(Type.POTION, "Tarro", "TAR", ItemID.TARROMIN_POTION_UNF),
HARRALANDER_POTION(Type.POTION, "Harra", "H", ItemID.HARRALANDER_POTION_UNF),
RANARR_POTION(Type.POTION, "Ranarr", "R", ItemID.RANARR_POTION_UNF),
TOADFLAX_POTION(Type.POTION, "Toad", "TOA", ItemID.TOADFLAX_POTION_UNF),
IRIT_POTION(Type.POTION, "Irit", "I", ItemID.IRIT_POTION_UNF),
AVANTOE_POTION(Type.POTION, "Avan", "A", ItemID.AVANTOE_POTION_UNF),
KWUARM_POTION(Type.POTION, "Kwuarm", "K", ItemID.KWUARM_POTION_UNF),
SNAPDRAGON_POTION(Type.POTION, "Snap", "S", ItemID.SNAPDRAGON_POTION_UNF),
CADANTINE_POTION(Type.POTION, "Cadan", "C", ItemID.CADANTINE_POTION_UNF),
LANTADYME_POTION(Type.POTION, "Lanta", "L", ItemID.LANTADYME_POTION_UNF),
DWARF_WEED_POTION(Type.POTION, "Dwarf", "D", ItemID.DWARF_WEED_POTION_UNF),
TORSTOL_POTION(Type.POTION, "Torstol", "TOR", ItemID.TORSTOL_POTION_UNF),
// Impling jars
BABY_IMPLING(Type.IMPLING_JAR, "Baby", "B", ItemID.BABY_IMPLING_JAR),
YOUNG_IMPLING(Type.IMPLING_JAR, "Young", "Y", ItemID.YOUNG_IMPLING_JAR),
GOURMET_IMPLING(Type.IMPLING_JAR, "Gourmet", "G", ItemID.GOURMET_IMPLING_JAR),
EARTH_IMPLING(Type.IMPLING_JAR, "Earth", "EAR", ItemID.EARTH_IMPLING_JAR),
ESSENCE_IMPLING(Type.IMPLING_JAR, "Essen", "ESS", ItemID.ESSENCE_IMPLING_JAR),
ECLECTIC_IMPLING(Type.IMPLING_JAR, "Eclect", "ECL", ItemID.ECLECTIC_IMPLING_JAR),
NATURE_IMPLING(Type.IMPLING_JAR, "Nature", "NAT", ItemID.NATURE_IMPLING_JAR),
MAGPIE_IMPLING(Type.IMPLING_JAR, "Magpie", "M", ItemID.MAGPIE_IMPLING_JAR),
NINJA_IMPLING(Type.IMPLING_JAR, "Ninja", "NIN", ItemID.NINJA_IMPLING_JAR),
CRYSTAL_IMPLING(Type.IMPLING_JAR, "Crystal", "C", ItemID.CRYSTAL_IMPLING_JAR),
DRAGON_IMPLING(Type.IMPLING_JAR, "Dragon", "D", ItemID.DRAGON_IMPLING_JAR),
LUCKY_IMPLING(Type.IMPLING_JAR, "Lucky", "L", ItemID.LUCKY_IMPLING_JAR),
// Tablets
VARROCK_TELEPORT(Type.TABLET, "Varro", "VAR", ItemID.VARROCK_TELEPORT),
LUMBRIDGE_TELEPORT(Type.TABLET, "Lumbr", "LUM", ItemID.LUMBRIDGE_TELEPORT),
FALADOR_TELEPORT(Type.TABLET, "Fala", "FAL", ItemID.FALADOR_TELEPORT),
CAMELOT_TELEPORT(Type.TABLET, "Cammy", "CAM", ItemID.CAMELOT_TELEPORT),
ARDOUGNE_TELEPORT(Type.TABLET, "Ardoug", "ARD", ItemID.ARDOUGNE_TELEPORT),
WATCHTOWER_TELEPORT(Type.TABLET, "W.tow", "WT", ItemID.WATCHTOWER_TELEPORT),
TELEPORT_TO_HOUSE(Type.TABLET, "House", "POH", ItemID.TELEPORT_TO_HOUSE),
ENCHANT_SAPPHIRE_OR_OPAL(Type.TABLET, "E.Saph", "E SO", ItemID.ENCHANT_SAPPHIRE_OR_OPAL),
ENCHANT_EMERALD_OR_JADE(Type.TABLET, "E.Emer", "E EJ", ItemID.ENCHANT_EMERALD_OR_JADE),
ENCHANT_RUBY_OR_TOPAZ(Type.TABLET, "E.Ruby", "E RT", ItemID.ENCHANT_RUBY_OR_TOPAZ),
ENCHANT_DIAMOND(Type.TABLET, "E.Diam", "E DIA", ItemID.ENCHANT_DIAMOND),
ENCHANT_DRAGONSTONE(Type.TABLET, "E.Dstn", "E DS", ItemID.ENCHANT_DRAGONSTONE),
ENCHANT_ONYX(Type.TABLET, "E.Onyx", "E ONX", ItemID.ENCHANT_ONYX),
TELEKINETIC_GRAB(Type.TABLET, "T.grab", "T.GRB", ItemID.TELEKINETIC_GRAB),
BONES_TO_PEACHES(Type.TABLET, "Peach", "BtP", ItemID.BONES_TO_PEACHES_8015),
BONES_TO_BANANAS(Type.TABLET, "Banana", "BtB", ItemID.BONES_TO_BANANAS),
RIMMINGTON_TELEPORT(Type.TABLET, "Rimmi", "RIM", ItemID.RIMMINGTON_TELEPORT),
TAVERLEY_TELEPORT(Type.TABLET, "Taver", "TAV", ItemID.TAVERLEY_TELEPORT),
POLLNIVNEACH_TELEPORT(Type.TABLET, "Pollnv", "POL", ItemID.POLLNIVNEACH_TELEPORT),
RELLEKKA_TELEPORT(Type.TABLET, "Rell", "REL", ItemID.RELLEKKA_TELEPORT),
BRIMHAVEN_TELEPORT(Type.TABLET, "Brimh", "BRIM", ItemID.BRIMHAVEN_TELEPORT),
YANILLE_TELEPORT(Type.TABLET, "Yanille", "YAN", ItemID.YANILLE_TELEPORT),
TROLLHEIM_TELEPORT(Type.TABLET, "Trollh", "T.HM", ItemID.TROLLHEIM_TELEPORT),
PRIFDDINAS_TELEPORT(Type.TABLET, "Prifd", "PRIF", ItemID.PRIFDDINAS_TELEPORT),
HOSIDIUS_TELEPORT(Type.TABLET, "Hosid", "HOS", ItemID.HOSIDIUS_TELEPORT),
ANNAKARL_TELEPORT(Type.TABLET, "Annak", "GDZ", ItemID.ANNAKARL_TELEPORT),
CARRALLANGAR_TELEPORT(Type.TABLET, "Carra", "CAR", ItemID.CARRALLANGAR_TELEPORT),
DAREEYAK_TELEPORT(Type.TABLET, "Dareey", "DAR", ItemID.DAREEYAK_TELEPORT),
KHARYRLL_TELEPORT(Type.TABLET, "Khary", "KHRL", ItemID.KHARYRLL_TELEPORT),
LASSAR_TELEPORT(Type.TABLET, "Lass", "LSR", ItemID.LASSAR_TELEPORT),
PADDEWWA_TELEPORT(Type.TABLET, "Paddew", "PDW", ItemID.PADDEWWA_TELEPORT),
SENNTISTEN_TELEPORT(Type.TABLET, "Sennt", "SNT", ItemID.SENNTISTEN_TELEPORT),
LUMBRIDGE_GRAVEYARD_TELEPORT(Type.TABLET, "L.Grave", "L.GRV", ItemID.LUMBRIDGE_GRAVEYARD_TELEPORT),
DRAYNOR_MANOR_TELEPORT(Type.TABLET, "D.Manor", "D.MNR", ItemID.DRAYNOR_MANOR_TELEPORT),
MIND_ALTAR_TELEPORT(Type.TABLET, "M.Altar", "M.ALT", ItemID.MIND_ALTAR_TELEPORT),
SALVE_GRAVEYARD_TELEPORT(Type.TABLET, "S.Grave", "S.GRV", ItemID.SALVE_GRAVEYARD_TELEPORT),
FENKENSTRAINS_CASTLE_TELEPORT(Type.TABLET, "Fenk", "FNK", ItemID.FENKENSTRAINS_CASTLE_TELEPORT),
WEST_ARDOUGNE_TELEPORT(Type.TABLET, "W.Ardy", "W.ARD", ItemID.WEST_ARDOUGNE_TELEPORT),
HARMONY_ISLAND_TELEPORT(Type.TABLET, "H.Isle", "HRM", ItemID.HARMONY_ISLAND_TELEPORT),
CEMETERY_TELEPORT(Type.TABLET, "Cemet", "CEM", ItemID.CEMETERY_TELEPORT),
BARROWS_TELEPORT(Type.TABLET, "Barrow", "BAR", ItemID.BARROWS_TELEPORT),
APE_ATOLL_TELEPORT(Type.TABLET, "Atoll", "APE", ItemID.APE_ATOLL_TELEPORT),
BATTLEFRONT_TELEPORT(Type.TABLET, "B.Front", "BF", ItemID.BATTLEFRONT_TELEPORT),
TARGET_TELEPORT(Type.TABLET, "Target", "TRG", ItemID.TARGET_TELEPORT),
VOLCANIC_MINE_TELEPORT(Type.TABLET, "V.Mine", "VM", ItemID.VOLCANIC_MINE_TELEPORT),
WILDERNESS_CRABS_TELEPORT(Type.TABLET, "W.Crab", "CRAB", ItemID.WILDERNESS_CRABS_TELEPORT);
final Type type;
final String medName;
final String shortName;
final int[] itemIDs;
ItemIdentification(Type type, String medName, String shortName, int... ids)
{
this.type = type;
this.medName = medName;
this.shortName = shortName;
this.itemIDs = ids;
}
private static final Map<Integer, ItemIdentification> itemIdentifications;
static
{
ImmutableMap.Builder<Integer, ItemIdentification> builder = new ImmutableMap.Builder<>();
for (ItemIdentification i : values())
{
for (int id : i.itemIDs)
{
builder.put(id, i);
}
}
itemIdentifications = builder.build();
}
static ItemIdentification get(int id)
{
return itemIdentifications.get(id);
}
enum Type
{
SEED,
SACK,
HERB,
SAPLING,
ORE,
GEM,
POTION,
IMPLING_JAR,
TABLET
}
}
|
package org.springframework.security.oauth2.provider;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.junit.Assume;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.oauth2.client.test.RestTemplateHolder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriTemplate;
/**
* <p>
* A rule that prevents integration tests from failing if the server application is not running or not accessible. If
* the server is not running in the background all the tests here will simply be skipped because of a violated
* assumption (showing as successful). Usage:
* </p>
*
* <pre>
* @Rule public static BrokerRunning brokerIsRunning = BrokerRunning.isRunning();
*
* @Test public void testSendAndReceive() throws Exception { // ... test using RabbitTemplate etc. }
* </pre>
* <p>
* The rule can be declared as static so that it only has to check once for all tests in the enclosing test case, but
* there isn't a lot of overhead in making it non-static.
* </p>
*
* @see Assume
* @see AssumptionViolatedException
*
* @author Dave Syer
*
*/
public class ServerRunning implements MethodRule, RestTemplateHolder {
private static Log logger = LogFactory.getLog(ServerRunning.class);
// Static so that we only test once on failure: speeds up test suite
private static Map<Integer, Boolean> serverOnline = new HashMap<Integer, Boolean>();
// Static so that we only test once on failure
private static Map<Integer, Boolean> serverOffline = new HashMap<Integer, Boolean>();
private final boolean assumeOnline;
private static int DEFAULT_PORT = 8080;
private static String DEFAULT_HOST = "localhost";
private int port;
private String hostName = DEFAULT_HOST;
private RestOperations client;
/**
* @return a new rule that assumes an existing running broker
*/
public static ServerRunning isRunning() {
return new ServerRunning(true);
}
/**
* @return a new rule that assumes there is no existing broker
*/
public static ServerRunning isNotRunning() {
return new ServerRunning(false);
}
private ServerRunning(boolean assumeOnline) {
this.assumeOnline = assumeOnline;
setPort(DEFAULT_PORT);
}
/**
* @param port the port to set
*/
public void setPort(int port) {
this.port = port;
if (!serverOffline.containsKey(port)) {
serverOffline.put(port, true);
}
if (!serverOnline.containsKey(port)) {
serverOnline.put(port, true);
}
client = createRestTemplate();
}
/**
* @param hostName the hostName to set
*/
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
// Check at the beginning, so this can be used as a static field
if (assumeOnline) {
Assume.assumeTrue(serverOnline.get(port));
}
else {
Assume.assumeTrue(serverOffline.get(port));
}
RestTemplate client = new RestTemplate();
boolean followRedirects = HttpURLConnection.getFollowRedirects();
HttpURLConnection.setFollowRedirects(false);
boolean online = false;
try {
client.getForEntity(new UriTemplate(getUrl("/sparklr2/login.jsp")).toString(), String.class);
online = true;
logger.info("Basic connectivity test passed");
}
catch (RestClientException e) {
logger.warn(String.format(
"Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
port), e);
if (assumeOnline) {
Assume.assumeNoException(e);
}
}
finally {
HttpURLConnection.setFollowRedirects(followRedirects);
if (online) {
serverOffline.put(port, false);
if (!assumeOnline) {
Assume.assumeTrue(serverOffline.get(port));
}
}
else {
serverOnline.put(port, false);
}
}
final RestOperations savedClient = getRestTemplate();
postForStatus(savedClient, "/sparklr2/oauth/uncache_approvals",
new LinkedMultiValueMap<String, String>());
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
}
finally {
postForStatus(savedClient, "/sparklr2/oauth/cache_approvals",
new LinkedMultiValueMap<String, String>());
}
}
};
}
public String getBaseUrl() {
return "http://" + hostName + ":" + port;
}
public String getUrl(String path) {
if (path.startsWith("http")) {
return path;
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return "http://" + hostName + ":" + port + path;
}
public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
headers), String.class);
}
public ResponseEntity<String> postForString(String path, HttpHeaders headers, MultiValueMap<String, String> formData) {
HttpHeaders actualHeaders = new HttpHeaders();
actualHeaders.putAll(headers);
actualHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
actualHeaders), String.class);
}
@SuppressWarnings("rawtypes")
public ResponseEntity<Map> postForMap(String path, MultiValueMap<String, String> formData) {
return postForMap(path, new HttpHeaders(), formData);
}
@SuppressWarnings("rawtypes")
public ResponseEntity<Map> postForMap(String path, HttpHeaders headers, MultiValueMap<String, String> formData) {
if (headers.getContentType() == null) {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
headers), Map.class);
}
public ResponseEntity<Void> postForStatus(String path, MultiValueMap<String, String> formData) {
return postForStatus(this.client, path, formData);
}
public ResponseEntity<Void> postForStatus(String path, HttpHeaders headers, MultiValueMap<String, String> formData) {
return postForStatus(this.client, path, headers, formData);
}
private ResponseEntity<Void> postForStatus(RestOperations client, String path,
MultiValueMap<String, String> formData) {
return postForStatus(client, path, new HttpHeaders(), formData);
}
private ResponseEntity<Void> postForStatus(RestOperations client, String path, HttpHeaders headers,
MultiValueMap<String, String> formData) {
HttpHeaders actualHeaders = new HttpHeaders();
actualHeaders.putAll(headers);
actualHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
actualHeaders), (Class<Void>)null);
}
public ResponseEntity<Void> postForRedirect(String path, HttpHeaders headers, MultiValueMap<String, String> params) {
ResponseEntity<Void> exchange = postForStatus(path, headers, params);
if (exchange.getStatusCode() != HttpStatus.FOUND) {
throw new IllegalStateException("Expected 302 but server returned status code " + exchange.getStatusCode());
}
if (exchange.getHeaders().containsKey("Set-Cookie")) {
String cookie = exchange.getHeaders().getFirst("Set-Cookie");
headers.set("Cookie", cookie);
}
String location = exchange.getHeaders().getLocation().toString();
return client.exchange(location, HttpMethod.GET, new HttpEntity<Void>(null, headers), (Class<Void>)null);
}
public ResponseEntity<String> getForString(String path) {
return getForString(path, new HttpHeaders());
}
public ResponseEntity<String> getForString(String path, final HttpHeaders headers) {
return client.exchange(getUrl(path), HttpMethod.GET, new HttpEntity<Void>((Void) null, headers), String.class);
}
public ResponseEntity<String> getForString(String path, final HttpHeaders headers, Map<String, String> uriVariables) {
return client.exchange(getUrl(path), HttpMethod.GET, new HttpEntity<Void>((Void) null, headers), String.class,
uriVariables);
}
public ResponseEntity<Void> getForResponse(String path, final HttpHeaders headers, Map<String, String> uriVariables) {
HttpEntity<Void> request = new HttpEntity<Void>(null, headers);
return client.exchange(getUrl(path), HttpMethod.GET, request, (Class<Void>)null, uriVariables);
}
public ResponseEntity<Void> getForResponse(String path, HttpHeaders headers) {
return getForResponse(path, headers, Collections.<String, String> emptyMap());
}
public HttpStatus getStatusCode(String path, final HttpHeaders headers) {
ResponseEntity<Void> response = getForResponse(path, headers);
return response.getStatusCode();
}
public HttpStatus getStatusCode(String path) {
return getStatusCode(getUrl(path), null);
}
public void setRestTemplate(RestOperations restTemplate) {
client = restTemplate;
}
public RestOperations getRestTemplate() {
return client;
}
public RestOperations createRestTemplate() {
RestTemplate client = new RestTemplate();
client.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
@Override
public HttpClient getHttpClient() {
HttpClient client = super.getHttpClient();
client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
return client;
}
});
client.setErrorHandler(new ResponseErrorHandler() {
// Pass errors through in response entity for status code analysis
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return client;
}
public UriBuilder buildUri(String url) {
return UriBuilder.fromUri(url.startsWith("http:") ? url : getUrl(url));
}
public static class UriBuilder {
private final String url;
private Map<String, String> params = new LinkedHashMap<String, String>();
public UriBuilder(String url) {
this.url = url;
}
public static UriBuilder fromUri(String url) {
return new UriBuilder(url);
}
public UriBuilder queryParam(String key, String value) {
params.put(key, value);
return this;
}
public String pattern() {
StringBuilder builder = new StringBuilder();
// try {
builder.append(url.replace(" ", "+"));
if (!params.isEmpty()) {
builder.append("?");
boolean first = true;
for (String key : params.keySet()) {
if (!first) {
builder.append("&");
}
else {
first = false;
}
String value = params.get(key);
if (value.contains("=")) {
value = value.replace("=", "%3D");
}
builder.append(key + "={" + key + "}");
}
}
return builder.toString();
}
public Map<String, String> params() {
return params;
}
public URI build() {
return new UriTemplate(pattern()).expand(params);
}
}
}
|
package org.eclipse.persistence.testing.sdo.helper.pluggable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.persistence.sdo.SDOChangeSummary;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.SDODataObject;
import org.eclipse.persistence.sdo.SDOProperty;
import org.eclipse.persistence.sdo.SDOType;
import org.eclipse.persistence.sdo.helper.ListWrapper;
import org.eclipse.persistence.testing.sdo.helper.pluggable.impl.POJOValueStore;
import org.eclipse.persistence.testing.sdo.helper.pluggable.impl.POJOValueStoreReadWrite;
import org.eclipse.persistence.testing.sdo.helper.pluggable.model.Address;
import org.eclipse.persistence.testing.sdo.helper.pluggable.model.Employee;
import org.eclipse.persistence.testing.sdo.helper.pluggable.model.Phone;
public class PluggableTest extends PluggableTestCases {
// constants
public static final String TEST_PHONE_1_ORIGINAL = "1014455";
public static final String TEST_PHONE_2_ORIGINAL = "1014466";
public static final String TEST_PHONE_3_ORIGINAL = "1014477";
public static final String TEST_EMPLOYEE_ADDRESS_FIELD_NAME = "address";
public static final String TEST_EMPLOYEE_NAME_FIELD_NAME = "name";
public static final String TEST_EMPLOYEE_PHONE_FIELD_NAME = "phones";
//public static final String TEST_EMPLOYEE_PHONE_FIELD_NAME = "phone";
public static final String TEST_PHONE_FIRST_IN_ARRAY_XPATH = "phones[1]";
public static final String TEST_PHONE_NUMBER_FIELD_NAME = "number";
public static final String TEST_ADDRESS_STREET_FIELD_NAME = "street";
public static final String TEST_ADDRESS_STREET_ORIGINAL = "101 A Street";
public static final String TEST_ADDRESS_STREET_MODIFICATION = "102 A New Street";
public static final String TEST_EMPLOYEE_NAME_ORIGINAL = "Employee1";
public static final String TEST_EMPLOYEE_NAME_MODIFICATION = "Employee2";
public static final String POJO_PLUGGABLE_IMPL_CLASS_NAME = "org.eclipse.persistence.testing.sdo.helper.pluggable.impl.POJOValueStoreReadWrite";
public PluggableTest(String name) {
super(name);
}
/**
* Test Objectives:
* T0010 Test simple datatype get
* T0011 Test simple datatype set
*
* (Before any get fills the properties map)
* T0021 1-1 POJO(DataObject) get
* T0031 1-1 POJO(DataObject) set(new)
* T0032 1-1 POJO(DataObject) set(move)
* T0041 1-1 POJO(DataObject) unset
* T0042 1-1 POJO(DataObject) delete
* T0121 1-n POJO(DataObject via List) get(index)
* T0122 1-n POJO(DataObject via List) get(List)
* T0131 1-n POJO(DataObject via List) set(index, new)
* T0132 1-n POJO(DataObject via List) set(index, new)
* T0133 1-n POJO(DataObject via List) set(index, move) - delete attributes
* T0134 1-n POJO(DataObject via List) set(index, move) - delete attributes
* T0141 1-n POJO(DataObject via List) unset(index)
* T0151 1-n POJO(DataObject via List) delete(index)
* T0152 1-n POJO(DataObject via List) delete(List)
* T0161 1-n POJO(DataObject via List) detach(index) - attributes remain
* T0162 1-n POJO(DataObject via List) detach(List) - attributes remain
*
*
* (After a get that fills the properties map for this object)
* T1021 1-1 POJO(DataObject) get
* T1031 1-1 POJO(DataObject) set(new)
* T1032 1-1 POJO(DataObject) set(new)
* T1041 1-1 POJO(DataObject) unset
* T1042 1-1 POJO(DataObject) delete
* T1121 1-n POJO(DataObject via List) get(index)
* T1122 1-n POJO(DataObject via List) get(List)
* T1131 1-n POJO(DataObject via List) set(index, new)
* T1132 1-n POJO(DataObject via List) set(index, new)
* T1133 1-n POJO(DataObject via List) set(index, move)
* T1134 1-n POJO(DataObject via List) set(index, move)
* T1141 1-n POJO(DataObject via List) unset(index)
* T1151 1-n POJO(DataObject via List) delete(index)
* T1152 1-n POJO(DataObject via List) delete(List)
* T0161 1-n POJO(DataObject via List) detach(index) - attributes remain
* T0162 1-n POJO(DataObject via List) detach(List) - attributes remain
*
* Change Summary
* T8xxx with ChangeSummary on after loading/creation
*/
// Note Order is significant when setting the system property
// Excercise the default system property value
/* public void testInitializeDefaultPluggableMapUsingSystemPropertyDuringNew() {
// create a dataObject
SDODataObject anObject = (SDODataObject)aHelperContext.getDataFactory().create(//
aHelperContext.getTypeHelper().getType(rootTypeUri, rootTypeName));
ValueStore aPluggableMap = anObject.getCurrentValueStore();
// check that we received a DataObject
assertNotNull(anObject);
assertNotNull(aPluggableMap);
// check for type
assertEquals(SDO_PLUGGABLE_MAP_IMPL_CLASS_VALUE,//
aPluggableMap.getClass().getName());
}
*/
// Prerequisites: system property must be set This test exercises the
// Pluggable initializer sections of DataFactory and SDODataObject's constructor
/* public void testInitializeDefaultPluggableMapUsingSystemPropertyDuringLoad() {
// set property
System.setProperty(SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,//
SDO_PLUGGABLE_MAP_IMPL_CLASS_VALUE);
String pluggableClassName = System.getProperty(//
SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,//
SDO_PLUGGABLE_MAP_IMPL_CLASS_VALUE);
assertNotNull(pluggableClassName);
assertEquals(SDO_PLUGGABLE_MAP_IMPL_CLASS_VALUE,//
pluggableClassName);
// create a dataObject
Object anEmployee = load(DATAOBJECT_XML_PATH);
// check that we received a DataObject
assertNotNull(anEmployee);
assertTrue(anEmployee instanceof SDODataObject);
// check for type
assertEquals(SDO_PLUGGABLE_MAP_IMPL_CLASS_VALUE,//
((SDODataObject)anEmployee).getCurrentValueStore().getClass().getName());
Object anAddress = ((SDODataObject)anEmployee).get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddress);
assertTrue(anEmployee instanceof SDODataObject);
// verify contianment
assertEquals(TEST_EMPLOYEE_ADDRESS_FIELD_NAME,//
((SDODataObject)anAddress).getContainmentPropertyName());
assertEquals(anEmployee, ((SDODataObject)anAddress).getContainer());
}
*/
public void testPOJOValueStoreCreatedObjectWithIsManyOperations() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(
POJO_PLUGGABLE_IMPL_CLASS_NAME, true, true);
// verify ValueStore is POJO type
assertEquals(POJO_PLUGGABLE_IMPL_CLASS_NAME,
((SDODataObject)anEmployee)._getCurrentValueStore().getClass().getName());
// get root POJO
Employee rootPOJO = (Employee)((POJOValueStore)anEmployee._getCurrentValueStore()).getObject();
// verify isMany=true for phone
SDOProperty aPhonesProperty = (SDOProperty)anEmployee.getInstanceProperty(
TEST_EMPLOYEE_PHONE_FIELD_NAME);
assertTrue(aPhonesProperty.isMany());
// verify isMany=false for address
SDOProperty anAddressProperty = (SDOProperty)anEmployee
.getType().getProperty(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertFalse(anAddressProperty.isMany());
// complex 1-1 property set (before a previous get of this object)
SDODataObject aNewAddress = wrap(new Address(TEST_ADDRESS_STREET_MODIFICATION), "AddressType");
//see public void updateContainment(Property property, Object value) {
anEmployee.set(TEST_EMPLOYEE_ADDRESS_FIELD_NAME, aNewAddress);
Object anAddressMod = anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddressMod);
// verify we are wrapping inside a DataObject
assertTrue(anAddressMod instanceof SDODataObject);
String aStreetName = (String)((SDODataObject)anAddressMod)
.get(TEST_ADDRESS_STREET_FIELD_NAME);
assertNotNull(aStreetName);
// verify dataType property was modified
assertEquals(TEST_ADDRESS_STREET_MODIFICATION, aStreetName);
// simple property get
Object aName = anEmployee.get(TEST_EMPLOYEE_NAME_FIELD_NAME);
assertNotNull(aName);
assertTrue(aName instanceof String);
assertEquals(TEST_EMPLOYEE_NAME_ORIGINAL, aName);
// complex 1-1 property get
Object anAddress = anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddress);
// verify we are wrapping inside a DataObject
assertTrue(anAddress instanceof SDODataObject);
String aStreet = (String)((SDODataObject)anAddress).get(TEST_ADDRESS_STREET_FIELD_NAME);
assertNotNull(aStreet);
assertEquals(TEST_ADDRESS_STREET_MODIFICATION, aStreet);
// get the same object and test hash equality
Object anAddress2 = anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddress2);
// verify we are wrapping inside a DataObject
assertTrue(anAddress2 instanceof SDODataObject);
assertEquals(TEST_ADDRESS_STREET_MODIFICATION, ((SDODataObject)anAddress)
.get(TEST_ADDRESS_STREET_FIELD_NAME));
// objects should be the same object
assertEquals(anAddress, anAddress2);
// Test 1-n POJO(DataObject via List) get
// get list first (do not perform update containmet on first wrap)
Object aPhoneList = anEmployee.get(TEST_EMPLOYEE_PHONE_FIELD_NAME);
assertNotNull(aPhoneList);
assertTrue(aPhoneList instanceof ListWrapper);
// TODO: This test will exercise the dataObject.updateContainment(property, items); in ListWrapper.java
assertEquals(3, ((List)aPhoneList).size());
// test cached object equality on 2nd get
Object aPhoneList2 = anEmployee.get(TEST_EMPLOYEE_PHONE_FIELD_NAME);
assertEquals(aPhoneList, aPhoneList2);
// get single isMany object - this object should be wrapped as an SDODataObject
//Object aPhone = ((List)aPhoneList).get(1);//"phone[1]");//1);
Object aPhone = anEmployee.get(TEST_PHONE_FIRST_IN_ARRAY_XPATH);
assertNotNull(aPhone);
assertTrue(aPhone instanceof SDODataObject);
// verify containment
assertEquals(TEST_EMPLOYEE_PHONE_FIELD_NAME,
((SDODataObject)aPhone)._getContainmentPropertyName());
assertEquals(anEmployee, ((SDODataObject)aPhone).getContainer());
// get back POJO from wrapped PhoneImpl
Phone aPhonePOJO = (Phone)((POJOValueStore)((SDODataObject)aPhone)._getCurrentValueStore()).getObject();
assertNotNull(aPhonePOJO);
assertTrue(aPhonePOJO instanceof Phone);
// get phone# (non-wrapped) dataType object
Object number = ((SDODataObject)aPhone).get(TEST_PHONE_NUMBER_FIELD_NAME);
assertNotNull(number);
assertTrue(number instanceof String);
assertEquals(TEST_PHONE_1_ORIGINAL, number);
// 2nd time verify we are getting the wrapped object from the cache
SDODataObject aPhone2 = (SDODataObject)anEmployee.get(TEST_PHONE_FIRST_IN_ARRAY_XPATH);
assertNotNull(aPhone2);
//assertTrue(aPhone2 instanceof SDODataObject);
assertEquals(aPhone, aPhone2);
// Object modification integrity: clear cached value on modifications/deletions
// NOTE: modify backend POJO, get it again, Synchronization of the cached property is not supported outside of interface calls
Phone aPhone2POJO = rootPOJO.getPhone(0);
aPhone2POJO.setNumber("0000000");
// 3rd time verify we are not getting the wrapped unupdated object from the cache
SDODataObject aPhone3 = (SDODataObject)anEmployee.get(TEST_PHONE_FIRST_IN_ARRAY_XPATH);
assertNotNull(aPhone3);
assertEquals(aPhone2, aPhone3);
assertNotSame(aPhone2POJO.getNumber(), aPhone3.get(TEST_PHONE_NUMBER_FIELD_NAME));
// set isMany object's property, check that we get the modified object on a subsequent get
aPhone3.set(TEST_PHONE_NUMBER_FIELD_NAME, "1111111");
SDODataObject aPhone4 = (SDODataObject)anEmployee.get(TEST_PHONE_FIRST_IN_ARRAY_XPATH);
assertNotNull(aPhone4);
assertEquals(aPhone3, aPhone4);
Object number4 = ((SDODataObject)aPhone4).get(TEST_PHONE_NUMBER_FIELD_NAME);
assertEquals("1111111", number4);
// swap out an isMany object, verify that we picked up the change on a subsequent get
((SDODataObject)aPhone).delete();
SDODataObject aPhone1 = (SDODataObject)anEmployee.get(TEST_PHONE_FIRST_IN_ARRAY_XPATH);
assertNotNull(aPhone1);
assertTrue(aPhone1 instanceof SDODataObject);
// objects deleted are removed from the Map, the next get is a "different" object hash
assertFalse(aPhone2.equals(aPhone1));
// complex 1-1 property set (after a previous get of this object)
SDODataObject aNewAddress2 = wrap(new Address(TEST_ADDRESS_STREET_MODIFICATION), "AddressType");
//see public void updateContainment(Property property, Object value) {
anEmployee.set(TEST_EMPLOYEE_ADDRESS_FIELD_NAME, aNewAddress2);
Object anAddressMod2 = anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddressMod2);
// verify we are wrapping inside a DataObject
assertTrue(anAddressMod2 instanceof SDODataObject);
String aStreetName2 = (String)((SDODataObject)anAddressMod2)
.get(TEST_ADDRESS_STREET_FIELD_NAME);
assertNotNull(aStreetName2);
// verify dataType property was modified
assertEquals(TEST_ADDRESS_STREET_MODIFICATION, aStreetName2);
// test set/unset
// simple property set
anEmployee.set(TEST_EMPLOYEE_NAME_FIELD_NAME,
TEST_EMPLOYEE_NAME_MODIFICATION);
anEmployee.unset(TEST_EMPLOYEE_NAME_FIELD_NAME);
Object aName3 = anEmployee.get(TEST_EMPLOYEE_NAME_FIELD_NAME);
// default value is null in XSD
assertNull(aName3);
Object defaultValue = anEmployee.getInstanceProperty(TEST_EMPLOYEE_NAME_FIELD_NAME)
.getDefault();
assertEquals(defaultValue, aName3);
// unset complex property
anEmployee.unset("phones[2]");
try {
Object anUnsetAddress = anEmployee.get("phones[2]");
} catch (IndexOutOfBoundsException e) {
//pass
return;
}
fail("An IndexOutOfBoundsException was expected but didn't occurr");
//assertNull(anUnsetAddress);
}
public void testPOJOValueStoreUnSetPreviouslyUnSet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address to null
SDODataObject anAddress = null;
anEmployee.unset(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// verify set status
boolean addressSet = anEmployee.isSet(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// isSet status should be false (but not for set(property, null))
assertFalse(addressSet);
// check pojo for default value
Address anAddressPOJO = null;//(Address)((POJOValueStore)((SDODataObject)anAddress).getCurrentValueStore()).getObject();
Object defaultValue = anEmployee.getInstanceProperty(TEST_EMPLOYEE_NAME_FIELD_NAME)
.getDefault();
assertEquals(defaultValue, anAddressPOJO);
}
/**
* UnSet tests
* Issue: Unset using default values other than null.
* An unset of a property will clear the cache value associated with this property (Cached) and
* do a set on the pojo to the default (usually null).
* The result of this is that an isSet() call will check the cache, will not find it and will do a
* get on the pojo which will return null or the default ??? if this value is not null then isSet() =
* true after an unset() using a non-null default value.
*/
public void testPOJOValueStoreUnSetPreviouslySet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address
//SDODataObject anAddress = (SDODataObject)anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
anEmployee.unset(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// verify set status
boolean addressSet = anEmployee.isSet(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// isSet status should be false (but not for set(property, null))
assertFalse(addressSet);
// get address the sdo way (should be null)
SDODataObject anAddress2 = (SDODataObject)anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
Object defaultValue = anEmployee.getInstanceProperty(TEST_EMPLOYEE_NAME_FIELD_NAME)
.getDefault();
assertEquals(defaultValue, anAddress2);
}
/**
* UnSet tests
* Issue: Unset using default values other than null.
* An unset of a property will clear the cache value associated with this property (Cached) and
* do a set on the pojo to the default (usually null).
* The result of this is that an isSet() call will check the cache, will not find it and will do a
* get on the pojo which will return null or the default ??? if this value is not null then isSet() =
* true after an unset() using a non-null default value.
*
* Issue: 20060831-2: external references are not updated after unset
* Here we get a reference to address, unset the address in its parent employee and verify that
* the address reference was also updated
*/
public void testFailPOJOValueStoreUnSetPreviouslySetReferenceNotUpdated() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address
SDODataObject anAddress = (SDODataObject)anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
anEmployee.unset(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// verify set status
boolean addressSet = anEmployee.isSet(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// isSet status should be false (but not for set(property, null))
assertFalse(addressSet);
// check old addressImpl reference to pojo for default value (it was not garbage collected in the unset above)
// get address directly via unsupported interface
Address anAddressPOJO = (Address)((POJOValueStore)((SDODataObject)anAddress)._getCurrentValueStore()).getObject();
// get address the sdo way (should be null)
SDODataObject anAddress2 = (SDODataObject)anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
Object defaultValue = anEmployee.getInstanceProperty(TEST_EMPLOYEE_NAME_FIELD_NAME)
.getDefault();
assertEquals(defaultValue, anAddress2);
// TODO: Note: external references to pojos will not be updated after unset, a new get(property) is required
//assertNotSame(defaultValue, anAddressPOJO);
assertEquals(defaultValue, anAddressPOJO);
}
// simple types will be cached so we can check for isSet status after an unSet
// testcase: get/unset/isset is different from unset/isset because the first get will cache the value
public void testPOJOValueStoreUnSetSimpleTypePreviouslySet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address
SDODataObject anAddress = (SDODataObject)anEmployee.get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
anAddress.unset(TEST_ADDRESS_STREET_FIELD_NAME);
// verify set status
boolean addressSet = anAddress.isSet(TEST_ADDRESS_STREET_FIELD_NAME);
// isSet status should be false (even for set(property, null)
assertFalse(addressSet);
// check pojo for default value
Address anAddressPOJO = (Address)((POJOValueStore)((SDODataObject)anAddress)._getCurrentValueStore()).getObject();
Object defaultValue = anEmployee.getInstanceProperty(TEST_EMPLOYEE_NAME_FIELD_NAME)
.getDefault();
//assertEquals(defaultValue, anAddressPOJO);
}
public void testPOJOValueStoreSetNullPreviouslySet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address to null
SDODataObject anAddress = null;
anEmployee.set(TEST_EMPLOYEE_ADDRESS_FIELD_NAME, anAddress);
// verify set status
boolean addressSet = anEmployee.isSet(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
// isSet status should be true (even for set(property, null)
assertTrue(addressSet);
}
/*
public void testPOJOValueStoreIsManySetNullPreviouslySet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(true, true);
// set address to null
SDODataObject anAddress = null;
anEmployee.set("address", anAddress);
// verify set status
boolean addressSet = anEmployee.isSet("address");
assertTrue(addressSet);
}
public void testPOJOValueStoreSetNullPreviouslyUnSet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(false, false);
// set address to null
SDODataObject anAddress = null;
anEmployee.set("address", anAddress);
// verify set status
boolean addressSet = anEmployee.isSet("address");
assertTrue(addressSet);
}
public void testPOJOValueStoreIsManySetNullPreviouslyUnSet() {
// setup root DO wrapped around a POJO with types set
SDODataObject anEmployee = setupDataObjectWithPOJOValueStore(false, false);
// set phones to null
SDODataObject anAddress = null;
anEmployee.set("address", anAddress);
// verify set status
boolean addressSet = anEmployee.isSet("address");
assertTrue(addressSet);
}
*/
/*
public void testFailInitializePOJOPluggableMapUsingSystemPropertyDuringLoad() {
// set property
System.setProperty(SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,//
POJO_PLUGGABLE_IMPL_CLASS_NAME);
String pluggableClassName = System.getProperty(//
SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,//
POJO_PLUGGABLE_IMPL_CLASS_NAME);
assertNotNull(pluggableClassName);
assertEquals(POJO_PLUGGABLE_IMPL_CLASS_NAME,//
pluggableClassName);
// create a dataObject
Object anEmployee = load(DATAOBJECT_XML_PATH);
// check that we received a DataObject
assertNotNull(anEmployee);
assertTrue(anEmployee instanceof SDODataObject);
// verify ValueStore is POJO type
assertEquals(POJO_PLUGGABLE_IMPL_CLASS_NAME,//
((SDODataObject)anEmployee).getCurrentValueStore().getClass().getName());
Object anAddress = ((SDODataObject)anEmployee).get(TEST_EMPLOYEE_ADDRESS_FIELD_NAME);
assertNotNull(anAddress);
assertTrue(anEmployee instanceof SDODataObject);
// verify containment
assertEquals(TEST_EMPLOYEE_ADDRESS_FIELD_NAME,//
((SDODataObject)anAddress).getContainmentPropertyName());
assertEquals(anEmployee, ((SDODataObject)anAddress).getContainer());
// check embedded POJO objects
Address anAddressPOJO = (Address)((POJOValueStore)((SDODataObject)anEmployee).getCurrentValueStore()).getObject();
assertNotNull(anAddressPOJO);
}
*/
/**
* We need to verify that calling createDataObject will not enter an infinite loop
* Also, we would like to know if reflectively setting an empty pojo before we actualy use
* getCurrentValueStore().setObject(pojo) will fix the invalid state the DO is in before this 2nd call
*/
/* public void testFailPOJOValueStoreUsingCreateDataObject() {
// create data object
// create an empty DataObject
SDODataObject anEmployee = (SDODataObject)aHelperContext.getDataFactory().create(//
aHelperContext.getTypeHelper().getType(rootTypeUri, rootTypeName));
POJOValueStore aPluggableMap = (POJOValueStore)anEmployee.getCurrentValueStore();
assertNotNull(aPluggableMap);
assertTrue(aPluggableMap instanceof POJOValueStore);
// types are not set until we call getType() on first get after SDODataObject initialization - force the check here
//SDOType aType = (SDOType)anEmployee.getType();
// set POJO
Employee anEmployeePOJO = new Employee("2", TEST_EMPLOYEE_NAME_ORIGINAL);
// associate pojo
aPluggableMap.setObject(anEmployeePOJO);
aPluggableMap.initialize(anEmployee);
// try {
// add address
SDODataObject anAddressWrapper = (SDODataObject)anEmployee.createDataObject(//
"address", rootTypeUri, "AddressType");
// get property
SDODataObject anAddress = (SDODataObject)anEmployeePOJO.get("address");
// TODO: Issue20060830-1: an unset Address POJO is returned as null or an empty Address?
assertNull(anAddress);
//assertTrue(anAddress instanceof SDODataObject);
//} catch (Exception e) {
// System.out.println("createDataObject not supported: " + e.getMessage());
//}
}
*/
private Object getControlObject() {
return getControlObject(true, true);
}
/**
* @param withPhones
* @return
*/
private Object getControlObject(boolean isAddressSet, boolean withPhones) {
// add address
Address anAddress = null;
List phones = null;
if (isAddressSet) {
anAddress = new Address(TEST_ADDRESS_STREET_ORIGINAL);
}
// create a list of phones to add to an employee
if (withPhones) {
phones = new ArrayList();
phones.add(new Phone("0", TEST_PHONE_1_ORIGINAL));
phones.add(new Phone("1", TEST_PHONE_2_ORIGINAL));
phones.add(new Phone("2", TEST_PHONE_3_ORIGINAL));
}
Employee anEmployee = new Employee("1", TEST_EMPLOYEE_NAME_ORIGINAL, anAddress, phones);
return anEmployee;
}
private SDODataObject wrap(Object pojo, String typeName) {
// create an empty DataObject
SDODataObject anSDO = (SDODataObject)aHelperContext.getDataFactory().create(
aHelperContext.getTypeHelper().getType(rootTypeUri, typeName));
POJOValueStore aPluggableMap = new POJOValueStoreReadWrite(aHelperContext);
//aPluggableMap = (POJOValueStore)anEmployee.getCurrentValueStore();
// set valueStore
anSDO._setCurrentValueStore(aPluggableMap);
//aPluggableMap.initialize(anSDO);
//POJOValueStore aPluggableMap = (POJOValueStore)anSDO.getCurrentValueStore();
assertNotNull(aPluggableMap);
assertTrue(aPluggableMap instanceof POJOValueStore);
// types are not set until we call getType() on first get after SDODataObject initialization - force the check here
//SDOType aType = (SDOType)anSDO.getType();
// set POJO
aPluggableMap.setObject(pojo);
aPluggableMap.initialize(anSDO);
return anSDO;
}
private SDODataObject setupDataObjectWithPOJOValueStore(boolean isPhoneArraySet) {
return setupDataObjectWithPOJOValueStore(POJO_PLUGGABLE_IMPL_CLASS_NAME,
true, isPhoneArraySet);
}
private SDODataObject setupDataObjectWithPOJOValueStore(
boolean isAddressSet, boolean isPhoneArraySet) {
return setupDataObjectWithPOJOValueStore(POJO_PLUGGABLE_IMPL_CLASS_NAME,
isAddressSet, isPhoneArraySet);
}
private SDODataObject setupDataObjectWithPOJOValueStore(
String implClass, boolean isAddressNull, boolean isPhoneArrayNull) {
// setup system for POJO (override JVM System property)
System.setProperty(SDOConstants.SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,
implClass);
assertEquals(System.getProperty(
SDOConstants.SDO_PLUGGABLE_MAP_IMPL_CLASS_KEY,
SDOConstants.EMPTY_STRING),
implClass);
// create an empty DataObject
SDODataObject anEmployee = (SDODataObject)dataFactory.create(
typeHelper.getType(rootTypeUri, rootTypeName));
// The following code section overwrites the default ValueStore
// Why? normally you would not change the ValueStore impl class in a JVM, therefore
// we set and cache the ValueStore cache on the first read from the system property
// in a testing environment where we test multiple implementations we need the code section below
// NOTE: valueStore cannot be changed after first DO intitialization - the classname is a static variable on DataObject
// directly create the valueStore (discard the default if it is a default implementation)
try {
POJOValueStore aPluggableMap = (POJOValueStore)Class.forName(implClass).newInstance();
//aPluggableMap = (POJOValueStore)anEmployee.getCurrentValueStore();
//aPluggableMap = (POJOValueStore)anEmployee.getCurrentValueStore();
// set valueStore
anEmployee._setCurrentValueStore(aPluggableMap);
assertNotNull(aPluggableMap);
assertTrue(aPluggableMap instanceof POJOValueStore);
// types are not set until we call getType() on first get after SDODataObject initialization - force the check here
SDOType aType = (SDOType)anEmployee.getType();
// set POJO
Employee rootPOJO = (Employee)getControlObject(isAddressNull, isPhoneArrayNull);
aPluggableMap.setObject(rootPOJO);
aPluggableMap.initialize(anEmployee);
} catch (ClassNotFoundException cnfe) {
// TODO: throw or propagate these properly
throw new IllegalArgumentException(cnfe.getMessage());
} catch (IllegalAccessException iae) {
throw new IllegalArgumentException(iae.getMessage());
} catch (InstantiationException ie) {
throw new IllegalArgumentException(ie.getMessage());
}
//anEmployee.setProperties(aPluggableMap);
return anEmployee;
}
}
|
package com.github.basking2.sdsai.itrex.functions.functional;
import com.github.basking2.sdsai.itrex.EvaluationContext;
import com.github.basking2.sdsai.itrex.Evaluator;
import com.github.basking2.sdsai.itrex.SExprRuntimeException;
import com.github.basking2.sdsai.itrex.functions.FunctionInterface;
import static com.github.basking2.sdsai.itrex.iterators.Iterators.wrap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A function that returns a function that ties many functions together.
*
* For readability any strings that are "|" or "=<" are ignored.
*/
public class PipelineFunction implements FunctionInterface<FunctionInterface<Object>> {
@Override
public FunctionInterface<Object> apply(final Iterator<?> iterator, final EvaluationContext evaluationContext) {
final List<FunctionInterface<?>> pipeline = new ArrayList<>();
while (iterator.hasNext()) {
final Object o = iterator.next();
if (o instanceof FunctionInterface<?>) {
@SuppressWarnings("unchecked")
final FunctionInterface<?> f = (FunctionInterface<Object>)o;
pipeline.add(f);
}
else if ("=>".equals(o) || "|".equals(o)) {
// Nop.
}
else {
final FunctionInterface<?> f = evaluationContext.getFunction(o);
if (f == null) {
throw new SExprRuntimeException("No such function: "+o);
}
pipeline.add(f);
}
}
return new FunctionInterface<Object>() {
@Override
public Object apply(final Iterator<?> iterator, final EvaluationContext evaluationContext) {
Object result = null;
Iterator<Object> args = (Iterator<Object>)iterator;
for (final FunctionInterface<?> f : pipeline) {
result = f.apply(args, evaluationContext);
args = wrap(result);
}
return result;
}
};
}
}
|
public class Verifier
{
public static final String EXAMPLE_DATA = "0222112222120000";
public static final int EXAMPLE_WIDTH = 2;
public static final int EXAMPLE_HEIGHT = 2;
public Verifier (boolean debug)
{
_theImage = new Image(EXAMPLE_WIDTH, EXAMPLE_HEIGHT, EXAMPLE_DATA);
_debug = debug;
if (_debug)
System.out.println("Created image:\n"+_theImage);
}
public final boolean verify ()
{
if (_theImage.numberOfLayers() == 4)
return true;
else
return false;
}
private Image _theImage;
private boolean _debug;
}
|
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.utilities;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.google.gson.Gson;
import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.Violation;
import com.hp.hpl.jena.query.DataSource;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.filestorage.FileServingHelper;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.AllPropertiesQueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.GenericQueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.QueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.GenericQueryMap;
/**
* This request handler is used when you need helpful information to add more context
* to the visualization. It does not have any code for generating the visualization,
* just fires sparql queries to get info for specific cases like,
* 1. thumbnail/image location for a particular individual
* 2. profile information for a particular individual like label, moniker etc
* 3. person level vis url for a particular individual
* etc.
* @author cdtank
*/
public class UtilitiesRequestHandler implements VisualizationRequestHandler {
public Object generateAjaxVisualization(VitroRequest vitroRequest,
Log log,
DataSource dataSource)
throws MalformedQueryParametersException {
String individualURI = vitroRequest.getParameter(
VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
String visMode = vitroRequest.getParameter(
VisualizationFrameworkConstants.VIS_MODE_KEY);
/*
* If the info being requested is about a profile which includes the name, moniker
* & image url.
* */
if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
String filterRule = "?predicate = j.2:mainImage "
+ "|| ?predicate = vitro:moniker "
+ "|| ?predicate = rdfs:label";
QueryRunner<GenericQueryMap> profileQueryHandler =
new AllPropertiesQueryRunner(individualURI,
filterRule,
dataSource,
log);
GenericQueryMap profilePropertiesToValues =
profileQueryHandler.getQueryResult();
Gson profileInformation = new Gson();
return profileInformation.toJson(profilePropertiesToValues);
} else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* If the url being requested is about a standalone image, which is used when we
* want to render an image & other info for a co-author OR ego for that matter.
* */
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
fieldLabelToOutputFieldLabel.put("downloadLocation",
QueryFieldLabels.THUMBNAIL_LOCATION_URL);
fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME);
String whereClause = "<" + individualURI
+ "> j.2:thumbnailImage ?thumbnailImage . "
+ "?thumbnailImage j.2:downloadLocation "
+ "?downloadLocation ; j.2:filename ?fileName .";
QueryRunner<ResultSet> imageQueryHandler =
new GenericQueryRunner(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
dataSource, log);
return getThumbnailInformation(imageQueryHandler.getQueryResult(),
fieldLabelToOutputFieldLabel);
} else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* By default we will be generating profile url else some specific url like
* coAuthorShip vis url for that individual.
* */
ParamMap coAuthorProfileURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
individualURI,
VisualizationFrameworkConstants.VIS_TYPE_KEY,
VisualizationFrameworkConstants.COAUTHORSHIP_VIS,
VisualizationFrameworkConstants.RENDER_MODE_KEY,
VisualizationFrameworkConstants.STANDALONE_RENDER_MODE);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX,
coAuthorProfileURLParams);
} else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* By default we will be generating profile url else some specific url like
* coPI vis url for that individual.
* */
ParamMap coInvestigatorProfileURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
individualURI,
VisualizationFrameworkConstants.VIS_TYPE_KEY,
VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
VisualizationFrameworkConstants.VIS_MODE_KEY,
VisualizationFrameworkConstants.COPI_VIS_MODE);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX,
coInvestigatorProfileURLParams);
} else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* By default we will be generating profile url else some specific url like
* coAuthorShip vis url for that individual.
* */
ParamMap personLevelURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
individualURI,
VisualizationFrameworkConstants.VIS_TYPE_KEY,
VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
VisualizationFrameworkConstants.RENDER_MODE_KEY,
VisualizationFrameworkConstants.STANDALONE_RENDER_MODE);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX,
personLevelURLParams);
} else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE
.equalsIgnoreCase(visMode)) {
String staffProvidedHighestLevelOrganization = ConfigurationProperties.getProperty("visualization.topLevelOrg");
/*
* First checking if the staff has provided highest level organization in deploy.properties
* if so use to temporal graph vis.
* */
if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) {
/*
* To test for the validity of the URI submitted.
* */
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Highest Level Organization URI provided is invalid " + errorMsg);
} else {
ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
staffProvidedHighestLevelOrganization,
VisualizationFrameworkConstants.VIS_TYPE_KEY,
VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX,
highestLevelOrganizationTemporalGraphVisURLParams);
}
}
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
fieldLabelToOutputFieldLabel.put("organization",
QueryFieldLabels.ORGANIZATION_URL);
fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL);
String aggregationRules = "(count(?organization) AS ?numOfChildren)";
String whereClause = "?organization rdf:type foaf:Organization ; rdfs:label ?organizationLabel . \n"
+ "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n"
+ "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n"
+ "FILTER ( !bound(?parent) ). \n";
String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n"
+ "ORDER BY DESC(?numOfChildren)\n"
+ "LIMIT 1\n";
QueryRunner<ResultSet> highestLevelOrganizationQueryHandler =
new GenericQueryRunner(fieldLabelToOutputFieldLabel,
aggregationRules,
whereClause,
groupOrderClause,
dataSource, log);
return getHighestLevelOrganizationTemporalGraphVisURL(
highestLevelOrganizationQueryHandler.getQueryResult(),
fieldLabelToOutputFieldLabel);
/*
GenericQueryMap highestLevelOrganizationToValues = getHighestLevelOrganizationInformation(
highestLevelOrganizationQueryHandler.getQueryResult(),
fieldLabelToOutputFieldLabel);
Gson highestLevelOrganizationInformation = new Gson();
return highestLevelOrganizationInformation.toJson(highestLevelOrganizationToValues);
*/
} else {
ParamMap individualProfileURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
individualURI);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX,
individualProfileURLParams);
}
}
private String getHighestLevelOrganizationTemporalGraphVisURL(ResultSet resultSet,
Map<String, String> fieldLabelToOutputFieldLabel) {
GenericQueryMap queryResult = new GenericQueryMap();
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.nextSolution();
RDFNode organizationNode = solution.get(
fieldLabelToOutputFieldLabel
.get("organization"));
if (organizationNode != null) {
queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organization"), organizationNode.toString());
ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY,
organizationNode.toString(),
VisualizationFrameworkConstants.VIS_TYPE_KEY,
VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS);
return UrlBuilder.getUrl(VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX,
highestLevelOrganizationTemporalGraphVisURLParams);
}
RDFNode organizationLabelNode = solution.get(
fieldLabelToOutputFieldLabel
.get("organizationLabel"));
if (organizationLabelNode != null) {
queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organizationLabel"), organizationLabelNode.toString());
}
RDFNode numberOfChildrenNode = solution.getLiteral("numOfChildren");
if (numberOfChildrenNode != null) {
queryResult.addEntry("numOfChildren", String.valueOf(numberOfChildrenNode.asLiteral().getInt()));
}
}
// return queryResult;
return "";
}
private String getThumbnailInformation(ResultSet resultSet,
Map<String, String> fieldLabelToOutputFieldLabel) {
String finalThumbNailLocation = "";
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.nextSolution();
RDFNode downloadLocationNode = solution.get(
fieldLabelToOutputFieldLabel
.get("downloadLocation"));
RDFNode fileNameNode = solution.get(fieldLabelToOutputFieldLabel.get("fileName"));
if (downloadLocationNode != null && fileNameNode != null) {
finalThumbNailLocation =
FileServingHelper
.getBytestreamAliasUrl(downloadLocationNode.toString(),
fileNameNode.toString());
}
}
return finalThumbNailLocation;
}
@Override
public Map<String, String> generateDataVisualization(
VitroRequest vitroRequest, Log log, DataSource dataSource)
throws MalformedQueryParametersException {
throw new UnsupportedOperationException("Utilities does not provide Data Response.");
}
@Override
public ResponseValues generateStandardVisualization(
VitroRequest vitroRequest, Log log, DataSource dataSource)
throws MalformedQueryParametersException {
throw new UnsupportedOperationException("Utilities does not provide Standard Response.");
}
}
|
package org.rstudio.studio.client.workbench.views.source.editors.text.visualmode;
import java.util.ArrayList;
import java.util.List;
import org.rstudio.core.client.BrowseCap;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.DebouncedCommand;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.PreemptiveTaskQueue;
import org.rstudio.core.client.Rendezvous;
import org.rstudio.core.client.SerializedCommand;
import org.rstudio.core.client.SerializedCommandQueue;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.patch.TextChange;
import org.rstudio.core.client.widget.HasFindReplace;
import org.rstudio.core.client.widget.ProgressPanel;
import org.rstudio.core.client.widget.ToolbarButton;
import org.rstudio.core.client.widget.images.ProgressImages;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.Value;
import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource;
import org.rstudio.studio.client.palette.model.CommandPaletteItem;
import org.rstudio.studio.client.panmirror.PanmirrorChanges;
import org.rstudio.studio.client.panmirror.PanmirrorCode;
import org.rstudio.studio.client.panmirror.PanmirrorContext;
import org.rstudio.studio.client.panmirror.PanmirrorKeybindings;
import org.rstudio.studio.client.panmirror.PanmirrorOptions;
import org.rstudio.studio.client.panmirror.PanmirrorSetMarkdownResult;
import org.rstudio.studio.client.panmirror.PanmirrorWidget;
import org.rstudio.studio.client.panmirror.command.PanmirrorCommands;
import org.rstudio.studio.client.panmirror.events.PanmirrorBlurEvent;
import org.rstudio.studio.client.panmirror.events.PanmirrorFocusEvent;
import org.rstudio.studio.client.panmirror.events.PanmirrorNavigationEvent;
import org.rstudio.studio.client.panmirror.events.PanmirrorStateChangeEvent;
import org.rstudio.studio.client.panmirror.events.PanmirrorUpdatedEvent;
import org.rstudio.studio.client.panmirror.location.PanmirrorEditingOutlineLocation;
import org.rstudio.studio.client.panmirror.location.PanmirrorEditingOutlineLocationItem;
import org.rstudio.studio.client.panmirror.outline.PanmirrorOutlineItem;
import org.rstudio.studio.client.panmirror.outline.PanmirrorOutlineItemType;
import org.rstudio.studio.client.panmirror.pandoc.PanmirrorPandocFormat;
import org.rstudio.studio.client.panmirror.ui.PanmirrorUIDisplay;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorUITools;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorUIToolsSource;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefs;
import org.rstudio.studio.client.workbench.views.source.Source;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.Scope;
import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeList;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditorContainer;
import org.rstudio.studio.client.workbench.views.source.editors.text.findreplace.FindReplaceBar;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkDefinition;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupRequest;
import org.rstudio.studio.client.workbench.views.source.editors.text.visualmode.events.VisualModeSpellingAddToDictionaryEvent;
import org.rstudio.studio.client.workbench.views.source.events.SourceDocAddedEvent;
import org.rstudio.studio.client.workbench.views.source.model.DirtyState;
import org.rstudio.studio.client.workbench.views.source.model.DocUpdateSentinel;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.inject.Inject;
import elemental2.core.JsObject;
import jsinterop.base.Js;
public class VisualMode implements VisualModeEditorSync,
CommandPaletteEntrySource,
SourceDocAddedEvent.Handler,
VisualModeSpelling.Context,
VisualModeConfirm.Context,
VisualModeSpellingAddToDictionaryEvent.Handler
{
public VisualMode(TextEditingTarget target,
TextEditingTarget.Display view,
TextEditingTargetRMarkdownHelper rmarkdownHelper,
DocDisplay docDisplay,
DirtyState dirtyState,
DocUpdateSentinel docUpdateSentinel,
EventBus eventBus,
final ArrayList<HandlerRegistration> releaseOnDismiss)
{
RStudioGinjector.INSTANCE.injectMembers(this);
target_ = target;
view_ = view;
docDisplay_ = docDisplay;
dirtyState_ = dirtyState;
docUpdateSentinel_ = docUpdateSentinel;
progress_ = new ProgressPanel(ProgressImages.createSmall(), 200);
// create peer helpers
visualModeFormat_ = new VisualModePanmirrorFormat(docUpdateSentinel_, docDisplay_, target_, view_);
visualModeChunks_ = new VisualModeChunks(docUpdateSentinel_, docDisplay_, target_, this);
visualModeLocation_ = new VisualModeEditingLocation(docUpdateSentinel_, docDisplay_);
visualModeWriterOptions_ = new VisualModeMarkdownWriter(docUpdateSentinel_, visualModeFormat_);
visualModeNavigation_ = new VisualModeNavigation(navigationContext_);
visualModeConfirm_ = new VisualModeConfirm(docUpdateSentinel_, docDisplay, this);
visualModeSpelling_ = new VisualModeSpelling(docUpdateSentinel_, docDisplay, this);
visualModeContext_ = new VisualModePanmirrorContext(
docUpdateSentinel_,
target_,
visualModeChunks_,
visualModeFormat_,
visualModeSpelling_
);
// create widgets that the rest of startup (e.g. manageUI) may rely on
initWidgets();
// subscribe to source doc added
releaseOnDismiss.add(eventBus.addHandler(SourceDocAddedEvent.TYPE, this));
// subscribe to spelling invalidation event
releaseOnDismiss.add(eventBus.addHandler(VisualModeSpellingAddToDictionaryEvent.TYPE, this));
// manage UI (then track changes over time)
manageUI(isActivated(), false);
releaseOnDismiss.add(onDocPropChanged(TextEditingTarget.RMD_VISUAL_MODE, (value) -> {
manageUI(isActivated(), true);
}));
// sync to outline visible prop
releaseOnDismiss.add(onDocPropChanged(TextEditingTarget.DOC_OUTLINE_VISIBLE, (value) -> {
withPanmirror(() -> {
panmirror_.showOutline(getOutlineVisible(), getOutlineWidth(), true);
});
}));
}
/**
* Classification of synchronization types from the visual editor to the code
* editor.
*/
public enum SyncType
{
// A normal synchronization (usually performed on idle)
SyncTypeNormal,
// A synchronization performed prior to executing code
SyncTypeExecution,
// A synchronization performed in order to activate the code editor
SyncTypeActivate
}
@Inject
public void initialize(Commands commands,
UserPrefs prefs,
SourceServerOperations source)
{
commands_ = commands;
prefs_ = prefs;
source_ = source;
}
public void onDismiss()
{
}
private void initWidgets()
{
findReplaceButton_ = new ToolbarButton(
ToolbarButton.NoText,
"Find/Replace",
FindReplaceBar.getFindIcon(),
(event) -> {
HasFindReplace findReplace = getFindReplace();
findReplace.showFindReplace(!findReplace.isFindReplaceShowing());
}
);
}
public boolean isActivated()
{
return docUpdateSentinel_.getBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
}
public boolean isVisualEditorActive()
{
return view_.editorContainer().isWidgetActive(panmirror_);
}
public void activate(ScheduledCommand completed)
{
if (!isActivated())
{
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, true);
manageUI(true, true, completed);
}
else if (isLoading_)
{
onReadyHandlers_.add(completed);
}
else
{
completed.execute();
}
}
public void deactivate(ScheduledCommand completed)
{
if (isActivated())
{
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
manageUI(false, true, completed);
}
else
{
completed.execute();
}
}
@Override
public void syncToEditor(SyncType syncType)
{
syncToEditor(syncType, null);
}
@Override
public void syncToEditor(SyncType syncType, Command ready)
{
// This is an asynchronous task, that we want to behave in a mostly FIFO
// way when overlapping calls to syncToEditor are made.
// Each syncToEditor operation can be thought of as taking place in three
// phases:
// 1 - Synchronously gathering state from panmirror, and kicking off the
// async pandoc operation
// 2 - The pandoc operation itself--this happens completely off the UI
// thread (in a different process in fact)
// 3 - With the result from pandoc, do some synchronous processing, sync
// the source editor, and invoke the `ready` parameter
// Part 2 is a "pure" operation so it doesn't matter when it runs. What
// matters is that phase 1 gathers state at the moment it's called, and
// if there are multiple operations in progress simultaneously, that the
// order in which different phase 3's are invoked reflect the order the
// operations were started. For example, if syncToEditor was called once
// (A) and then again (B), any of these sequences are fine:
// A1->A2->A3->B1->B2->B3
// A1->B1->A2->B2->A3->B3
// or even
// A1->B1->B2->A2->A3->B3
// but NOT
// A1->A2->B1->B2->B3->A3
// because if A1 comes before B1, then A3 must come before B3.
// Our plan of execution is:
// 1. Start the async operation
// 2a. Wait for the async operation to finish
// 2b. Wait for all preceding async operations to finish
// 3. Run our phase 3 logic and ready.execute()
// 4. Signal to the next succeeding async operation (if any) that we're
// done
// We use syncToEditorQueue_ to enforce the FIFO ordering. Because we
// don't know whether the syncToEditorQueue_ or the pandoc operation will
// finish first, we use a Rendezvous object to make sure both conditions
// are satisfied before we proceed.
Rendezvous rv = new Rendezvous(2);
syncToEditorQueue_.addCommand(new SerializedCommand() {
@Override
public void onExecute(Command continuation)
{
// We pass false to arrive() because it's important to not invoke
// the continuation before our phase 3 work has completed; the whole
// point is to enforce ordering of phase 3.
rv.arrive(() -> {
continuation.execute();
}, false);
}
});
if (isVisualEditorActive() && (syncType == SyncType.SyncTypeActivate || isDirty_)) {
// set flags
isDirty_ = false;
withPanmirror(() -> {
VisualModeMarkdownWriter.Options writerOptions =
visualModeWriterOptions_.optionsFromConfig(panmirror_.getPandocFormatConfig(true));
panmirror_.getMarkdown(writerOptions.options, kSerializationProgressDelayMs,
new CommandWithArg<JsObject>() {
@Override
public void execute(JsObject obj)
{
PanmirrorCode markdown = Js.uncheckedCast(obj);
rv.arrive(() ->
{
if (markdown == null)
{
// note that ready.execute() is never called in the error case
return;
}
// we are about to mutate the document, so create a single
// shot handler that will adjust the known position of
// items in the outline (we do this opportunistically
// unless executing code)
if (markdown.location != null && syncType != SyncType.SyncTypeExecution)
{
alignScopeTreeAfterUpdate(markdown.location);
}
// apply diffs unless the wrap column changed (too expensive)
if (!writerOptions.wrapChanged)
{
TextEditorContainer.Changes changes = toEditorChanges(markdown);
getSourceEditor().applyChanges(changes, syncType == SyncType.SyncTypeActivate);
}
else
{
getSourceEditor().setCode(markdown.code);
}
// if the format comment has changed then show the reload prompt
if (panmirrorFormatConfig_.requiresReload())
{
view_.showPanmirrorFormatChanged(() ->
{
// dismiss the warning bar
view_.hideWarningBar();
// this will trigger the refresh b/c the format changed
syncFromEditorIfActivated();
});
}
if (markdown.location != null && syncType == SyncType.SyncTypeExecution)
{
// if syncing for execution, force a rebuild of the scope tree
alignScopeOutline(markdown.location);
}
// invoke ready callback if supplied
if (ready != null)
{
ready.execute();
}
}, true);
}
});
});
} else {
// Even if ready is null, it's important to arrive() so the
// syncToEditorQueue knows it can continue
rv.arrive(() ->
{
if (ready != null) {
ready.execute();
}
}, true);
}
}
@Override
public void syncFromEditorIfActivated()
{
if (isActivated())
{
// new editor content about to be sent to prosemirror, validate that we can edit it
String invalid = validateActivation();
if (invalid != null)
{
deactivateForInvalidSource(invalid);
return;
}
// get reference to the editing container
TextEditorContainer editorContainer = view_.editorContainer();
// show progress
progress_.beginProgressOperation(400);
editorContainer.activateWidget(progress_);
syncFromEditor((success) -> {
// clear progress
progress_.endProgressOperation();
// re-activate panmirror widget
editorContainer.activateWidget(panmirror_, false);
}, false);
}
}
@Override
public void syncFromEditor(final CommandWithArg<Boolean> done, boolean focus)
{
// flag to prevent the document being set to dirty when loading
// from source mode
loadingFromSource_ = true;
// if there is a previous format comment and it's changed then
// we need to tear down the editor instance and create a new one
if (panmirrorFormatConfig_ != null && panmirrorFormatConfig_.requiresReload())
{
panmirrorFormatConfig_ = null;
view_.editorContainer().removeWidget(panmirror_);
panmirror_ = null;
}
withPanmirror(() -> {
final String editorCode = getEditorCode();
final VisualModeMarkdownWriter.Options writerOptions = visualModeWriterOptions_.optionsFromCode(editorCode);
// serialize these calls (they are expensive on both the server side for the call(s)
// to pandoc, and on the client side for initialization of the editor (esp. ace editors)
setMarkdownQueue_.addTask(new PreemptiveTaskQueue.Task()
{
@Override
public String getLabel()
{
return target_.getTitle();
}
@Override
public boolean shouldPreempt()
{
return target_.isActiveDocument();
}
@Override
public void execute(final Command taskDone)
{
// join done commands
final CommandWithArg<Boolean> allDone = (result) -> {
taskDone.execute();
if (done != null)
done.execute(result);
};
panmirror_.setMarkdown(editorCode, writerOptions.options, true, kCreationProgressDelayMs,
new CommandWithArg<JsObject>() {
@Override
public void execute(JsObject obj)
{
// get result
PanmirrorSetMarkdownResult result = Js.uncheckedCast(obj);
// update flags
isDirty_ = false;
loadingFromSource_ = false;
// bail on error
if (result == null)
{
allDone.execute(false);
return;
}
// show warning and terminate if there was unparsed metadata. note that the other
// option here would be to have setMarkdown send the unparsed metadata back to the
// server to generate yaml, and then include the metadata as yaml at end the of the
// document. this could be done using the method outlined here:
// specifically using this template:
/// ...with this command line:
/*
pandoc -t markdown --template=yaml.template foo.md
*/
if (JsObject.keys(result.unparsed_meta).length > 0)
{
view_.showWarningBar("Unable to activate visual mode (unsupported front matter format or non top-level YAML block)");
allDone.execute(false);
return;
}
progress_.endProgressOperation();
// confirm if necessary
visualModeConfirm_.withSwitchConfirmation(
// allow inspection of result
result,
// onConfirmed
() -> {
// if pandoc's view of the document doesn't match the editor's we
// need to reset the editor's code (for both dirty state and
// so that diffs are efficient)
if (result.canonical != editorCode)
{
// ensure we realign the scope tree after changing the code
alignScopeTreeAfterUpdate(result.location);
getSourceEditor().setCode(result.canonical);
markDirty();
}
// completed
allDone.execute(true);
// deferred actions
Scheduler.get().scheduleDeferred(() -> {
// if we are being focused it means we are switching from source mode, in that
// case sync our editing location to what it is in source
if (focus)
{
// catch exceptions which occur here (can result from attempting to restore
// an invalid position). generally we'd like to diagnose and fix instances
// of this error in a more targeted fashion, however we are now at the point
// of v1.4 release and the error results in an inability to switch to visual
// mode, so we do more coarse grained error handling here
try
{
panmirror_.focus();
panmirror_.setEditingLocation(
visualModeLocation_.getSourceOutlineLocation(),
visualModeLocation_.savedEditingLocation()
);
}
catch(Exception e)
{
Debug.logException(e);
}
}
// show any warnings
PanmirrorPandocFormat format = panmirror_.getPandocFormat();
if (result.unrecognized.length > 0)
{
view_.showWarningBar("Unrecognized Pandoc token(s); " + String.join(", ", result.unrecognized));
}
else if (format.warnings.invalidFormat.length() > 0)
{
view_.showWarningBar("Invalid Pandoc format: " + format.warnings.invalidFormat);
}
else if (format.warnings.invalidOptions.length > 0)
{
view_.showWarningBar("Unsupported extensions for markdown mode: " + String.join(", ", format.warnings.invalidOptions));;
}
});
},
// onCancelled
() -> {
allDone.execute(false);
}
);
}
});
}
});
});
}
public boolean canWriteCanonical()
{
return validateActivation() == null;
}
public void getCanonicalChanges(String code, CommandWithArg<PanmirrorChanges> completed)
{
withPanmirror(() -> {
VisualModeMarkdownWriter.Options writerOptions = visualModeWriterOptions_.optionsFromCode(code);
panmirror_.getCanonical(code, writerOptions.options, kSerializationProgressDelayMs,
(markdown) -> {
if (markdown != null)
{
if (!writerOptions.wrapChanged)
{
PanmirrorUIToolsSource sourceTools = new PanmirrorUITools().source;
TextChange[] changes = sourceTools.diffChars(code, markdown, 1);
completed.execute(new PanmirrorChanges(null, changes));
}
else
{
completed.execute(new PanmirrorChanges(markdown, null));
}
}
else
{
completed.execute(null);
}
});
});
}
/**
* Returns the width of the entire visual editor
*
* @return The visual editor's width.
*/
public int getPixelWidth()
{
return panmirror_.getOffsetWidth();
}
/**
* Returns the width of the content inside the visual editor
*
* @return Width of content.
*/
public int getContentWidth()
{
Element[] elements = DomUtils.getElementsByClassName(panmirror_.getElement(),
"pm-content");
if (elements.length < 1)
{
// if no root node, use the entire surface
return getPixelWidth();
}
return elements[0].getOffsetWidth();
}
public void manageCommands()
{
// hookup devtools
syncDevTools();
// disable commands
disableForVisualMode(
// Disabled since diagnostics aren't active in visual mode
commands_.showDiagnosticsActiveDocument(),
// Disabled since we can't meaningfully select instances in several
// embedded editors simultaneously
commands_.findSelectAll(),
// Disabled since code folding doesn't work in embedded editors (there's
// no gutter in which to toggle folds)
commands_.fold(),
commands_.foldAll(),
commands_.unfold(),
commands_.unfoldAll(),
// Disabled since we don't have line numbers in the visual editor
commands_.goToLine()
);
// initially disable code commands (they will be re-enabled later when an
// editor has focus)
if (isActivated())
{
setCodeCommandsEnabled(false);
}
}
public void unmanageCommands()
{
restoreDisabledForVisualMode();
setCodeCommandsEnabled(true);
}
public void insertChunk(String chunkPlaceholder, int rowOffset, int colOffset)
{
panmirror_.insertChunk(chunkPlaceholder, rowOffset, colOffset);
}
/**
* Perform a command after synchronizing the selection state of the visual
* editor. Note that the command will not be performed unless focus is in a
* code editor (as otherwise we can't map selection 1-1).
*
* @param command
*/
public void performWithSelection(Command command)
{
// Drive focus to the editing surface. This is necessary so we correctly
// identify the active (focused) editor on which to perform the command.
panmirror_.focus();
// Perform the command in the active code editor, if any.
visualModeChunks_.performWithSelection(command);
}
/**
* Moves the cursor in source mode to the currently active outline item in visual mode.
*/
public void syncSourceOutlineLocation()
{
visualModeLocation_.setSourceOutlineLocation(
panmirror_.getEditingOutlineLocation());
}
public DocDisplay getActiveEditor()
{
return activeEditor_;
}
/**
* Sets the active (currently focused) code chunk editor.
*
* @param editor The current code chunk editor, or null if no code chunk
* editor has focus.
*/
public void setActiveEditor(DocDisplay editor)
{
activeEditor_ = editor;
if (editor != null)
{
// A code chunk has focus; enable code commands
setCodeCommandsEnabled(true);
}
}
/**
* Sets the enabled state for code commands -- i.e. those that require
* selection to be inside a chunk of code. We disable these outside code
* chunks.
*
* @param enabled Whether to enable code commands
*/
private void setCodeCommandsEnabled(boolean enabled)
{
AppCommand[] commands = {
commands_.commentUncomment(),
commands_.executeCode(),
commands_.executeCodeWithoutFocus(),
commands_.executeCodeWithoutMovingCursor(),
commands_.executeCurrentFunction(),
commands_.executeCurrentLine(),
commands_.executeCurrentParagraph(),
commands_.executeCurrentSection(),
commands_.executeCurrentStatement(),
commands_.executeFromCurrentLine(),
commands_.executeToCurrentLine(),
commands_.extractFunction(),
commands_.extractLocalVariable(),
commands_.goToDefinition(),
commands_.insertRoxygenSkeleton(),
commands_.profileCode(),
commands_.profileCodeWithoutFocus(),
commands_.reflowComment(),
commands_.reformatCode(),
commands_.reindent(),
commands_.renameInScope(),
commands_.runSelectionAsJob(),
commands_.runSelectionAsLauncherJob(),
commands_.sendToTerminal(),
};
for (AppCommand command : commands)
{
if (command.isVisible())
{
command.setEnabled(enabled);
}
}
}
public void goToNextSection()
{
panmirror_.execCommand(PanmirrorCommands.GoToNextSection);
}
public void goToPreviousSection()
{
panmirror_.execCommand(PanmirrorCommands.GoToPreviousSection);
}
public HasFindReplace getFindReplace()
{
if (panmirror_ != null) {
return panmirror_.getFindReplace();
} else {
return new HasFindReplace() {
public boolean isFindReplaceShowing() { return false; }
public void showFindReplace(boolean defaultForward) {}
public void hideFindReplace() {}
public void findFromSelection(String text) {}
public void findNext() {}
public void findPrevious() {}
public void replaceAndFind() {}
};
}
}
public ToolbarButton getFindReplaceButton()
{
return findReplaceButton_;
}
public void checkSpelling()
{
visualModeSpelling_.checkSpelling(panmirror_.getSpellingDoc());
}
@Override
public void invalidateAllWords()
{
if (panmirror_ != null)
panmirror_.spellingInvalidateAllWords();
}
@Override
public void invalidateWord(String word)
{
if (panmirror_ != null)
panmirror_.spellingInvalidateWord(word);
}
@Override
public void onVisualModeSpellingAddToDictionary(VisualModeSpellingAddToDictionaryEvent event)
{
if (panmirror_ != null)
panmirror_.spellingInvalidateWord(event.getWord());
}
public boolean isVisualModePosition(SourcePosition position)
{
return visualModeNavigation_.isVisualModePosition(position);
}
public void navigate(SourcePosition position, boolean recordCurrentPosition)
{
visualModeNavigation_.navigate(position, recordCurrentPosition);
}
public void navigateToXRef(String xref, boolean recordCurrentPosition)
{
visualModeNavigation_.navigateToXRef(xref, recordCurrentPosition);
}
public void recordCurrentNavigationPosition()
{
visualModeNavigation_.recordCurrentNavigationPosition();
}
public SourcePosition getSourcePosition()
{
return visualModeNavigation_.getSourcePosition();
}
public boolean isAtRow(SourcePosition position)
{
if (visualModeNavigation_.isVisualModePosition(position))
{
return position.getRow() == getSourcePosition().getRow();
}
else
{
return false;
}
}
@Override
public String getYamlFrontMatter()
{
return panmirror_.getYamlFrontMatter();
}
@Override
public boolean applyYamlFrontMatter(String yaml)
{
panmirror_.applyYamlFrontMatter(yaml);
return true;
}
public void activateDevTools()
{
withPanmirror(() -> {
panmirror_.activateDevTools();
});
}
@Override
public void onSourceDocAdded(SourceDocAddedEvent e)
{
if (e.getDoc().getId() != docUpdateSentinel_.getId())
return;
// when interactively adding a visual mode doc, make sure we set the focus
// (special handling required b/c initialization of visual mode docs is
// async so can miss the normal setting of focus)
if (e.getMode() == Source.OPEN_INTERACTIVE && isActivated() && target_.isActiveDocument())
{
if (panmirror_ != null)
{
panmirror_.focus();
}
else if (isLoading_)
{
onReadyHandlers_.add(() -> panmirror_.focus());
}
}
}
public void onClosing()
{
if (syncOnIdle_ != null)
syncOnIdle_.suspend();
if (saveLocationOnIdle_ != null)
saveLocationOnIdle_.suspend();
if (panmirror_ != null)
panmirror_.destroy();
}
public VisualModeChunk getChunkAtRow(int row)
{
return visualModeChunks_.getChunkAtRow(row);
}
public JsArray<ChunkDefinition> getChunkDefs()
{
return visualModeChunks_.getChunkDefs();
}
public ChunkDefinition getChunkDefAtRow(int row)
{
VisualModeChunk chunk = getChunkAtRow(row);
if (chunk == null)
return null;
return chunk.getDefinition();
}
/**
* Gets the document outline for the status bar popup; displayed when
* clicking on the status bar or using the Jump To command.
*
* @return Menu of items in the outline
*/
public StatusBarPopupRequest getStatusBarPopup()
{
StatusBarPopupMenu menu = new StatusBarPopupMenu();
buildStatusBarMenu(panmirror_.getOutline(), menu);
return new StatusBarPopupRequest(menu, null);
}
/**
* Recursively builds a status bar popup menu out of editor outline items.
*
* @param items An array of items to add to the menu
* @param menu The menu to add to
*/
private void buildStatusBarMenu(PanmirrorOutlineItem[] items, StatusBarPopupMenu menu)
{
for (PanmirrorOutlineItem item: items)
{
// Don't generate a menu entry for the YAML metadata
if (StringUtil.equals(item.type, PanmirrorOutlineItemType.YamlMetadata))
{
continue;
}
SafeHtmlBuilder label = new SafeHtmlBuilder();
// Add non-breaking spaces to indent to the level of the item
label.appendHtmlConstant(
StringUtil.repeat(" ", item.level));
// Make headings bold
if (StringUtil.equals(item.type, PanmirrorOutlineItemType.Heading))
{
label.appendHtmlConstant("<strong>");
}
if (StringUtil.equals(item.type, PanmirrorOutlineItemType.RmdChunk))
{
label.appendEscaped("Chunk " + item.sequence);
if (!StringUtil.equals(item.title, PanmirrorOutlineItemType.RmdChunk))
{
label.appendEscaped(": " + item.title);
}
}
else
{
// For non-chunk outline items, use the title directly
label.appendEscaped(item.title);
}
if (StringUtil.equals(item.type, PanmirrorOutlineItemType.Heading))
{
label.appendHtmlConstant("</strong>");
}
// Create a menu item representing the item and add it to the menu
final MenuItem menuItem = new MenuItem(
label.toSafeHtml(),
() ->
{
// Navigate to the given ID
visualModeNavigation_.navigateToId(item.navigation_id, false);
// Immediately update the status bar with the new location
// (this is usually done on idle so can lag a bit otherwise)
syncStatusBarLocation();
});
menu.addItem(menuItem);
// If this item has children, add them recursively
if (item.children != null)
{
buildStatusBarMenu(item.children, menu);
}
}
}
@Override
public List<CommandPaletteItem> getCommandPaletteItems()
{
return panmirror_.getCommandPaletteItems();
}
public void focus(Command onComplete)
{
activate(() ->
{
panmirror_.focus();
if (onComplete != null)
{
onComplete.execute();
}
});
}
public void setChunkLineExecState(int start, int end, int state)
{
visualModeChunks_.setChunkLineExecState(start, end, state);
}
public void setChunkState(Scope chunk, int state)
{
visualModeChunks_.setChunkState(chunk, state);
}
public void onUserSwitchingToVisualMode()
{
visualModeConfirm_.onUserSwitchToVisualModePending();
}
public String getSelectedText()
{
return panmirror_.getSelectedText();
}
public void replaceSelection(String value)
{
panmirror_.replaceSelection(value);
}
private void manageUI(boolean activate, boolean focus)
{
manageUI(activate, focus, () -> {});
}
private void manageUI(boolean activate, boolean focus, ScheduledCommand completed)
{
// validate the activation
if (activate)
{
String invalid = validateActivation();
if (invalid != null)
{
deactivateWithMessage(invalid);
return;
}
}
// manage commands
manageCommands();
// manage toolbar buttons / menus in display
view_.manageCommandUI();
// get references to the editing container and it's source editor
TextEditorContainer editorContainer = view_.editorContainer();
// visual mode enabled (panmirror editor)
if (activate)
{
// set flag indicating that we are loading
isLoading_ = true;
// show progress (as this may well require either loading the
// panmirror library for the first time or a reload of visual mode,
// which is normally instant but for very, very large documents
// can take a couple of seconds)
progress_.beginProgressOperation(400);
editorContainer.activateWidget(progress_);
CommandWithArg<Boolean> done = (success) -> {
// clear progress
progress_.endProgressOperation();
if (success)
{
// sync to editor outline prefs
panmirror_.showOutline(establishOutlineVisible(), getOutlineWidth());
// show find replace button
findReplaceButton_.setVisible(true);
// activate widget
editorContainer.activateWidget(panmirror_, focus);
// begin idle behavior
syncOnIdle_.resume();
saveLocationOnIdle_.resume();
displayLocationOnIdle_.resume();
// update status bar widget with current position
syncStatusBarLocation();
// hide cursor position widget (doesn't update in visual mode)
if (target_.getStatusBar() != null)
{
target_.getStatusBar().setPositionVisible(false);
}
// (re)inject notebook output from the editor
target_.getNotebook().migrateCodeModeOutput();
// execute completed hook
Scheduler.get().scheduleDeferred(completed);
// clear loading flag and execute any onReady handlers
isLoading_ = false;
onReadyHandlers_.forEach(handler -> { Scheduler.get().scheduleDeferred(handler); });
onReadyHandlers_.clear();
}
else
{
editorContainer.activateEditor(focus);
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
}
};
withPanmirror(() -> {
// if we aren't currently active then set our markdown based
// on what's currently in the source ditor
if (!isVisualEditorActive())
{
syncFromEditor(done, focus);
}
else
{
done.execute(true);
}
});
}
// visual mode not enabled (source editor)
else
{
Command activateSourceEditor = () -> {
unmanageCommands();
// hide find replace button
findReplaceButton_.setVisible(false);
editorContainer.activateEditor(focus);
if (syncOnIdle_ != null)
syncOnIdle_.suspend();
if (saveLocationOnIdle_ != null)
saveLocationOnIdle_.suspend();
if (displayLocationOnIdle_ != null)
displayLocationOnIdle_.suspend();
// move notebook outputs from visual mode
target_.getNotebook().migrateVisualModeOutput();
// bring the cursor position indicator back
if (target_.getStatusBar() != null)
{
target_.getStatusBar().setPositionVisible(true);
}
// execute completed hook
Scheduler.get().scheduleDeferred(completed);
};
// if we are deactivating to allow the user to edit invalid source code then don't sync
// back to the source editor (as this would have happened b/c we inspected the contents
// of the source editor in syncFromEditorIfActivated() and decided we couldn't edit it)
if (deactivatingForInvalidSource_)
{
deactivatingForInvalidSource_ = false;
activateSourceEditor.execute();
}
else
{
syncToEditor(SyncType.SyncTypeActivate, activateSourceEditor);
}
}
}
private void markDirty()
{
dirtyState_.markDirty(true);
source_.setSourceDocumentDirty(
docUpdateSentinel_.getId(), true,
new VoidServerRequestCallback());
}
private TextEditorContainer.Changes toEditorChanges(PanmirrorCode panmirrorCode)
{
// code to diff
String fromCode = getEditorCode();
String toCode = panmirrorCode.code;
// do the diff (timeout after 1 second). note that we only do this
// once the user has stopped typing for 1 second so it's not something
// that will run continuously during editing (in which case a much
// lower timeout would be warranted). note also that timeouts are for
// the diff planning phase so we will still get a valid diff back
// even if the timeout occurs.
PanmirrorUIToolsSource sourceTools = new PanmirrorUITools().source;
TextChange[] changes = sourceTools.diffChars(fromCode, toCode, 1);
// return changes w/ cursor
return new TextEditorContainer.Changes(
changes,
panmirrorCode.selection_only
? new TextEditorContainer.Navigator()
{
@Override
public void onNavigate(DocDisplay docDisplay)
{
visualModeLocation_.setSourceOutlineLocation(panmirrorCode.location);
}
}
: null
);
}
private void syncDevTools()
{
if (panmirror_ != null && panmirror_.devToolsLoaded())
panmirror_.activateDevTools();
}
/**
* Updates the status bar with the name of the current location.
*/
private void syncStatusBarLocation()
{
// Get the current outline so we can look up details of the selection
PanmirrorOutlineItem[] items = panmirror_.getOutline();
String targetId = panmirror_.getSelection().navigation_id;
// Find the selection and display it
PanmirrorOutlineItem item = findNavigationId(items, targetId);
if (item == null || StringUtil.equals(item.type, PanmirrorOutlineItemType.YamlMetadata))
{
// If we didn't find the selection in the outline, we're at the top
// level of the document.
// We also show this when beneath the top level YAML metadata region,
// if present.
target_.updateStatusBarLocation("(Top Level)", StatusBar.SCOPE_TOP_LEVEL);
}
else
{
// Convert the outline type into a status bar type
int type = StatusBar.SCOPE_ANON;
String title = item.title;
if (StringUtil.equals(item.type, PanmirrorOutlineItemType.Heading))
{
type = StatusBar.SCOPE_SECTION;
}
else if (StringUtil.equals(item.type, PanmirrorOutlineItemType.RmdChunk))
{
type = StatusBar.SCOPE_CHUNK;
title = "Chunk " + item.sequence;
if (!StringUtil.equals(item.title, PanmirrorOutlineItemType.RmdChunk))
{
title += ": " + item.title;
}
}
// Update the status bar and mark that we found an item
target_.updateStatusBarLocation(title, type);
}
}
/**
* Recursively finds the outline item associated with a given navigation ID.
*
* @param items An array of outline items.
* @param targetId The navigation ID to find.
* @return The outline item with the given ID, or null if no item was found.
*/
private PanmirrorOutlineItem findNavigationId(
PanmirrorOutlineItem[] items, String targetId)
{
for (PanmirrorOutlineItem item: items)
{
// Check whether this is the item being sought
if (item.navigation_id == targetId)
{
return item;
}
// If this item has children, check them recursively
if (item.children != null)
{
PanmirrorOutlineItem childItem = findNavigationId(
item.children, targetId);
if (childItem != null)
{
return childItem;
}
}
}
// Item not found in this level
return null;
}
private void withPanmirror(Command ready)
{
if (panmirror_ == null)
{
// create panmirror (no progress b/c we alread have pane progress)
PanmirrorContext context = createPanmirrorContext();
PanmirrorOptions options = panmirrorOptions();
PanmirrorWidget.Options widgetOptions = new PanmirrorWidget.Options();
PanmirrorWidget.create(context, visualModeFormat_.formatSource(),
options, widgetOptions, kCreationProgressDelayMs, (panmirror) -> {
// save reference to panmirror
panmirror_ = panmirror;
// track format comment (used to detect when we need to reload for a new format)
panmirrorFormatConfig_ = new VisualModeReloadChecker(view_);
// remove some keybindings that conflict with the ide
// (currently no known conflicts)
disableKeys();
// periodically sync edits back to main editor
syncOnIdle_ = new DebouncedCommand(1000)
{
@Override
protected void execute()
{
if (isDirty_ && !panmirror_.isInitialDoc())
syncToEditor(SyncType.SyncTypeNormal);
}
};
// periodically save selection
saveLocationOnIdle_ = new DebouncedCommand(1000)
{
@Override
protected void execute()
{
visualModeLocation_.saveEditingLocation(panmirror_.getEditingLocation());
}
};
// periodically display the selection in the status bar
displayLocationOnIdle_ = new DebouncedCommand(500)
{
@Override
protected void execute()
{
syncStatusBarLocation();
}
};
// set dirty flag + nudge idle sync on change
panmirror_.addPanmirrorUpdatedHandler(new PanmirrorUpdatedEvent.Handler()
{
@Override
public void onPanmirrorUpdated(PanmirrorUpdatedEvent event)
{
// set flag and nudge sync on idle
isDirty_ = true;
syncOnIdle_.nudge();
// update editor dirty state if necessary
if (!loadingFromSource_ && !dirtyState_.getValue())
markDirty();
}
});
// save selection
panmirror_.addPanmirrorStateChangeHandler(new PanmirrorStateChangeEvent.Handler()
{
@Override
public void onPanmirrorStateChange(PanmirrorStateChangeEvent event)
{
saveLocationOnIdle_.nudge();
displayLocationOnIdle_.nudge();
}
});
// forward navigation event
panmirror_.addPanmirrorNavigationHandler(new PanmirrorNavigationEvent.Handler()
{
@Override
public void onPanmirrorNavigation(PanmirrorNavigationEvent event)
{
visualModeNavigation_.onNavigated(event.getNavigation());
}
});
// propagate blur to text editing target
panmirror_.addPanmirrorBlurHandler(new PanmirrorBlurEvent.Handler()
{
@Override
public void onPanmirrorBlur(PanmirrorBlurEvent event)
{
target_.onVisualEditorBlur();
}
});
// check for external edit on focus
panmirror_.addPanmirrorFocusHandler(new PanmirrorFocusEvent.Handler()
{
@Override
public void onPanmirrorFocus(PanmirrorFocusEvent event)
{
target_.checkForExternalEdit(100);
// Disable code-related commands, on the presumption that we
// are in a prose region of the document. These commands will
// be re-enabled shortly if focus is sent to a code chunk, and
// will remain disabled if we aren't.
// Note that the PanmirrorFocusEvent is fired when selection
// exits a code chunk as well as when the entire widget loses
// focus.
setCodeCommandsEnabled(false);
// Also clear the last focused Ace editor. This is normally
// used by addins which need to target the 'active' editor,
// with the 'active' state persisting after other UI elements
// (e.g. the Addins toolbar) has been clicked. However, if
// focus has been moved to a new editor context, then we instead
// want to clear that state.
AceEditor.clearLastFocusedEditor();
}
});
// track changes in outline sidebar and save as prefs
panmirror_.addPanmirrorOutlineVisibleHandler((event) -> {
setOutlineVisible(event.getVisible());
});
panmirror_.addPanmirrorOutlineWidthHandler((event) -> {
setOutlineWidth(event.getWidth());
});
// manage latch state of findreplace button
panmirror_.addPanmirrorFindReplaceVisibleHandler((event) -> {
findReplaceButton_.setLeftImage(event.getVisible()
? FindReplaceBar.getFindLatchedIcon()
: FindReplaceBar.getFindIcon());
});
// good to go!
ready.execute();
});
}
else
{
// panmirror already created
ready.execute();
}
}
private PanmirrorContext createPanmirrorContext()
{
PanmirrorUIDisplay.ShowContextMenu showContextMenu = (commands, clientX, clientY) -> {
return panmirror_.showContextMenu(commands, clientX, clientY);
};
return visualModeContext_.createContext(showContextMenu);
}
private String getEditorCode()
{
return VisualModeUtil.getEditorCode(view_);
}
private TextEditorContainer.Editor getSourceEditor()
{
return view_.editorContainer().getEditor();
}
private boolean establishOutlineVisible()
{
return target_.establishPreferredOutlineWidgetVisibility(
prefs_.visualMarkdownEditingShowDocOutline().getValue()
);
}
private boolean getOutlineVisible()
{
return target_.getPreferredOutlineWidgetVisibility(
prefs_.visualMarkdownEditingShowDocOutline().getValue()
);
}
private void setOutlineVisible(boolean visible)
{
target_.setPreferredOutlineWidgetVisibility(visible);
}
private double getOutlineWidth()
{
return target_.getPreferredOutlineWidgetSize();
}
private void setOutlineWidth(double width)
{
target_.setPreferredOutlineWidgetSize(width);
}
private void disableKeys(String... commands)
{
PanmirrorKeybindings keybindings = disabledKeybindings(commands);
panmirror_.setKeybindings(keybindings);
}
private PanmirrorKeybindings disabledKeybindings(String... commands)
{
PanmirrorKeybindings keybindings = new PanmirrorKeybindings();
for (String command : commands)
keybindings.add(command, new String[0]);
return keybindings;
}
private void disableForVisualMode(AppCommand... commands)
{
if (isActivated())
{
for (AppCommand command : commands)
{
if (command.isVisible() && command.isEnabled())
{
command.setEnabled(false);
if (!disabledForVisualMode_.contains(command))
disabledForVisualMode_.add(command);
}
}
}
}
private void restoreDisabledForVisualMode()
{
disabledForVisualMode_.forEach((command) -> {
command.setEnabled(true);
});
disabledForVisualMode_.clear();
}
private HandlerRegistration onDocPropChanged(String prop, ValueChangeHandler<String> handler)
{
return docUpdateSentinel_.addPropertyValueChangeHandler(prop, handler);
}
private VisualModeNavigation.Context navigationContext_ = new VisualModeNavigation.Context() {
@Override
public String getId()
{
return docUpdateSentinel_.getId();
}
@Override
public String getPath()
{
return docUpdateSentinel_.getPath();
}
@Override
public PanmirrorWidget panmirror()
{
return panmirror_;
}
};
private PanmirrorOptions panmirrorOptions()
{
// create options
PanmirrorOptions options = new PanmirrorOptions();
// use embedded codemirror for code blocks
options.codeEditor = prefs_.visualMarkdownCodeEditor().getValue();
// highlight rmd example chunks
options.rmdExampleHighlight = true;
// add focus-visible class to prevent interaction with focus-visible.js
// (it ends up attempting to apply the "focus-visible" class b/c ProseMirror
// is contentEditable, and that triggers a dom mutation event for ProseMirror,
// which in turn causes us to lose table selections)
options.className = "focus-visible";
return options;
}
private String validateActivation()
{
if (this.docDisplay_.hasActiveCollabSession())
{
return "You cannot enter visual mode while using realtime collaboration.";
}
else if (BrowseCap.isInternetExplorer())
{
return "Visual mode is not supported in Internet Explorer.";
}
else
{
return visualModeFormat_.validateSourceForVisualMode();
}
}
private void deactivateForInvalidSource(String invalid)
{
deactivatingForInvalidSource_ = true;
deactivateWithMessage(invalid);
}
private void deactivateWithMessage(String message)
{
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
view_.showWarningBar(message);
}
/**
* Align the document's scope tree with the code chunks in visual mode.
*
* @param location Array of outline locations from visual mode
*/
private void alignScopeOutline(PanmirrorEditingOutlineLocation location)
{
// Get all of the chunks from the document (code view)
ArrayList<Scope> chunkScopes = new ArrayList<Scope>();
ScopeList chunks = new ScopeList(docDisplay_);
chunks.selectAll(ScopeList.CHUNK);
for (Scope chunk : chunks)
{
chunkScopes.add(chunk);
}
// Get all of the chunks from the outline emitted by visual mode
ArrayList<PanmirrorEditingOutlineLocationItem> chunkItems =
new ArrayList<PanmirrorEditingOutlineLocationItem>();
for (int j = 0; j < location.items.length; j++)
{
if (StringUtil.equals(location.items[j].type, PanmirrorOutlineItemType.RmdChunk))
{
chunkItems.add(location.items[j]);
}
}
// Refuse to proceed if cardinality doesn't match (consider: does this
// need to account for deeply nested chunks that might appear in one
// outline but not the other?)
if (chunkScopes.size() != chunkItems.size())
{
Debug.logWarning(chunkScopes.size() + " chunks in scope tree, but " +
chunkItems.size() + " chunks in visual editor.");
return;
}
for (int k = 0; k < chunkItems.size(); k++)
{
PanmirrorEditingOutlineLocationItem visualItem =
Js.uncheckedCast(chunkItems.get(k));
VisualModeChunk chunk = visualModeChunks_.getChunkAtVisualPosition(
visualItem.position);
if (chunk == null)
{
// This is normal; it is possible that we haven't created a chunk
// editor at this position yet.
continue;
}
chunk.setScope(chunkScopes.get(k));
}
}
/**
* Aligns the scope tree with chunks in visual mode; intended to be called when code
* has been mutated in the editor.
*
* @param location An outline of editing locations
*/
private void alignScopeTreeAfterUpdate(PanmirrorEditingOutlineLocation location)
{
final Value<HandlerRegistration> handler = new Value<HandlerRegistration>(null);
handler.setValue(docDisplay_.addScopeTreeReadyHandler((evt) ->
{
if (location != null)
{
alignScopeOutline(location);
}
handler.getValue().removeHandler();
}));
}
private Commands commands_;
private UserPrefs prefs_;
private SourceServerOperations source_;
private DocDisplay activeEditor_; // the current embedded editor
private final TextEditingTarget target_;
private final TextEditingTarget.Display view_;
private final DocDisplay docDisplay_; // the parent editor
private final DirtyState dirtyState_;
private final DocUpdateSentinel docUpdateSentinel_;
private final VisualModePanmirrorFormat visualModeFormat_;
private final VisualModeChunks visualModeChunks_;
private final VisualModePanmirrorContext visualModeContext_;
private final VisualModeEditingLocation visualModeLocation_;
private final VisualModeMarkdownWriter visualModeWriterOptions_;
private final VisualModeNavigation visualModeNavigation_;
private final VisualModeConfirm visualModeConfirm_;
private final VisualModeSpelling visualModeSpelling_;
private VisualModeReloadChecker panmirrorFormatConfig_;
private DebouncedCommand syncOnIdle_;
private DebouncedCommand saveLocationOnIdle_;
private DebouncedCommand displayLocationOnIdle_;
private boolean isDirty_ = false;
private boolean loadingFromSource_ = false;
private boolean deactivatingForInvalidSource_ = false;
private PanmirrorWidget panmirror_;
private ToolbarButton findReplaceButton_;
private ArrayList<AppCommand> disabledForVisualMode_ = new ArrayList<AppCommand>();
private final ProgressPanel progress_;
private SerializedCommandQueue syncToEditorQueue_ = new SerializedCommandQueue();
private boolean isLoading_ = false;
private List<ScheduledCommand> onReadyHandlers_ = new ArrayList<ScheduledCommand>();
private static final int kCreationProgressDelayMs = 0;
private static final int kSerializationProgressDelayMs = 5000;
// priority task queue for expensive calls to panmirror_.setMarkdown
// (currently active tab bumps itself up in priority)
private static PreemptiveTaskQueue setMarkdownQueue_ = new PreemptiveTaskQueue(true, false);
}
|
package ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.clients;
/**
* Used by the UI to send details for a new client.
*/
public class CreateClientRequest {
private String clientId;
private int tokenValidity;
private String grantType;
private int refreshToken;
private String read;
private String write;
private String redirectURI;
public CreateClientRequest(String clientId, int tokenValidity, String grantType, int refreshToken, String read,
String write) {
this.clientId = clientId;
this.tokenValidity = tokenValidity;
this.grantType = grantType;
this.refreshToken = refreshToken;
this.read = read;
this.write = write;
}
public CreateClientRequest(String clientId, int tokenValidity, String grantType, int refreshToken, String read,
String write, String redirectURI) {
this.clientId = clientId;
this.tokenValidity = tokenValidity;
this.grantType = grantType;
this.refreshToken = refreshToken;
this.read = read;
this.write = write;
this.redirectURI = redirectURI;
}
public CreateClientRequest() {
}
public String getClientId() {
return clientId;
}
public int getTokenValidity() {
return tokenValidity;
}
public String getGrantType() {
return grantType;
}
public int getRefreshToken() {
return refreshToken;
}
public String getRead() {
return read;
}
public String getWrite() {
return write;
}
public String getRedirectURI() {
return redirectURI;
}
}
|
package com.teamacronymcoders.contenttweaker.modules.materials;
import com.teamacronymcoders.base.materialsystem.MaterialSystem;
import com.teamacronymcoders.base.materialsystem.materialparts.MaterialPart;
import com.teamacronymcoders.contenttweaker.api.ctobjects.blockstate.ICTBlockState;
import com.teamacronymcoders.contenttweaker.api.ctobjects.blockstate.MCBlockState;
import com.teamacronymcoders.contenttweaker.modules.materials.materialparts.CTMaterialPart;
import com.teamacronymcoders.contenttweaker.modules.materials.materialparts.IMaterialPart;
import com.teamacronymcoders.contenttweaker.modules.vanilla.resources.BlockBracketHandler;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.annotations.BracketHandler;
import crafttweaker.mc1120.block.MCSpecificBlock;
import crafttweaker.zenscript.IBracketHandler;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import stanhebben.zenscript.compiler.IEnvironmentGlobal;
import stanhebben.zenscript.expression.ExpressionCallStatic;
import stanhebben.zenscript.expression.ExpressionInt;
import stanhebben.zenscript.expression.ExpressionString;
import stanhebben.zenscript.expression.partial.IPartialExpression;
import stanhebben.zenscript.parser.Token;
import stanhebben.zenscript.symbols.IZenSymbol;
import stanhebben.zenscript.type.ZenType;
import stanhebben.zenscript.type.natives.IJavaMethod;
import stanhebben.zenscript.util.ZenPosition;
import java.util.List;
import java.util.stream.Collectors;
@BracketHandler
public class MaterialPartBracketHandler implements IBracketHandler {
private final IJavaMethod method;
public MaterialPartBracketHandler() {
method = CraftTweakerAPI.getJavaMethod(MaterialPartBracketHandler.class, "geMaterialPart", String.class);
}
public static IMaterialPart getMaterialPart(String name) {
MaterialPart materialPart = null; //MaterialSystem.getMaterialPart(name);
IMaterialPart zenMaterialPart = null;
if (materialPart != null) {
zenMaterialPart = new CTMaterialPart(materialPart);
}
return zenMaterialPart;
}
@Override
public IZenSymbol resolve(IEnvironmentGlobal environment, List<Token> tokens) {
IZenSymbol zenSymbol = null;
if (tokens.size() == 5) {
if ("materialpart".equalsIgnoreCase(tokens.get(0).getValue())) {
String partName = String.join("", tokens.subList(2, 4)
.stream()
.map(Token::getValue)
.collect(Collectors.toList())
.toArray(new String[0]));
zenSymbol = new MaterialPartBracketHandler.MaterialPartReferenceSymbol(environment, partName);
}
}
return zenSymbol;
}
private class MaterialPartReferenceSymbol implements IZenSymbol {
private final IEnvironmentGlobal environment;
private final String name;
public MaterialPartReferenceSymbol(IEnvironmentGlobal environment, String name) {
this.environment = environment;
this.name = name;
}
@Override
public IPartialExpression instance(ZenPosition position) {
return new ExpressionCallStatic(position, environment, method, new ExpressionString(position, name));
}
}
}
|
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.set;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.channel.Conf;
import org.buddycloud.channelserver.db.NodeStore.Transaction;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessorAbstract;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubSet;
import org.buddycloud.channelserver.pubsub.accessmodel.AccessModels;
import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.buddycloud.channelserver.pubsub.event.Event;
import org.buddycloud.channelserver.pubsub.model.NodeAffiliation;
import org.buddycloud.channelserver.pubsub.model.NodeSubscription;
import org.buddycloud.channelserver.pubsub.model.impl.NodeSubscriptionImpl;
import org.buddycloud.channelserver.pubsub.subscription.Subscriptions;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
import org.xmpp.packet.IQ;
import org.xmpp.packet.IQ.Type;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import org.xmpp.resultsetmanagement.ResultSet;
public class SubscribeSet extends PubSubElementProcessorAbstract {
private static final String FIREHOSE = "/firehose";
private static final Logger LOGGER = Logger.getLogger(SubscribeSet.class);
private final BlockingQueue<Packet> outQueue;
private final ChannelManager channelManager;
public SubscribeSet(BlockingQueue<Packet> outQueue,
ChannelManager channelManager) {
this.outQueue = outQueue;
this.channelManager = channelManager;
}
@Override
public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm)
throws Exception {
node = elm.attributeValue("node");
request = reqIQ;
if ((node == null) || (node.equals(""))) {
missingNodeName();
return;
}
JID subscribingJid = request.getFrom();
boolean isLocalSubscriber = false;
if (actorJID != null) {
subscribingJid = actorJID;
} else {
isLocalSubscriber = channelManager.isLocalJID(subscribingJid);
// Check that user is registered.
if (!isLocalSubscriber) {
failAuthRequired();
return;
}
}
Map<String, String> nodeConf = null;
if (node.equals(FIREHOSE)) {
if (!channelManager.nodeExists(FIREHOSE)) {
channelManager.addRemoteNode(FIREHOSE);
}
nodeConf = new HashMap<String, String>();
nodeConf.put(Conf.DEFAULT_AFFILIATION, "member");
nodeConf.put(Conf.ACCESS_MODEL, "open");
} else {
if (!handleNodeSubscription(elm, actorJID, subscribingJid)) {
return;
}
nodeConf = channelManager.getNodeConf(node);
}
// Subscribe to a node.
Transaction t = null;
try {
t = channelManager.beginTransaction();
NodeSubscription nodeSubscription = channelManager
.getUserSubscription(node, subscribingJid);
NodeAffiliation nodeAffiliation = channelManager
.getUserAffiliation(node, subscribingJid);
Affiliations possibleExistingAffiliation = nodeAffiliation
.getAffiliation();
Subscriptions possibleExistingSubscription = nodeSubscription
.getSubscription();
if (Affiliations.outcast.toString().equals(
possibleExistingAffiliation.toString())) {
/*
* 6.1.3.8 Blocked <iq type='error'
* from='pubsub.shakespeare.lit'
* to='[email protected]/barracks' id='sub1'> <error
* type='auth'> <forbidden
* xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/> </error> </iq>
*/
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
PacketError pe = new PacketError(
org.xmpp.packet.PacketError.Condition.forbidden,
org.xmpp.packet.PacketError.Type.auth);
reply.setError(pe);
outQueue.put(reply);
return;
}
Affiliations defaultAffiliation = null;
Subscriptions defaultSubscription = null;
if (!possibleExistingSubscription.in(Subscriptions.none)) {
LOGGER.debug("User already has a '"
+ possibleExistingSubscription.toString()
+ "' subscription");
defaultAffiliation = possibleExistingAffiliation;
defaultSubscription = possibleExistingSubscription;
} else {
try {
defaultAffiliation = Affiliations.createFromString(nodeConf
.get(Conf.DEFAULT_AFFILIATION));
} catch (NullPointerException e) {
LOGGER.error("Could not create affiliation.", e);
defaultAffiliation = Affiliations.member;
}
defaultSubscription = Subscriptions.subscribed;
String accessModel = nodeConf.get(Conf.ACCESS_MODEL);
if ((null == accessModel)
|| (accessModel.equals(AccessModels.authorize.toString()))) {
defaultSubscription = Subscriptions.pending;
}
NodeSubscription newSubscription = new NodeSubscriptionImpl(node,
subscribingJid, request.getFrom(), defaultSubscription);
channelManager.addUserSubscription(newSubscription);
if (null != possibleExistingAffiliation) {
defaultAffiliation = possibleExistingAffiliation;
}
channelManager.setUserAffiliation(node, subscribingJid,
defaultAffiliation);
}
IQ reply = IQ.createResultIQ(request);
Element pubsub = reply.setChildElement(PubSubSet.ELEMENT_NAME,
JabberPubsub.NAMESPACE_URI);
pubsub.addElement("subscription")
.addAttribute("node", node)
.addAttribute("jid", subscribingJid.toBareJID())
.addAttribute("subscription",
defaultSubscription.toString());
pubsub.addElement("affiliation").addAttribute("node", node)
.addAttribute("jid", subscribingJid.toBareJID())
.addAttribute("affiliation", defaultAffiliation.toString());
outQueue.put(reply);
notifySubscribers(defaultSubscription, defaultAffiliation, subscribingJid);
t.commit();
} finally {
if (t != null) {
t.close();
}
}
}
private boolean handleNodeSubscription(Element elm, JID actorJID, JID subscribingJid)
throws NodeStoreException, InterruptedException {
if ((!channelManager.isLocalNode(node)) && (!node.equals("/firehose"))) {
makeRemoteRequest();
return false;
}
// 6.1.3.1 JIDs Do Not Match
// Covers where we have [email protected]/the-balcony
String[] jidParts = elm.attributeValue("jid").split("/");
String jid = jidParts[0];
if (!subscribingJid.toBareJID().equals(jid)) {
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
Element badRequest = new DOMElement("bad-request",
new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS));
Element nodeIdRequired = new DOMElement("invalid-jid",
new org.dom4j.Namespace("", JabberPubsub.NS_PUBSUB_ERROR));
Element error = new DOMElement("error");
error.addAttribute("type", PacketError.Type.modify.toXMPP());
error.add(badRequest);
error.add(nodeIdRequired);
reply.setChildElement(error);
outQueue.put(reply);
return false;
}
if (!channelManager.nodeExists(node)) {
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
PacketError pe = new PacketError(
PacketError.Condition.item_not_found,
PacketError.Type.cancel);
reply.setError(pe);
outQueue.put(reply);
return false;
}
return true;
}
private void makeRemoteRequest() throws InterruptedException {
request.setTo(new JID(node.split("/")[2]).getDomain());
Element actor = request.getElement()
.element("pubsub")
.addElement("actor", JabberPubsub.NS_BUDDYCLOUD);
actor.addText(request.getFrom().toBareJID());
outQueue.put(request);
}
private void notifySubscribers(Subscriptions subscriptionStatus,
Affiliations affiliationType, JID subscribingJid) throws NodeStoreException,
InterruptedException {
ResultSet<NodeSubscription> subscribers = channelManager
.getNodeSubscriptionListeners(node);
// Get all the affiliated users (so we can work out moderators)
ResultSet<NodeAffiliation> nodeAffiliations = channelManager
.getNodeAffiliations(node);
HashSet<JID> moderatorOwners = new HashSet<JID>();
for (NodeAffiliation nodeAffiliation : nodeAffiliations) {
if (nodeAffiliation.getAffiliation().in(Affiliations.owner,
Affiliations.moderator)) {
moderatorOwners.add(nodeAffiliation.getUser());
}
}
Document document = getDocumentHelper();
Element message = document.addElement("message");
message.addAttribute("remote-server-discover", "false");
Element event = message.addElement("event", Event.NAMESPACE);
Element subscription = event.addElement("subscription");
message.addAttribute("from", request.getTo().toString());
message.addAttribute("type", "headline");
subscription
.addAttribute("subscription", subscriptionStatus.toString());
subscription.addAttribute("jid", subscribingJid.toBareJID());
subscription.addAttribute("node", node);
Element affiliations = event.addElement("affiliations");
Element affiliation = affiliations.addElement("affiliation");
affiliation.addAttribute("node", node);
affiliation.addAttribute("jid", subscribingJid.toBareJID());
affiliation.addAttribute("affiliation", affiliationType.toString());
Message rootElement = new Message(message);
for (NodeSubscription subscriber : subscribers) {
Message notification = rootElement.createCopy();
notification.setTo(subscriber.getListener());
outQueue.put(notification);
if (moderatorOwners.contains(subscriber.getUser())
&& subscriptionStatus.equals(Subscriptions.pending)) {
outQueue.put(getPendingSubscriptionNotification(subscriber
.getListener().toBareJID(), subscribingJid.toBareJID()));
}
}
Collection<JID> admins = getAdminUsers();
for (JID admin : admins) {
Message notification = rootElement.createCopy();
notification.setTo(admin);
outQueue.put(notification);
}
}
private Message getPendingSubscriptionNotification(String receiver, String subscriber) {
Document document = getDocumentHelper();
Element message = document.addElement("message");
message.addAttribute("from", request.getTo().toString());
message.addAttribute("type", "headline");
message.addAttribute("to", receiver);
DataForm dataForm = new DataForm(DataForm.Type.form);
dataForm.addInstruction("Allow " + subscriber
+ " to subscribe to node " + node + "?");
dataForm.setTitle("Confirm channel subscription");
FormField formType = dataForm.addField();
formType.addValue(JabberPubsub.NS_AUTHORIZATION);
formType.setType(FormField.Type.hidden);
formType.setVariable("FORM_TYPE");
FormField subscribingNode = dataForm.addField();
subscribingNode.setType(FormField.Type.text_single);
subscribingNode.setVariable(JabberPubsub.VAR_NODE);
subscribingNode.setLabel("Node");
subscribingNode.addValue(node);
FormField jid = dataForm.addField();
jid.setType(FormField.Type.jid_single);
jid.addValue(subscriber);
jid.setLabel("Subscriber Address");
jid.setVariable(JabberPubsub.VAR_SUBSCRIBER_JID);
FormField allow = dataForm.addField();
allow.setLabel("Allow " + subscriber + " to subscribe to posts of " + node + "?");
allow.setVariable(JabberPubsub.VAR_ALLOW);
allow.addValue("false");
allow.setType(FormField.Type.boolean_type);
message.add(dataForm.getElement());
return new Message(message);
}
private void failAuthRequired() throws InterruptedException {
// If the packet did not have actor, and the sender is not a local user
// subscription is not allowed.
/*
* <iq type='error' from='pubsub.shakespeare.lit'
* to='[email protected]/elsinore' id='create1'> <error type='auth'>
* <registration-required xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
* </error> </iq>
*/
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
PacketError pe = new PacketError(
org.xmpp.packet.PacketError.Condition.registration_required,
org.xmpp.packet.PacketError.Type.auth);
reply.setError(pe);
outQueue.put(reply);
}
private void missingNodeName() throws InterruptedException {
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
Element badRequest = new DOMElement("bad-request",
new org.dom4j.Namespace("", JabberPubsub.NS_XMPP_STANZAS));
Element nodeIdRequired = new DOMElement("nodeid-required",
new org.dom4j.Namespace("", JabberPubsub.NS_PUBSUB_ERROR));
Element error = new DOMElement("error");
error.addAttribute("type", "modify");
error.add(badRequest);
error.add(nodeIdRequired);
reply.setChildElement(error);
outQueue.put(reply);
}
@Override
public boolean accept(Element elm) {
return elm.getName().equals("subscribe");
}
}
|
package ca.corefacility.bioinformatics.irida.processing.impl.unit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.util.ReflectionUtils;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.OverrepresentedSequence;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisFastQC;
import ca.corefacility.bioinformatics.irida.processing.FileProcessorException;
import ca.corefacility.bioinformatics.irida.processing.impl.FastqcFileProcessor;
import ca.corefacility.bioinformatics.irida.repositories.sequencefile.SequencingObjectRepository;
/**
* Tests for {@link FastqcFileProcessor}.
*
*
*/
public class FastqcFileProcessorTest {
private FastqcFileProcessor fileProcessor;
private SequencingObjectRepository objectRepository;
private MessageSource messageSource;
private static final Logger logger = LoggerFactory.getLogger(FastqcFileProcessorTest.class);
private static final String SEQUENCE = "ACGTACGTN";
private static final String FASTQ_FILE_CONTENTS = "@testread\n" + SEQUENCE + "\n+\n?????????\n@testread2\n"
+ SEQUENCE + "\n+\n?????????";
private static final String FASTA_FILE_CONTENTS = ">test read\n" + SEQUENCE;
@Before
public void setUp() {
messageSource = mock(MessageSource.class);
objectRepository = mock(SequencingObjectRepository.class);
fileProcessor = new FastqcFileProcessor(messageSource, objectRepository);
}
@Test(expected = FileProcessorException.class)
public void testHandleFastaFile() throws IOException {
// fastqc fails to handle fasta files (there's no quality scores,
// dummy), but that's A-OK.
Path fasta = Files.createTempFile(null, null);
Files.write(fasta, FASTA_FILE_CONTENTS.getBytes());
SequenceFile sf = new SequenceFile(fasta);
sf.setId(1L);
SingleEndSequenceFile so = new SingleEndSequenceFile(sf);
Runtime.getRuntime().addShutdownHook(new DeleteFileOnExit(fasta));
when(objectRepository.findOne(1L)).thenReturn(so);
fileProcessor.process(1L);
}
@Test
public void testHandleFastqFile() throws IOException, IllegalArgumentException, IllegalAccessException {
// fastqc shouldn't barf on a fastq file.
Path fastq = Files.createTempFile(null, null);
Files.write(fastq, FASTQ_FILE_CONTENTS.getBytes());
Runtime.getRuntime().addShutdownHook(new DeleteFileOnExit(fastq));
ArgumentCaptor<SequencingObject> argument = ArgumentCaptor.forClass(SequencingObject.class);
SequenceFile sf = new SequenceFile(fastq);
sf.setId(1L);
SingleEndSequenceFile so = new SingleEndSequenceFile(sf);
when(objectRepository.findOne(1L)).thenReturn(so);
try {
fileProcessor.process(1L);
} catch (Exception e) {
e.printStackTrace();
fail();
}
verify(objectRepository).save(argument.capture());
SequencingObject updatedObject = argument.getValue();
assertEquals("There should be 1 file associated with this SequencingObject", 1, updatedObject.getFiles().size());
SequenceFile updatedFile = updatedObject.getFiles().iterator().next();
final Field fastqcAnalysis = ReflectionUtils.findField(SequenceFile.class, "fastqcAnalysis");
ReflectionUtils.makeAccessible(fastqcAnalysis);
AnalysisFastQC updated = (AnalysisFastQC) fastqcAnalysis.get(updatedFile);
assertEquals("GC Content was not set correctly.", Short.valueOf((short) 50), updated.getGcContent());
assertEquals("Filtered sequences was not 0.", Integer.valueOf(0), updated.getFilteredSequences());
assertEquals("File type was not correct.", "Conventional base calls", updated.getFileType());
assertEquals("Max length was not correct.", Integer.valueOf(SEQUENCE.length()), updated.getMaxLength());
assertEquals("Min length was not correct.", Integer.valueOf(SEQUENCE.length()), updated.getMinLength());
assertEquals("Total sequences was not correct.", Integer.valueOf(2), updated.getTotalSequences());
assertEquals("Encoding was not correct.", "Illumina <1.3", updated.getEncoding());
assertEquals("Total number of bases was not correct.", Long.valueOf(SEQUENCE.length() * 2),
updated.getTotalBases());
assertNotNull("Per-base quality score chart was not created.", updated.getPerBaseQualityScoreChart());
assertTrue("Per-base quality score chart was created, but was empty.",
((byte[]) updated.getPerBaseQualityScoreChart()).length > 0);
assertNotNull("Per-sequence quality score chart was not created.", updated.getPerSequenceQualityScoreChart());
assertTrue("Per-sequence quality score chart was created, but was empty.",
((byte[]) updated.getPerSequenceQualityScoreChart()).length > 0);
assertNotNull("Duplication level chart was not created.", updated.getDuplicationLevelChart());
assertTrue("Duplication level chart was not created.", ((byte[]) updated.getDuplicationLevelChart()).length > 0);
Iterator<OverrepresentedSequence> ovrs = updated.getOverrepresentedSequences().iterator();
assertTrue("No overrepresented sequences added to analysis.", ovrs.hasNext());
OverrepresentedSequence overrepresentedSequence = updated.getOverrepresentedSequences().iterator().next();
assertEquals("Sequence was not the correct sequence.", SEQUENCE, overrepresentedSequence.getSequence());
assertEquals("The count was not correct.", 2, overrepresentedSequence.getOverrepresentedSequenceCount());
assertEquals("The percent was not correct.", BigDecimal.valueOf(100.), overrepresentedSequence.getPercentage());
}
private static final class DeleteFileOnExit extends Thread {
private final Path fileToDelete;
public DeleteFileOnExit(Path fileToDelete) {
this.fileToDelete = fileToDelete;
}
@Override
public void run() {
try {
Files.deleteIfExists(fileToDelete);
} catch (IOException e) {
logger.debug("Couldn't delete path ["
+ fileToDelete
+ "]. This should be safe to ignore; FastQC opens an input stream on the file and never closes it.");
}
}
}
}
|
package com.exner.tools.analyticstdd.SiteInfrastructureTests.tests;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.exner.tools.analyticstdd.SiteInfrastructureTests.AllTests;
import com.google.common.base.Predicate;
import junit.framework.TestCase;
public abstract class WebDriverBasedTestCase extends TestCase {
private final static Logger LOGGER = Logger.getLogger(WebDriverBasedTestCase.class.getName());
protected final String _pageURL;
protected WebDriver _webDriver;
protected JavascriptExecutor _jsExecutor;
protected WebDriverBasedTestCase(String pageURL) {
super();
_pageURL = pageURL;
}
@Override
protected void setUp() throws Exception {
super.setUp();
LOGGER.log(Level.FINE, "Setting up test for " + _pageURL);
_webDriver = AllTests.getWebDriverPool().borrowObject();
try {
_webDriver.get(_pageURL);
_jsExecutor = (JavascriptExecutor) _webDriver;
_jsExecutor.executeScript("localStorage.setItem('sdsat_debug', true);");
_jsExecutor.executeScript("if (typeof _satellite !== 'undefined') { _satellite.setDebug(true); }");
_webDriver.get(_pageURL);
// Wait up to 10 seconds for jQuery to load
WebDriverWait waiting = new WebDriverWait(_webDriver, 10);
waiting.until(new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
String testresult = (String) ((JavascriptExecutor) driver).executeScript("return document.readyState");
LOGGER.log(Level.FINE, "Page " + _pageURL + " - document.readyState: " + testresult);
return testresult.equals("complete");
}
});
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Page load took too long: " + e.getMessage());
AllTests.getWebDriverPool().returnObject(_webDriver);
_webDriver = null;
}
}
@Override
protected void tearDown() throws Exception {
LOGGER.log(Level.FINE, "Tearing down test for " + _pageURL);
if (null != _webDriver) {
AllTests.getWebDriverPool().returnObject(_webDriver);
}
super.tearDown();
}
}
|
package com.grayben.riskExtractor.htmlScorer.nodeVisitor;
import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.ScoredTextElement;
import com.grayben.riskExtractor.htmlScorer.ScoringAndFlatteningNodeVisitor;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers.ElementScorerSetSupplier;
import com.grayben.tools.testOracle.SystemUnderTest;
import com.grayben.tools.testOracle.oracle.passive.PassiveOracle;
import com.grayben.tools.testOracle.testContainer.TestContainer;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* For a nominated test configuration: generates the test input, SUT and expected output.
* <p>
*
*/
@RunWith(MockitoJUnitRunner.class)
public class NodeVisitorTestContainerSupplier implements Supplier<TestContainer<NodeVisitorTestContainerSupplier.Config, ScoredText>> {
@Override
public TestContainer<Config, ScoredText> get() {
Function<Config, Set<Scorer<Element>>> configElementScorerSetFunction = config1 -> {
throw new UnsupportedOperationException("Not implemented");
};
Function<Config, AnnotatedElement> configAnnotatedElementFunction = config1 -> {
//TODO: List<Element> produces hits for Set<Scorer<Element>>
Function<Config, List<Element>> configElementListFunction = config11 -> {
throw new UnsupportedOperationException("Not implemented");
};
Function<Config, AnnotatedElementTreeAssembler.Configuration> configConfigurationFunction = config11 -> {
throw new UnsupportedOperationException("Not implemented");
};
return new AnnotatedElementTreeAssembler(
configElementListFunction.apply(config1),
configConfigurationFunction.apply(config1),
configElementScorerSetFunction.apply(config1)
).getRootAnnotation();
};
Supplier<SystemUnderTest<Config, ScoredText>> systemUnderTestSupplier = () -> {
Function<Config, ScoringAndFlatteningNodeVisitor> scoringAndFlatteningNodeVisitorFunction
= config1 -> new ScoringAndFlatteningNodeVisitor(configElementScorerSetFunction.apply(config1));
Function<AnnotatedElement, Element> annotatedElementToElementFunction = annotatedElement -> annotatedElement;
return config1 -> {
Element rootElement = configAnnotatedElementFunction.andThen(annotatedElementToElementFunction).apply(config1);
ScoringAndFlatteningNodeVisitor nodeVisitor = scoringAndFlatteningNodeVisitorFunction.apply(config1);
NodeTraversor nodeTraversor = new NodeTraversor(nodeVisitor);
nodeTraversor.traverse(rootElement);
return nodeVisitor.getFlatText();
};
};
Supplier<PassiveOracle<Config, ScoredText>> passiveOracleSupplier = () -> {
Function<Config, ScoredText> configScoredTextFunction = config1 -> {
Function<AnnotatedElement, ScoredText> annotatedElementScoredTextFunction = annotatedElement -> {
ScoredText scoredText = new ScoredText();
NodeVisitor nodeVisitor = new NodeVisitor() {
@Override
public void head(Node node, int i) {
if(isAnnotatedElement(node)) {
AnnotatedElement annotatedElement = (AnnotatedElement) node;
scoredText.add(
new ScoredTextElement(annotatedElement.ownText(), annotatedElement.getScores())
);
}
}
@Override
public void tail(Node node, int i) {
isAnnotatedElement(node);
}
private boolean isAnnotatedElement(Node node) {
return node.getClass().equals(AnnotatedElement.class);
}
};
NodeTraversor nt = new NodeTraversor(nodeVisitor);
nt.traverse(annotatedElement);
return scoredText;
};
return configAnnotatedElementFunction.andThen(annotatedElementScoredTextFunction).apply(config1);
};
return (config1, scoredText) -> configScoredTextFunction.apply(config1).equals(scoredText);
};
return new TestContainer.Builder<Config, ScoredText>()
.begin()
.systemUnderTest(systemUnderTestSupplier.get())
.oracle(passiveOracleSupplier.get())
.build();
}
// TestContainerSupplier<Config, ScoredText> extends Supplier<TestContainer<Config, ScoredText>>
// - transformToUnderlyingInput: Config -> Element {}
// - buildUnderlyingSUT: Element -> ScoredText {}
// - buildSUT: () -> SUT<Config, ScoredText> {
// | return () -> transformToUnderlyingInput.andThen(buildUnderlyingSUT);
// - buildPassiveOracle: () -> PassiveOracle<Config, ScoredText> {
// | Element element = transformToUnderlyingInput.apply(config);
// | ScoredText scoredText =
// | return () -> {
// | underlyingPassiveOracle.test(
// + get: () -> TestContainer<Config, ScoredText> {
// return new TestContainer<>.Builder().build().sut(
// :TestContainer<Element, ScoredText>
// determine adapters
// determineScorers: Config -> Set<Scorer<Element>>
// configToSeed: Config -> Tree<AnnotatedElement>
// determineScorers.apply(config) -> Set<Scorer<Element>>
// determineElements: Config -> List<Element>
// adaptConfiguration: Config -> AnnotatedElementTreeAssembler.Config
// AnnotatedElementTreeAssembler.getRootAnnotation:
// List<Element>
// * Set<Scorer<Element>>
// * AnnotatedElementTreeAssembler.Config
// -> Tree<AnnotatedElement>
// annotationTreeToElementTree: Tree<AnnotatedElement> -> Tree<Element>
// annotationTreeToFile
// input generator: Tree<AnnotatedElement> -> File
// annotationTreeToElementTree.apply(annotationTree) -> Tree<Element>
// writeToFile: Tree<Element> -> File
// determine SUT: SystemUnderTest<Config, ScoredText>
// configToSeed.apply(config) -> Tree<AnnotatedElement>
// setup nv: Set<Scorer<Element>> -> ScoringAndFlatteningNodeVisitor
// setup nt: ScoringAndFlatteningNodeVisitor -> NodeTraversor
// apply nt to input: Tree<Element> * ScoringAndFlatteningNodeVisitor -> ScoredText
// determine PassiveOracle<Config, ScoredText>
// configToSeed.apply(config) -> Tree<AnnotatedElement>
// determine INPUT: Tree<AnnotatedElement> -> File
// determine EXPECTED OUTPUT: Tree<AnnotatedElement> -> ScoredText
public enum Config {
DEFAULT
}
// NEW SCAFFOLDING /\
// OLD CRAP \/
// INSTANCE VARIABLES
private Set<Scorer<Element>> sutParams;
private ScoringAndFlatteningNodeVisitor sut;
private ElementScorerSetSupplier elementScorerSetProducer;
private AnnotatedElementTreeAssembler.Configuration config;
private AnnotatedElement rootAnnotation;
private ScoredText expectedOutput;
Random random;
/// HIGH LEVEL
/*
private void generateArtifacts() {
instantiateGenerators();
generateSutParams();
generateSut();
generateAnnotatedInput();
determineExpectedOutput();
}
*/
private void instantiateGenerators() {
Set<ElementScorerSetSupplier.Content> contents = new HashSet<>();
contents.add(ElementScorerSetSupplier.Content.SEGMENTATION_ELEMENT_SCORER);
contents.add(ElementScorerSetSupplier.Content.EMPHASIS_ELEMENT_SCORER);
this.elementScorerSetProducer = new ElementScorerSetSupplier(contents);
}
private void generateSut() {
this.sut = new ScoringAndFlatteningNodeVisitor(this.sutParams);
}
private void generateSutParams() {
this.sutParams = elementScorerSetProducer.get();
}
/*
private void generateAnnotatedInput() {
List<Element> elementList = generateElements();
AnnotatedElementTreeAssembler annotatedElementTreeAssembler = new AnnotatedElementTreeAssembler(elementList, config, this.sutParams);
rootAnnotation = annotatedElementTreeAssembler.getRootAnnotation();
}
*/
// ENCAPSULATED HELPERS
}
|
package eu.ydp.empiria.player.client.controller.extensions;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.XMLParser;
import eu.ydp.empiria.player.client.controller.communication.sockets.ModuleInterferenceSocket;
import eu.ydp.empiria.player.client.controller.communication.sockets.PageInterferenceSocket;
import eu.ydp.empiria.player.client.controller.delivery.DeliveryEngine;
import eu.ydp.empiria.player.client.controller.extensions.internal.InternalExtension;
import eu.ydp.empiria.player.client.controller.extensions.internal.modules.ModuleExtension;
import eu.ydp.empiria.player.client.controller.extensions.types.ModuleConnectorExtension;
import eu.ydp.empiria.player.client.controller.extensions.types.PageInterferenceSocketUserExtension;
import eu.ydp.empiria.player.client.module.IInteractionModule;
import eu.ydp.empiria.player.client.module.IModule;
import eu.ydp.empiria.player.client.module.ModuleCreator;
import eu.ydp.empiria.player.client.module.ModuleSocket;
import eu.ydp.empiria.player.client.module.listener.ModuleInteractionListener;
import eu.ydp.empiria.player.client.util.xml.document.XMLData;
public class PageInterferenceSocketUserExtensionTest extends ExtensionTestBase {
protected DeliveryEngine de;
protected PageInterferenceSocket pis;
protected String lastAction = "";
public void testGetJsSocket(){
ModuleInterferenceSocket mis = initTests();
mis.getJsSocket();
assertEquals("getJsSocket", lastAction);
}
public void testGetState(){
ModuleInterferenceSocket mis = initTests();
mis.getState();
assertEquals("getState", lastAction);
}
public void testLock(){
ModuleInterferenceSocket mis = initTests();
mis.lock(false);
assertEquals("lock", lastAction);
}
public void testMarkAnswers(){
ModuleInterferenceSocket mis = initTests();
mis.markAnswers(false);
assertEquals("markAnswers", lastAction);
}
public void testReset(){
ModuleInterferenceSocket mis = initTests();
mis.reset();
assertEquals("reset", lastAction);
}
public void testSetState(){
ModuleInterferenceSocket mis = initTests();
mis.setState(new JSONArray());
assertEquals("setState", lastAction);
}
public void testShowCorrectAnswers(){
ModuleInterferenceSocket mis = initTests();
mis.showCorrectAnswers(false);
assertEquals("showCorrectAnswers", lastAction);
}
protected ModuleInterferenceSocket initTests(){
List<Extension> exts = new ArrayList<Extension>();
exts.add(new MockPageInterferenceSocketUserExtension());
exts.add(new MockModuleExtension());
de = initDeliveryEngine(exts, false);
assertNotNull(pis.getItemSockets());
assertEquals(1, pis.getItemSockets().length);
assertNotNull(pis.getItemSockets()[0].getModuleSockets());
assertEquals(1, pis.getItemSockets()[0].getModuleSockets().length);
ModuleInterferenceSocket mis = pis.getItemSockets()[0].getModuleSockets()[0];
return mis;
}
protected XMLData getAssessmentXMLData(){
String assessmentXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><assessmentTest xmlns=\"http:
Document assessmentDoc = XMLParser.parse(assessmentXml);
return new XMLData(assessmentDoc, "");
}
protected XMLData[] getItemXMLDatas(){
Document itemDoc = XMLParser.parse("<assessmentItem identifier=\"inlineChoice\" title=\"Interactive text\"><itemBody><testModule8273629297347 responseIdentifier=\"RESPONSE1\"/></itemBody><variableProcessing template=\"default\"/></assessmentItem>");
XMLData itemData = new XMLData(itemDoc, "");
XMLData[] itemDatas = new XMLData[1];
itemDatas[0] = itemData;
return itemDatas;
}
protected class MockPageInterferenceSocketUserExtension extends InternalExtension implements PageInterferenceSocketUserExtension{
@Override
public void init() {
}
@Override
public void setPageInterferenceSocket(PageInterferenceSocket socket) {
pis = socket;
}
}
protected class MockModuleExtension extends ModuleExtension implements ModuleConnectorExtension{
@Override
public ModuleCreator getModuleCreator() {
return new ModuleCreator() {
@Override
public boolean isInteractionModule() {
return true;
}
@Override
public boolean isInlineModule() {
return false;
}
@Override
public IModule createModule() {
return new MockModule();
}
};
}
@Override
public String getModuleNodeName() {
// TODO Auto-generated method stub
return "testModule8273629297347";
}
}
protected class MockModule implements IInteractionModule{
@Override
public void markAnswers(boolean mark) {
lastAction = "markAnswers";
}
@Override
public void showCorrectAnswers(boolean show) {
lastAction = "showCorrectAnswers";
}
@Override
public void lock(boolean l) {
lastAction = "lock";
}
@Override
public void reset() {
lastAction = "reset";
}
@Override
public JSONArray getState() {
lastAction = "getState";
return new JSONArray();
}
@Override
public void setState(JSONArray newState) {
lastAction = "setState";
}
@Override
public JavaScriptObject getJsSocket() {
lastAction = "getJsSocket";
return JavaScriptObject.createObject();
}
@Override
public String getIdentifier() {
return "RESPONSE1";
}
@Override
public void initModule(ModuleSocket moduleSocket, ModuleInteractionListener moduleInteractionListener) {
}
@Override
public void addElement(Element element) {
// TODO Auto-generated method stub
}
@Override
public void installViews(List<HasWidgets> placeholders) {
// TODO Auto-generated method stub
}
@Override
public void onBodyLoad() {
// TODO Auto-generated method stub
}
@Override
public void onBodyUnload() {
// TODO Auto-generated method stub
}
@Override
public void onSetUp() {
// TODO Auto-generated method stub
}
@Override
public void onStart() {
}
@Override
public void onClose() {
}
}
}
|
package org.elasticsearch.xpack.security.authc;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.SecurityIntegTestCase;
import org.elasticsearch.test.SecuritySettingsSource;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.security.action.token.CreateTokenResponse;
import org.elasticsearch.xpack.core.security.action.token.InvalidateTokenRequest;
import org.elasticsearch.xpack.core.security.action.token.InvalidateTokenResponse;
import org.elasticsearch.xpack.core.security.action.user.AuthenticateAction;
import org.elasticsearch.xpack.core.security.action.user.AuthenticateRequest;
import org.elasticsearch.xpack.core.security.action.user.AuthenticateResponse;
import org.elasticsearch.xpack.core.security.authc.TokenMetaData;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.xpack.core.security.client.SecurityClient;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.After;
import org.junit.Before;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout;
import static org.hamcrest.Matchers.equalTo;
@TestLogging("org.elasticsearch.xpack.security.authz.store.FileRolesStore:DEBUG")
public class TokenAuthIntegTests extends SecurityIntegTestCase {
@Override
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
// crank up the deletion interval and set timeout for delete requests
.put(TokenService.DELETE_INTERVAL.getKey(), TimeValue.timeValueMillis(200L))
.put(TokenService.DELETE_TIMEOUT.getKey(), TimeValue.timeValueSeconds(5L))
.put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true)
.build();
}
@Override
protected int maxNumberOfNodes() {
// we start one more node so we need to make sure if we hit max randomization we can still start one
return defaultMaxNumberOfNodes() + 1;
}
public void testTokenServiceBootstrapOnNodeJoin() throws Exception {
final Client client = client();
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse response = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
for (TokenService tokenService : internalCluster().getInstances(TokenService.class)) {
PlainActionFuture<UserToken> userTokenFuture = new PlainActionFuture<>();
tokenService.decodeToken(response.getTokenString(), userTokenFuture);
assertNotNull(userTokenFuture.actionGet());
}
// start a new node and see if it can decrypt the token
String nodeName = internalCluster().startNode();
for (TokenService tokenService : internalCluster().getInstances(TokenService.class)) {
PlainActionFuture<UserToken> userTokenFuture = new PlainActionFuture<>();
tokenService.decodeToken(response.getTokenString(), userTokenFuture);
assertNotNull(userTokenFuture.actionGet());
}
TokenService tokenService = internalCluster().getInstance(TokenService.class, nodeName);
PlainActionFuture<UserToken> userTokenFuture = new PlainActionFuture<>();
tokenService.decodeToken(response.getTokenString(), userTokenFuture);
assertNotNull(userTokenFuture.actionGet());
}
public void testTokenServiceCanRotateKeys() throws Exception {
final Client client = client();
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse response = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
String masterName = internalCluster().getMasterName();
TokenService masterTokenService = internalCluster().getInstance(TokenService.class, masterName);
String activeKeyHash = masterTokenService.getActiveKeyHash();
for (TokenService tokenService : internalCluster().getInstances(TokenService.class)) {
PlainActionFuture<UserToken> userTokenFuture = new PlainActionFuture<>();
tokenService.decodeToken(response.getTokenString(), userTokenFuture);
assertNotNull(userTokenFuture.actionGet());
assertEquals(activeKeyHash, tokenService.getActiveKeyHash());
}
client().admin().cluster().prepareHealth().execute().get();
PlainActionFuture<ClusterStateUpdateResponse> rotateActionFuture = new PlainActionFuture<>();
logger.info("rotate on master: {}", masterName);
masterTokenService.rotateKeysOnMaster(rotateActionFuture);
assertTrue(rotateActionFuture.actionGet().isAcknowledged());
assertNotEquals(activeKeyHash, masterTokenService.getActiveKeyHash());
for (TokenService tokenService : internalCluster().getInstances(TokenService.class)) {
PlainActionFuture<UserToken> userTokenFuture = new PlainActionFuture<>();
tokenService.decodeToken(response.getTokenString(), userTokenFuture);
assertNotNull(userTokenFuture.actionGet());
assertNotEquals(activeKeyHash, tokenService.getActiveKeyHash());
}
}
@TestLogging("org.elasticsearch.xpack.security.authc:DEBUG")
public void testExpiredTokensDeletedAfterExpiration() throws Exception {
final Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse response = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
Instant created = Instant.now();
InvalidateTokenResponse invalidateResponse = securityClient
.prepareInvalidateToken(response.getTokenString())
.setType(InvalidateTokenRequest.Type.ACCESS_TOKEN)
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(1));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
AtomicReference<String> docId = new AtomicReference<>();
assertBusy(() -> {
SearchResponse searchResponse = client.prepareSearch(SecurityIndexManager.SECURITY_INDEX_NAME)
.setSource(SearchSourceBuilder.searchSource()
.query(QueryBuilders.termQuery("doc_type", "token")))
.setSize(1)
.setTerminateAfter(1)
.get();
assertThat(searchResponse.getHits().getTotalHits().value, equalTo(1L));
docId.set(searchResponse.getHits().getAt(0).getId());
});
// hack doc to modify the creation time to the day before
Instant yesterday = created.minus(36L, ChronoUnit.HOURS);
assertTrue(Instant.now().isAfter(yesterday));
client.prepareUpdate(SecurityIndexManager.SECURITY_INDEX_NAME, "doc", docId.get())
.setDoc("creation_time", yesterday.toEpochMilli())
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
AtomicBoolean deleteTriggered = new AtomicBoolean(false);
assertBusy(() -> {
if (deleteTriggered.compareAndSet(false, true)) {
// invalidate a invalid token... doesn't matter that it is bad... we just want this action to trigger the deletion
try {
securityClient.prepareInvalidateToken("fooobar")
.setType(randomFrom(InvalidateTokenRequest.Type.values()))
.execute()
.actionGet();
} catch (ElasticsearchSecurityException e) {
assertEquals("token malformed", e.getMessage());
}
}
client.admin().indices().prepareRefresh(SecurityIndexManager.SECURITY_INDEX_NAME).get();
SearchResponse searchResponse = client.prepareSearch(SecurityIndexManager.SECURITY_INDEX_NAME)
.setSource(SearchSourceBuilder.searchSource()
.query(QueryBuilders.termQuery("doc_type", "token")))
.setTerminateAfter(1)
.get();
assertThat(searchResponse.getHits().getTotalHits().value, equalTo(0L));
}, 30, TimeUnit.SECONDS);
}
public void testInvalidateAllTokensForUser() throws Exception{
final int numOfRequests = randomIntBetween(5, 10);
for (int i = 0; i < numOfRequests; i++) {
securityClient().prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
}
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClientSuperuser = new SecurityClient(client);
InvalidateTokenResponse invalidateResponse = securityClientSuperuser
.prepareInvalidateToken()
.setUserName(SecuritySettingsSource.TEST_USER_NAME)
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(2 * (numOfRequests)));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
}
public void testInvalidateAllTokensForRealm() throws Exception{
final int numOfRequests = randomIntBetween(5, 10);
for (int i = 0; i < numOfRequests; i++) {
securityClient().prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
}
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClientSuperuser = new SecurityClient(client);
InvalidateTokenResponse invalidateResponse = securityClientSuperuser
.prepareInvalidateToken()
.setRealmName("file")
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(2 * (numOfRequests)));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
}
public void testInvalidateAllTokensForRealmThatHasNone() {
final int numOfRequests = randomIntBetween(2, 4);
for (int i = 0; i < numOfRequests; i++) {
securityClient().prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
}
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClientSuperuser = new SecurityClient(client);
InvalidateTokenResponse invalidateResponse = securityClientSuperuser
.prepareInvalidateToken()
.setRealmName("saml")
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
}
public void testExpireMultipleTimes() {
CreateTokenResponse response = securityClient().prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
InvalidateTokenResponse invalidateResponse = securityClient()
.prepareInvalidateToken(response.getTokenString())
.setType(InvalidateTokenRequest.Type.ACCESS_TOKEN)
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(1));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
InvalidateTokenResponse invalidateAgainResponse = securityClient()
.prepareInvalidateToken(response.getTokenString())
.setType(InvalidateTokenRequest.Type.ACCESS_TOKEN)
.get();
assertThat(invalidateAgainResponse.getResult().getInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateAgainResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(1));
assertThat(invalidateAgainResponse.getResult().getErrors().size(), equalTo(0));
}
public void testRefreshingToken() {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
assertNotNull(createTokenResponse.getRefreshToken());
// get cluster health with token
assertNoTimeout(client()
.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + createTokenResponse.getTokenString()))
.admin().cluster().prepareHealth().get());
CreateTokenResponse refreshResponse = securityClient.prepareRefreshToken(createTokenResponse.getRefreshToken()).get();
assertNotNull(refreshResponse.getRefreshToken());
assertNotEquals(refreshResponse.getRefreshToken(), createTokenResponse.getRefreshToken());
assertNotEquals(refreshResponse.getTokenString(), createTokenResponse.getTokenString());
assertNoTimeout(client().filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + refreshResponse.getTokenString()))
.admin().cluster().prepareHealth().get());
}
public void testRefreshingInvalidatedToken() {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
assertNotNull(createTokenResponse.getRefreshToken());
InvalidateTokenResponse invalidateResponse = securityClient
.prepareInvalidateToken(createTokenResponse.getRefreshToken())
.setType(InvalidateTokenRequest.Type.REFRESH_TOKEN)
.get();
assertThat(invalidateResponse.getResult().getInvalidatedTokens().size(), equalTo(1));
assertThat(invalidateResponse.getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponse.getResult().getErrors().size(), equalTo(0));
ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class,
() -> securityClient.prepareRefreshToken(createTokenResponse.getRefreshToken()).get());
assertEquals("invalid_grant", e.getMessage());
assertEquals(RestStatus.BAD_REQUEST, e.status());
assertEquals("token has been invalidated", e.getHeader("error_description").get(0));
}
public void testRefreshingMultipleTimes() {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
assertNotNull(createTokenResponse.getRefreshToken());
CreateTokenResponse refreshResponse = securityClient.prepareRefreshToken(createTokenResponse.getRefreshToken()).get();
assertNotNull(refreshResponse);
ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class,
() -> securityClient.prepareRefreshToken(createTokenResponse.getRefreshToken()).get());
assertEquals("invalid_grant", e.getMessage());
assertEquals(RestStatus.BAD_REQUEST, e.status());
assertEquals("token has already been refreshed", e.getHeader("error_description").get(0));
}
public void testRefreshAsDifferentUser() {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
assertNotNull(createTokenResponse.getRefreshToken());
ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class,
() -> new SecurityClient(client()
.filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING))))
.prepareRefreshToken(createTokenResponse.getRefreshToken()).get());
assertEquals("invalid_grant", e.getMessage());
assertEquals(RestStatus.BAD_REQUEST, e.status());
assertEquals("tokens must be refreshed by the creating client", e.getHeader("error_description").get(0));
}
public void testCreateThenRefreshAsDifferentUser() {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("password")
.setUsername(SecuritySettingsSource.TEST_USER_NAME)
.setPassword(new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))
.get();
assertNotNull(createTokenResponse.getRefreshToken());
CreateTokenResponse refreshResponse = securityClient.prepareRefreshToken(createTokenResponse.getRefreshToken()).get();
assertNotEquals(refreshResponse.getTokenString(), createTokenResponse.getTokenString());
assertNotEquals(refreshResponse.getRefreshToken(), createTokenResponse.getRefreshToken());
PlainActionFuture<AuthenticateResponse> authFuture = new PlainActionFuture<>();
AuthenticateRequest request = new AuthenticateRequest();
request.username(SecuritySettingsSource.TEST_SUPERUSER);
client.execute(AuthenticateAction.INSTANCE, request, authFuture);
AuthenticateResponse response = authFuture.actionGet();
assertEquals(SecuritySettingsSource.TEST_SUPERUSER, response.authentication().getUser().principal());
authFuture = new PlainActionFuture<>();
request = new AuthenticateRequest();
request.username(SecuritySettingsSource.TEST_USER_NAME);
client.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + createTokenResponse.getTokenString()))
.execute(AuthenticateAction.INSTANCE, request, authFuture);
response = authFuture.actionGet();
assertEquals(SecuritySettingsSource.TEST_USER_NAME, response.authentication().getUser().principal());
authFuture = new PlainActionFuture<>();
request = new AuthenticateRequest();
request.username(SecuritySettingsSource.TEST_USER_NAME);
client.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + refreshResponse.getTokenString()))
.execute(AuthenticateAction.INSTANCE, request, authFuture);
response = authFuture.actionGet();
assertEquals(SecuritySettingsSource.TEST_USER_NAME, response.authentication().getUser().principal());
}
public void testClientCredentialsGrant() throws Exception {
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
SecurityClient securityClient = new SecurityClient(client);
CreateTokenResponse createTokenResponse = securityClient.prepareCreateToken()
.setGrantType("client_credentials")
.get();
assertNull(createTokenResponse.getRefreshToken());
AuthenticateRequest request = new AuthenticateRequest();
request.username(SecuritySettingsSource.TEST_SUPERUSER);
PlainActionFuture<AuthenticateResponse> authFuture = new PlainActionFuture<>();
client.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + createTokenResponse.getTokenString()))
.execute(AuthenticateAction.INSTANCE, request, authFuture);
AuthenticateResponse response = authFuture.get();
assertEquals(SecuritySettingsSource.TEST_SUPERUSER, response.authentication().getUser().principal());
// invalidate
PlainActionFuture<InvalidateTokenResponse> invalidateResponseFuture = new PlainActionFuture<>();
InvalidateTokenRequest invalidateTokenRequest =
new InvalidateTokenRequest(createTokenResponse.getTokenString(), InvalidateTokenRequest.Type.ACCESS_TOKEN.getValue());
securityClient.invalidateToken(invalidateTokenRequest, invalidateResponseFuture);
assertThat(invalidateResponseFuture.get().getResult().getInvalidatedTokens().size(), equalTo(1));
assertThat(invalidateResponseFuture.get().getResult().getPreviouslyInvalidatedTokens().size(), equalTo(0));
assertThat(invalidateResponseFuture.get().getResult().getErrors().size(), equalTo(0));
ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> {
PlainActionFuture<AuthenticateResponse> responseFuture = new PlainActionFuture<>();
client.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + createTokenResponse.getTokenString()))
.execute(AuthenticateAction.INSTANCE, request, responseFuture);
responseFuture.actionGet();
});
}
@Before
public void waitForSecurityIndexWritable() throws Exception {
assertSecurityIndexActive();
}
@After
public void wipeSecurityIndex() throws InterruptedException {
// get the token service and wait until token expiration is not in progress!
for (TokenService tokenService : internalCluster().getInstances(TokenService.class)) {
final boolean done = awaitBusy(() -> tokenService.isExpirationInProgress() == false);
assertTrue(done);
}
super.deleteSecurityIndex();
}
public void testMetadataIsNotSentToClient() {
ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().setCustoms(true).get();
assertFalse(clusterStateResponse.getState().customs().containsKey(TokenMetaData.TYPE));
}
}
|
package org.knowm.xchange.coinbasepro.dto.marketdata;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
public class CoinbaseProTrade {
private final String timestamp;
private final long tradeId;
private final BigDecimal price;
private final BigDecimal size;
private final String side;
private String maker_order_id;
private String taker_order_id;
/**
* @param timestamp
* @param tradeId
* @param price
* @param size
* @param side
*/
public CoinbaseProTrade(
@JsonProperty("time") String timestamp,
@JsonProperty("trade_id") long tradeId,
@JsonProperty("price") BigDecimal price,
@JsonProperty("size") BigDecimal size,
@JsonProperty("side") String side) {
this.timestamp = timestamp;
this.tradeId = tradeId;
this.price = price;
this.size = size;
this.side = side;
}
public CoinbaseProTrade(
@JsonProperty("time") String timestamp,
@JsonProperty("trade_id") long tradeId,
@JsonProperty("price") BigDecimal price,
@JsonProperty("size") BigDecimal size,
@JsonProperty("side") String side,
@JsonProperty("maker_order_id") String maker_order_id,
@JsonProperty("taker_order_id") String taker_order_id)
{
this.timestamp = timestamp;
this.tradeId = tradeId;
this.price = price;
this.size = size;
this.side = side;
this.maker_order_id = maker_order_id;
this.taker_order_id = taker_order_id;
}
public String getTimestamp() {
return timestamp;
}
public long getTradeId() {
return tradeId;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getSize() {
return size;
}
public String getSide() {
return side;
}
public String getMaker_order_id() {
return maker_order_id;
}
public String getTaker_order_id() {
return taker_order_id;
}
@Override
public String toString() {
return "CoinbaseProTrade [timestamp="
+ timestamp
+ ", tradeId="
+ tradeId
+ ", price="
+ price
+ ", size="
+ size
+ ", side="
+ side
+ "]";
}
}
|
package org.opendaylight.yangtools.yang.data.impl.codec;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.YangModeledAnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for tracking the underlying state of the underlying
* schema node.
*/
@Beta
public final class SchemaTracker {
private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
private final Deque<Object> schemaStack = new ArrayDeque<>();
private final DataNodeContainer root;
private SchemaTracker(final SchemaContext context, final SchemaPath path) {
SchemaNode current = SchemaUtils.findParentSchemaOnPath(context, path);
Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",path,current);
root = (DataNodeContainer) current;
}
/**
* Create a new writer with the specified context as its root.
*
* @param context Associated {@link SchemaContext}.
* @return A new {@link NormalizedNodeStreamWriter}
*/
public static SchemaTracker create(final SchemaContext context) {
return create(context, SchemaPath.ROOT);
}
/**
* Create a new writer with the specified context and rooted in the specified schema path
*
* @param context Associated {@link SchemaContext}
* @param path schema path
*
* @return A new {@link NormalizedNodeStreamWriter}
*/
public static SchemaTracker create(final SchemaContext context, final SchemaPath path) {
return new SchemaTracker(context, path);
}
public Object getParent() {
if (schemaStack.isEmpty()) {
return root;
}
return schemaStack.peek();
}
private SchemaNode getSchema(final PathArgument name) {
final Object parent = getParent();
SchemaNode schema = null;
final QName qname = name.getNodeType();
if (parent instanceof DataNodeContainer) {
schema = ((DataNodeContainer)parent).getDataChildByName(qname);
if (schema == null) {
if (parent instanceof GroupingDefinition) {
schema = (GroupingDefinition) parent;
} else if (parent instanceof NotificationDefinition) {
schema = (NotificationDefinition) parent;
}
}
} else if (parent instanceof ChoiceSchemaNode) {
schema = findChildInCases((ChoiceSchemaNode) parent, qname);
} else {
throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
}
Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
return schema;
}
private static SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
DataSchemaNode schema = null;
for (final ChoiceCaseNode caze : parent.getCases()) {
final DataSchemaNode potential = caze.getDataChildByName(qname);
if (potential != null) {
schema = potential;
break;
}
}
return schema;
}
private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
DataSchemaNode schema = null;
for (final ChoiceCaseNode caze : parent.getCases()) {
final DataSchemaNode potential = caze.getDataChildByName(qname);
if (potential != null) {
schema = caze;
break;
}
}
return schema;
}
public void startList(final PathArgument name) {
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
schemaStack.push(schema);
}
public void startListItem(final PathArgument name) throws IOException {
final Object schema = getParent();
Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
schemaStack.push(schema);
}
public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
return (LeafSchemaNode) schema;
}
public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
schemaStack.push(schema);
return (LeafListSchemaNode)schema;
}
@Deprecated
public LeafListSchemaNode leafSetEntryNode() {
final Object parent = getParent();
Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
return (LeafListSchemaNode) parent;
}
public LeafListSchemaNode leafSetEntryNode(final QName qname) {
final Object parent = getParent();
if (parent instanceof LeafListSchemaNode) {
return (LeafListSchemaNode) parent;
}
final SchemaNode child = SchemaUtils.findChildSchemaByQName((SchemaNode) parent, qname);
Preconditions.checkArgument(child instanceof LeafListSchemaNode,
"Node %s is neither a leaf-list nor currently in a leaf-list", child.getPath());
return (LeafListSchemaNode) child;
}
public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
LOG.debug("Enter choice {}", name);
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
schemaStack.push(schema);
return (ChoiceSchemaNode)schema;
}
public SchemaNode startContainerNode(final NodeIdentifier name) {
LOG.debug("Enter container {}", name);
final SchemaNode schema = getSchema(name);
boolean isAllowed = schema instanceof ContainerSchemaNode;
isAllowed |= schema instanceof NotificationDefinition;
Preconditions.checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
schemaStack.push(schema);
return schema;
}
public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
LOG.debug("Enter yang modeled anyXml {}", name);
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof YangModeledAnyXmlSchemaNode,
"Node %s is not an yang modeled anyXml.", schema.getPath());
schemaStack.push(((YangModeledAnyXmlSchemaNode) schema).getSchemaOfAnyXmlData());
return schema;
}
public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
LOG.debug("Enter augmentation {}", identifier);
Object parent = getParent();
Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
if (parent instanceof ChoiceSchemaNode) {
final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
parent = findCaseByChild((ChoiceSchemaNode) parent, name);
}
Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
for (final DataSchemaNode child : schema.getChildNodes()) {
realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
}
final AugmentationSchema resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
schemaStack.push(resolvedSchema);
return resolvedSchema;
}
public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
return (AnyXmlSchemaNode)schema;
}
public Object endNode() {
return schemaStack.pop();
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// Init() - Initialization code for teleop mode
// should go here. Will be called each time the robot enters
// teleop mode.
// Periodic() - Periodic code for teleop mode should
// go here. Will be called periodically at a regular rate while
// the robot is in teleop mode.
// Team 339.
package org.usfirst.frc.team339.robot;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.Utils.Drive;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This class contains all of the user code for the Autonomous part of the
* match, namely, the Init and Periodic code
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Teleop
{
/**
* User Initialization code for teleop mode should go here. Will be called
* once when the robot enters teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
int control = 1;
public static void init ()
{
// initialize all encoders here
Hardware.leftFrontEncoder.reset();
Hardware.rightFrontEncoder.reset();
Hardware.rightRearEncoder.reset();
Hardware.leftRearEncoder.reset();
// initialize all motors here
Hardware.leftRearMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.leftFrontMotor.set(0.0);
// Hardware.rightFrontMotor.setInverted(true); // TODO takeout
// Hardware.rightRearMotor.setInverted(true);
// Hardware.leftFrontMotor.setInverted(true);
// Hardware.leftRearMotor.setInverted(true);
Hardware.mecanumDrive.setMecanumJoystickReversed(false);
// Hardware.tankDrive.setGear(1);
// Hardware.leftUS.setScalingFactor(.13);
// Hardware.leftUS.setOffsetDistanceFromNearestBummper(0);
// Sets the scaling factor and general ultrasonic stuff
Hardware.rightUS.setScalingFactor(.13);
Hardware.rightUS.setOffsetDistanceFromNearestBummper(3);
Hardware.rightUS.setNumberOfItemsToCheckBackwardForValidity(3);
// Hardware.leftUS.setNumberOfItemsToCheckBackwardForValidity(1);
// Hardware.LeftUS.setConfidenceCalculationsOn(false);
// Hardware.RightUS.setConfidenceCalculationsOn(false);
// Hardware.tankDrive.setRightMotorDirection(MotorDirection.REVERSED);
// boolean testchoosers = true;
// SendableChooser sendablechoosetest;
// sendablechoosetest = new SendableChooser();
// sendablechoosetest.addDefault("default", testchoosers);
// Sendable testsendable = ;
// SmartDashboard.putData("teleoptest", testsendable);
Hardware.tankDrive.setGear(1);
isAligning = false;
isStrafingToTarget = false;
Hardware.autoDrive.setDriveCorrection(.3);
Hardware.autoDrive.setEncoderSlack(1); // TODO
} // end Init
/**
* User Periodic code for teleop mode should go here. Will be called
* periodically at a regular rate while the robot is in teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
Command chooseTrueorFalse;
SendableChooser testbool;
testbool = new SendableChooser();
testbool.addDefault("true", Hardware.changeBool.equals(true));
testbool.addObject(" false", Hardware.changeBool.equals(false));
int control = 1;
SmartDashboard.putData("testbool", testbool);
switch (control)
{
case 1:
// System.out.println(Hardware.changeBool.getClass());
control = 1;
break;
case 2:
break;
}
if (Hardware.leftDriver.getTrigger() && !previousFireButton)
{
firing = !firing;
}
if (firing)
Hardware.shooter.fire();
// previousFireButton = Hardware.leftDriver.getTrigger();
// if (fireCount > 0)
// if (Hardware.shooter.fire())
// fireCount--;
if (preparingToFire == false)
Hardware.shooter.stopFlywheelMotor();
/*
* System.out.println("Firecount: " + fireCount);
*
* System.out.println(
* "Flywheel speed: " + Hardware.shooterMotor.getSpeed());
*/
// TODO Figure out why the ring light is flickering
if (Hardware.ringlightSwitch.isOnCheckNow())
{
Hardware.ringlightRelay.set(Relay.Value.kOn);
}
else
{
Hardware.ringlightRelay.set(Relay.Value.kOff);
}
// Hardware.gearServo.setAngle(200);
// Hardware.gearServo.getAngle();
// Print out any data we want from the hardware elements.
printStatements();
// TESTING CODE:
if (Hardware.rightOperator.getRawButton(2))
Hardware.intake.startIntake();
else if (Hardware.rightOperator.getRawButton(3))
Hardware.intake.reverseIntake();
else
Hardware.intake.stopIntake();
// Driving code
if (Hardware.leftDriver.getTrigger())
{
rotationValue = Hardware.leftDriver.getTwist();
System.out.println("Twist: " + Hardware.leftDriver.getTwist());
}
else
rotationValue = 0.0;
if (!isAligning && !isStrafingToTarget)// TODO remove isAccing
// stuff
{
if (Hardware.isUsingMecanum == true)
Hardware.mecanumDrive.drive(
Hardware.leftDriver.getMagnitude(),
Hardware.leftDriver.getDirectionDegrees(),
rotationValue);
else
Hardware.tankDrive.drive(Hardware.rightDriver.getY(),
Hardware.leftDriver.getY());
}
// CAMERA CODE
// "Cancel basically everything" button
// if (Hardware.leftOperator.getRawButton(7)
// || Hardware.leftOperator.getRawButton(6))
// System.out.println("Cancelling everything");
// isAligning = false;
// isStrafingToTarget = false;
// // Testing aligning to target
// if (Hardware.rightOperator.getRawButton(4))
// isAligning = true;
// if (isAligning)
// alignValue = Hardware.autoDrive.alignToGear(CAMERA_ALIGN_CENTER,
// movementSpeed, CAMERA_ALIGN_DEADBAND);
// if (alignValue == Drive.AlignReturnType.ALIGNED)
// System.out.println("We are aligned!");
// isAligning = false;
// else if (alignValue == Drive.AlignReturnType.MISALIGNED)
// System.out.println("We are not aligned!");
// else if (alignValue == Drive.AlignReturnType.NO_BLOBS)
// System.out.println("We don't see anything!");
// // Testing Strafe to target
// if (Hardware.rightOperator.getRawButton(8))
// isStrafingToTarget = true;
// if (isStrafingToTarget)
// alignValue = Hardware.autoDrive.strafeToGear(movementSpeed, .2,
// CAMERA_ALIGN_DEADBAND, CAMERA_ALIGN_CENTER, 20);
// if (alignValue == Drive.AlignReturnType.ALIGNED)
// System.out.println("We are aligned!");
// else if (alignValue == Drive.AlignReturnType.MISALIGNED)
// System.out.println("WE are NOT aligned!");
// else if (alignValue == Drive.AlignReturnType.NO_BLOBS)
// System.out.println("We have no blobs!");
// else if (alignValue == Drive.AlignReturnType.CLOSE_ENOUGH)
// System.out.println("We are good to go!");
// isStrafingToTarget = false;
// Testing good speed values
// if (Hardware.leftOperator.getRawButton(4) && !hasPressedFive)
// // adds .05 to movement speed then prints movementSpeed
// movementSpeed += .05;
// System.out.println(movementSpeed);
// hasPressedFour = Hardware.leftOperator.getRawButton(4);
// if (Hardware.leftOperator.getRawButton(5) && !hasPressedFour)
// // subtracts .05 from movement speed then prints movementSpeed
// movementSpeed -= .05;
// System.out.println(movementSpeed);
// hasPressedFive = Hardware.leftOperator.getRawButton(5);
Hardware.axisCamera
.takeSinglePicture(Hardware.leftOperator.getRawButton(8)
|| Hardware.rightOperator.getRawButton(8));
} // end
// Periodic
// private static boolean isSpeedTesting = false;
private static double rotationValue = 0.0;
private static Drive.AlignReturnType alignValue = Drive.AlignReturnType.MISALIGNED;
private static boolean isAligning = false;
private static boolean isStrafingToTarget = false;
private static double movementSpeed = 0.3;
private static boolean hasPressedFour = false;
private static boolean hasPressedFive = false;
private static boolean previousFireButton = false;
private static boolean preparingToFire = false;
private static boolean firing = false;
/**
* stores print statements for future use in the print "bank", statements
* are commented out when not in use, when you write a new print
* statement, "deposit" the statement in the correct "bank"
* do not "withdraw" statements, unless directed to.
*
* NOTE: Keep the groupings below, which coorespond in number and
* order as the hardware declarations in the HARDWARE class
*
* @author Ashley Espeland
* @written 1/28/16
*
* Edited by Ryan McGee
* Also Edited by Josef Liebl
*
*/
public static void printStatements ()
{
// Motor controllers
// prints value of the motors
// System.out.println("Right Front Motor Controller: "
// + Hardware.rightFrontMotor.get());
// System.out.println("Left Front Motor Controller: " +
// Hardware.leftFrontMotor.get());
// System.out.println("Right Rear Motor Controller: " +
// Hardware.rightRearMotor.get());
// System.out.println("Left Rear Motor Controller: " +
// Hardware.leftRearMotor.get());
// System.out
// .println("Flywheel Motor: " + Hardware.shooterMotor.get());
// System.out.println("Intake Motor: " + Hardware.intakeMotor.get());
if (Hardware.rightOperator.getRawButton(11))
{
Hardware.elevatorMotor.setSpeed(1);
System.out.println(
"Elevator Motor: " + Hardware.elevatorMotor.get());
}
// System.out.println("Turret Spark: " + Hardware.gimbalMotor.get());
// CAN items
// prints value of the CAN controllers
// Hardware.CAN.printAllPDPChannels();
// Relay
// prints value of the relay states
// if (Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is On");
// else if (!Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is Off");
// Digital Inputs
// Switches
// prints state of switches
// System.out.println("Gear Limit Switch: "
// + Hardware.gearLimitSwitch.isOn());
// System.out.println("Backup or fire: " + Hardware.backupOrFire.isOn());
// System.out.println("Enable Auto: " + Hardware.enableAutonomous.isOn());
// System.out.println(
// "Path Selector: " + Hardware.pathSelector.getPosition());
// Encoders
// prints the distance from the encoders
System.out.println("Right Front Encoder: "
+ Hardware.rightFrontEncoder.get());
System.out.println("Right Front Encoder Distance: "
+ Hardware.autoDrive.getRightRearEncoderDistance());
System.out.println("Right Rear Encoder: "
+ Hardware.rightRearEncoder.get());
System.out.println("Right Rear Encoder Distance: "
+ Hardware.autoDrive.getRightRearEncoderDistance());
System.out.println("Left Front Encoder: "
+ Hardware.leftFrontEncoder.get());
System.out.println("Left Front Encoder Distance: "
+ Hardware.autoDrive.getLeftFrontEncoderDistance());
System.out.println("Left Rear Encoder: "
+ Hardware.leftRearEncoder.get());
System.out.println("Left Rear Encoder Distance: "
+ Hardware.autoDrive.getLeftFrontEncoderDistance());
// Red Light/IR Sensors
// prints the state of the sensor
// if (Hardware.ballLoaderSensor.isOn() == true)
// System.out.println("Ball IR Sensor is On");
// else if (Hardware.ballLoaderSensor.isOn() == false)
// System.out.println("Ball IR Sensor is Off");
// Pneumatics
// Compressor
// prints information on the compressor
// There isn't one
// Solenoids
// prints the state of solenoids
// There are none
// Analogs
// We don't want the print statements to flood everything and go ahhhhhhhh
// if (Hardware.rightOperator.getRawButton(11))
// System.out.println("LeftUS = "
// + Hardware.leftUS.getDistanceFromNearestBumper());
// System.out.println("RightUS = "
// + Hardware.rightUS.getDistanceFromNearestBumper());
// System.out.println("Delay Pot: " + Hardware.delayPot.get());
// pots
// where the pot is turned to
// System.out.println("Delay Pot Degrees" + Hardware.delayPot.get());
// Connection Items
// Cameras
// prints any camera information required
// System.out.println("Expected center: " + CAMERA_ALIGN_CENTER);
// Hardware.imageProcessor.processImage();
// System.out.println("Number of blobs: " + Hardware.imageProcessor
// .getParticleAnalysisReports().length);
// if (Hardware.imageProcessor.getNthSizeBlob(1) != null)
// System.out
// .println("Actual center: " + ((Hardware.imageProcessor
// .getNthSizeBlob(0).center_mass_x
// + Hardware.imageProcessor
// .getNthSizeBlob(1).center_mass_x)
// / Hardware.axisCamera
// .getHorizontalResolution());
// System.out.println("Deadband: " + CAMERA_ALIGN_DEADBAND);
// Driver station
// Joysticks
// information about the joysticks
// System.out.println("Left Joystick: " +
// Hardware.leftDriver.getDirectionDegrees());
// System.out.println("Twist: " + Hardware.leftDriver.getTwist());
// System.out.println("Left Joystick: " + Hardware.leftDriver.getY());
// System.out.println("Right Joystick: " + Hardware.rightDriver.getY());
// System.out.println("Left Operator: " + Hardware.leftOperator.getY());
// System.out.println("Right Operator: " + Hardware.rightOperator.getY());
// Kilroy ancillary items
// timers
// what time does the timer have now
} // end printStatements
private final static double CAMERA_ALIGN_SPEED = .5;
//// The dead zone for the aligning TODO
private final static double CAMERA_ALIGN_DEADBAND = 10.0 // +/- Pixels
/ Hardware.axisCamera.getHorizontalResolution();
private final static double CAMERA_ALIGN_CENTER = .478; // Relative coordinates
// TUNEABLES
} // end class
|
package org.usfirst.frc.team4536.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Timer;
public class Robot extends IterativeRobot {
// Robot Systems
DriveTrain driveTrain;
Platform platform;
Tipper tipper;
Elevator elevator;
Timer teleopTimer;
Timer autoTimer;
Auto auto;
int autoNumber;
DigitalInput toteLimitSwitch;
Compressor compressor;
// Joysticks
Joystick mainStick;
Joystick secondaryStick;
// Previous values used for toggles for the platform and tipper
boolean prevPlatformControllingButton;
boolean prevTipperControllingButton;
// This value is necessary for our acceleration limit on the elevator
double prevElevatorThrottle;
double prevThrottleY = 0;
double prevThrottleX = 0;
double finalThrottleY = 0;
double finalThrottleX = 0;
public void robotInit() {
// Robot Systems
driveTrain = new DriveTrain(Constants.LEFT_TALON_CHANNEL,
Constants.RIGHT_TALON_CHANNEL);
driveTrain.startGyro();
platform = new Platform(Constants.RIGHT_PLATFORM_SOLENOID_CHANNEL, Constants.LEFT_PLATFORM_SOLENOID_CHANNEL);
platform.retract();
tipper = new Tipper(Constants.RIGHT_TIPPER_SOLENOID_CHANNEL, Constants.LEFT_TIPPER_SOLENOID_CHANNEL);
tipper.retract();
elevator = new Elevator(Constants.ELEVATOR_MOTOR_CHANNEL,
Constants.ENCODER_SENSOR_A_CHANNEL,
Constants.ENCODER_SENSOR_B_CHANNEL,
Constants.TOP_LIMIT_SWITCH_CHANNEL,
Constants.MIDDLE_LIMIT_SWITCH_CHANNEL,
Constants.BOTTOM_LIMIT_SWITCH_CHANNEL);
elevator.setActualHeight(0);
teleopTimer = new Timer();
teleopTimer.start();
// Joysticks
mainStick = new Joystick(Constants.LEFT_STICK_PORT);
secondaryStick = new Joystick(Constants.RIGHT_STICK_PORT);
compressor = new Compressor();
// Previous values used for toggles for the platform and tipper
prevPlatformControllingButton = false;
prevTipperControllingButton = false;
// This value is necessary for our acceleration limit on the elevator
prevElevatorThrottle = 0;
toteLimitSwitch = new DigitalInput(Constants.TOTE_LIMIT_SWITCH_CHANNEL);
autoTimer = new Timer();
auto = new Auto(driveTrain, elevator);
//This gets the stuff on the SmartDashboard, it's like a dummy variable. Ask and I shall explain more
autoNumber = (int) auto.autoNumber();
}
public void autonomousInit() {
compressor.start();
autoTimer.reset();
autoTimer.start();
}
public void autonomousPeriodic() {
//driveTrain.turnTo(90, Constants.AUTO_TURN_FULL_SPEED_TIME);
/*driveTrain.driveStraight(0.5, 0, Constants.AUTO_TURN_FULL_SPEED_TIME);
System.out.println(driveTrain.gyroGetAngle());*/
double autoTime = autoTimer.get();
//Can't have autoNumber since that would be the value when the code's deployed
switch ((int) auto.autoNumber()){
case 1: auto.driveForward(autoTime);
break;
case 2: auto.driveForwardWithRecyclingContainer(autoTime);
break;
case 3: auto.driveForwardPushingTote(autoTime);
break;
case 4: auto.twoTote(autoTime);
break;
case 5: auto.twoRecyclingContainers(autoTime);
break;
case 6: auto.doNothing();
break;
default: auto.doNothing();
break;
}
}
public void teleopInit() {
compressor.start();
teleopTimer.reset();
}
public void teleopPeriodic() {
// Gets X and Y values from mainStick and puts a dead zone on them
double mainStickY = Utilities.deadZone(-mainStick.getY(), Constants.DEAD_ZONE);
double mainStickX = Utilities.deadZone(-mainStick.getX(), Constants.DEAD_ZONE);
//driveTrain.driveStraight(-0.5, 0, Constants.AUTO_TURN_FULL_SPEED_TIME);
//System.out.println(driveTrain.gyroGetAngle());
/*
* If the tipper (back piston) is extended, we don't want the driver to have full driving ability
*/
if(mainStick.getRawButton(7)) {
if(elevator.getHeight() < Constants.TOP_LIMIT_SWITCH_HEIGHT - 0.5
|| elevator.getHeight() > Constants.TOP_LIMIT_SWITCH_HEIGHT + 0.5) {
tipper.extend();
if(tipper.timeExtended() > 1) {
elevator.setDesiredHeight(Constants.TOP_LIMIT_SWITCH_HEIGHT);
}
}
else {
tipper.retract();
}
}
else {
// If button 4 on the main stick is pressed slow mode is enabled
if(mainStick.getRawButton(4) == true) {
// Multiplying by the speed limit puts a speed limit on the forward and turn throttles
double throttleY = Utilities.speedCurve(mainStickY, Constants.SLOW_FORWARD_SPEED_CURVE) * Constants.SLOW_FORAWRD_SPEED_LIMIT;
double throttleX = Utilities.speedCurve(-mainStickX, Constants.SLOW_TURN_SPEED_CURVE) * Constants.SLOW_TURN_SPEED_LIMIT;
finalThrottleY = Utilities.accelLimit(Constants.SLOW_FORWARD_FULL_SPEED_TIME, throttleY, prevThrottleY);
finalThrottleX = Utilities.accelLimit(Constants.SLOW_TURN_FULL_SPEED_TIME, throttleX, prevThrottleX);
prevThrottleY = finalThrottleY;
prevThrottleX = finalThrottleX;
}
else {
double throttleY = Utilities.speedCurve(mainStickY, Constants.FORWARD_SPEED_CURVE) * Constants.FORWARD_SPEED_LIMIT;
double throttleX = Utilities.speedCurve(-mainStickX, Constants.TURN_SPEED_CURVE) * Constants.TURN_FULL_SPEED_TIME;
finalThrottleY = Utilities.accelLimit(Constants.FORWARD_FULL_SPEED_TIME, throttleY, prevThrottleY);
finalThrottleX = Utilities.accelLimit(Constants.TURN_FULL_SPEED_TIME, throttleX, prevThrottleX);
prevThrottleY = finalThrottleY;
prevThrottleX = finalThrottleX;
}
driveTrain.drive(finalThrottleY, finalThrottleX);
}
// Uses button 3 on the main stick as a toggle for the platform
if(secondaryStick.getRawButton(5) == true && prevPlatformControllingButton == false) {
platform.flip();
}
prevPlatformControllingButton = secondaryStick.getRawButton(5);
// Uses button 2 on the main stick as a toggle for the tipper
if(mainStick.getRawButton(2) == true && prevTipperControllingButton == false) {
tipper.flip();
}
prevTipperControllingButton = mainStick.getRawButton(2);
// Gets Y value from secondaryStick and puts a dead zone on it
double secondaryStickY = Utilities.deadZone(secondaryStick.getY(), Constants.DEAD_ZONE);
// Puts a speed curve on the Y value from the secondaryStick
secondaryStickY = Utilities.speedCurve(secondaryStickY, Constants.ELEVATOR_SPEED_CURVE);
// Sets the elevator throttle as the secondary stick Y value (with dead zone and speed curve)
double elevatorThrottle = secondaryStickY;
elevatorThrottle = Utilities.accelLimit(Constants.ELEVATOR_FULL_SPEED_TIME, elevatorThrottle, prevElevatorThrottle);
if(secondaryStick.getRawButton(1) && !toteLimitSwitch.get()) {
if ((elevator.getHeight() < Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION - 0.5
|| elevator.getHeight() > Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION + 4)
&& elevator.getDesiredHeight() != Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION){
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION);
}
else if (elevator.getHeight() >= Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION - 0.5
&& elevator.getHeight() <= Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION + 0.5
&& elevator.getDesiredHeight() != Constants.ELEVATOR_HEIGHT_FOR_A_TOTE_ABOVE_FEEDER_STATION){
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_A_TOTE_ABOVE_FEEDER_STATION);
}
}
//Automation of setting tote stack then backing up
/*
if (mainStick.getRawButton(11) == true) {
} */
/*if (teleopTimer.get() > 133){
tipper.extend();
elevator.setHeight(0);
}*/
else if(secondaryStick.getRawButton(3)) {
elevator.setDesiredHeight(elevator.getHeight() + Constants.ELEVATOR_HEIGHT_FOR_ONE_TOTE);
}
else if(secondaryStick.getRawButton(2)) {
elevator.setDesiredHeight(elevator.getHeight() - Constants.ELEVATOR_HEIGHT_FOR_ONE_TOTE);
}
else if(secondaryStick.getRawButton(4)) {
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_SCORING_PLATFORM);
}
else if(secondaryStick.getRawButton(8)) {
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_STEP);
}
else if(secondaryStick.getRawButton(11)) {
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_A_TOTE_ABOVE_FEEDER_STATION);
}
else if(secondaryStick.getRawButton(10)) {
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_BOTTOM_OF_FEEDER_STATION);
}
else if(secondaryStick.getRawButton(7)) {
elevator.setDesiredHeight(Constants.ELEVATOR_HEIGHT_FOR_RECYCLING_CONTAINER_PICKING_OFF_THE_GROUND);
}
else if(secondaryStick.getRawButton(9)) {
}
/*
* This is code for the override button. When button 6 is pressed it allows the secondary
* driver to manually drive the elevator with the joystick. In this case you need to set the
* desired height as the current height so that it doesn't recoil to the previous desired height
* when the driver lets off of the button.
*/
if (secondaryStick.getRawButton(6)){
elevator.drive(elevatorThrottle);
elevator.setDesiredHeight(elevator.getHeight());
}
else elevator.goToDesiredHeight();
prevElevatorThrottle = elevatorThrottle;
elevator.update();
System.out.println(elevator.getHeight());
}
public void disabledInit() {
System.out.println("DISABLED");
compressor.stop();
teleopTimer.stop();
}
public void disabledPeriodic() {
driveTrain.resetGyro();
}
public void testPeriodic() {
}
}
|
// Util.java
// AdjustIo
package com.adeven.adjustio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
public class Util {
private static final String BASEURL = "http://app.adjust.io";
private static final String CLIENTSDK = "android1.1";
public static String getBase64EncodedParameters(
Map<String, String> parameters) {
if (parameters == null) {
return null;
}
JSONObject jsonObject = new JSONObject(parameters);
String jsonString = jsonObject.toString();
String encoded = Base64.encodeToString(jsonString.getBytes(),
Base64.DEFAULT);
return encoded;
}
public static StringEntity getEntityEncodedParameters(String... parameters)
throws UnsupportedEncodingException {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i + 1 < parameters.length; i += 2) {
String key = parameters[i];
String value = parameters[i + 1];
if (value != null) {
pairs.add(new BasicNameValuePair(key, value));
}
}
StringEntity entity = new UrlEncodedFormEntity(pairs);
return entity;
}
public static HttpClient getHttpClient(String userAgent) {
HttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
params.setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
return httpClient;
}
public static HttpPost getPostRequest(String path) {
String url = BASEURL + path;
HttpPost request = new HttpPost(url);
String language = Locale.getDefault().getLanguage();
request.addHeader("Accept-Language", language);
request.addHeader("Client-SDK", CLIENTSDK);
return request;
}
protected static String getUserAgent(Application app) {
Resources resources = app.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
Locale locale = configuration.locale;
int screenLayout = configuration.screenLayout;
StringBuilder builder = new StringBuilder();
builder.append(getPackageName(app));
builder.append(" " + getAppVersion(app));
builder.append(" " + getDeviceType(screenLayout));
builder.append(" " + getDeviceName());
builder.append(" " + getOsName());
builder.append(" " + getOsVersion());
builder.append(" " + getLanguage(locale));
builder.append(" " + getCountry(locale));
builder.append(" " + getScreenSize(screenLayout));
builder.append(" " + getScreenFormat(screenLayout));
builder.append(" " + getScreenDensity(displayMetrics));
builder.append(" " + getDisplayWidth(displayMetrics));
builder.append(" " + getDisplayHeight(displayMetrics));
String userAgent = builder.toString();
return userAgent;
}
private static String getPackageName(Application app) {
String packageName = app.getPackageName();
String sanitized = sanitizeString(packageName);
return sanitized;
}
private static String getAppVersion(Application app) {
try {
PackageManager packageManager = app.getPackageManager();
String name = app.getPackageName();
PackageInfo info = packageManager.getPackageInfo(name, 0);
String versionName = info.versionName;
String result = sanitizeString(versionName);
return result;
} catch (NameNotFoundException e) {
return "unknown";
}
}
private static String getDeviceType(int screenLayout) {
int screenSize = screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenSize) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return "phone";
case Configuration.SCREENLAYOUT_SIZE_LARGE:
case 4:
return "tablet";
default:
return "unknown";
}
}
private static String getDeviceName() {
String deviceName = Build.MODEL;
String sanitized = sanitizeString(deviceName);
return sanitized;
}
private static String getOsName() {
return "android";
}
private static String getOsVersion() {
String osVersion = "" + Build.VERSION.SDK_INT;
String sanitized = sanitizeString(osVersion);
return sanitized;
}
private static String getLanguage(Locale locale) {
String language = locale.getLanguage();
String sanitized = sanitizeString(language, "zz");
return sanitized;
}
private static String getCountry(Locale locale) {
String country = locale.getCountry();
String sanitized = sanitizeString(country, "zz");
return sanitized;
}
private static String getScreenSize(int screenLayout) {
int screenSize = screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenSize) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
return "small";
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return "normal";
case Configuration.SCREENLAYOUT_SIZE_LARGE:
return "large";
case 4:
return "xlarge";
default:
return "unknown";
}
}
private static String getScreenFormat(int screenLayout) {
int screenFormat = screenLayout & Configuration.SCREENLAYOUT_LONG_MASK;
switch (screenFormat) {
case Configuration.SCREENLAYOUT_LONG_YES:
return "long";
case Configuration.SCREENLAYOUT_LONG_NO:
return "normal";
default:
return "unknown";
}
}
private static String getScreenDensity(DisplayMetrics displayMetrics) {
int density = displayMetrics.densityDpi;
int low = (DisplayMetrics.DENSITY_MEDIUM + DisplayMetrics.DENSITY_LOW) / 2;
int high = (DisplayMetrics.DENSITY_MEDIUM + DisplayMetrics.DENSITY_HIGH) / 2;
if (density == 0) {
return "unknown";
} else if (density < low) {
return "low";
} else if (density > high) {
return "high";
} else {
return "medium";
}
}
private static String getDisplayWidth(DisplayMetrics displayMetrics) {
String displayWidth = String.valueOf(displayMetrics.widthPixels);
String sanitized = sanitizeString(displayWidth);
return sanitized;
}
private static String getDisplayHeight(DisplayMetrics displayMetrics) {
String displayHeight = String.valueOf(displayMetrics.heightPixels);
String sanitized = sanitizeString(displayHeight);
return sanitized;
}
protected static String getMacAddress(Application app) {
String address = null;
// android devices should have a wlan address
if (address == null) {
address = loadAddress("wlan0");
}
// emulators should have an ethernet address
if (address == null) {
address = loadAddress("eth0");
}
String sanitized = sanitizeString(address);
Log.d("mac", sanitized);
return sanitized;
}
// removes spaces and replaces empty string with "unknown"
private static String sanitizeString(String string) {
return sanitizeString(string, "unknown");
}
private static String sanitizeString(String string, String defaultString) {
if (string == null) {
string = defaultString;
}
String result = string.replaceAll("\\s", "");
if (result.length() == 0) {
result = defaultString;
}
return result;
}
public static String loadAddress(String interfaceName) {
try {
String filePath = "/sys/class/net/" + interfaceName + "/address";
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader;
reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
String string = fileData.toString();
String address = string.replaceAll(":", "").toUpperCase();
return address;
} catch (IOException e) {
return null;
}
}
}
|
package alien4cloud.deployment.matching.services.nodes;
import static alien4cloud.utils.AlienUtils.safe;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.alien4cloud.tosca.model.definitions.constraints.IMatchPropertyConstraint;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.types.CapabilityType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.springframework.stereotype.Component;
import alien4cloud.deployment.matching.plugins.INodeMatcherPlugin;
import alien4cloud.model.deployment.matching.MatchingConfiguration;
import alien4cloud.model.deployment.matching.MatchingFilterDefinition;
import alien4cloud.model.orchestrators.locations.LocationResourceTemplate;
import alien4cloud.model.orchestrators.locations.LocationResources;
import lombok.extern.slf4j.Slf4j;
/**
* Default implementation of INodeMatcherPlugin to be used when no matching plugin has been defined.
*/
@Slf4j
@Component
public class DefaultNodeMatcher extends AbstractTemplateMatcher<LocationResourceTemplate, NodeTemplate, NodeType> implements INodeMatcherPlugin {
/**
* Match a node against a location.
*
* @param nodeTemplate The node template to match.
* @param nodeType The node type that defines the type of the node template to match.
* @param locationResources The resources configured for the location against which we are matching the nodes.
*/
public List<LocationResourceTemplate> matchNode(NodeTemplate nodeTemplate, NodeType nodeType, LocationResources locationResources,
Map<String, MatchingConfiguration> matchingConfigurations) {
return super.match(nodeTemplate, nodeType, locationResources.getNodeTemplates(), locationResources.getNodeTypes(), locationResources,
matchingConfigurations);
}
@Override
protected boolean typeSpecificMatching(NodeTemplate abstractTemplate, LocationResourceTemplate candidate, NodeType candidateType,
LocationResources locationResources, MatchingConfiguration matchingConfiguration) {
for (Entry<String, Capability> candidateCapability : safe(candidate.getTemplate().getCapabilities()).entrySet()) {
MatchingFilterDefinition configuredFilterDefinition = matchingConfiguration == null ? null
: safe(matchingConfiguration.getCapabilities()).get(candidateCapability.getKey());
Map<String, List<IMatchPropertyConstraint>> configuredFilters = configuredFilterDefinition == null ? null
: configuredFilterDefinition.getProperties();
CapabilityType capabilityType = locationResources.getCapabilityTypes().get(candidateCapability.getValue().getType());
Capability templateCapability = safe(abstractTemplate.getCapabilities()).get(candidateCapability.getKey());
if (templateCapability != null && !isValidTemplatePropertiesMatch(templateCapability.getProperties(),
candidateCapability.getValue().getProperties(), capabilityType.getProperties(), configuredFilters)) {
return false;
}
}
return true;
}
}
|
package org.usfirst.frc.team4914.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 java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.usfirst.frc.team4914.robot.commands.ExampleCommand;
import org.usfirst.frc.team4914.robot.subsystems.ExampleSubsystem;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* 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 ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static OI oi;
public static Properties config = new Properties();
Command autonomousCommand;
SendableChooser chooser;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
oi = new OI();
chooser = new SendableChooser();
chooser.addDefault("Default Auto", new ExampleCommand());
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
// Imports all the config variables
try {
config.load(new FileInputStream("config.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 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.
*/
public void disabledInit(){
}
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.
*/
public void autonomousInit() {
autonomousCommand = (Command) 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
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
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
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
|
package org.sbolstandard.core2;
import static org.sbolstandard.core2.URIcompliance.createCompliantURI;
import static org.sbolstandard.core2.URIcompliance.isChildURIcompliant;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Represents a CombinatorialDerivation object in the SBOL data model.
*
* @author Zach Zundel
* @author Igor Durovic
* @version 2.1
*/
public class CombinatorialDerivation extends TopLevel {
private URI template;
private StrategyType strategy;
private HashMap<URI, VariableComponent> variableComponents;
/**
* @param identity
* @param template
* @param strategy
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in the following
* constructor or method:
* <ul>
* <li>{@link TopLevel#TopLevel(URI)}, or</li>
* </ul>
*/
public CombinatorialDerivation(URI identity, URI template, StrategyType strategy) throws SBOLValidationException {
super(identity);
this.template = template;
this.strategy = strategy;
this.variableComponents = new HashMap<>();
}
/**
* @param componentDefinition
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in any of the
* following constructors or methods:
* <ul>
* <li>{@link TopLevel#TopLevel(TopLevel)},</li>
* <li>{@link #addVariableComponent(VariableComponent)},</li>
* <li>{@link VariableComponent#deepCopy()}</li>
* </ul>
*/
private CombinatorialDerivation(CombinatorialDerivation combinatorialDerivation) throws SBOLValidationException {
super(combinatorialDerivation);
this.variableComponents = new HashMap<>();
for (VariableComponent variableComponent : combinatorialDerivation.getVariableComponents()) {
this.addVariableComponent(variableComponent.deepCopy());
}
}
/**
* Checks if the strategy property is set.
*
* @return {@code true} if it is not {@code null}, {@code false} otherwise
*/
public boolean isSetStrategy() {
return strategy != null;
}
/**
* Adds the given variable component to the list of variable components.
*
* @param variableComponent
*/
private void addVariableComponent(VariableComponent variableComponent) throws SBOLValidationException {
variableComponent.setSBOLDocument(this.getSBOLDocument());
variableComponent.setCombinatorialDerivation(this);
//TODO:
/*if (this.getSBOLDocument() != null && this.getSBOLDocument().isComplete()) {
if (variableComponent.getVariable() == null) {
throw new SBOLValidationException("sbol-XXXXX", variableComponent);
}
}*/
for (CombinatorialDerivation cd : variableComponent.getVariants()) {
Set<URI> visited = new HashSet<>();
visited.add(this.getIdentity());
try {
//TODO:
SBOLValidate.checkCombinatorialDerivationCycle(this.getSBOLDocument(), cd, visited);
} catch (SBOLValidationException e) {
throw new SBOLValidationException("sbol-XXXXX", variableComponent);
}
}
addChildSafely(variableComponent, variableComponents, "variableComponent");
}
/**
* Removes the given variable component from the list of variable components.
*
* @param variableComponent the given variable component
* @return {@code true} if the matching variable component was removed successfully,
* {@code false} otherwise.
* @throws SBOLValidationException if any of the following SBOL validation rules were violated:
* 10803, 10808, 10905, 11402, 11404,
*/
public boolean removeVariableComponent(VariableComponent variableComponent) throws SBOLValidationException {
return removeChildSafely(variableComponent, variableComponents);
}
/**
* Returns the instance matching the given variable component's identity URI.
*
* @param variableComponentURI
* the identity URI of the variable component to be retrieved
* @return the matching variable component if present, or {@code null}
* otherwise.
*/
public VariableComponent getVariableComponent(URI variableComponentURI) {
return this.variableComponents.get(variableComponentURI);
}
/**
* Returns the variable component matching the given variable component's
* display ID.
* <p>
* This method first creates a compliant URI for the variable component to be
* retrieved. It starts with this combinatorial derivation's persistent
* identity, followed by the given variable component's display ID, and ends
* with this combinatorial derivation's version.
*
* @param displayId
* the display ID of the variable component to be retrieved
* @return the matching variable component if present, or {@code null}
* otherwise.
*/
public VariableComponent getVariableComponent(String displayId) {
try {
return variableComponents
.get(createCompliantURI(this.getPersistentIdentity().toString(), displayId, this.getVersion()));
} catch (SBOLValidationException e) {
return null;
}
}
/**
* Returns the set of variable components owned by this combinatorial
* derivation.
*
* @return the set of variable components owned by this combinatorial
* derivation.
*/
public Set<VariableComponent> getVariableComponents() {
Set<VariableComponent> variableComponents = new HashSet<>();
variableComponents.addAll(this.variableComponents.values());
return variableComponents;
}
/**
* Removes all entries of this combinatorial derivation's list of variable
* components. The list will be empty after this call returns.
* <p>
* This method calls
* {@link #removeVariableComponent(VariableComponent variableComponent)} to
* iteratively remove each variable component.
*
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in
* {@link #removeVariableComponent(VariableComponent)}.
*/
public void clearVariableComponents() throws SBOLValidationException {
Object[] valueSetArray = variableComponents.values().toArray();
for (Object variableComponent : valueSetArray) {
removeVariableComponent((VariableComponent) variableComponent);
}
}
/**
* @param variableComponents
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in any of the
* following methods:
* <ul>
* <li>{@link #clearVariableComponents()}</li>
* <li>{@link #addVariableComponentNoCheck(VariableComponent)},
* or</li>
* <li>{@link #checkMapsTosLocalURIs()}.</li>
* </ul>
*/
public void setVariableComponents(Set<VariableComponent> variableComponents) {
this.variableComponents.clear();
for (VariableComponent variableComponent : variableComponents) {
this.variableComponents.put(variableComponent.getIdentity(), variableComponent);
}
}
void copy(CombinatorialDerivation combinatorialDerivation) throws SBOLValidationException {
((TopLevel) this).copy((TopLevel) combinatorialDerivation);
for (VariableComponent variableComponent : combinatorialDerivation.getVariableComponents()) {
String displayId = variableComponent.getDisplayId();
if (displayId == null) {
displayId = URIcompliance.extractDisplayId(variableComponent.getIdentity());
}
this.createVariableComponent(variableComponent.getIdentity(), variableComponent.getOperator(),
variableComponent.getVariable());
}
this.setTemplate(combinatorialDerivation.getTemplateURI());
this.setStrategy(combinatorialDerivation.getStrategy());
}
/**
* Creates a child variable component instance for this combinatorial derivation
* instance with the given arguments, and then adds to this combinatorial
* derivation's list of variable component instances.
*
* @param identity
* the identifier for this instance
* @param operator
* indicates the operator type of the variable component
* @param variable
* the component referenced by the variable component
* @return a variable component instance
* @throws SBOLValidationException
* if either of the following condition is satisfied:
* <ul>
* <li>an SBOL validation rule violation occurred in
* {@link VariableComponent#VariableComponent(URI, OperatorType, URI)}</li>
* <li>an SBOL validation rule violation occurred in
* {@link #addVariableComponent(VariableComponent)}</li>
* </ul>
*/
private VariableComponent createVariableComponent(URI identity, OperatorType operator, URI variable)
throws SBOLValidationException {
VariableComponent newVariableComponent = new VariableComponent(identity, variable, operator);
this.addVariableComponent(newVariableComponent);
return null;
}
/**
* Creates a child variable component for this combinatorial derivation with the
* given arguments, and then adds to this combinatorial derivation's list of
* variable components.
* <p>
* This method first creates a compliant URI for the child variable component to
* be created. This URI starts with this combinatorial derivation's persistent
* identity, followed by the given display ID and ends with this combinatorial
* derivation's version.
*
* @param displayId
* the display ID for the variable component to be created
* @param operator
* the operator property for the variable component to be created
* @param variableURI
* the URI of the component referenced by the variable component to
* be created
* @return the created variable component
* @throws SBOLValidationException
* if any of the following SBOL validation rules was violated: TODO:
* 10201, 10202, 10204, 10206, 10602, 10604, 10605, 10607, 10803.
*/
public VariableComponent createVariableComponent(String displayId, OperatorType operator, URI variableURI)
throws SBOLValidationException {
// TODO:
/*
* if (this.getSBOLDocument() != null && this.getSBOLDocument().isComplete()) {
* if (this.getSBOLDocument().getComponentDefintion(template).getComponent(variableURI) == null) { throw new
* SBOLValidationException("sbol-XXXXX", this); } }
*/
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
VariableComponent c = createVariableComponent(createCompliantURI(URIprefix, displayId, version), operator,
variableURI);
c.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
c.setDisplayId(displayId);
c.setVersion(version);
return c;
}
/**
* Returns the reference component definition URI.
*
* @return the reference component definition URI
*/
public URI getTemplateURI() {
return template;
}
/**
* Returns the component definition identity referenced by this combinatorial
* derivation.
*
* @return {@code null} if the associated SBOLDocument instance is {@code null}
* or no matching component definition referenced by this combinatorial
* derivation exists; or the matching component definition otherwise.
*/
public URI getTemplateIdentity() {
if (this.getSBOLDocument() == null)
return null;
if (this.getSBOLDocument().getComponentDefinition(template) == null)
return null;
return this.getSBOLDocument().getComponentDefinition(template).getIdentity();
}
/**
* Returns the component definition referenced by this combinatorial derivation.
*
* @return {@code null} if the associated SBOLDocument instance is {@code null}
* or no matching component definition referenced by this combinatorial
* derivation; or the matching component definition otherwise.
*/
public ComponentDefinition getTemplate() {
if (this.getSBOLDocument() == null)
return null;
return this.getSBOLDocument().getComponentDefinition(template);
}
/**
* Sets the template property to the given one.
*
* @param template
* the given template URI to set to
* @throws SBOLValidationException
* if either of the following SBOL validation rules was violated:
* TODO: 10602, 10604.
*/
public void setTemplate(URI template) throws SBOLValidationException {
this.template = template;
if (template == null) {
throw new SBOLValidationException("sbol-XXXXX", this);
}
if (this.getSBOLDocument() != null && this.getSBOLDocument().isComplete()) {
if (this.getSBOLDocument().getComponentDefinition(template) == null) {
throw new SBOLValidationException("sbol-XXXXX", this);
}
}
this.template = template;
}
/**
* Returns the strategy property.
*
* @return the strategy property
*/
public StrategyType getStrategy() {
return this.strategy;
}
/**
* Sets the strategy property to the given one.
*
* @param strategy
* the given strategy type to set to
* @throws SBOLValidationException
* if the following SBOL validation rule was violated: TODO: 10607
*/
public void setStrategy(StrategyType strategy) throws SBOLValidationException {
if (strategy == null) {
throw new SBOLValidationException("sbol-XXXXX", this);
}
this.strategy = strategy;
}
/**
* Sets the strategy property of this combinatorial derivation to {@code null}.
*/
public void unsetStrategy() {
this.strategy = null;
}
/**
* @throws SBOLValidationException
* an SBOL validation rule violation occurred in either of the
* following methods:
* <ul>
* <li>{@link URIcompliance#isTopLevelURIformCompliant(URI)},
* or</li>
* <li>{@link URIcompliance#isChildURIcompliant(Identified, Identified)}.</li>
* </ul>
*/
@Override
public void checkDescendantsURIcompliance() throws SBOLValidationException {
if (!variableComponents.isEmpty()) {
for (VariableComponent variableComponent : variableComponents.values()) {
try {
isChildURIcompliant(this, variableComponent);
} catch (SBOLValidationException e) {
throw new SBOLValidationException(e.getRule(), variableComponent);
}
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode() * prime;
for (Entry<URI, VariableComponent> entry : this.variableComponents.entrySet()) {
result *= entry.getValue().hashCode();
result *= entry.getKey().hashCode();
}
result *= this.template != null ? this.template.hashCode() : 1;
result *= this.strategy != null ? this.strategy.hashCode() : 1;
return result;
}
/*
* (non-Javadoc)
*
* @see
* org.sbolstandard.core2.abstract_classes.Documented#equals(java.lang.Instance)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
CombinatorialDerivation other = (CombinatorialDerivation) obj;
if (strategy != other.strategy)
return false;
if (template == null) {
if (other.template != null)
return false;
} else if (!template.equals(other.template)) {
if (getTemplateIdentity() == null || other.getTemplateIdentity() == null
|| !getTemplateIdentity().equals(other.getTemplateIdentity())) {
return false;
}
}
if (variableComponents == null) {
if (other.variableComponents != null)
return false;
} else if (!variableComponents.equals(other.variableComponents))
return false;
return true;
}
/**
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in any of the
* following constructors or methods:
* <ul>
* <li>{@link #deepCopy()},</li>
* <li>{@link URIcompliance#createCompliantURI(String, String, String)},</li>
* <li>{@link #setDisplayId(String)},</li>
* <li>{@link #setVersion(String)},</li>
* <li>{@link #setWasDerivedFrom(URI)},</li>
* <li>{@link #setIdentity(URI)}</li>
* <li>{@link VariableComponent#setDisplayId(String)}</li>
* <li>{@link VariableComponent#updateCompliantURI(String, String, String)},</li>
* <li>{@link #addVariableComponent(VariableComponent)},</li>
* </ul>
*/
@Override
CombinatorialDerivation copy(String URIprefix, String displayId, String version) throws SBOLValidationException {
CombinatorialDerivation combinatorialDerivation = this.getDocument().getCombinatorialDerivation(URIprefix,
displayId, version);
CombinatorialDerivation cloned = this.deepCopy();
cloned.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
cloned.setDisplayId(displayId);
cloned.setVersion(version);
URI newIdentity = createCompliantURI(URIprefix, displayId, version);
if (!this.getIdentity().equals(newIdentity)) {
cloned.addWasDerivedFrom(this.getIdentity());
} else {
cloned.setWasDerivedFroms(this.getWasDerivedFroms());
}
cloned.setIdentity(newIdentity);
int count = 0;
for (VariableComponent variableComponent : cloned.getVariableComponents()) {
if (!variableComponent.isSetDisplayId())
variableComponent.setDisplayId("variableComponent" + ++count);
// TODO: does VariableComponent need updateCompliantURI()?
variableComponent.updateCompliantURI(cloned.getPersistentIdentity().toString(),
variableComponent.getDisplayId(), version);
cloned.removeChildSafely(variableComponent, cloned.variableComponents);
cloned.addVariableComponent(variableComponent);
}
return cloned;
}
@Override
/**
* @throws SBOLValidationException
* if an SBOL validation rule violation occurred in
* {@link #CombinatorialDerivation(CombinatorialDerivation)}.
*/
CombinatorialDerivation deepCopy() throws SBOLValidationException {
return new CombinatorialDerivation(this);
}
@Override
public String toString() {
return "CombinatorialDerivation [" + super.toString()
+ (this.getStrategy() != null ? ", strategy=" + this.getStrategy() : "") + ", template="
+ this.getTemplateURI()
+ (this.getVariableComponents().size() > 0 ? ", variableComponents=" + this.getVariableComponents()
: "")
+ "]";
}
}
|
package com.atlassian.plugin.servlet;
import static com.atlassian.plugin.servlet.descriptors.ServletFilterModuleDescriptor.byWeight;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import com.atlassian.plugin.servlet.filter.FilterDispatcherCondition;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.event.PluginEventListener;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.events.PluginDisabledEvent;
import com.atlassian.plugin.servlet.descriptors.ServletContextListenerModuleDescriptor;
import com.atlassian.plugin.servlet.descriptors.ServletContextParamModuleDescriptor;
import com.atlassian.plugin.servlet.descriptors.ServletFilterModuleDescriptor;
import com.atlassian.plugin.servlet.descriptors.ServletModuleDescriptor;
import com.atlassian.plugin.servlet.filter.DelegatingPluginFilter;
import com.atlassian.plugin.servlet.filter.FilterLocation;
import com.atlassian.plugin.servlet.filter.PluginFilterConfig;
import com.atlassian.plugin.servlet.util.DefaultPathMapper;
import com.atlassian.plugin.servlet.util.PathMapper;
import com.atlassian.plugin.servlet.util.ServletContextServletModuleManagerAccessor;
import com.atlassian.plugin.util.ClassLoaderStack;
import com.atlassian.util.concurrent.LazyReference;
/**
* A simple servletModuleManager to track and retrieve the loaded servlet plugin
* modules.
*
* @since 2.1.0
*/
public class DefaultServletModuleManager implements ServletModuleManager
{
private static final Logger log = LoggerFactory.getLogger(DefaultServletModuleManager.class);
private final PathMapper servletMapper;
private final Map<String, ServletModuleDescriptor> servletDescriptors = new HashMap<String, ServletModuleDescriptor>();
private final ConcurrentMap<String, LazyReference<HttpServlet>> servletRefs = new ConcurrentHashMap<String, LazyReference<HttpServlet>>();
private final PathMapper filterMapper;
private final Map<String, ServletFilterModuleDescriptor> filterDescriptors = new HashMap<String, ServletFilterModuleDescriptor>();
private final ConcurrentMap<String, LazyReference<Filter>> filterRefs = new ConcurrentHashMap<String, LazyReference<Filter>>();
private final ConcurrentMap<Plugin, ContextLifecycleReference> pluginContextRefs = new ConcurrentHashMap<Plugin, ContextLifecycleReference>();
/**
* Constructor that sets itself in the servlet context for later use in
* dispatching servlets and filters.
*
* @param servletContext The servlet context to store itself in
* @param pluginEventManager The plugin event manager
* @since 2.2.0
*/
public DefaultServletModuleManager(final ServletContext servletContext, final PluginEventManager pluginEventManager)
{
this(pluginEventManager);
ServletContextServletModuleManagerAccessor.setServletModuleManager(servletContext, this);
}
/**
* Creates the servlet module manager, but assumes you will be calling
* {@link com.atlassian.plugin.servlet.util.ServletContextServletModuleManagerAccessor#setServletModuleManager(javax.servlet.ServletContext, ServletModuleManager)}
* yourself if you don't extend the dispatching servlet and filter classes
* to provide the servlet module manager instance.
*
* @param pluginEventManager The plugin event manager
*/
public DefaultServletModuleManager(final PluginEventManager pluginEventManager)
{
this(pluginEventManager, new DefaultPathMapper(), new DefaultPathMapper());
}
/**
* Creates the servlet module manager, but assumes you will be calling
* {@link com.atlassian.plugin.servlet.util.ServletContextServletModuleManagerAccessor#setServletModuleManager(javax.servlet.ServletContext, ServletModuleManager)}
* yourself if you don't extend the dispatching servlet and filter classes
* to provide the servlet module manager instance.
*
* @param pluginEventManager The plugin event manager
* @param servletPathMapper The path mapper used for mapping servlets to
* paths
* @param filterPathMapper The path mapper used for mapping filters to paths
*/
public DefaultServletModuleManager(final PluginEventManager pluginEventManager, final PathMapper servletPathMapper, final PathMapper filterPathMapper)
{
servletMapper = servletPathMapper;
filterMapper = filterPathMapper;
pluginEventManager.register(this);
}
public void addServletModule(final ServletModuleDescriptor descriptor)
{
servletDescriptors.put(descriptor.getCompleteKey(), descriptor);
// for some reason the JDK complains about getPaths not returning a
// List<String> ?!?!?
final List<String> paths = descriptor.getPaths();
for (final String path : paths)
{
servletMapper.put(descriptor.getCompleteKey(), path);
}
final LazyReference<HttpServlet> servletRef = servletRefs.remove(descriptor.getCompleteKey());
if (servletRef != null)
{
servletRef.get().destroy();
}
}
public HttpServlet getServlet(final String path, final ServletConfig servletConfig) throws ServletException
{
final String completeKey = servletMapper.get(path);
if (completeKey == null)
{
return null;
}
final ServletModuleDescriptor descriptor = servletDescriptors.get(completeKey);
if (descriptor == null)
{
return null;
}
final HttpServlet servlet = getServlet(descriptor, servletConfig);
if (servlet == null)
{
servletRefs.remove(descriptor.getCompleteKey());
}
return servlet;
}
public void removeServletModule(final ServletModuleDescriptor descriptor)
{
servletDescriptors.remove(descriptor.getCompleteKey());
servletMapper.put(descriptor.getCompleteKey(), null);
final LazyReference<HttpServlet> servletRef = servletRefs.remove(descriptor.getCompleteKey());
if (servletRef != null)
{
servletRef.get().destroy();
}
}
public void addFilterModule(final ServletFilterModuleDescriptor descriptor)
{
filterDescriptors.put(descriptor.getCompleteKey(), descriptor);
for (final String path : descriptor.getPaths())
{
filterMapper.put(descriptor.getCompleteKey(), path);
}
final LazyReference<Filter> filterRef = filterRefs.remove(descriptor.getCompleteKey());
if (filterRef != null)
{
filterRef.get().destroy();
}
}
public Iterable<Filter> getFilters(final FilterLocation location, final String path, final FilterConfig filterConfig) throws ServletException
{
return getFilters(location, path, filterConfig, FilterDispatcherCondition.REQUEST);
}
public Iterable<Filter> getFilters(FilterLocation location, String path, FilterConfig filterConfig, FilterDispatcherCondition condition) throws ServletException
{
Validate.notNull(condition);
final List<ServletFilterModuleDescriptor> matchingFilterDescriptors = new ArrayList<ServletFilterModuleDescriptor>();
for (final String completeKey : filterMapper.getAll(path))
{
final ServletFilterModuleDescriptor descriptor = filterDescriptors.get(completeKey);
if (!descriptor.getDispatcherConditions().isEmpty() && !descriptor.getDispatcherConditions().contains(condition))
{
if (log.isDebugEnabled())
{
log.debug("Skipping filter " + descriptor.getCompleteKey() + " as condition " + condition +
" doesn't match list:" + Arrays.asList(descriptor.getDispatcherConditions()));
}
continue;
}
if (location.equals(descriptor.getLocation()))
{
sortedInsert(matchingFilterDescriptors, descriptor, byWeight);
}
}
final List<Filter> filters = new LinkedList<Filter>();
for (final ServletFilterModuleDescriptor descriptor : matchingFilterDescriptors)
{
final Filter filter = getFilter(descriptor, filterConfig);
if (filter == null)
{
filterRefs.remove(descriptor.getCompleteKey());
}
else
{
filters.add(getFilter(descriptor, filterConfig));
}
}
return filters;
}
static <T> void sortedInsert(final List<T> list, final T e, final Comparator<T> comparator)
{
int insertIndex = Collections.binarySearch(list, e, comparator);
if (insertIndex < 0)
{
// no entry already there, so the insertIndex is the negative value
// of where it should be inserted
insertIndex = -insertIndex - 1;
}
else
{
// there is already a value at that position, so we need to find the
// next available spot for it
while ((insertIndex < list.size()) && (comparator.compare(list.get(insertIndex), e) == 0))
{
insertIndex++;
}
}
list.add(insertIndex, e);
}
public void removeFilterModule(final ServletFilterModuleDescriptor descriptor)
{
filterDescriptors.remove(descriptor.getCompleteKey());
filterMapper.put(descriptor.getCompleteKey(), null);
final LazyReference<Filter> filterRef = filterRefs.remove(descriptor.getCompleteKey());
if (filterRef != null)
{
filterRef.get().destroy();
}
}
/**
* Call the plugins servlet context listeners contextDestroyed methods and
* cleanup any servlet contexts that are associated with the plugin that was
* disabled.
*/
@PluginEventListener
public void onPluginDisabled(final PluginDisabledEvent event)
{
final Plugin plugin = event.getPlugin();
final ContextLifecycleReference context = pluginContextRefs.remove(plugin);
if (context == null)
{
return;
}
context.get().contextDestroyed();
}
/**
* Returns a wrapped Servlet for the servlet module. If a wrapped servlet
* for the module has not been created yet, we create one using the
* servletConfig.
* <p/>
* Note: We use a map of lazily loaded references to the servlet so that
* only one can ever be created and initialized for each module descriptor.
*
* @param descriptor
* @param servletConfig
* @return
*/
HttpServlet getServlet(final ServletModuleDescriptor descriptor, final ServletConfig servletConfig)
{
// check for an existing reference, if there is one it's either in the
// process of loading, in which case
// servletRef.get() below will block until it's available, otherwise we
// go about creating a new ref to use
LazyReference<HttpServlet> servletRef = servletRefs.get(descriptor.getCompleteKey());
if (servletRef == null)
{
// if there isn't an existing reference, create one.
final ServletContext servletContext = getWrappedContext(descriptor.getPlugin(), servletConfig.getServletContext());
servletRef = new LazyLoadedServletReference(descriptor, servletContext);
// check that another thread didn't beat us to the punch of creating
// a lazy reference. if it did, we
// want to use that so there is only ever one reference
if (servletRefs.putIfAbsent(descriptor.getCompleteKey(), servletRef) != null)
{
servletRef = servletRefs.get(descriptor.getCompleteKey());
}
}
HttpServlet servlet = null;
try
{
servlet = servletRef.get();
}
catch (final RuntimeException ex)
{
log.error("Unable to create servlet", ex);
}
return servlet;
}
/**
* Returns a wrapped Filter for the filter module. If a wrapped filter for
* the module has not been created yet, we create one using the
* filterConfig.
* <p/>
* Note: We use a map of lazily loaded references to the filter so that only
* one can ever be created and initialized for each module descriptor.
*
* @param descriptor
* @param filterConfig
* @return The filter, or null if the filter is invalid and should be
* removed
*/
Filter getFilter(final ServletFilterModuleDescriptor descriptor, final FilterConfig filterConfig)
{
// check for an existing reference, if there is one it's either in the
// process of loading, in which case
// filterRef.get() below will block until it's available, otherwise we
// go about creating a new ref to use
LazyReference<Filter> filterRef = filterRefs.get(descriptor.getCompleteKey());
if (filterRef == null)
{
// if there isn't an existing reference, create one.
final ServletContext servletContext = getWrappedContext(descriptor.getPlugin(), filterConfig.getServletContext());
filterRef = new LazyLoadedFilterReference(descriptor, servletContext);
// check that another thread didn't beat us to the punch of creating
// a lazy reference. if it did, we
// want to use that so there is only ever one reference
if (filterRefs.putIfAbsent(descriptor.getCompleteKey(), filterRef) != null)
{
filterRef = filterRefs.get(descriptor.getCompleteKey());
}
}
try
{
return filterRef.get();
}
catch (final RuntimeException ex)
{
log.error("Unable to create filter", ex);
return null;
}
}
/**
* Returns a wrapped ServletContext for the plugin. If a wrapped servlet
* context for the plugin has not been created yet, we create using the
* baseContext, any context params specified in the plugin and initialize
* any context listeners the plugin may define.
* <p/>
* Note: We use a map of lazily loaded references to the context so that
* only one can ever be created for each plugin.
*
* @param plugin Plugin for whom we're creating a wrapped servlet context.
* @param baseContext The applications base servlet context which we will be
* wrapping.
* @return A wrapped, fully initialized servlet context that can be used for
* all the plugins filters and servlets.
*/
private ServletContext getWrappedContext(final Plugin plugin, final ServletContext baseContext)
{
ContextLifecycleReference pluginContextRef = pluginContextRefs.get(plugin);
if (pluginContextRef == null)
{
pluginContextRef = new ContextLifecycleReference(plugin, baseContext);
if (pluginContextRefs.putIfAbsent(plugin, pluginContextRef) != null)
{
pluginContextRef = pluginContextRefs.get(plugin);
}
}
return pluginContextRef.get().servletContext;
}
private static final class LazyLoadedFilterReference extends LazyReference<Filter>
{
private final ServletFilterModuleDescriptor descriptor;
private final ServletContext servletContext;
private LazyLoadedFilterReference(final ServletFilterModuleDescriptor descriptor, final ServletContext servletContext)
{
this.descriptor = descriptor;
this.servletContext = servletContext;
}
@Override
protected Filter create() throws Exception
{
final Filter filter = new DelegatingPluginFilter(descriptor);
filter.init(new PluginFilterConfig(descriptor, servletContext));
return filter;
}
}
private static final class LazyLoadedServletReference extends LazyReference<HttpServlet>
{
private final ServletModuleDescriptor descriptor;
private final ServletContext servletContext;
private LazyLoadedServletReference(final ServletModuleDescriptor descriptor, final ServletContext servletContext)
{
this.descriptor = descriptor;
this.servletContext = servletContext;
}
@Override
protected HttpServlet create() throws Exception
{
final HttpServlet servlet = new DelegatingPluginServlet(descriptor);
servlet.init(new PluginServletConfig(descriptor, servletContext));
return servlet;
}
}
private static final class ContextLifecycleReference extends LazyReference<ContextLifecycleManager>
{
private final Plugin plugin;
private final ServletContext baseContext;
private ContextLifecycleReference(final Plugin plugin, final ServletContext baseContext)
{
this.plugin = plugin;
this.baseContext = baseContext;
}
@Override
protected ContextLifecycleManager create() throws Exception
{
final ConcurrentMap<String, Object> contextAttributes = new ConcurrentHashMap<String, Object>();
final Map<String, String> initParams = mergeInitParams(baseContext, plugin);
final ServletContext context = new PluginServletContextWrapper(plugin, baseContext, contextAttributes, initParams);
ClassLoaderStack.push(plugin.getClassLoader());
final List<ServletContextListener> listeners = new ArrayList<ServletContextListener>();
try
{
for (final ServletContextListenerModuleDescriptor descriptor : findModuleDescriptorsByType(ServletContextListenerModuleDescriptor.class, plugin))
{
listeners.add(descriptor.getModule());
}
}
finally
{
ClassLoaderStack.pop();
}
return new ContextLifecycleManager(context, listeners);
}
private Map<String, String> mergeInitParams(final ServletContext baseContext, final Plugin plugin)
{
final Map<String, String> mergedInitParams = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<String> e = baseContext.getInitParameterNames();
while (e.hasMoreElements())
{
final String paramName = e.nextElement();
mergedInitParams.put(paramName, baseContext.getInitParameter(paramName));
}
for (final ServletContextParamModuleDescriptor descriptor : findModuleDescriptorsByType(ServletContextParamModuleDescriptor.class, plugin))
{
mergedInitParams.put(descriptor.getParamName(), descriptor.getParamValue());
}
return Collections.unmodifiableMap(mergedInitParams);
}
}
static <T extends ModuleDescriptor<?>> Iterable<T> findModuleDescriptorsByType(final Class<T> type, final Plugin plugin)
{
final Set<T> descriptors = new HashSet<T>();
for (final ModuleDescriptor<?> descriptor : plugin.getModuleDescriptors())
{
if (type.isAssignableFrom(descriptor.getClass()))
{
descriptors.add(type.cast(descriptor));
}
}
return descriptors;
}
static final class ContextLifecycleManager
{
private final ServletContext servletContext;
private final Iterable<ServletContextListener> listeners;
ContextLifecycleManager(final ServletContext servletContext, final Iterable<ServletContextListener> listeners)
{
this.servletContext = servletContext;
this.listeners = listeners;
for (final ServletContextListener listener : listeners)
{
listener.contextInitialized(new ServletContextEvent(servletContext));
}
}
ServletContext getServletContext()
{
return servletContext;
}
void contextDestroyed()
{
final ServletContextEvent event = new ServletContextEvent(servletContext);
for (final ServletContextListener listener : listeners)
{
listener.contextDestroyed(event);
}
}
}
}
|
package org.pdxfinder.services.ds;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.dao.Drug;
import org.pdxfinder.dao.Response;
import org.pdxfinder.dao.TreatmentComponent;
import org.pdxfinder.dao.TreatmentProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
/**
*
* @author sbn
*/
public class Standardizer {
public static final String MALE = "Male";
public static final String FEMALE = "Female";
public static final String NOT_SPECIFIED = "Not Specified";
// tumor types
public static final String PRIMARY ="Primary";
public static final String RECURRENT = "Recurrent";
public static final String METASTATIC = "Metastatic";
public static final String REFRACTORY = "Refractory";
private final static Logger log = LoggerFactory.getLogger(Standardizer.class);
public static String getGender(String gender){
if(gender.toUpperCase().startsWith("F")){
gender = FEMALE;
}else if(gender.toUpperCase().startsWith("M")){
gender = MALE;
}else {
gender = NOT_SPECIFIED;
}
return gender;
}
public static String getTumorType(String tumorType){
if(tumorType == null){
tumorType = "";
}
if(tumorType.toUpperCase().startsWith("PRI")){
tumorType = PRIMARY;
}else if(tumorType.toUpperCase().startsWith("MET")){
tumorType = METASTATIC;
}else if(tumorType.toUpperCase().startsWith("REF")){
tumorType = REFRACTORY;
}else if(tumorType.toUpperCase().startsWith("REC")){
tumorType = RECURRENT;
}else{
tumorType = NOT_SPECIFIED;
}
return tumorType;
}
public static String getAge(String age){
try{
age = new Integer(age).toString();
}catch(NumberFormatException nfe){
log.error("Cant convert "+age+" to a numeric age. Using "+NOT_SPECIFIED);
age = NOT_SPECIFIED;
}
return age;
}
public static String getValue(String name, JSONObject j){
String value = NOT_SPECIFIED;
try{
value = j.getString(name);
if(value.trim().length()==0){
value = NOT_SPECIFIED;
}
}catch(Exception e){}
return value;
}
public static String fixNotString(String in){
if(in.toUpperCase().startsWith("Not")){
in = Standardizer.NOT_SPECIFIED;
}
return in;
}
public static String getDrugResponse(String r){
if(r == null || r.isEmpty()) return "Not Specified";
if(r.toLowerCase().equals("pd") || r.toLowerCase().equals("progressive disease")) return "Progressive Disease";
if(r.toLowerCase().equals("sd") || r.toLowerCase().equals("stable disease")) return "Stable Disease";
if(r.toLowerCase().equals("cr") || r.toLowerCase().equals("complete response")) return "Complete Response";
if(r.toLowerCase().equals("pr") || r.toLowerCase().equals("partial response")) return "Partial Response";
if(r.equals("stable disease/complete response")) return "Stable Disease And Complete Response";
return r;
}
public static String getDrugName(String drug){
if(drug.toLowerCase().equals("doxorubicin")){
return "Doxorubicin";
}
else if(drug.toLowerCase().equals("cyclophosphamide")){
return "Cyclophosphamide";
}
else if(drug.toLowerCase().equals("paclitaxel")){
return "Paclitaxel";
}
else if(drug.toLowerCase().equals("tamoxifen")){
return "Tamoxifen";
}
else if(drug.toLowerCase().equals("trastuzumab")){
return "Trastuzumab";
}
else if(drug.equals("0.9% Solution of Sodium Chloride") || drug.equals("Saline")){
return "Sodium chloride solution";
}
else if(drug.equals("Erbitux, Cetuximab")){
return "Cetuximab";
}
else if(drug.equals("DSW (control)")){
return "Dextrose solution";
}
else if(drug.equals("D5W")){
return "Dextrose solution";
}
else if(drug.equals("CMC")){
return "Carboxymethyl cellulose";
}
else if(drug.equals("DMSO")){
return "Dimethyl sulfoxide";
}
else if(drug.equals("Docetaxel")){
return "Docetaxel";
}
else if(drug.equals("Trametinib")){
return "Trametinib";
}
else if(drug.equals("Erlotinib")){
return "Erlotinib";
}
else if(drug.equals("Avastin")){
return "Bevacizumab";
}
else if(drug.equals("Carboplatin")){
return "Carboplatin";
}
else if(drug.equals("CMC")){
return "Carboxymethyl cellulose";
}
else if(drug.equals("Cisplatin")){
return "Cisplatin";
}
else if(drug.equals("Etoposide")){
return "Etoposide";
}
else if(drug.equals("Gemcitabine")){
return "Gemcitabine";
}
else if(drug.equals("Crizotinib")){
return "Crizotinib";
}
else if(drug.equals("Dabrafenib")){
return "Dabrafenib";
}
else if(drug.equals("Etoposide")){
return "Etoposide";
}
else if(drug.equals("Topotecan")){
return drug;
}
else if(drug.equals("5-FU") || drug.equals("5-Fluorouracil")){
return "Fluorouracil";
}
else if(drug.equals("Oxaliplatin")){
return "Oxaliplatin";
}
else if(drug.equals("Rapamycin")){
return "Rapamycin";
}
else if(drug.equals("Temozolomide")){
return "Temozolomide";
}
else if(drug.equals("Trametinib")){
return "Trametinib";
}
else if(drug.equals("Valproic acid")){
return "Valproic Acid";
}
else if(drug.equals("Epirubicin")){
return "Epirubicin";
}
else if(drug.equals("Radiotherapy")){
return drug;
}
else if(drug.equals("Goserelin")){
return drug;
}
else if(drug.equals("Letrozole")){
return drug;
}
else if(drug.equals("Capecitabine")){
return drug;
}
else if(drug.equals("Denosumab")){
return drug;
}
return "Not Specified";
}
public static String getTreatmentComponentType(String drugName){
drugName = drugName.trim();
if(drugName.toLowerCase().contains("control")) return "Control";
if(drugName.equals("Saline") || drugName.equals("D5W") || drugName.equals("CMC") ||
drugName.equals("DMSO") || drugName.equals("0.9% Solution of Sodium Chloride")) return "Control";
return "Drug";
}
public static String getEthnicity(String ethnicity){
if(ethnicity.toLowerCase().equals("caucasian")) return "Caucasian";
if(ethnicity.toLowerCase().equals("hispanic") || ethnicity.toLowerCase().equals("hispanic or latino")) return "Hispanic or Latino";
if(ethnicity.toLowerCase().equals("white")) return "White";
if(ethnicity.toLowerCase().equals("african american") || ethnicity.toLowerCase().equals("aa")) return "African American";
if(ethnicity.toLowerCase().equals("unknown") || ethnicity.toLowerCase().equals("not specified") || ethnicity.toLowerCase().equals("not reported")) return "Not Specified";
if(ethnicity.equals("White; Hispanic or Latino")) return ethnicity;
if(ethnicity.toLowerCase().equals("black")) return "Black";
if(ethnicity.toLowerCase().equals("asian")) return "Asian";
if(ethnicity.equals("Black or African American; Not Hispanic or Latino")) return "Black or African American; Not Hispanic or Latino";
if(ethnicity.equals("White; Not Hispanic or Latino")) return ethnicity;
if(ethnicity.equals("Black or African American")) return ethnicity;
if(ethnicity.equals("Not Hispanic or Latino")) return ethnicity;
return "Not Specified";
}
}
|
package org.project.openbaton.catalogue.mano.record;
import org.project.openbaton.catalogue.mano.common.AutoScalePolicy;
import org.project.openbaton.catalogue.mano.common.ConnectionPoint;
import org.project.openbaton.catalogue.mano.common.LifecycleEvent;
import org.project.openbaton.catalogue.mano.common.VNFRecordDependency;
import org.project.openbaton.catalogue.mano.descriptor.InternalVirtualLink;
import org.project.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.project.openbaton.catalogue.util.IdGenerator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
public class VirtualNetworkFunctionRecord implements Serializable{
/**
* ID of the VNF instance
* */
@Id
private String id = IdGenerator.createUUID();
@Version
private int hb_version = 0;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<AutoScalePolicy> auto_scale_policy;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<ConnectionPoint> connection_point;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<VNFRecordDependency> dependency;
/**
* Reference to selected deployment flavour (vnfd:deployment_flavour_key:id)
* */
private String deployment_flavour_key;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<LifecycleEvent> lifecycle_event;
/**
* A language attribute may be specified to identify default localisation/language
* */
private String localization;
/**
* Active monitoring parameters
* */
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> monitoring_parameter;
/**
* VDU elements describing the VNFC-related relevant information, see clause @VirtualDeploymentUnit
* */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<VirtualDeploymentUnit> vdu;
private String vendor;
private String version;
/**
* Internal Virtual Links instances used in this VNF
* */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<InternalVirtualLink> virtual_link;
// @JsonIgnore
// @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @XmlTransient
// private transient NetworkServiceRecord parent_ns;
/**
* The reference to the VNFD used to instantiate this VNF
* */
private String descriptor_reference;
/**
* The identification of the VNFM entity managing this VNF
* TODO probably it is better to have a reference than a string pointing to the id
* */
private String vnfm_id;
/**
* Reference to a VLR (vlr:id) used for the management access path or other internal and external connection
* interface configured for use by this VNF instance
* */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<VirtualLinkRecord> connected_external_virtual_link;
/**
* A network address (e.g. VLAN, IP) configured for the management access or other internal and external connection
* interface on this VNF
* */
@ElementCollection
private Set<String> vnf_address;
/**
* Flag to report status of the VNF (e.g. 0=Failed, 1= normal operation, 2= degraded operation, 3= offline through
* management action)
* */
@Enumerated(EnumType.STRING)
private Status status;
/**
* Listing of systems that have registered to received notifications of status changes
* TODO maybe passing to a notification framework
* */
@ElementCollection
private Set<String> notification;
/**
* Record of significant VNF lifecycle event (e.g. creation, scale up/down, configuration changes)
* */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<LifecycleEvent> lifecycle_event_history;
/**
* Record of detailed operational event, (e.g. VNF boot, operator logins, alarms sent)
* */
private String audit_log;
/**
* Generic placeholder for input information related to VNF orchestration and management policies to be applied
* during runtime of a specific VNF instance (e.g. for VNF prioritization, etc.)
* */
@ElementCollection
private Set<String> runtime_policy_info;
private String name;
private String type;
public VirtualNetworkFunctionRecord() {
this.lifecycle_event = new HashSet<LifecycleEvent>();
}
public Set<AutoScalePolicy> getAuto_scale_policy() {
return auto_scale_policy;
}
/**
* Reference to records of Network Service instances (nsr:id) that this VNF instance is part of
* */
public int getHb_version() {
return hb_version;
}
public void setHb_version(int hb_version) {
this.hb_version = hb_version;
}
public void setAuto_scale_policy(Set<AutoScalePolicy> auto_scale_policy) {
this.auto_scale_policy = auto_scale_policy;
}
public Set<ConnectionPoint> getConnection_point() {
return connection_point;
}
public void setConnection_point(Set<ConnectionPoint> connection_point) {
this.connection_point = connection_point;
}
public Set<VNFRecordDependency> getDependency() {
return dependency;
}
public void setDependency(Set<VNFRecordDependency> dependency) {
this.dependency = dependency;
}
public String getDeployment_flavour_key() {
return deployment_flavour_key;
}
public void setDeployment_flavour_key(String deployment_flavour_key) {
this.deployment_flavour_key = deployment_flavour_key;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Set<LifecycleEvent> getLifecycle_event() {
return lifecycle_event;
}
public void setLifecycle_event(Set<LifecycleEvent> lifecycle_event) {
this.lifecycle_event = lifecycle_event;
}
public String getLocalization() {
return localization;
}
public void setLocalization(String localization) {
this.localization = localization;
}
public Set<String> getMonitoring_parameter() {
return monitoring_parameter;
}
public void setMonitoring_parameter(Set<String> monitoring_parameter) {
this.monitoring_parameter = monitoring_parameter;
}
public Set<VirtualDeploymentUnit> getVdu() {
return vdu;
}
public void setVdu(Set<VirtualDeploymentUnit> vdu) {
this.vdu = vdu;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Set<InternalVirtualLink> getVirtual_link() {
return virtual_link;
}
public void setVirtual_link(Set<InternalVirtualLink> virtual_link) {
this.virtual_link = virtual_link;
}
// public NetworkServiceRecord getParent_ns() {
// return parent_ns;
// public void setParent_ns(NetworkServiceRecord parent_ns) {
// this.parent_ns = parent_ns;
public String getDescriptor_reference() {
return descriptor_reference;
}
public void setDescriptor_reference(String descriptor_reference) {
this.descriptor_reference = descriptor_reference;
}
public String getVnfm_id() {
return vnfm_id;
}
public void setVnfm_id(String vnfm_id) {
this.vnfm_id = vnfm_id;
}
public Set<VirtualLinkRecord> getConnected_external_virtual_link() {
return connected_external_virtual_link;
}
public void setConnected_external_virtual_link(Set<VirtualLinkRecord> connected_external_virtual_link) {
this.connected_external_virtual_link = connected_external_virtual_link;
}
public Set<String> getVnf_address() {
return vnf_address;
}
public void setVnf_address(Set<String> vnf_address) {
this.vnf_address = vnf_address;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Set<String> getNotification() {
return notification;
}
public void setNotification(Set<String> notification) {
this.notification = notification;
}
public Set<LifecycleEvent> getLifecycle_event_history() {
return lifecycle_event_history;
}
public void setLifecycle_event_history(Set<LifecycleEvent> lifecycle_event_history) {
this.lifecycle_event_history = lifecycle_event_history;
}
public String getAudit_log() {
return audit_log;
}
public void setAudit_log(String audit_log) {
this.audit_log = audit_log;
}
public Set<String> getRuntime_policy_info() {
return runtime_policy_info;
}
public void setRuntime_policy_info(Set<String> runtime_policy_info) {
this.runtime_policy_info = runtime_policy_info;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "VirtualNetworkFunctionRecord{" +
"auto_scale_policy=" + auto_scale_policy +
", connection_point=" + connection_point +
", dependency=" + dependency +
", deployment_flavour_key=" + deployment_flavour_key +
", id='" + id + '\'' +
", lifecycle_event=" + lifecycle_event +
", localization='" + localization + '\'' +
", monitoring_parameter=" + monitoring_parameter +
", vdu=" + vdu +
", vendor='" + vendor + '\'' +
", version='" + version + '\'' +
", virtual_link=" + virtual_link +
// ", parent_ns=" + parent_ns +
", descriptor_reference='" + descriptor_reference + '\'' +
", vnfm_id='" + vnfm_id + '\'' +
", connected_external_virtual_link=" + connected_external_virtual_link +
", vnf_address=" + vnf_address +
", status=" + status +
", notification=" + notification +
", lifecycle_event_history=" + lifecycle_event_history +
", audit_log='" + audit_log + '\'' +
", runtime_policy_info=" + runtime_policy_info +
", name='" + name + '\'' +
", type='" + type + '\'' +
'}';
}
}
|
package org.vitrivr.cineast.core.features.abstracts;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.vitrivr.cineast.core.config.QueryConfig;
import org.vitrivr.cineast.core.data.query.containers.TextQueryContainer;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
public class AbstractTextRetrieverTest {
private AbstractTextRetriever retriever = new AbstractTextRetriever("test-abstract") {
};
@DisplayName("quoted string is not split")
@Test
public void testQuotedStringNotSplit() {
testMatch("\"hello world\"", "\"hello world\"");
}
@DisplayName("double quoted string is split")
@Test
public void testDoubleQuotedStringSplit() {
testMatch("\"hello\" \"world\"", "\"hello\"", "\"world\"");
}
@DisplayName("non-quoted string is split")
@Test
public void testNonQuotedStringSplit() {
testMatch("hello world", "hello", "world");
}
public void testMatch(String input, String... output) {
org.junit.jupiter.api.Assertions.assertArrayEquals(output, retriever.generateQuery(new TextQueryContainer(input), new QueryConfig(null)));
}
public SegmentContainer generateSegmentContainerFromText(String text) {
return new TextQueryContainer(text);
}
}
|
package org.openforis.collect.remoting.service.dataimport;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openforis.collect.manager.RecordFileManager;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.SurveyManager;
import org.openforis.collect.manager.dataexport.BackupProcess;
import org.openforis.collect.manager.dataexport.BackupProcess.RecordEntry;
import org.openforis.collect.manager.exception.DataImportExeption;
import org.openforis.collect.manager.exception.RecordFileException;
import org.openforis.collect.manager.exception.SurveyValidationException;
import org.openforis.collect.manager.validation.SurveyValidator;
import org.openforis.collect.manager.validation.SurveyValidator.SurveyValidationResult;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectRecord.Step;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.User;
import org.openforis.collect.persistence.RecordDao;
import org.openforis.collect.persistence.SurveyImportException;
import org.openforis.collect.persistence.xml.DataHandler;
import org.openforis.collect.persistence.xml.DataHandler.NodeUnmarshallingError;
import org.openforis.collect.persistence.xml.DataUnmarshaller;
import org.openforis.collect.persistence.xml.DataUnmarshaller.ParseRecordResult;
import org.openforis.collect.remoting.service.dataimport.DataImportState.MainStep;
import org.openforis.collect.remoting.service.dataimport.DataImportState.SubStep;
import org.openforis.collect.remoting.service.dataimport.DataImportSummary.FileErrorItem;
import org.openforis.collect.utils.OpenForisIOUtils;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.xml.IdmlParseException;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.FileAttribute;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author S. Ricci
*
*/
public class DataImportProcess implements Callable<Void> {
private static Log LOG = LogFactory.getLog(DataImportProcess.class);
private RecordDao recordDao;
private RecordManager recordManager;
private RecordFileManager recordFileManager;
private SurveyManager surveyManager;
private SurveyValidator surveyValidator;
private Map<String, User> users;
private String selectedSurveyUri;
private String newSurveyName;
private DataImportState state;
private File packagedFile;
/**
* Survey contained into the package file
*/
private CollectSurvey packagedSurvey;
private boolean overwriteAll;
private DataUnmarshaller dataUnmarshaller;
private List<Integer> processedRecords;
private DataImportSummary summary;
private List<Integer> entryIdsToImport;
private boolean includesRecordFiles;
public DataImportProcess(SurveyManager surveyManager, SurveyValidator surveyValidator, RecordManager recordManager, RecordDao recordDao,
RecordFileManager recordFileManager,
String selectedSurveyUri, Map<String, User> users, File packagedFile, boolean overwriteAll) {
super();
this.surveyManager = surveyManager;
this.surveyValidator = surveyValidator;
this.recordManager = recordManager;
this.recordDao = recordDao;
this.recordFileManager = recordFileManager;
this.selectedSurveyUri = selectedSurveyUri;
this.users = users;
this.packagedFile = packagedFile;
this.overwriteAll = overwriteAll;
this.state = new DataImportState();
processedRecords = new ArrayList<Integer>();
entryIdsToImport = new ArrayList<Integer>();
}
public DataImportState getState() {
return state;
}
public void cancel() {
state.setCancelled(true);
state.setRunning(false);
if ( state.getSubStep() == DataImportState.SubStep.RUNNING) {
state.setSubStep(DataImportState.SubStep.CANCELLED);
}
}
public boolean isRunning() {
return state.isRunning();
}
public boolean isComplete() {
return state.isComplete();
}
@Override
public Void call() throws Exception {
if ( state.getSubStep() == SubStep.PREPARING ) {
switch ( state.getMainStep() ) {
case SUMMARY_CREATION:
createDataImportSummary();
break;
case IMPORT:
importPackagedFile();
break;
}
}
return null;
}
private void createDataImportSummary() throws DataImportExeption {
ZipFile zipFile = null;
try {
state.setSubStep(SubStep.RUNNING);
summary = null;
packagedSurvey = extractPackagedSurvey();
validatePackagedSurvey();
CollectSurvey existingSurvey = getExistingSurvey();
dataUnmarshaller = initDataUnmarshaller(packagedSurvey, existingSurvey);
Map<Step, Integer> totalPerStep = new HashMap<CollectRecord.Step, Integer>();
for (Step step : Step.values()) {
totalPerStep.put(step, 0);
}
Map<Integer, CollectRecord> packagedRecords = new HashMap<Integer, CollectRecord>();
Map<Integer, List<Step>> packagedStepsPerRecord = new HashMap<Integer, List<Step>>();
Map<String, List<NodeUnmarshallingError>> packagedSkippedFileErrors = new HashMap<String, List<NodeUnmarshallingError>>();
Map<Integer, CollectRecord> conflictingPackagedRecords = new HashMap<Integer, CollectRecord>();
Map<Integer, Map<Step, List<NodeUnmarshallingError>>> warnings = new HashMap<Integer, Map<Step,List<NodeUnmarshallingError>>>();
zipFile = new ZipFile(packagedFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
state.setTotal(zipFile.size());
state.resetCount();
while (entries.hasMoreElements()) {
if ( state.getSubStep() == DataImportState.SubStep.RUNNING ) {
createSummaryForEntry(entries, zipFile, packagedSkippedFileErrors,
packagedRecords, packagedStepsPerRecord, totalPerStep,
conflictingPackagedRecords, warnings);
} else {
break;
}
}
if ( state.getSubStep() == SubStep.RUNNING ) {
String oldSurveyName = existingSurvey == null ? null: existingSurvey.getName();
summary = createSummary(packagedSkippedFileErrors, oldSurveyName,
totalPerStep, packagedRecords, packagedStepsPerRecord,
conflictingPackagedRecords, warnings);
state.setSubStep(DataImportState.SubStep.COMPLETE);
}
includesRecordFiles = isIncludingRecordFiles(zipFile);
} catch (Exception e) {
state.setSubStep(SubStep.ERROR);
state.setErrorMessage(e.getMessage());
LOG.error(e.getMessage(), e);
} finally {
if ( zipFile != null ) {
try {
zipFile.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}
}
private void validatePackagedSurvey() throws DataImportExeption {
CollectSurvey existingSurvey = getExistingSurvey();
if ( packagedSurvey == null && existingSurvey == null ) {
throw new IllegalStateException("Published survey not found and " + BackupProcess.IDML_FILE_NAME + " not found in packaged file");
} else if ( packagedSurvey == null ) {
packagedSurvey = existingSurvey;
} else {
String packagedSurveyUri = packagedSurvey.getUri();
if ( selectedSurveyUri != null && !selectedSurveyUri.equals(packagedSurveyUri) ) {
throw new IllegalArgumentException("Cannot import data related to survey '" + packagedSurveyUri +
"' into on a different survey (" + selectedSurveyUri + ")");
}
List<SurveyValidationResult> compatibilityResult = surveyValidator.validateCompatibility(existingSurvey, packagedSurvey);
if ( ! compatibilityResult.isEmpty() ) {
throw new DataImportExeption("Packaged survey is not compatible with the survey already present into the system.\n" +
"Please try to import it using the Designer to get the list of errors.");
}
}
}
protected CollectSurvey getExistingSurvey() {
String uri;
if ( selectedSurveyUri == null ) {
if ( packagedSurvey == null ) {
throw new IllegalStateException("Survey uri not specified and packaged survey not found");
} else {
uri = packagedSurvey.getUri();
}
} else {
uri = selectedSurveyUri;
}
CollectSurvey survey = surveyManager.getByUri(uri);
if ( survey == null && selectedSurveyUri != null ) {
throw new IllegalArgumentException("Published survey not found. URI: " + selectedSurveyUri);
} else {
return survey;
}
}
private void createSummaryForEntry(Enumeration<? extends ZipEntry> entries, ZipFile zipFile,
Map<String, List<NodeUnmarshallingError>> packagedSkippedFileErrors, Map<Integer, CollectRecord> packagedRecords,
Map<Integer, List<Step>> packagedStepsPerRecord, Map<Step, Integer> totalPerStep,
Map<Integer, CollectRecord> conflictingPackagedRecords, Map<Integer, Map<Step, List<NodeUnmarshallingError>>> warnings) throws DataImportExeption, IOException {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
if ( ! RecordEntry.isValidRecordEntry(zipEntry) ) {
return;
}
String entryName = zipEntry.getName();
RecordEntry recordEntry = RecordEntry.parse(entryName);
Step step = recordEntry.getStep();
InputStream is = zipFile.getInputStream(zipEntry);
InputStreamReader reader = OpenForisIOUtils.toReader(is);
ParseRecordResult parseRecordResult = parseRecord(reader);
CollectRecord parsedRecord = parseRecordResult.getRecord();
if ( ! parseRecordResult.isSuccess()) {
List<NodeUnmarshallingError> failures = parseRecordResult.getFailures();
packagedSkippedFileErrors.put(entryName, failures);
} else {
int entryId = recordEntry.getRecordId();
CollectRecord recordSummary = createRecordSummary(parsedRecord);
packagedRecords.put(entryId, recordSummary);
List<Step> stepsPerRecord = packagedStepsPerRecord.get(entryId);
if ( stepsPerRecord == null ) {
stepsPerRecord = new ArrayList<CollectRecord.Step>();
packagedStepsPerRecord.put(entryId, stepsPerRecord);
}
stepsPerRecord.add(step);
Integer totalPerStep1 = totalPerStep.get(step);
totalPerStep.put(step, totalPerStep1 + 1);
CollectRecord oldRecord = findAlreadyExistingRecordSummary(parsedRecord);
if ( oldRecord != null ) {
conflictingPackagedRecords.put(entryId, oldRecord);
}
if ( parseRecordResult.hasWarnings() ) {
Map<Step, List<NodeUnmarshallingError>> warningsPerEntry = warnings.get(entryId);
if ( warningsPerEntry == null ) {
warningsPerEntry = new HashMap<CollectRecord.Step, List<NodeUnmarshallingError>>();
warnings.put(entryId, warningsPerEntry);
}
warningsPerEntry.put(step, parseRecordResult.getWarnings());
}
}
state.incrementCount();
}
private DataImportSummary createSummary(
Map<String, List<NodeUnmarshallingError>> packagedSkippedFileErrors,
String surveyName,
Map<Step, Integer> totalPerStep,
Map<Integer, CollectRecord> packagedRecords,
Map<Integer, List<Step>> packagedStepsPerRecord,
Map<Integer, CollectRecord> conflictingPackagedRecords,
Map<Integer, Map<Step, List<NodeUnmarshallingError>>> warnings) {
DataImportSummary summary = new DataImportSummary();
summary.setSurveyName(surveyName);
List<DataImportSummaryItem> recordsToImport = new ArrayList<DataImportSummaryItem>();
Set<Integer> entryIds = packagedRecords.keySet();
for (Integer entryId: entryIds) {
CollectRecord record = packagedRecords.get(entryId);
if ( ! conflictingPackagedRecords.containsKey(entryId)) {
List<Step> steps = packagedStepsPerRecord.get(entryId);
DataImportSummaryItem item = new DataImportSummaryItem(entryId, record, steps);
item.setWarnings(warnings.get(entryId));
recordsToImport.add(item);
}
}
List<DataImportSummaryItem> conflictingRecordItems = new ArrayList<DataImportSummaryItem>();
Set<Integer> conflictingEntryIds = conflictingPackagedRecords.keySet();
for (Integer entryId: conflictingEntryIds) {
CollectRecord record = packagedRecords.get(entryId);
CollectRecord conflictingRecord = conflictingPackagedRecords.get(entryId);
List<Step> steps = packagedStepsPerRecord.get(entryId);
DataImportSummaryItem item = new DataImportSummaryItem(entryId, record, steps, conflictingRecord);
item.setWarnings(warnings.get(entryId));
conflictingRecordItems.add(item);
}
summary.setRecordsToImport(recordsToImport);
summary.setConflictingRecords(conflictingRecordItems);
List<FileErrorItem> packagedSkippedFileErrorsList = new ArrayList<DataImportSummary.FileErrorItem>();
Set<String> skippedFileNames = packagedSkippedFileErrors.keySet();
for (String fileName : skippedFileNames) {
List<NodeUnmarshallingError> nodeErrors = packagedSkippedFileErrors.get(fileName);
FileErrorItem fileErrorItem = new FileErrorItem(fileName, nodeErrors);
packagedSkippedFileErrorsList.add(fileErrorItem);
}
summary.setSkippedFileErrors(packagedSkippedFileErrorsList);
summary.setTotalPerStep(totalPerStep);
return summary;
}
public void prepareToStartSummaryCreation() {
state.setMainStep(MainStep.SUMMARY_CREATION);
state.setSubStep(DataImportState.SubStep.PREPARING);
}
public void prepareToStartImport() {
state.setMainStep(MainStep.IMPORT);
state.setSubStep(DataImportState.SubStep.PREPARING);
}
@Transactional
protected void importPackagedFile() {
ZipFile zipFile = null;
try {
state.setSubStep(DataImportState.SubStep.RUNNING);
processedRecords = new ArrayList<Integer>();
state.setTotal(entryIdsToImport.size());
state.resetCount();
CollectSurvey oldSurvey = getExistingSurvey();
if ( oldSurvey == null ) {
packagedSurvey.setName(newSurveyName);
surveyManager.importModel(packagedSurvey);
}
zipFile = new ZipFile(packagedFile);
state.setRunning(true);
for (Integer entryId : entryIdsToImport) {
if ( state.getSubStep() == SubStep.RUNNING && ! processedRecords.contains(entryId) ) {
importEntries(zipFile, entryId);
processedRecords.add(entryId);
state.incrementCount();
} else {
break;
}
}
if ( state.getSubStep() == SubStep.RUNNING ) {
state.setSubStep(SubStep.COMPLETE);
}
} catch (Exception e) {
state.setError(true);
state.setErrorMessage(e.getMessage());
state.setSubStep(SubStep.ERROR);
LOG.error("Error during data export", e);
} finally {
state.setRunning(false);
if ( zipFile != null ) {
try {
zipFile.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}
}
private void importEntries(ZipFile zipFile, int recordId) throws IOException, DataImportExeption, RecordFileException {
CollectRecord lastProcessedRecord = null;
Step originalRecordStep = null;
Step[] steps = Step.values();
for (Step step : steps) {
RecordEntry recordEntry = new RecordEntry(step, recordId);
String entryName = recordEntry.getName();
InputStream inputStream = getRecordEntryInputStream(zipFile, recordEntry);
if ( inputStream != null ) {
InputStreamReader reader = OpenForisIOUtils.toReader(inputStream);
ParseRecordResult parseRecordResult = parseRecord(reader);
CollectRecord parsedRecord = parseRecordResult.getRecord();
if (parsedRecord == null) {
String message = parseRecordResult.getMessage();
state.addError(entryName, message);
} else {
parsedRecord.setStep(step);
if ( lastProcessedRecord == null ) {
CollectRecord oldRecordSummary = findAlreadyExistingRecordSummary(parsedRecord);
if (oldRecordSummary == null) {
//insert new record
recordDao.insert(parsedRecord);
LOG.info("Inserted: " + parsedRecord.getId() + " (from file " + entryName + ")");
} else {
//overwrite existing record
originalRecordStep = oldRecordSummary.getStep();
parsedRecord.setId(oldRecordSummary.getId());
if ( includesRecordFiles ) {
recordFileManager.deleteAllFiles(parsedRecord);
}
recordDao.update(parsedRecord);
LOG.info("Updated: " + oldRecordSummary.getId() + " (from file " + entryName + ")");
}
lastProcessedRecord = parsedRecord;
} else {
replaceData(parsedRecord, lastProcessedRecord);
recordDao.update(lastProcessedRecord);
}
if ( parseRecordResult.hasWarnings() ) {
//state.addWarnings(entryName, parseRecordResult.getWarnings());
}
}
}
}
if ( lastProcessedRecord != null && originalRecordStep != null && originalRecordStep.compareTo(lastProcessedRecord.getStep()) > 0 ) {
//reset the step to the original one and revalidate the record
CollectSurvey survey = (CollectSurvey) lastProcessedRecord.getSurvey();
CollectRecord originalRecord = recordDao.load(survey, lastProcessedRecord.getId(), originalRecordStep.getStepNumber());
originalRecord.setStep(originalRecordStep);
validateRecord(originalRecord);
recordDao.update(originalRecord);
}
if ( includesRecordFiles ) {
importRecordFiles(zipFile, lastProcessedRecord);
}
}
private void importRecordFiles(ZipFile zipFile, CollectRecord record) throws IOException, RecordFileException {
recordFileManager.resetTempInfo();
List<FileAttribute> fileAttributes = record.getFileAttributes();
String sessionId = "admindataimport";
for (FileAttribute fileAttribute : fileAttributes) {
String recordFileEntryName = BackupProcess.calculateRecordFileEntryName(fileAttribute);
InputStream is = getEntryInputStream(zipFile, recordFileEntryName);
if ( is != null ) {
recordFileManager.saveToTempFolder(is, fileAttribute.getFilename(),
sessionId, record, fileAttribute.getInternalId());
}
}
if ( recordFileManager.commitChanges(sessionId, record) ) {
if ( record.getStep() == Step.ANALYSIS ) {
record.setStep(Step.CLEANSING);
recordDao.update(record);
record.setStep(Step.ANALYSIS);
}
recordDao.update(record);
}
}
private InputStream getEntryInputStream(ZipFile zipFile, String entryName)
throws IOException {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
if ( zipEntry.getName().equals(entryName) ) {
return zipFile.getInputStream(zipEntry);
}
}
return null;
}
private boolean isIncludingRecordFiles(ZipFile zipFile) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
if ( zipEntry.getName().startsWith(BackupProcess.RECORD_FILE_DIRECTORY_NAME)) {
return true;
}
}
return false;
}
private InputStream getRecordEntryInputStream(ZipFile zipFile, RecordEntry entry) throws IOException, DataImportExeption {
String entryName = entry.getName();
InputStream result = getEntryInputStream(zipFile, entryName);
return result;
}
private DataUnmarshaller initDataUnmarshaller(CollectSurvey packagedSurvey, CollectSurvey existingSurvey) throws SurveyImportException {
CollectSurvey currentSurvey = existingSurvey == null ? packagedSurvey : existingSurvey;
DataHandler handler = new DataHandler(currentSurvey, packagedSurvey, users);;
DataUnmarshaller dataUnmarshaller = new DataUnmarshaller(handler);
return dataUnmarshaller;
}
private CollectRecord findAlreadyExistingRecordSummary(CollectRecord parsedRecord) {
CollectSurvey survey = (CollectSurvey) parsedRecord.getSurvey();
List<String> keyValues = parsedRecord.getRootEntityKeyValues();
Entity rootEntity = parsedRecord.getRootEntity();
String rootEntityName = rootEntity.getName();
List<CollectRecord> oldRecords = recordManager.loadSummaries(survey, rootEntityName, keyValues.toArray(new String[0]));
if ( oldRecords == null || oldRecords.isEmpty() ) {
return null;
} else if ( oldRecords.size() == 1 ) {
return oldRecords.get(0);
} else {
throw new IllegalStateException(String.format("Multiple records found in survey %s with key(s): %s", survey.getName(), keyValues));
}
}
public CollectSurvey extractPackagedSurvey() throws IOException, IdmlParseException, DataImportExeption, SurveyValidationException {
ZipFile zipFile = null;
CollectSurvey survey = null;
try {
zipFile = new ZipFile(packagedFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
if (zipEntry.isDirectory()) {
continue;
}
String entryName = zipEntry.getName();
if (BackupProcess.IDML_FILE_NAME.equals(entryName)) {
InputStream is = zipFile.getInputStream(zipEntry);
survey = surveyManager.unmarshalSurvey(is);
List<SurveyValidationResult> validationResults = surveyValidator.validate(survey);
if ( ! validationResults.isEmpty() ) {
throw new IllegalStateException("Packaged survey is not valid." +
"\nPlease try to import it using the Designer to get the list of errors.");
}
}
}
} finally {
if ( zipFile != null) {
zipFile.close();
}
}
return survey;
}
private ParseRecordResult parseRecord(Reader reader) throws IOException {
ParseRecordResult result = dataUnmarshaller.parse(reader);
if ( result.isSuccess() ) {
CollectRecord record = result.getRecord();
validateRecord(record);
record.updateRootEntityKeyValues();
record.updateEntityCounts();
}
return result;
}
private void validateRecord(CollectRecord record) {
try {
recordManager.validate(record);
} catch (Exception e) {
LOG.info("Error validating record: " + record.getRootEntityKeyValues());
}
}
private void replaceData(CollectRecord fromRecord, CollectRecord toRecord) {
toRecord.setCreatedBy(fromRecord.getCreatedBy());
toRecord.setCreationDate(fromRecord.getCreationDate());
toRecord.setModifiedBy(fromRecord.getModifiedBy());
toRecord.setModifiedDate(fromRecord.getModifiedDate());
toRecord.setStep(fromRecord.getStep());
toRecord.setState(fromRecord.getState());
toRecord.setRootEntity(fromRecord.getRootEntity());
toRecord.updateRootEntityKeyValues();
toRecord.updateEntityCounts();
recordManager.validate(toRecord);
}
protected CollectRecord createRecordSummary(CollectRecord record) {
CollectSurvey survey = (CollectSurvey) record.getSurvey();
ModelVersion version = record.getVersion();
String versionName = version != null ? version.getName(): null;
CollectRecord result = new CollectRecord(survey, versionName);
result.setCreatedBy(record.getCreatedBy());
result.setCreationDate(record.getCreationDate());
result.setEntityCounts(record.getEntityCounts());
result.setErrors(record.getErrors());
result.setId(record.getId());
result.setMissing(record.getMissing());
result.setModifiedBy(record.getModifiedBy());
result.setModifiedDate(record.getModifiedDate());
result.setRootEntityKeyValues(record.getRootEntityKeyValues());
result.setSkipped(record.getSkipped());
result.setState(record.getState());
result.setStep(record.getStep());
return result;
}
public boolean isOverwriteAll() {
return overwriteAll;
}
public void setOverwriteAll(boolean overwriteAll) {
this.overwriteAll = overwriteAll;
}
public void setNewSurveyName(String newSurveyName) {
this.newSurveyName = newSurveyName;
}
public DataImportSummary getSummary() {
return summary;
}
public List<Integer> getEntryIdsToImport() {
return entryIdsToImport;
}
public void setEntryIdsToImport(List<Integer> entryIdsToImport) {
this.entryIdsToImport = entryIdsToImport;
}
}
|
package peergos.server.storage;
import static peergos.server.util.Logging.LOG;
import peergos.server.util.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.api.*;
import peergos.shared.io.ipfs.cid.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.util.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
/**
* A Utility for installing IPFS and associated plugins.
*/
public class IpfsInstaller {
public enum DownloadTarget {
LINUX_AMD64("https://github.com/peergos/ipfs-nucleus-releases/blob/main/v0.1.0/linux-amd64/ipfs?raw=true",
Cid.decode("QmNsQvCAefREYRirS1Nk1VicoHq3R9UJtEixBrdt968NRh"));
public final String url;
public final Multihash multihash;
public final List<DownloadTarget> plugins;
DownloadTarget(String url, Multihash multihash, List<DownloadTarget> plugins) {
this.url = url;
this.multihash = multihash;
this.plugins = Collections.unmodifiableList(plugins);
}
DownloadTarget(String url, Multihash multihash) {
this.url = url;
this.multihash = multihash;
this.plugins = Collections.emptyList();
}
}
public interface Plugin {
void ensureInstalled(Path ipfsDir);
void configure(IpfsWrapper ipfs);
final class S3 implements Plugin {
public static final String TYPE = "S3";
public final String path, bucket, region, accessKey, secretKey, regionEndpoint;
public S3(S3Config config) {
this.path = config.path;
this.bucket = config.bucket;
this.region = config.region;
this.accessKey = config.accessKey;
this.secretKey = config.secretKey;
this.regionEndpoint = config.regionEndpoint;
}
public String getFileName() {
return "go-ds-s3.so";
}
public Object toJson() {
Map<String, Object> res = new TreeMap<>();
Map<String, Object> child = new TreeMap<>();
child.put("path", path);
child.put("bucket", bucket);
child.put("accessKey", accessKey);
child.put("secretKey", secretKey);
child.put("region", region);
child.put("regionEndpoint", regionEndpoint);
child.put("type", "s3ds");
res.put("child", child);
res.put("mountpoint", "/blocks");
res.put("prefix", "s3.datastore");
res.put("type", "measure");
return res;
}
public static S3 build(Args a) {
S3Config config = S3Config.build(a);
return new S3(config);
}
@Override
public void configure(IpfsWrapper ipfs) {
// Do the configuration dance..
System.out.println("Configuring S3 datastore IPFS plugin");
// update the config file
List<Object> mount = Arrays.asList(
toJson(),
JSONParser.parse("{\n" +
" \"child\": {\n" +
" \"compression\": \"none\",\n" +
" \"path\": \"datastore\",\n" +
" \"type\": \"levelds\"\n" +
" },\n" +
" \"mountpoint\": \"/\",\n" +
" \"prefix\": \"leveldb.datastore\",\n" +
" \"type\": \"measure\"\n" +
" }")
);
String mounts = JSONParser.toString(mount);
ipfs.setConfig("Datastore.Spec.mounts", mounts);
// replace the datastore spec file
String newDataStoreSpec = "{\"mounts\":[{\"bucket\":\"" + bucket +
"\",\"mountpoint\":\"/blocks\",\"region\":\"" + region +
"\",\"rootDirectory\":\"\"},{\"mountpoint\":\"/\",\"path\":\"datastore\",\"type\":\"levelds\"}],\"type\":\"mount\"}";
Path specPath = ipfs.ipfsDir.resolve("datastore_spec");
try {
Files.write(specPath, newDataStoreSpec.getBytes());
} catch (IOException e) {
throw new RuntimeException("Couldn't overwrite ipfs datastore spec file", e);
}
}
@Override
public void ensureInstalled(Path ipfsDir) {
if (! getOsArch().equals("linux_amd64"))
throw new IllegalStateException("S3 plugin is only available on linux-amd64");
// IpfsInstaller.ensurePluginInstalled(ipfsDir.resolve("plugins").resolve(getFileName()), version);
}
}
static List<Plugin> parseAll(Args args) {
List<String> plugins = Arrays.asList(args.getArg("ipfs-plugins", "").split(","))
.stream()
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
return plugins.stream()
.map(name -> parse(name, args))
.collect(Collectors.toList());
}
static Plugin parse(String pluginName, Args a) {
switch (pluginName) {
case "go-ds-s3": {
return S3.build(a);
}
default:
throw new IllegalStateException("Unknown plugin: " + pluginName);
}
}
}
/**
* Ensure the ipfs executable is installed and that it's contents are correct.
*/
public static void ensureInstalled(Path targetFile) {
ensureInstalled(targetFile, getForPlatform());
}
public static Path getExecutableForOS(Path targetFile) {
if (System.getProperty("os.name").toLowerCase().contains("windows"))
return targetFile.getParent().resolve(targetFile.getFileName() + ".exe");
return targetFile;
}
private static DownloadTarget getForPlatform() {
String type = getOsArch();
return DownloadTarget.valueOf(type.toUpperCase());
}
private static String getOsArch() {
String os = canonicaliseOS(System.getProperty("os.name").toLowerCase());
String arch = canonicaliseArchitecture(System.getProperty("os.arch"));
return os + "_" + arch;
}
private static String canonicaliseArchitecture(String arch) {
System.out.println("Looking up architecture: " + arch);
if (arch.startsWith("arm64"))
return "arm64";
if (arch.startsWith("arm"))
return "arm";
if (arch.startsWith("x86_64"))
return "amd64";
if (arch.startsWith("x86"))
return "386";
return arch;
}
private static String canonicaliseOS(String os) {
System.out.println("Looking up OS: " + os);
if (os.startsWith("mac"))
return "darwin";
if (os.startsWith("windows"))
return "windows";
return os;
}
private static void ensurePluginInstalled(Path targetFile, DownloadTarget downloadTarget) {
if (Files.exists(targetFile)) {
//check contents are correct
try {
byte[] raw = Files.readAllBytes(targetFile);
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (computed.equals(downloadTarget.multihash)) {
//all present and correct
return;
}
targetFile.toFile().delete();
install(targetFile, downloadTarget, Optional.empty());
return;
} catch (IOException ioe) {
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}
else {
LOG().info("Binary "+ targetFile + " not available");
}
install(targetFile, downloadTarget, Optional.empty());
}
private static void ensureInstalled(Path targetFile, DownloadTarget downloadTarget) {
if (Files.exists(targetFile)) {
//check contents are correct
try {
byte[] raw = Files.readAllBytes(targetFile);
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (computed.equals(downloadTarget.multihash)) {
//all present and correct
return;
}
ProcessBuilder pb = new ProcessBuilder(Arrays.asList(targetFile.toString(), "version"));
Process started = pb.start();
InputStream in = started.getInputStream();
String output = new String(Serialize.readFully(in)).trim();
Version ipfsVersion = Version.parse(output.substring(output.lastIndexOf(" ") + 1));
LOG().info("Upgrading IPFS from " + ipfsVersion);
targetFile.toFile().delete();
install(targetFile, downloadTarget, Optional.of(ipfsVersion));
return;
} catch (IOException ioe) {
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}
else {
LOG().info("ipfs-exe "+ targetFile + " not available");
}
install(targetFile, downloadTarget, Optional.empty());
}
private static void install(Path targetFile, DownloadTarget downloadTarget, Optional<Version> previousIpfsVersion) {
try {
Path cacheFile = getLocalCacheDir().resolve(downloadTarget.multihash.toString());
Path fileName = targetFile.getFileName();
File targetParent = targetFile.getParent().toFile();
if (! targetParent.exists())
if (! targetParent.mkdirs())
throw new IllegalStateException("Couldn't create parent directory: " + targetFile.getParent());
if (cacheFile.toFile().exists()) {
LOG().info("Using cached " + fileName + " " + cacheFile);
byte[] raw = Files.readAllBytes(cacheFile);
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (computed.equals(downloadTarget.multihash)) {
try {
Files.createSymbolicLink(targetFile, cacheFile);
} catch (Throwable t) {
// Windows requires extra privilege to symlink, so just copy it
Files.copy(cacheFile, targetFile);
}
targetFile.toFile().setExecutable(true);
return;
}
}
URI uri = new URI(downloadTarget.url);
LOG().info("Downloading " + fileName + " binary "+ downloadTarget.url +"...");
byte[] raw = Serialize.readFully(uri.toURL().openStream());
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (! computed.equals(downloadTarget.multihash))
throw new IllegalStateException("Incorrect hash for binary, aborting install!");
// save to local cache
cacheFile.getParent().toFile().mkdirs();
atomicallySaveToFile(cacheFile, raw);
LOG().info("Writing " + fileName + " binary to "+ targetFile);
try {
atomicallySaveToFile(targetFile, raw);
} catch (FileAlreadyExistsException e) {
boolean delete = targetFile.toFile().delete();
if (! delete)
throw new IllegalStateException("Couldn't delete old version of " + fileName + "!");
atomicallySaveToFile(targetFile, raw);
}
targetFile.toFile().setExecutable(true);
// TODO run any upgrade scripts for IPFS like converting the repo etc.
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void atomicallySaveToFile(Path targetFile, byte[] data) throws IOException {
Path tempFile = Files.createTempFile("ipfs-temp-exe", "");
Files.write(tempFile, data);
try {
Files.move(tempFile, targetFile, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException ex) {
Files.move(tempFile, targetFile);
}
}
private static Path getLocalCacheDir() {
return Paths.get(System.getProperty("user.home"), ".cache");
}
public static void main(String[] args) throws Exception {
String version = "v0.1.0";
// String s3Filename = "s3plugin.so";
// byte[] bytes = Files.readAllBytes(Paths.get("/home", "ian", "ipfs-releases", version,
// "linux-amd64", "plugins", s3Filename));
// Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(bytes));
// "/linux-amd64/plugins/" + s3Filename + "?raw=true\", Cid.decode(\"" + hash + "\")),");
codegen(Paths.get("/home/ian/ipfs-nucleus-releases/" + version));
}
private static void codegen(Path root) throws Exception {
String urlBase = "https://github.com/peergos/ipfs-nucleus-releases/blob/master/" + root.getFileName() + "/";
for (File arch: Arrays.asList(root.toFile().listFiles()).stream().sorted().collect(Collectors.toList())) {
for (File binary: arch.listFiles()) {
if (binary.isDirectory())
continue;
byte[] bytes = Files.readAllBytes(binary.toPath());
Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(bytes));
System.out.println(arch.getName().toUpperCase().replaceAll("-", "_")
+ "(\"" + urlBase + arch.getName() + "/" + binary.getName()
+ "?raw=true\", Cid.decode(\"" + hash + "\")),");
}
}
}
private static class ReleasePreparation {
public static void main(String[] a) throws Exception {
String version = "v0.9.0";
Path baseDir = Files.createTempDirectory("ipfs");
for (String os: Arrays.asList("linux", "windows", "darwin", "freebsd")) {
for (String arch: Arrays.asList("386", "amd64", "arm", "arm64")) {
String archive = os.equals("windows") ? "zip" : "tar.gz";
String filename = "go-ipfs_"+version+"_" + os + "-" + arch + "." + archive;
URI target = new URI("https://dist.ipfs.io/go-ipfs/"+version+"/" + filename);
Path archDir = baseDir.resolve(os + "-" + arch);
try {
archDir.toFile().mkdirs();
URLConnection conn = target.toURL().openConnection();
Path tarPath = archDir.resolve(filename);
System.out.printf("Downloading " + filename + " ...");
Files.write(tarPath, Serialize.readFully(conn.getInputStream()));
System.out.println("done");
ProcessBuilder pb = os.equals("windows") ?
new ProcessBuilder("unzip", filename) :
new ProcessBuilder("tar", "-xvzf", filename);
pb.directory(archDir.toFile());
Process proc = pb.start();
while (proc.isAlive())
Thread.sleep(100);
tarPath.toFile().delete();
Path extracted = archDir.resolve("go-ipfs");
String executable = os.equals("windows") ? "ipfs.exe" : "ipfs";
for (File file : extracted.toFile().listFiles()) {
if (!file.getName().equals(executable))
file.delete();
else {
ProcessBuilder movepb = new ProcessBuilder("mv", "go-ipfs/" + executable, ".");
movepb.directory(archDir.toFile());
Process moveproc = movepb.start();
while (moveproc.isAlive())
Thread.sleep(100);
}
}
extracted.toFile().delete();
byte[] bytes = Files.readAllBytes(archDir.resolve(executable));
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(bytes));
System.out.println(os + "-" + arch + "-" + computed);
} catch (FileNotFoundException e) {
archDir.toFile().delete();
// OS + arch combination doesn't exist
}
}
}
}
}
}
|
package slavetest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.helpers.collection.IteratorUtil;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.kernel.EmbeddedGraphDatabase;
public abstract class AbstractHaTest
{
static final RelationshipType REL_TYPE = DynamicRelationshipType.withName( "HA_TEST" );
static final File PARENT_PATH = new File( "target/havar" );
static final File DBS_PATH = new File( PARENT_PATH, "dbs" );
static final File SKELETON_DB_PATH = new File( DBS_PATH, "skeleton" );
static final Map<String, String> INDEX_CONFIG = MapUtil.stringMap( "index", "true" );
private boolean expectsResults;
private int nodeCount;
private int relCount;
private int nodePropCount;
private int relPropCount;
private int nodeIndexServicePropCount;
private int nodeIndexProviderPropCount;
protected static File dbPath( int num )
{
return new File( DBS_PATH, "" + num );
}
@Before
public void clearExpectedResults()
{
expectsResults = false;
}
public void verify( VerifyDbContext refDb, VerifyDbContext... dbs )
{
for ( VerifyDbContext otherDb : dbs )
{
int vNodeCount = 0;
int vRelCount = 0;
int vNodePropCount = 0;
int vRelPropCount = 0;
int vNodeIndexServicePropCount = 0;
int vNodeIndexProviderPropCount = 0;
Set<Node> otherNodes = IteratorUtil.addToCollection( otherDb.db.getAllNodes().iterator(),
new HashSet<Node>() );
for ( Node node : refDb.db.getAllNodes() )
{
Node otherNode = otherDb.db.getNodeById( node.getId() );
int[] counts = verifyNode( node, otherNode, refDb, otherDb );
vRelCount += counts[0];
vNodePropCount += counts[1];
vRelPropCount += counts[2];
vNodeIndexServicePropCount += counts[3];
vNodeIndexProviderPropCount += counts[4];
otherNodes.remove( otherNode );
vNodeCount++;
}
assertTrue( otherNodes.isEmpty() );
if ( expectsResults )
{
assertEquals( nodeCount, vNodeCount );
assertEquals( relCount, vRelCount );
assertEquals( nodePropCount, vNodePropCount );
assertEquals( relPropCount, vRelPropCount );
// assertEquals( nodeIndexServicePropCount, vNodeIndexServicePropCount );
assertEquals( nodeIndexProviderPropCount, vNodeIndexProviderPropCount );
}
}
}
private static int[] verifyNode( Node node, Node otherNode,
VerifyDbContext refDb, VerifyDbContext otherDb )
{
int vNodePropCount = verifyProperties( node, otherNode );
int vNodeIndexServicePropCount = verifyIndexService( node, otherNode, refDb, otherDb );
int vNodeIndexProviderProCount = verifyIndexProvider( node, otherNode, refDb, otherDb );
Set<Long> otherRelIds = new HashSet<Long>();
for ( Relationship otherRel : otherNode.getRelationships( Direction.OUTGOING ) )
{
otherRelIds.add( otherRel.getId() );
}
int vRelCount = 0;
int vRelPropCount = 0;
for ( Relationship rel : node.getRelationships( Direction.OUTGOING ) )
{
Relationship otherRel = otherDb.db.getRelationshipById( rel.getId() );
vRelPropCount += verifyProperties( rel, otherRel );
if ( rel.getStartNode().getId() != otherRel.getStartNode().getId() )
{
throw new RuntimeException( "Start node differs on " + rel );
}
if ( rel.getEndNode().getId() != otherRel.getEndNode().getId() )
{
throw new RuntimeException( "End node differs on " + rel );
}
if ( !rel.getType().name().equals( otherRel.getType().name() ) )
{
throw new RuntimeException( "Type differs on " + rel );
}
otherRelIds.remove( rel.getId() );
vRelCount++;
}
if ( !otherRelIds.isEmpty() )
{
throw new RuntimeException( "Other node " + otherNode + " has more relationships " +
otherRelIds );
}
return new int[] { vRelCount, vNodePropCount, vRelPropCount, vNodeIndexServicePropCount, vNodeIndexProviderProCount };
}
private static int verifyIndexService( Node node, Node otherNode, VerifyDbContext refDb,
VerifyDbContext otherDb )
{
return 0;
/* int count = 0;
if ( refDb.indexService == null || otherDb.indexService == null )
{
return count;
}
Set<String> otherKeys = new HashSet<String>();
for ( String key : otherNode.getPropertyKeys() )
{
if ( isIndexedWithIndexService( otherNode, otherDb, key ) )
{
otherKeys.add( key );
}
}
count = otherKeys.size();
for ( String key : node.getPropertyKeys() )
{
if ( otherKeys.remove( key ) != isIndexedWithIndexService( node, refDb, key ) )
{
throw new RuntimeException( "Index differs on " + node + ", " + key );
}
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherNode + " has more indexing: " +
otherKeys );
}
return count;*/
}
private static boolean isIndexedWithIndexService( Node node, VerifyDbContext db, String key )
{
return false;
// return db.indexService.getSingleNode( key, node.getProperty( key ) ) != null;
}
private static int verifyIndexProvider( Node node, Node otherNode, VerifyDbContext refDb,
VerifyDbContext otherDb )
{
int count = 0;
if ( refDb.indexProvider == null || otherDb.indexProvider == null )
{
return count;
}
Set<String> otherKeys = new HashSet<String>();
for ( String key : otherNode.getPropertyKeys() )
{
if ( isIndexedWithIndexProvider( otherNode, otherDb, key ) )
{
otherKeys.add( key );
}
}
count = otherKeys.size();
for ( String key : node.getPropertyKeys() )
{
if ( otherKeys.remove( key ) != isIndexedWithIndexProvider( node, refDb, key ) )
{
throw new RuntimeException( "Index differs on " + node + ", " + key );
}
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherNode + " has more indexing: " +
otherKeys );
}
return count;
}
private static boolean isIndexedWithIndexProvider( Node node, VerifyDbContext db, String key )
{
return db.indexProvider.nodeIndex( "users", null ).get( key, node.getProperty( key ) ).getSingle() != null;
}
private static int verifyProperties( PropertyContainer entity, PropertyContainer otherEntity )
{
int count = 0;
Set<String> otherKeys = IteratorUtil.addToCollection(
otherEntity.getPropertyKeys().iterator(), new HashSet<String>() );
for ( String key : entity.getPropertyKeys() )
{
Object value1 = entity.getProperty( key );
Object value2 = otherEntity.getProperty( key );
if ( value1.getClass().isArray() && value2.getClass().isArray() )
{
}
else if ( !value1.equals( value2 ) )
{
throw new RuntimeException( entity + " not equals property '" + key + "': " +
value1 + ", " + value2 );
}
otherKeys.remove( key );
count++;
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherEntity + " has more properties: " +
otherKeys );
}
return count;
}
public static <T> void assertCollection( Collection<T> collection, T... expectedItems )
{
String collectionString = join( ", ", collection.toArray() );
assertEquals( collectionString, expectedItems.length,
collection.size() );
for ( T item : expectedItems )
{
assertTrue( collection.contains( item ) );
}
}
public static <T> String join( String delimiter, T... items )
{
StringBuffer buffer = new StringBuffer();
for ( T item : items )
{
if ( buffer.length() > 0 )
{
buffer.append( delimiter );
}
buffer.append( item.toString() );
}
return buffer.toString();
}
protected void createDeadDbs( int numSlaves ) throws IOException
{
FileUtils.deleteDirectory( PARENT_PATH );
new EmbeddedGraphDatabase( SKELETON_DB_PATH.getAbsolutePath() ).shutdown();
for ( int i = 0; i <= numSlaves; i++ )
{
FileUtils.copyDirectory( SKELETON_DB_PATH, dbPath( i ) );
}
}
protected final void initializeDbs( int numSlaves ) throws Exception
{
initializeDbs( numSlaves, MapUtil.stringMap( ) );
}
protected abstract void initializeDbs( int numSlaves, Map<String, String> config ) throws Exception;
protected abstract void pullUpdates( int... slaves ) throws Exception;
protected abstract <T> T executeJob( Job<T> job, int onSlave ) throws Exception;
protected abstract <T> T executeJobOnMaster( Job<T> job ) throws Exception;
protected abstract void startUpMaster( Map<String, String> config ) throws Exception;
protected abstract Job<Void> getMasterShutdownDispatcher();
protected abstract void shutdownDbs() throws Exception;
protected abstract Fetcher<DoubleLatch> getDoubleLatch() throws Exception;
private class Worker extends Thread
{
private boolean successfull;
private boolean deadlocked;
private final int slave;
private final Job<Boolean[]> job;
Worker( int slave, Job<Boolean[]> job )
{
this.slave = slave;
this.job = job;
}
@Override
public void run()
{
try
{
Boolean[] result = executeJob( job, slave );
successfull = result[0];
deadlocked = result[1];
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
protected void setExpectedResults( int nodeCount, int relCount,
int nodePropCount, int relPropCount, int nodeIndexServicePropCount, int nodeIndexProviderPropCount )
{
this.expectsResults = true;
this.nodeCount = nodeCount;
this.relCount = relCount;
this.nodePropCount = nodePropCount;
this.relPropCount = relPropCount;
this.nodeIndexServicePropCount = nodeIndexServicePropCount;
this.nodeIndexProviderPropCount = nodeIndexProviderPropCount;
}
@Test
public void slaveCreateNode() throws Exception
{
setExpectedResults( 3, 2, 2, 2, 0, 0 );
initializeDbs( 1 );
executeJob( new CommonJobs.CreateSomeEntitiesJob(), 0 );
}
@Test
public void testMultipleSlaves() throws Exception
{
setExpectedResults( 2, 1, 1, 1, 0, 0 );
initializeDbs( 3 );
executeJob( new CommonJobs.CreateSubRefNodeJob( CommonJobs.REL_TYPE.name(), null, null ), 0 );
executeJob( new CommonJobs.SetSubRefPropertyJob( "name", "Hello" ), 1 );
pullUpdates( 0, 2 );
}
// This is difficult to test a.t.m. since you can't really bring down a master
// and expect it to be able to come up again without any work.
@Test
public void testMasterFailure() throws Exception
{
initializeDbs( 1 );
Serializable[] result = executeJob( new CommonJobs.CreateSubRefNodeMasterFailJob(
getMasterShutdownDispatcher() ), 0 );
assertFalse( (Boolean) result[0] );
startUpMaster( MapUtil.stringMap() );
long nodeId = (Long) result[1];
Boolean existed = executeJob( new CommonJobs.GetNodeByIdJob( nodeId ), 0 );
assertFalse( existed.booleanValue() );
}
@Test
public void testSlaveConstraintViolation() throws Exception
{
setExpectedResults( 2, 1, 0, 1, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJob( new CommonJobs.CreateSubRefNodeJob(
CommonJobs.REL_TYPE.name(), null, null ), 0 );
Boolean successful = executeJob( new CommonJobs.DeleteNodeJob( nodeId.longValue(),
false ), 0 );
assertFalse( successful.booleanValue() );
}
@Test
public void testMasterConstrainViolation() throws Exception
{
setExpectedResults( 2, 1, 1, 1, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJob( new CommonJobs.CreateSubRefNodeJob( CommonJobs.REL_TYPE.name(),
"name", "Mattias" ), 0 );
Boolean successful = executeJobOnMaster(
new CommonJobs.DeleteNodeJob( nodeId.longValue(), false ) );
assertFalse( successful.booleanValue() );
pullUpdates();
}
@Test
public void testGetRelationships() throws Exception
{
setExpectedResults( 3, 2, 0, 0, 0, 0 );
initializeDbs( 1 );
assertEquals( (Integer) 1, executeJob( new CommonJobs.CreateSubRefNodeWithRelCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJob( new CommonJobs.CreateSubRefNodeWithRelCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJob( new CommonJobs.GetRelationshipCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJobOnMaster( new CommonJobs.GetRelationshipCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ) ) );
}
@Test
public void testNoTransaction() throws Exception
{
setExpectedResults( 2, 1, 0, 1, 0, 0 );
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.CreateSubRefNodeJob(
CommonJobs.REL_TYPE.name(), null, null ) );
assertFalse( executeJob( new CommonJobs.CreateNodeOutsideOfTxJob(), 0 ).booleanValue() );
assertFalse( executeJobOnMaster( new CommonJobs.CreateNodeOutsideOfTxJob() ).booleanValue() );
}
@Test
public void testNodeDeleted() throws Exception
{
setExpectedResults( 1, 0, 0, 0, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJobOnMaster( new CommonJobs.CreateNodeJob() );
pullUpdates();
assertTrue( executeJobOnMaster( new CommonJobs.DeleteNodeJob(
nodeId.longValue(), false ) ).booleanValue() );
assertFalse( executeJob( new CommonJobs.SetNodePropertyJob( nodeId.longValue(), "something",
"some thing" ), 0 ) );
}
@Test
public void testDeadlock() throws Exception
{
initializeDbs( 2 );
Long[] nodes = executeJobOnMaster( new CommonJobs.CreateNodesJob( 2 ) );
pullUpdates();
Fetcher<DoubleLatch> fetcher = getDoubleLatch();
Worker w1 = new Worker( 0, new CommonJobs.Worker1Job( nodes[0], nodes[1], fetcher ) );
Worker w2 = new Worker( 1, new CommonJobs.Worker2Job( nodes[0], nodes[1], fetcher ) );
w1.start();
w2.start();
while ( w1.isAlive() || w2.isAlive() )
{
Thread.sleep( 500 );
}
boolean case1 = w2.successfull && !w2.deadlocked && !w1.successfull && w1.deadlocked;
boolean case2 = !w2.successfull && w2.deadlocked && w1.successfull && !w1.deadlocked;
assertTrue( case1 != case2 );
assertTrue( case1 || case2 );
pullUpdates();
}
@Test
public void createNodeAndIndex() throws Exception
{
setExpectedResults( 2, 0, 1, 0, 1, 0 );
initializeDbs( 1, INDEX_CONFIG );
executeJob( new CommonJobs.CreateNodeAndIndexJob( "name", "Neo" ), 0 );
}
@Test
public void indexingAndTwoSlaves() throws Exception
{
initializeDbs( 2, INDEX_CONFIG );
long id = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Morpheus" ) );
pullUpdates();
long id2 = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Trinity" ) );
executeJob( new CommonJobs.AddIndex( id, MapUtil.map( "key1",
new String[] { "value1", "value2" }, "key 2", 105.43f ) ), 1 );
pullUpdates();
}
@Test
public void testNewIndexFramework() throws Exception
{
setExpectedResults( 2, 0, 2, 0, 0, 2 );
initializeDbs( 2, INDEX_CONFIG );
long id = executeJobOnMaster( new CommonJobs.CreateNodeAndNewIndexJob( "users",
"name", "Morpheus", "rank", "Captain" ) );
pullUpdates();
}
public void testVeryLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob(), 0 );
}
}
|
package org.phenotips.entities.internal;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.entities.PrimaryEntity;
import org.phenotips.entities.PrimaryEntityGroup;
import org.phenotips.entities.PrimaryEntityManager;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.stability.Unstable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
/**
* Base class for implementing specific entity groups, where members declare the groups that they belong to.
* <p>
* By default, this uses the document name as the identifier, the document title as the name, and either a
* {@code description} property in the main XObject, or the document content, as the description. If two objects use the
* same document for storage, they are assumed to be equal, and no actual data equality is checked.
* </p>
* <p>
* Members declare their group membership by attaching an XObject of type {@link #GROUP_MEMBERSHIP_CLASS} pointing to
* the group document.
* </p>
* <p>
* In order to function properly, a {@link PrimaryEntityManager} component with the hint ({@code @Named}) set to the
* name of {@link #getMemberType() the XClass used for members} must exist. Shorter versions of the XClass name are also
* accepted. For example, for members of type {@code PhenoTips.PatientClass}, the following names are supported:
* </p>
* <ol>
* <li>PhenoTips.PatientClass</li>
* <li>PatientClass</li>
* <li>Patient</li>
* </ol>
*
* @param <E> the type of entities belonging to this group; if more than one type of entities can be part of the group,
* then a generic {@code PrimaryEntity} should be used instead
* @version $Id$
* @since 1.3M2
*/
@Unstable("New class and interface added in 1.3")
public abstract class AbstractPrimaryEntityGroup<E extends PrimaryEntity>
extends AbstractPrimaryEntity implements PrimaryEntityGroup<E>
{
protected final PrimaryEntityManager<E> membersManager;
protected AbstractPrimaryEntityGroup(XWikiDocument document)
{
super(document);
PrimaryEntityManager<E> manager = null;
if (getMemberType() != null) {
ComponentManager cm = ComponentManagerRegistry.getContextComponentManager();
String[] possibleRoles = new String[3];
possibleRoles[0] = getLocalSerializer().serialize(getMemberType());
possibleRoles[1] = getMemberType().getName();
possibleRoles[2] = StringUtils.removeEnd(getMemberType().getName(), "Class");
for (String role : possibleRoles) {
try {
manager = cm.getInstance(PrimaryEntityManager.class, role);
} catch (ComponentLookupException ex) {
// TODO Use a generic manager that can work with any type of group
}
}
}
if (manager == null) {
this.logger.error("No suitable primary entity manager found for entities of type [{}] available;"
+ " certain group operations will fail", getMemberType());
}
this.membersManager = manager;
}
@Override
public Collection<E> getMembers()
{
return getMembersOfType(getMemberType());
}
@Override
public Collection<E> getMembersOfType(EntityReference type)
{
Collection<E> result = new LinkedList<>();
try {
StringBuilder hql = new StringBuilder();
hql.append("select distinct binding.name from BaseObject binding, StringProperty groupReference");
if (type != null) {
hql.append(", BaseObject entity");
}
hql.append(" where binding.className = :memberClass")
.append(" and groupReference.id.id = binding.id and groupReference.id.name = :referenceProperty")
.append(" and groupReference.value = :selfReference");
if (type != null) {
hql.append(" and entity.name = binding.name and entity.className = :entityType");
}
Query q = getQueryManager().createQuery(hql.toString(), Query.HQL);
q.bindValue("memberClass", getLocalSerializer().serialize(getMembershipClass()));
q.bindValue("referenceProperty", getMembershipProperty());
q.bindValue("selfReference", getFullSerializer().serialize(getDocument()));
q.bindValue("entityType", getLocalSerializer().serialize(type));
List<String> memberIds = q.execute();
for (String memberId : memberIds) {
result.add(this.membersManager.get(memberId));
}
} catch (QueryException ex) {
this.logger.warn("Failed to query members: {}", ex.getMessage());
}
return result;
}
@Override
public boolean addMember(E member)
{
try {
DocumentAccessBridge dab =
ComponentManagerRegistry.getContextComponentManager().getInstance(DocumentAccessBridge.class);
XWikiDocument doc = (XWikiDocument) dab.getDocument(member.getDocument());
BaseObject obj = doc.getXObject(getMembershipClass(), getMembershipProperty(),
getFullSerializer().serialize(getDocument()), false);
if (obj != null) {
return true;
}
obj = doc.newXObject(getMembershipClass(), getXContext());
obj.setStringValue(getMembershipProperty(), getFullSerializer().serialize(getDocument()));
getXContext().getWiki().saveDocument(doc, "Added to group " + getDocument(), true, getXContext());
return true;
} catch (Exception ex) {
this.logger.warn("Failed to add member to group: {}", ex.getMessage());
}
return false;
}
@Override
public boolean removeMember(E member)
{
try {
DocumentAccessBridge dab =
ComponentManagerRegistry.getContextComponentManager().getInstance(DocumentAccessBridge.class);
XWikiDocument doc = (XWikiDocument) dab.getDocument(member.getDocument());
BaseObject obj = doc.getXObject(getMembershipClass(), getMembershipProperty(),
getFullSerializer().serialize(getDocument()), false);
if (obj == null) {
return true;
}
doc.removeXObject(obj);
getXContext().getWiki().saveDocument(doc, "Removed from group " + getDocument(), true, getXContext());
return true;
} catch (Exception ex) {
this.logger.warn("Failed to remove member from group: {}", ex.getMessage());
}
return false;
}
protected QueryManager getQueryManager()
{
try {
return ComponentManagerRegistry.getContextComponentManager().getInstance(QueryManager.class);
} catch (ComponentLookupException ex) {
this.logger.error("Failed to access the query manager: {}", ex.getMessage(), ex);
}
return null;
}
protected EntityReference getMembershipClass()
{
return GROUP_MEMBERSHIP_CLASS;
}
protected String getMembershipProperty()
{
return REFERENCE_XPROPERTY;
}
}
|
package peergos.shared.user;
import jsinterop.annotations.*;
import java.util.*;
import java.util.concurrent.*;
public class JavaScriptPoster implements HttpPoster {
private final NativeJSHttp http = new NativeJSHttp();
private final boolean isAbsolute;
public JavaScriptPoster(boolean isAbsolute) {
this.isAbsolute = isAbsolute;
}
private String canonicalise(String url) {
if (isAbsolute && ! url.startsWith("/"))
return "/" + url;
return url;
}
@Override
public CompletableFuture<byte[]> post(String url, byte[] payload, boolean unzip) {
return http.post(canonicalise(url), payload);
}
@Override
public CompletableFuture<byte[]> postUnzip(String url, byte[] payload) {
return post(canonicalise(url), payload, true);
}
@Override
public CompletableFuture<byte[]> postMultipart(String url, List<byte[]> files) {
return http.postMultipart(canonicalise(url), files);
}
@Override
public CompletableFuture<byte[]> get(String url) {
if (isAbsolute) // Still do a get if we are served from an IPFS gateway
return http.get(url);
return postUnzip(url, new byte[0]);
}
@JsMethod
public static byte[] emptyArray() {
return new byte[0];
}
// This is an ugly hack to convert Uint8Array to a valid byte[]
@JsMethod
public static byte[] convertToBytes(short[] uints) {
byte[] res = new byte[uints.length];
for (int i=0; i < res.length; i++)
res[i] = (byte) uints[i];
return res;
}
}
|
package org.tiatus.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "app_user")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator = "UseExistingOrGenerateIdGenerator")
@GenericGenerator(name="UseExistingOrGenerateIdGenerator",
strategy="org.tiatus.entity.UseExistingOrGenerateIdGenerator",
parameters = {
@org.hibernate.annotations.Parameter(name = "sequence_name", value = "app_user_id_sequence")
})
@Column(name = "id")
private Long id;
@Column(name = "user_name", unique = true)
private String userName;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "password")
private String password;
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user", orphanRemoval = true)
@JsonManagedReference(value="user-role")
private Set<UserRole> roles = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
}
|
package com.yahoo.config.application;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.w3c.dom.Document;
import javax.xml.transform.TransformerException;
import java.io.StringReader;
/**
* Demonstrates that only the most specific match is retained and that this can be overridden by using ids.
*
* @author bratseth
*/
public class MultiOverrideProcessorTest {
static {
XMLUnit.setIgnoreWhitespace(true);
}
private static final String input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
" <container id='qrserver' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
" <item>\n" +
" <id>comp-B-item-0</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item deploy:environment=\"dev perf test staging prod\" deploy:region=\"us-west-1 us-east-3\">\n" +
" <id>comp-B-item-1</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item>\n" +
" <id>comp-B-item-2</id>\n" +
" <type></type>\n" +
" </item>\n" +
" </resource>\n" +
" </config>\n" +
" </component>\n" +
" </container>\n" +
"</services>\n";
private static final String inputWithIds =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
" <container id='qrserver' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
" <item id='1'>\n" +
" <id>comp-B-item-0</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item id='2' deploy:environment=\"dev perf test staging prod\" deploy:region=\"us-west-1 us-east-3\">\n" +
" <id>comp-B-item-1</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item id='3'>\n" +
" <id>comp-B-item-2</id>\n" +
" <type></type>\n" +
" </item>\n" +
" </resource>\n" +
" </config>\n" +
" </component>\n" +
" </container>\n" +
"</services>\n";
@Test
public void testParsingDev() throws TransformerException {
String expected =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
" <container id='qrserver' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
" <item>\n" +
" <id>comp-B-item-1</id>\n" +
" <type></type>\n" +
" </item>\n" +
" </resource>\n" +
" </config>\n" +
" </component>\n" +
" </container>\n" +
"</services>";
assertOverride(Environment.dev, RegionName.defaultName(), expected);
}
@Test
public void testParsingDevWithIds() throws TransformerException {
String expected =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
" <container id='qrserver' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
" <item id='1'>\n" +
" <id>comp-B-item-0</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item id='2'>\n" +
" <id>comp-B-item-1</id>\n" +
" <type></type>\n" +
" </item>\n" +
" <item id='3'>\n" +
" <id>comp-B-item-2</id>\n" +
" <type></type>\n" +
" </item>\n" +
" </resource>\n" +
" </config>\n" +
" </component>\n" +
" </container>\n" +
"</services>";
assertOverrideWithIds(Environment.dev, RegionName.defaultName(), expected);
}
private void assertOverride(Environment environment, RegionName region, String expected) throws TransformerException {
Document inputDoc = Xml.getDocument(new StringReader(input));
Document newDoc = new OverrideProcessor(environment, region).process(inputDoc);
TestBase.assertDocument(expected, newDoc);
}
private void assertOverrideWithIds(Environment environment, RegionName region, String expected) throws TransformerException {
Document inputDoc = Xml.getDocument(new StringReader(inputWithIds));
Document newDoc = new OverrideProcessor(environment, region).process(inputDoc);
TestBase.assertDocument(expected, newDoc);
}
}
|
package org.teiid.translator.jdbc.oracle;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.teiid.language.ColumnReference;
import org.teiid.language.Command;
import org.teiid.language.DerivedColumn;
import org.teiid.language.Expression;
import org.teiid.language.ExpressionValueSource;
import org.teiid.language.Function;
import org.teiid.language.Insert;
import org.teiid.language.Limit;
import org.teiid.language.Literal;
import org.teiid.language.NamedTable;
import org.teiid.language.QueryExpression;
import org.teiid.language.Select;
import org.teiid.language.SQLConstants.Tokens;
import org.teiid.language.SetQuery.Operation;
import org.teiid.language.visitor.CollectorVisitor;
import org.teiid.metadata.Column;
import org.teiid.metadata.FunctionMethod;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.SourceSystemFunctions;
import org.teiid.translator.Translator;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.TypeFacility;
import org.teiid.translator.jdbc.AliasModifier;
import org.teiid.translator.jdbc.ConvertModifier;
import org.teiid.translator.jdbc.ExtractFunctionModifier;
import org.teiid.translator.jdbc.FunctionModifier;
import org.teiid.translator.jdbc.JDBCExecutionFactory;
import org.teiid.translator.jdbc.LocateFunctionModifier;
@Translator(name="oracle", description="A translator for Oracle 9i Database or later")
public class OracleExecutionFactory extends JDBCExecutionFactory {
private static final String TIME_FORMAT = "HH24:MI:SS"; //$NON-NLS-1$
private static final String DATE_FORMAT = "YYYY-MM-DD"; //$NON-NLS-1$
private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; //$NON-NLS-1$
private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".FF"; //$NON-NLS-1$
/*
* If a missing auto_increment column is modeled with name in source indicating that an Oracle Sequence
* then pull the Sequence name out of the name in source of the column.
*/
if (!(insert.getValueSource() instanceof ExpressionValueSource)) {
return;
}
ExpressionValueSource values = (ExpressionValueSource)insert.getValueSource();
List<Column> allElements = insert.getTable().getMetadataObject().getColumns();
if (allElements.size() == values.getValues().size()) {
return;
}
int index = 0;
List<ColumnReference> elements = insert.getColumns();
for (Column element : allElements) {
if (!element.isAutoIncremented()) {
continue;
}
String name = element.getNameInSource();
int seqIndex = name.indexOf(SEQUENCE);
if (seqIndex == -1) {
continue;
}
boolean found = false;
while (index < elements.size()) {
if (element.equals(elements.get(index).getMetadataObject())) {
found = true;
break;
}
index++;
}
if (found) {
continue;
}
String sequence = name.substring(seqIndex + SEQUENCE.length());
int delimiterIndex = sequence.indexOf(Tokens.DOT);
if (delimiterIndex == -1) {
throw new TranslatorException("Invalid name in source sequence format. Expected <element name>" + SEQUENCE + "<sequence name>.<sequence value>, but was " + name); //$NON-NLS-1$ //$NON-NLS-2$
}
String sequenceGroupName = sequence.substring(0, delimiterIndex);
String sequenceElementName = sequence.substring(delimiterIndex + 1);
NamedTable sequenceGroup = this.getLanguageFactory().createNamedTable(sequenceGroupName, null, null);
ColumnReference sequenceElement = this.getLanguageFactory().createColumnReference(sequenceElementName, sequenceGroup, null, element.getJavaType());
insert.getColumns().add(index, this.getLanguageFactory().createColumnReference(element.getName(), insert.getTable(), element, element.getJavaType()));
values.getValues().add(index, sequenceElement);
}
}
@Override
public List<?> translateCommand(Command command, ExecutionContext context) {
if (command instanceof Insert) {
try {
handleInsertSequences((Insert)command);
} catch (TranslatorException e) {
throw new RuntimeException(e);
}
}
if (!(command instanceof QueryExpression)) {
return null;
}
QueryExpression queryCommand = (QueryExpression)command;
if (queryCommand.getLimit() == null) {
return null;
}
Limit limit = queryCommand.getLimit();
queryCommand.setLimit(null);
List<Object> parts = new ArrayList<Object>();
parts.add("SELECT "); //$NON-NLS-1$
/*
* if all of the columns are aliased, assume that names matter - it actually only seems to matter for
* the first query of a set op when there is a order by. Rather than adding logic to traverse up,
* we just use the projected names
*/
boolean allAliased = true;
for (DerivedColumn selectSymbol : queryCommand.getProjectedQuery().getDerivedColumns()) {
if (selectSymbol.getAlias() == null) {
allAliased = false;
break;
}
}
if (allAliased) {
String[] columnNames = queryCommand.getColumnNames();
for (int i = 0; i < columnNames.length; i++) {
if (i > 0) {
parts.add(", "); //$NON-NLS-1$
}
parts.add(columnNames[i]);
}
} else {
parts.add("*"); //$NON-NLS-1$
}
if (limit.getRowOffset() > 0) {
parts.add(" FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM ("); //$NON-NLS-1$
} else {
parts.add(" FROM ("); //$NON-NLS-1$
}
parts.add(queryCommand);
if (limit.getRowOffset() > 0) {
parts.add(") VIEW_FOR_LIMIT WHERE ROWNUM <= "); //$NON-NLS-1$
parts.add(limit.getRowLimit() + limit.getRowOffset());
parts.add(") WHERE ROWNUM_ > "); //$NON-NLS-1$
parts.add(limit.getRowOffset());
} else {
parts.add(") WHERE ROWNUM <= "); //$NON-NLS-1$
parts.add(limit.getRowLimit());
}
return parts;
}
@Override
public boolean useAsInGroupAlias(){
return false;
}
@Override
public String getSetOperationString(Operation operation) {
if (operation == Operation.EXCEPT) {
return "MINUS"; //$NON-NLS-1$
}
return super.getSetOperationString(operation);
}
@Override
public String getSourceComment(ExecutionContext context, Command command) {
String comment = super.getSourceComment(context, command);
if (context != null) {
// Check for db hints
Object payload = context.getExecutionPayload();
if (payload instanceof String) {
String payloadString = (String)payload;
if (payloadString.startsWith(HINT_PREFIX)) {
comment += payloadString + " "; //$NON-NLS-1$
}
}
}
if (command instanceof Select) {
// This simple algorithm determines the hint which will be added to the
// query.
// Right now, we look through all functions passed in the query
// (returned as a collection)
// Then we check if any of those functions are sdo_relate
// If so, the ORDERED hint is added, if not, it isn't
Collection<Function> col = CollectorVisitor.collectObjects(Function.class, command);
for (Function func : col) {
if (func.getName().equalsIgnoreCase(OracleSpatialFunctions.RELATE)) {
return comment + "/*+ ORDERED */ "; //$NON-NLS-1$
}
}
}
return comment;
}
/**
* Don't fully qualify elements if table = DUAL or element = ROWNUM or special stuff is packed into name in source value.
*
* @see org.teiid.language.visitor.SQLStringVisitor#skipGroupInElement(java.lang.String, java.lang.String)
* @since 5.0
*/
@Override
public String replaceElementName(String group, String element) {
// Check if the element was modeled as using a Sequence
int useIndex = element.indexOf(SEQUENCE);
if (useIndex >= 0) {
String name = element.substring(0, useIndex);
if (group != null) {
return group + Tokens.DOT + name;
}
return name;
}
// Check if the group name should be discarded
if((group != null && DUAL.equalsIgnoreCase(group)) || element.equalsIgnoreCase(ROWNUM)) {
// Strip group if group or element are pseudo-columns
return element;
}
return null;
}
@Override
public boolean hasTimeType() {
return false;
}
@Override
public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
if(param == null && Object.class.equals(paramType)){
//Oracle drive does not support JAVA_OBJECT type
stmt.setNull(i, Types.LONGVARBINARY);
return;
}
super.bindValue(stmt, param, paramType, i);
}
@Override
public NullOrder getDefaultNullOrder() {
return NullOrder.HIGH;
}
@Override
public boolean supportsOrderByNullOrdering() {
return true;
}
@Override
public List<String> getSupportedFunctions() {
List<String> supportedFunctions = new ArrayList<String>();
supportedFunctions.addAll(super.getSupportedFunctions());
supportedFunctions.add("ABS"); //$NON-NLS-1$
supportedFunctions.add("ACOS"); //$NON-NLS-1$
supportedFunctions.add("ASIN"); //$NON-NLS-1$
supportedFunctions.add("ATAN"); //$NON-NLS-1$
supportedFunctions.add("ATAN2"); //$NON-NLS-1$
supportedFunctions.add("COS"); //$NON-NLS-1$
supportedFunctions.add(SourceSystemFunctions.COT);
supportedFunctions.add("EXP"); //$NON-NLS-1$
supportedFunctions.add("FLOOR"); //$NON-NLS-1$
supportedFunctions.add("CEILING"); //$NON-NLS-1$
supportedFunctions.add("LOG"); //$NON-NLS-1$
supportedFunctions.add("LOG10"); //$NON-NLS-1$
supportedFunctions.add("MOD"); //$NON-NLS-1$
supportedFunctions.add("POWER"); //$NON-NLS-1$
supportedFunctions.add("SIGN"); //$NON-NLS-1$
supportedFunctions.add("SIN"); //$NON-NLS-1$
supportedFunctions.add("SQRT"); //$NON-NLS-1$
supportedFunctions.add("TAN"); //$NON-NLS-1$
supportedFunctions.add("ASCII"); //$NON-NLS-1$
supportedFunctions.add("CHAR"); //$NON-NLS-1$
supportedFunctions.add("CHR"); //$NON-NLS-1$
supportedFunctions.add("CONCAT"); //$NON-NLS-1$
supportedFunctions.add("||"); //$NON-NLS-1$
supportedFunctions.add("INITCAP"); //$NON-NLS-1$
supportedFunctions.add("LCASE"); //$NON-NLS-1$
supportedFunctions.add("LENGTH"); //$NON-NLS-1$
supportedFunctions.add("LEFT"); //$NON-NLS-1$
supportedFunctions.add("LOCATE"); //$NON-NLS-1$
supportedFunctions.add("LOWER"); //$NON-NLS-1$
supportedFunctions.add("LPAD"); //$NON-NLS-1$
supportedFunctions.add("LTRIM"); //$NON-NLS-1$
supportedFunctions.add("REPLACE"); //$NON-NLS-1$
supportedFunctions.add("RPAD"); //$NON-NLS-1$
supportedFunctions.add("RIGHT"); //$NON-NLS-1$
supportedFunctions.add("RTRIM"); //$NON-NLS-1$
supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
supportedFunctions.add("UCASE"); //$NON-NLS-1$
supportedFunctions.add("UPPER"); //$NON-NLS-1$
supportedFunctions.add("HOUR"); //$NON-NLS-1$
supportedFunctions.add("MONTH"); //$NON-NLS-1$
supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
supportedFunctions.add("YEAR"); //$NON-NLS-1$
supportedFunctions.add("DAY"); //$NON-NLS-1$
supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
supportedFunctions.add("QUARTER"); //$NON-NLS-1$
supportedFunctions.add("MINUTE"); //$NON-NLS-1$
supportedFunctions.add("SECOND"); //$NON-NLS-1$
supportedFunctions.add("QUARTER"); //$NON-NLS-1$
supportedFunctions.add("WEEK"); //$NON-NLS-1$
//supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
//supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
//supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
//supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
//supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
//supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
supportedFunctions.add("CAST"); //$NON-NLS-1$
supportedFunctions.add("CONVERT"); //$NON-NLS-1$
supportedFunctions.add("IFNULL"); //$NON-NLS-1$
supportedFunctions.add("NVL"); //$NON-NLS-1$
supportedFunctions.add("COALESCE"); //$NON-NLS-1$
return supportedFunctions;
}
@Override
public List<FunctionMethod> getPushDownFunctions(){
return OracleSpatialFunctions.getOracleSpatialFunctions();
}
@Override
public String translateLiteralTimestamp(Timestamp timestampValue) {
if (timestampValue.getNanos() == 0) {
String val = formatDateValue(timestampValue);
val = val.substring(0, val.length() - 2);
return "to_date('" + val + "', '" + DATETIME_FORMAT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return super.translateLiteralTimestamp(timestampValue);
}
@Override
public boolean supportsInlineViews() {
return true;
}
@Override
public boolean supportsFunctionsInGroupBy() {
return true;
}
@Override
public boolean supportsRowLimit() {
return true;
}
@Override
public boolean supportsRowOffset() {
return true;
}
@Override
public boolean supportsExcept() {
return true;
}
@Override
public boolean supportsIntersect() {
return true;
}
@Override
public boolean supportsAggregatesEnhancedNumeric() {
return true;
}
}
|
package petablox.util.soot;
import soot.SootMethod;
/**
* This class is a wrapper to store DFS pre and post order
* numbering of a method during scope construction in RTA
*
* Author Aditya Kamath([email protected])
*/
public class SootMethodWrapper {
private SootMethod m;
private int preOrder;
private int postOrder;
private int index;
public boolean processed;
public SootMethodWrapper(){
m = null;
preOrder = -1;
postOrder = -1;
index = -1;
processed = false;
}
public SootMethodWrapper(SootMethod m){
this();
this.m = m;
}
public SootMethodWrapper(SootMethod m, int pre, int index){
this.m = m;
this.preOrder = pre;
this.postOrder = -1;
this.index = index;
processed = false;
}
public SootMethod getSootMethod(){
return m;
}
public int getIndex(){
return index;
}
public int getPreOrder(){
return preOrder;
}
public void setPreOrder(int pre){
this.preOrder = pre;
}
public int getPostOrder(){
return postOrder;
}
public void setPostOrder(int post){
this.postOrder = post;
}
}
|
package se.vgregion.ldapservice;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.*;
@Service
@SuppressWarnings("unchecked")
public class AsyncCachingLdapServiceWrapper implements LdapService {
private static final CacheManager SINGLE_CACHE_MANAGER = CacheManager.create();
private Ehcache cache;
private LdapService ldapService;
private static final int N_THREADS = 10;
private ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> lastScheduledTask;
/**
* Constructor.
*
* @param ldapService ldapService
*/
public AsyncCachingLdapServiceWrapper(LdapService ldapService) {
final int hours = 48;
final int minutes = 60;
final int seconds = 60;
final int millis = 1000;
long timeoutInMillis = hours * minutes * seconds * millis; // 48 hours
// The timeout arguments mean that it's only the time from creation that matters; the idle time can
// never be longer than the time since creation.
String name = this.getClass() + "Cache_" + timeoutInMillis;
if (!SINGLE_CACHE_MANAGER.cacheExists(name)) {
final int maxElementsInMemory = 500;
this.cache = new Cache(name, maxElementsInMemory, false, false, timeoutInMillis, timeoutInMillis);
SINGLE_CACHE_MANAGER.addCache(cache);
} else {
this.cache = SINGLE_CACHE_MANAGER.getCache(name);
}
this.ldapService = ldapService;
}
/**
* Constructor.
*
* @param ldapService ldapService
* @param timeToLiveSeconds the time the cached elements should live (from creation)
*/
public AsyncCachingLdapServiceWrapper(LdapService ldapService, long timeToLiveSeconds) {
// The timeout arguments mean that it's only the time from creation that matters; the idle time can
// never be longer than the time since creation.
String name = this.getClass() + "Cache_" + timeToLiveSeconds;
if (!SINGLE_CACHE_MANAGER.cacheExists(name)) {
final int maxElementsInMemory = 500;
cache = new Cache(name, maxElementsInMemory, false, false, timeToLiveSeconds, timeToLiveSeconds);
SINGLE_CACHE_MANAGER.addCache(cache);
} else {
this.cache = SINGLE_CACHE_MANAGER.getCache(name);
}
this.ldapService = ldapService;
}
@Override
public LdapUser[] search(final String base, final String filter) {
Integer cacheKey = createCacheKey(base, filter);
Element element = cache.get(cacheKey);
if (element != null) {
return (LdapUser[]) element.getValue();
}
// We cannot make a wrapper of an Array, so just delegate synchronously.
LdapUser[] search = ldapService.search(base, filter);
if (search != null) {
cache.put(new Element(cacheKey, search));
}
return search;
}
private Integer createCacheKey(Object... args) {
int callingLineNumber = new Exception().getStackTrace()[1].getLineNumber();
int prime = 7;
int hash = callingLineNumber * prime;
for (Object arg : args) {
if (arg != null) {
hash += arg.hashCode() * prime;
}
}
return hash;
}
@Override
public LdapUser[] search(String s, String s1, String[] strings) {
throw new UnsupportedOperationException();
}
@Override
public LdapUser getLdapUser(String s, String s1) {
throw new UnsupportedOperationException();
}
@Override
public LdapUser getLdapUser(String s, String s1, String[] strings) {
throw new UnsupportedOperationException();
}
@Override
public Properties getProperties() {
throw new UnsupportedOperationException();
}
@Override
public boolean addLdapUser(String s, HashMap<String, String> stringStringHashMap) {
throw new UnsupportedOperationException();
}
@Override
public boolean modifyLdapUser(LdapUser ldapUser, HashMap<String, String> stringStringHashMap) {
throw new UnsupportedOperationException();
}
@Override
public boolean deleteLdapUser(LdapUser ldapUser) {
throw new UnsupportedOperationException();
}
@Override
public LdapUser getLdapUserByUid(String s, String s1) {
throw new UnsupportedOperationException();
}
@Override
public LdapUser getLdapUserByUid(final String userId) {
Integer cacheKey = createCacheKey(userId);
Element element = cache.get(cacheKey);
if (element != null) {
return (LdapUser) element.getValue();
}
Callable callable = new Callable<LdapUser>() {
@Override
public LdapUser call() throws Exception {
return ldapService.getLdapUserByUid(userId);
}
};
Future<LdapUser> futureLdapUser = executor.submit(callable);
AsyncLdapUserWrapper ldapUser = new AsyncLdapUserWrapper(futureLdapUser, cacheKey);
cache.put(new Element(cacheKey, ldapUser));
// Cleanup null objects since we don't want to cache them.
if (lastScheduledTask == null || lastScheduledTask.isDone()) {
// Otherwise it is unnecessary to pile up tasks
lastScheduledTask = scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
final List keys = cache.getKeys();
for (Object key : keys) {
final Element element1 = cache.get(key);
if (element1 == null || element1.getObjectValue() == null) {
cache.remove(key);
}
}
}
}, 5, TimeUnit.SECONDS);
}
return ldapUser;
}
private class AsyncLdapUserWrapper implements LdapUser {
private final Logger LOGGER = LoggerFactory.getLogger(AsyncLdapUserWrapper.class);
private static final long serialVersionUID = -1123850060733039675L;
private Future<LdapUser> futureLdapUser;
private Integer cacheKey;
/**
* Constructor.
*
* @param futureLdapUser futureLdapUser
* @param cacheKey
*/
public AsyncLdapUserWrapper(Future<LdapUser> futureLdapUser, Integer cacheKey) {
this.futureLdapUser = futureLdapUser;
this.cacheKey = cacheKey;
}
@Override
public String getDn() {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return null;
}
cache.put(new Element(cacheKey, ldapUser));
return ldapUser.getDn();
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public String getAttributeValue(String s) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return null;
}
cache.put(new Element(cacheKey, ldapUser));
return ldapUser.getAttributeValue(s);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public String[] getAttributeValues(String s) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return null;
}
cache.put(new Element(cacheKey, ldapUser));
return ldapUser.getAttributeValues(s);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public Map<String, ArrayList<String>> getAttributes() {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return null;
}
cache.put(new Element(cacheKey, ldapUser));
return ldapUser.getAttributes();
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public void clearAttribute(String s) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return;
}
cache.put(new Element(cacheKey, ldapUser));
ldapUser.clearAttribute(s);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public void setAttributeValue(String s, Object o) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return;
}
cache.put(new Element(cacheKey, ldapUser));
ldapUser.setAttributeValue(s, o);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public void addAttributeValue(String s, Object o) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return;
}
cache.put(new Element(cacheKey, ldapUser));
ldapUser.addAttributeValue(s, o);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
@Override
public void setAttributeValue(String s, Object[] objects) {
try {
LdapUser ldapUser = futureLdapUser.get();
if (ldapUser == null) {
return;
}
cache.put(new Element(cacheKey, ldapUser));
ldapUser.setAttributeValue(s, objects);
} catch (InterruptedException e) {
throw new LdapUserRetrievalException(e);
} catch (ExecutionException e) {
throw new LdapUserRetrievalException(e);
}
}
}
}
|
package crazypants.enderio.integration.tic.recipes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.tuple.Pair;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.util.NNList.NNIterator;
import com.enderio.core.common.util.NullHelper;
import com.enderio.core.common.util.stackable.Things;
import crazypants.enderio.base.Log;
import crazypants.enderio.integration.tic.queues.BasinQueue;
import crazypants.enderio.integration.tic.queues.CastQueue;
import crazypants.enderio.integration.tic.queues.SmeltQueue;
import crazypants.enderio.integration.tic.queues.TiCQueues;
import crazypants.enderio.integration.tic.queues.TicHandler;
import crazypants.enderio.util.Prep;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import slimeknights.mantle.util.RecipeMatch;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.smeltery.CastingRecipe;
import slimeknights.tconstruct.library.smeltery.MeltingRecipe;
public class TicRegistration {
private static void registerAlloyRecipe(Pair<Things, NNList<Things>> alloy) {
final Things result = NullHelper.notnull(alloy.getLeft(), "missing result item stack in alloy recipe");
final NNList<Things> input = alloy.getRight();
FluidStack fluidResult = getFluidForItems(result);
if (fluidResult == null) {
tryBasinAloying(result, input);
return;
}
Set<String> used = new HashSet<>();
used.add(fluidResult.getFluid().getName());
FluidStack[] fluids = new FluidStack[input.size()];
List<String> debug = new ArrayList<>();
for (int i = 0; i < input.size(); i++) {
if ((fluids[i] = getFluidForItems(NullHelper.notnull(input.get(i), "missing input item stack in alloy recipe"))) == null
|| used.contains(fluids[i].getFluid().getName())) {
return;
}
used.add(fluids[i].getFluid().getName());
debug.add(toString(fluids[i]));
}
gcd(fluidResult, fluids);
TinkerRegistry.registerAlloy(fluidResult, fluids);
Log.debug("Tinkers.registerAlloy: " + toString(fluidResult) + ", " + debug);
}
private static void tryBasinAloying(@Nonnull Things result, NNList<Things> inputs) {
if (!result.isValid() || result.getItemStack().getCount() != 1 || !(result.getItemStack().getItem() instanceof ItemBlock) || inputs.size() != 2) {
return;
}
final Things input0 = inputs.get(0);
final Things input1 = inputs.get(1);
if (!input0.isValid() || !input1.isValid()) {
return;
}
FluidStack a = getFluidForItems(input0);
FluidStack b = getFluidForItems(input1);
if ((a == null) == (b == null)) {
return;
}
if (a == null && !(input0.getItemStack().getCount() == 1 && input0.getItemStack().getItem() instanceof ItemBlock)) {
return;
}
if (b == null && !(input1.getItemStack().getCount() == 1 && input1.getItemStack().getItem() instanceof ItemBlock)) {
return;
}
if (a != null) {
TicHandler.instance.registerBasinCasting(result, input1, a.getFluid(), a.amount);
} else if (b != null) {
TicHandler.instance.registerBasinCasting(result, input0, b.getFluid(), b.amount);
}
}
public static void registerBasinCasting() {
for (BasinQueue basin : TiCQueues.getBasinQueue()) {
if (basin.getFluid() == null) {
FluidStack fluid = getFluidForItems(basin.getFluidItem());
if (fluid != null) {
basin.setFluid(fluid.getFluid());
basin.setAmount(basin.getAmount() * fluid.amount);
}
}
if (basin.getFluid() == null) {
Log.warn("Item used in basin cast recipe '" + toString(basin.getFluidItem()) + "' doesn't smelt into a fluid");
}
if (!basin.getOutput().isValid()) {
Log.warn("Item used in basin cast recipe '" + toString(basin.getOutput()) + "' doesn't exist");
}
if (!basin.getCast().isEmpty()) {
for (NNIterator<ItemStack> itr = basin.getCast().getItemStacks().fastIterator(); itr.hasNext();) {
ItemStack castStack = itr.next();
TinkerRegistry.registerBasinCasting(basin.getOutput().getItemStack(), castStack, basin.getFluid(), (int) Math.ceil(basin.getAmount()));
Log.debug("Tinkers.registerBasinCasting: " + toString(basin.getOutput()) + ", " + toString(castStack) + ", " + basin.getFluid().getName() + ", "
+ basin.getAmount());
}
} else {
TinkerRegistry.registerBasinCasting(basin.getOutput().getItemStack(), Prep.getEmpty(), basin.getFluid(), (int) Math.ceil(basin.getAmount()));
Log.debug("Tinkers.registerBasinCasting: " + toString(basin.getOutput()) + ", (empty), " + basin.getFluid().getName() + ", " + basin.getAmount());
}
}
TiCQueues.getBasinQueue().clear();
}
public static void registerTableCasting() {
for (CastQueue cast : TiCQueues.getCastQueue()) {
if (cast.getFluid() == null) {
FluidStack fluid = getFluidForItems(cast.getItem());
if (fluid != null) {
cast.setFluid(fluid.getFluid());
cast.setAmount(cast.getAmount() * fluid.amount);
}
}
if (cast.getFluid() == null) {
Log.warn("Item used in cast recipe '" + toString(cast.getItem()) + "' doesn't smelt into a fluid");
} else if (!cast.getResult().isValid()) {
Log.warn("Item used in cast recipe '" + toString(cast.getResult()) + "' doesn't exist");
} else {
if (!cast.getCast().isEmpty()) {
for (NNIterator<ItemStack> itr = cast.getCast().getItemStacks().fastIterator(); itr.hasNext();) {
ItemStack castStack = itr.next();
TinkerRegistry.registerTableCasting(new CastingRecipe(cast.getResult().getItemStack(), RecipeMatch.ofNBT(castStack), cast.getFluid(),
(int) Math.ceil(cast.getAmount()), cast.isConsumeCast(), false));
Log.debug("Tinkers.registerTableCasting: " + toString(cast.getResult()) + ", " + toString(castStack) + ", " + cast.getFluid().getName() + ", "
+ cast.getAmount());
}
} else {
TinkerRegistry.registerTableCasting(
new CastingRecipe(cast.getResult().getItemStack(), null, cast.getFluid(), (int) Math.ceil(cast.getAmount()), cast.isConsumeCast(), false));
Log.debug("Tinkers.registerTableCasting: " + toString(cast.getResult()) + ", (no cast), " + cast.getFluid().getName() + ", " + cast.getAmount());
}
}
}
TiCQueues.getCastQueue().clear();
}
public static void registerAlloys() {
for (Pair<Things, NNList<Things>> alloy : TiCQueues.getAlloyQueue()) {
registerAlloyRecipe(alloy);
}
TiCQueues.getAlloyQueue().clear();
}
public static void registerSmeltings() {
for (SmeltQueue smelt : TiCQueues.getSmeltQueue()) { // 1st because it may provide fluids for later
if (smelt.getFluidOutput() == null) {
FluidStack fluid = getFluidForItems(smelt.getOutput());
if (fluid == null) {
Log.warn("Item used in Smeltery recipe '" + toString(smelt.getOutput()) + "' doesn't smelt into a fluid");
} else {
smelt.setFluidOutput(fluid.getFluid());
smelt.setAmount(smelt.getAmount() * fluid.amount);
}
}
if (smelt.getFluidOutput() != null) {
for (ItemStack in : smelt.getInput().getItemStacks()) {
TinkerRegistry.registerMelting(in, smelt.getFluidOutput(), (int) Math.max(1, Math.floor(smelt.getAmount())));
Log.debug("Tinkers.registerMelting: " + toString(in) + ", " + smelt.getFluidOutput().getName() + ", " + smelt.getAmount());
}
}
}
TiCQueues.getSmeltQueue().clear();
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
private static void gcd(FluidStack input, FluidStack... inputs) {
int result = input.amount;
for (FluidStack stack : inputs) {
result = gcd(result, stack.amount);
}
if (result > 1) {
input.amount /= result;
for (FluidStack stack : inputs) {
stack.amount /= result;
}
}
}
private static FluidStack getFluidForItems(@Nonnull ItemStack input) {
ItemStack itemStack = input.copy();
itemStack.setCount(1);
MeltingRecipe melting = TinkerRegistry.getMelting(itemStack);
if (melting == null) {
// For some reason this recipe isn't yet available in postInit...
if (itemStack.getItem() == Item.getItemFromBlock(Blocks.OBSIDIAN)) {
Fluid fluid = FluidRegistry.getFluid("obsidian");
if (fluid != null) {
return new FluidStack(fluid, 288 * input.getCount());
}
}
Log.debug("Failed to get Tinker's Construct melting recipe for " + toString(itemStack));
return null;
}
FluidStack result = melting.getResult();
if (result != null) {
result.amount *= input.getCount();
return result;
} else {
Log.info("Failed to get Tinker's Construct melting recipe result for " + toString(itemStack) + " -> " + toString(result));
return null;
}
}
private static FluidStack getFluidForItems(Things item) {
if (item != null) {
NNList<ItemStack> itemStacks = item.getItemStacks();
for (NNIterator<ItemStack> itr = itemStacks.fastIterator(); itr.hasNext();) {
FluidStack fluidStack = getFluidForItems(itr.next());
if (fluidStack != null) {
return fluidStack;
}
}
}
return null;
}
private static @Nonnull String toString(Things o) {
return (o == null || o.isEmpty()) ? "(empty)" : (o + " (" + toString(o.getItemStacks()) + ")");
}
private static @Nonnull String toString(@Nonnull List<ItemStack> o) {
List<String> result = new NNList<>();
for (ItemStack itemStack : o) {
result.add(toString(itemStack));
}
return "" + result.toString();
}
private static @Nonnull String toString(ItemStack o) {
return (o == null || Prep.isInvalid(o)) ? "(empty)" : (o + " (" + o.getDisplayName() + ")");
}
private static @Nonnull String toString(FluidStack o) {
return o == null ? "(null)" : (o + " (" + o.getLocalizedName() + ")");
}
}
|
package com.github.aureliano.evtbridge.core.register;
import java.util.HashMap;
import java.util.Map;
import com.github.aureliano.evtbridge.common.exception.EventBridgeException;
import com.github.aureliano.evtbridge.common.helper.ReflectionHelper;
import com.github.aureliano.evtbridge.common.helper.StringHelper;
import com.github.aureliano.evtbridge.core.agent.IAgent;
import com.github.aureliano.evtbridge.core.config.IConfiguration;
import com.github.aureliano.evtbridge.core.config.IConfigurationConverter;
public final class ApiServiceRegistrator {
private static ApiServiceRegistrator instance;
private Map<String, ServiceRegistration> registrations;
private ApiServiceRegistrator() {
this.registrations = new HashMap<String, ServiceRegistration>();
}
public void registrate(Class<? extends IConfiguration> configuration, Class<? extends IAgent> executor) {
this.registrate(configuration, executor, null);
}
public void registrate(Class<? extends IConfiguration> configuration, Class<? extends IAgent> executor, Class<? extends IConfigurationConverter<?>> converter) {
this.registrate(this.createService(configuration, executor, converter));
}
public void registrate(ServiceRegistration registration) {
if (StringHelper.isEmpty(registration.getId())) {
if (registration.getConfiguration() != null) {
IConfiguration configuration = (IConfiguration) ReflectionHelper.newInstance(registration.getConfiguration());
registration.withId(configuration.id());
} else {
throw new EventBridgeException("Service registration expected to get a valid id but got an empty value.");
}
}
this.registrations.put(registration.getId(), registration);
}
public IAgent createAgent(IConfiguration configuration) {
ServiceRegistration registration = this.registrations.get(configuration.id());
if ((registration == null) || (registration.getAgent() == null)) {
throw new EventBridgeException("There isn't an executor (reader/writer) registered with ID " + configuration.id());
}
IAgent executor = (IAgent) ReflectionHelper.newInstance(registration.getAgent());
return executor.withConfiguration(configuration);
}
public IConfigurationConverter<?> createConverter(String id) {
ServiceRegistration registration = this.registrations.get(id.toUpperCase());
if (registration == null) {
return null;
}
return (IConfigurationConverter<?>) ReflectionHelper.newInstance(registration.getConverter());
}
public Class<? extends IConfiguration> getConfiguration(String id) {
ServiceRegistration registration = this.registrations.get(id.toUpperCase());
if (registration == null) {
return null;
}
return registration.getConfiguration();
}
public static ApiServiceRegistrator instance() {
if (instance == null) {
instance = new ApiServiceRegistrator();
}
return instance;
}
private ServiceRegistration createService(Class<? extends IConfiguration> configuration,
Class<? extends IAgent> executor, Class<? extends IConfigurationConverter<?>> converter) {
return new ServiceRegistration()
.withConfiguration(configuration)
.withAgent(executor)
.withConverter(converter);
}
}
|
package org.opennms.netmgt.config.accesspointmonitor;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
/**
* <p>
* Service class.
* </p>
*
* @author <a href="mailto:[email protected]">Jesse White</a>
*/
@XmlType(name = "service")
public class Service extends ServiceTemplate implements Cloneable {
private static final long serialVersionUID = -7231942028852991463L;
@XmlAttribute(name = "template-name")
private String m_templateName;
@XmlTransient
private ServiceTemplate m_template;
public Service() {
super();
}
public Service(Service copy) {
super(copy);
if (copy.m_templateName != null) {
m_templateName = new String(copy.m_templateName);
}
if (copy.m_template != null) {
m_template = new ServiceTemplate(copy.m_template);
}
}
@XmlTransient
public String getTemplateName() {
return m_templateName;
}
public void setTemplateName(String templateName) {
m_templateName = templateName;
}
@XmlTransient
public ServiceTemplate getTemplate() {
return m_template;
}
public void setTemplate(ServiceTemplate template) {
m_template = template;
}
public int compareTo(final ServiceTemplate obj) {
final CompareToBuilder builder = new CompareToBuilder()
.append(getName(), obj.getName())
.append(getThreads(), obj.getThreads())
.append(getPassiveServiceName(), obj.getPassiveServiceName())
.append(getInterval(), obj.getInterval())
.append(getStatus(), obj.getStatus());
if (obj instanceof Service) {
builder.append(getTemplateName(), ((Service)obj).getTemplateName());
}
builder.append(getParameters().toArray(OF_PARAMETERS), obj.getParameters().toArray(OF_PARAMETERS));
return builder.toComparison();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((m_template == null) ? 0 : m_template.hashCode());
result = prime * result + ((m_templateName == null) ? 0 : m_templateName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Service) {
Service other = (Service) obj;
return new EqualsBuilder()
.append(getName(), other.getName())
.append(getThreads(), other.getThreads())
.append(getPassiveServiceName(), other.getPassiveServiceName())
.append(getInterval(), other.getInterval())
.append(getStatus(), other.getStatus())
.append(getTemplateName(), other.getTemplateName())
.append(getParameters().toArray(OF_PARAMETERS), other.getParameters().toArray(OF_PARAMETERS))
.isEquals();
}
return false;
}
@Override
public Object clone() throws CloneNotSupportedException {
Service cloned = new Service();
cloned.m_template = m_template;
cloned.m_templateName = m_templateName;
cloned.m_name = m_name;
cloned.m_threads = m_threads;
cloned.m_passiveServiceName = m_passiveServiceName;
cloned.m_interval = m_interval;
cloned.m_status = m_status;
cloned.m_parameters = new ArrayList<Parameter>();
for (Parameter p : getParameters()) {
cloned.m_parameters.add((Parameter) p.clone());
}
return cloned;
}
}
|
package me.zzp.ar;
import java.util.Map;
import java.util.Set;
import me.zzp.ar.ex.IllegalFieldNameException;
public final class Record {
private final Table table;
private final Map<String, Object> values;
Record(Table table, Map<String, Object> values) {
this.table = table;
this.values = values;
}
public Set<String> columnNames() {
return values.keySet();
}
public <E> E get(String name) {
name = name.toLowerCase();
if (values.containsKey(name)) {
return (E) values.get(name);
} else if (table.relations.containsKey(name)) {
Association relation = table.relations.get(name);
Table active = table.dbo.active(relation.target);
active.join(relation.assoc(table.name, getInt("id")));
if (relation.isAncestor() && !relation.isCross()) {
active.constrain(relation.key, getInt("id"));
}
return (E)(relation.isOnlyOneResult()? active.first(): active);
} else {
throw new IllegalFieldNameException(name);
}
}
/* For primitive types */
public boolean getBool(String name) {
return get(name);
}
public byte getByte(String name) {
return get(name);
}
public char getChar(String name) {
return get(name);
}
public short getShort(String name) {
return get(name);
}
public int getInt(String name) {
return get(name);
}
public long getLong(String name) {
return get(name);
}
public float getFloat(String name) {
return get(name);
}
public double getDouble(String name) {
return get(name);
}
/* For any other types */
public String getStr(String name) {
return get(name);
}
public <E> E get(String name, Class<E> type) {
return type.cast(get(name));
}
public Record set(String name, Object value) {
name = name.toLowerCase();
values.put(name, value);
return this;
}
public Record save() {
table.update(this);
return this;
}
public Record update(Object... args) {
for (int i = 0; i < args.length; i += 2) {
String name = args[0].toString();
if (name.endsWith(":")) {
name = name.substring(0, name.length() - 1);
}
set(name, args[1]);
}
return save();
}
public void destroy() {
table.delete(this);
}
@Override
public String toString() {
StringBuilder line = new StringBuilder();
for (Map.Entry<String, Object> e : values.entrySet()) {
line.append(String.format("%s = %s\n", e.getKey(), e.getValue()));
}
return line.toString();
}
}
|
package netty;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueue;
import servers.NodeServerProperties1;
import servers.Notification;
import servers.Proposal;
import servers.Vote;
import servers.ZxId;
import util.FileOps;
/**
* Handles a server-side channel.
*/
public class InHandler2 extends ChannelInboundHandlerAdapter {
private static final Logger LOG = LogManager.getLogger(InHandler2.class);
private NodeServerProperties1 properties;
private NettyClient1 nettyClient;
public InHandler2(NodeServerProperties1 nsProperties) {
this.properties = nsProperties;
nettyClient = new NettyClient1(nsProperties);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
String requestMsg = in.toString(StandardCharsets.UTF_8 );
LOG.info(">>>Channel Read:" + requestMsg);
String response = handleClientRequest(requestMsg);
LOG.info("<<<Response:" + response);
if(response.length()>0){
ctx.write(Unpooled.copiedBuffer(response+"\r\n", StandardCharsets.UTF_8));
ctx.flush();
ctx.close();
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
LOG.info("Channel Registered: "+ ctx.channel().localAddress() + ":" + ctx.channel().remoteAddress());
}
private String handleClientRequest(String requestMsg) {
// LOG.info("handleClientRequest:"+requestMsg);
if(requestMsg.contains("WRITE:")){
if(!properties.isLeader()){ //follower
//Forward write request to the leader
LOG.info("Follower received WRITE request from client, forwarding to the leader..!!");
this.nettyClient.sendMessage(properties.getLeaderAddress().getHostName(), properties.getLeaderAddress().getPort(), requestMsg);
return "OK";
}
else{ //leader
//"WRITE:KEY:VALUE"
String[] arr = requestMsg.split(":");
//Key-value pair to be proposed
String key = arr[1].trim();
String value = arr[2].trim();
long epoch = 3;//this.properties.getAcceptedEpoch()
long counter = 4;//this.getCounter()++;
//Form a proposal
ZxId z = new ZxId(epoch, counter);
Proposal p = new Proposal(z, key, value);
String proposal = "PROPOSE:" + p.toString();
//enqueue this proposal to proposed transactions to keep the count of Acknowledgements
ConcurrentHashMap<Proposal, AtomicInteger> proposedtransactions = properties.getSynData().getProposedTransactions();
proposedtransactions.put(p, new AtomicInteger(1));
//checking if the entry is enqueued in the proposed transaction map
LOG.info("Checking the counter right after enqueueing the entry: " + proposedtransactions.get(p));
//send proposal to quorum
LOG.info("Leader:" + "Sending proposal to everyone:" + proposal);
LOG.info("Number of members:" + properties.getMemberList().size());
for (Entry<Long, InetSocketAddress> member : properties.getMemberList().entrySet()) {
LOG.info("Sending "+proposal+" to: "+ member.getValue().getHostName() + ":"+ member.getValue().getPort());
this.nettyClient.sendMessage(member.getValue().getHostName(), member.getValue().getPort(), proposal);
}
}
return "OK";
}
if(requestMsg.contains("PROPOSE")){
if(properties.isLeader()){ // Leader will not accept this message
LOG.info("I am the Leader, I do not accept proposals");
return "ERROR: I am the eader, I send proposals, not accept!";
}
else{ ///Follower
//enqueue this message to proposal queue
String[] arr = requestMsg.split(":");
Long epoch = Long.parseLong(arr[1].trim());
Long counter = Long.parseLong(arr[2].trim());
ZxId z = new ZxId(epoch, counter);
String key = arr[3].trim();
String value = arr[4].trim();
Proposal proposal = new Proposal(z,key,value);
properties.getSynData().getProposedTransactions().put(proposal, new AtomicInteger(0));
LOG.info("Enqueing proposal in Proposal Queue:" + proposal);
LOG.info("Sending Acknowledgement to the leader");
return "ACK_PROPOSAL:" + proposal.toString();
}
}
if(requestMsg.contains("ACK_PROPOSAL")){
if(!properties.isLeader()){//follower
//follower should disregard this message
LOG.info("Follower got ACK_PROPOSAL, shouldn't happen!");
return "ERROR:Follower got ACK_PROPOSAL";
}
else{//Leader
String[] arr = requestMsg.split(":");
//Parsing proposal for which acknowledgement was received
Long epoch = Long.parseLong(arr[1].trim());
Long counter = Long.parseLong(arr[2].trim());
ZxId z = new ZxId(epoch, counter);
String key = arr[3].trim();
String value = arr[4].trim();
Proposal p = new Proposal(z,key,value);
//we have to increment the ack count for this zxid
LOG.info("Leader: Got ACK_PROPOSAL, incrementing count for zxid" + z);
//checking the ack count for the proposal (counter value)
ConcurrentHashMap<Proposal, AtomicInteger> proposedtransactions = properties.getSynData().getProposedTransactions();
//LOG.info("
int count = proposedtransactions.get(p).incrementAndGet();
proposedtransactions.put(p, new AtomicInteger(count));
//LOG.info("
return "OK";
}
}
if(requestMsg.contains("COMMIT:")){
if(properties.isLeader()){ // leader will not accept this message
LOG.info("I am the Leader, I do not accept commit messages");
return "ERROR: I am the eader, I send proposals, not accept!";
}
else{//follower
LOG.info ("Follower received COMMIT message");
LOG.info ("COMMIT message is:" + requestMsg);
String[] arr = requestMsg.split(":");
//Parsing proposal for which acknowledgement was received
Long epoch = Long.parseLong(arr[1].trim());
Long counter = Long.parseLong(arr[2].trim());
ZxId z = new ZxId(epoch, counter);
String key = arr[3].trim();
String value = arr[4].trim();
Proposal p = new Proposal(z,key,value);
if(properties.getSynData().getProposedTransactions().contains(p)){
LOG.info("Commit Queue contains the transaction to be removed:" + p);
//String fileName = "CommitedHistory_" + properties.getNodePort() + ".log";
//FileOps.appendTransaction(fileName, p.toString());
synchronized (properties.getSynData().getProposedTransactions()) {
//remove from proposedtransactions map
LOG.info("Inside synchronized block....!!!");
properties.getSynData().getProposedTransactions().remove(p);
//enqueue in commitQueue
properties.getSynData().getCommittedTransactions().add(p);
}
}
return "OK";
}
}
if(requestMsg.contains("JOIN_GROUP:")){
//add the ip:port to the group member list;
String[] arr = requestMsg.split(":");
long nodeId = Integer.parseInt(arr[1].trim());
InetSocketAddress addr = new InetSocketAddress(arr[2].trim(), Integer.parseInt(arr[3].trim()));
properties.addMemberToList(nodeId, addr);
LOG.info(properties.getMemberList());
return "OK";
}
if(requestMsg.contains("CNOTIFICATION:")){
//add the ip:port to thefore group member list;
String[] arr = requestMsg.split(":");
Notification responseNotification = new Notification(arr[1].trim());
if(properties.getNodestate() == NodeServerProperties1.State.ELECTION){
MpscArrayQueue<Notification> currentElectionQueue = properties.getSynData().getElectionQueue();
LOG.info("Before:"+currentElectionQueue.currentProducerIndex());
LOG.info("adding notification to the queue"+ responseNotification.toString());
currentElectionQueue.offer(responseNotification);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOG.info("After:"+currentElectionQueue.currentProducerIndex());
LOG.info("NODE is in STATE: "+ properties.getNodestate());
LOG.info("My Election ROUND: "+ properties.getElectionRound());
LOG.info("his Election ROUND: "+ responseNotification.getSenderRound());
if(responseNotification.getSenderState() == NodeServerProperties1.State.ELECTION
&& responseNotification.getSenderRound() <= properties.getElectionRound()){
// get my current vote from FLE or when FLE is underway
Vote myVote = properties.getMyVote();
//public Notification(Vote vote, long id, servers.NodeServerProperties1.State state, long round)
Notification myNotification = new Notification(myVote, properties.getNodeId(), properties.getNodestate(), properties.getElectionRound());
return("SNOTIFICATION:"+myNotification.toString());
}
}
else if(responseNotification.getSenderState() == NodeServerProperties1.State.ELECTION){
// get my current vote from FLE or when FLE is underway
Vote myVote = properties.getMyVote();
Notification myNotification = new Notification(myVote, properties.getNodeId(), properties.getNodestate(), properties.getElectionRound());
LOG.info("myNotification:"+myNotification);
return("SNOTIFICATION:"+myNotification.toString());
}
return("");
}
if(requestMsg.contains("SNOTIFICATION:")){
//add the ip:port to the group member list;
String[] arr = requestMsg.split(":");
Notification responseNotification = new Notification(arr[1].trim());
if(properties.getNodestate() == NodeServerProperties1.State.ELECTION){
MpscArrayQueue<Notification> currentElectionQueue = properties.getSynData().getElectionQueue();
LOG.info("Before:"+currentElectionQueue.currentProducerIndex());
currentElectionQueue.offer(responseNotification);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOG.info("After:"+currentElectionQueue.currentProducerIndex());
}
LOG.info(properties.getMemberList());
return("ERROR");
}
if(requestMsg.contains("OK")){
//add the ip:port to the group member list;
// String[] arr = requestMsg.split(":");
// InetSocketAddress addr = new InetSocketAddress(arr[1].trim(), Integer.parseInt(arr[2].trim()));
// server.addMemberToList(addr);
LOG.info("Client received OK!!");
LOG.info(properties.getMemberList());
return "";
}
if (requestMsg.contains("FOLLOWERINFO")){
String[] accEpoch = requestMsg.split(":");
long nodeId = Long.parseLong(accEpoch[1]);
long acceptedEpoch = Long.parseLong(accEpoch[2]);
long currentEpoch = Long.parseLong(accEpoch[3]);
long currentCounter = Long.parseLong(accEpoch[4]);
ZxId followerLastCommittedZxid = new ZxId(currentEpoch, currentCounter);
ConcurrentHashMap<Long, Long> acceptedEpochMap = properties.getSynData().getAcceptedEpochMap();
ConcurrentHashMap<Long, ZxId> currentEpochMap = properties.getSynData().getCurrentEpochMap();
acceptedEpochMap.put(nodeId, acceptedEpoch);
currentEpochMap.put(nodeId, followerLastCommittedZxid);
properties.getSynData().setAcceptedEpochMap(acceptedEpochMap);
properties.getSynData().setCurrentEpochMap(currentEpochMap);
return "";
}
if (requestMsg.contains("NEWEPOCH")){
String[] newEpocharr = requestMsg.split(":");
long newEpoch = Long.parseLong(newEpocharr[1]);
}
return "";
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
|
package no.javazone;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.pattern.Patterns;
import akka.routing.RoundRobinPool;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;
import java.util.concurrent.TimeUnit;
import static no.javazone.util.Timer.time;
public class Akka {
private static class TaskActor extends UntypedActor {
@Override
public void onReceive(Object msg) throws Exception {
if ("run".equals(msg)) {
sender().tell(Big.task(), self());
} else {
unhandled(msg);
}
}
}
private static class TaskRunner extends UntypedActor {
private ActorRef taskActor;
private ActorRef originator;
private int activeTasks = 0;
public TaskRunner() {
this.taskActor =
context().actorOf(
Props.create(TaskActor.class).withRouter(new RoundRobinPool(10)),
"task"
);
}
@Override
public void onReceive(Object msg) throws Exception {
if ("start".equals(msg)) {
for (int i = 0; i < RunConfig.numRuns; i++) {
taskActor.tell("run", self());
activeTasks++;
}
originator = sender();
} else if (msg instanceof Long) {
activeTasks
if (activeTasks == 0) {
originator.tell("done", self());
} else if (activeTasks % 1000 == 0) {
System.out.println("Remaining: " + activeTasks);
}
} else {
unhandled(msg);
}
}
}
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create();
time(() -> {
ActorRef taskRunner = system.actorOf(Props.create(TaskRunner.class), "runner");
Await.result(Patterns.ask(taskRunner, "start", 30000), Duration.create(30, TimeUnit.SECONDS));
});
system.shutdown();
}
}
|
package org.ethereum.net.eth.sync;
import org.ethereum.core.Block;
import org.ethereum.core.BlockWrapper;
import org.ethereum.core.Blockchain;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.rlpx.discover.DiscoverListener;
import org.ethereum.net.rlpx.discover.NodeHandler;
import org.ethereum.net.rlpx.discover.NodeManager;
import org.ethereum.net.rlpx.discover.NodeStatistics;
import org.ethereum.net.server.Channel;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.util.Functional;
import org.ethereum.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;
import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.net.eth.sync.SyncStateName.*;
import static org.ethereum.util.BIUtil.isIn20PercentRange;
import static org.ethereum.util.TimeUtils.secondsToMillis;
/**
* @author Mikhail Kalinin
* @since 14.07.2015
*/
@Component
public class SyncManager {
private final static Logger logger = LoggerFactory.getLogger("sync");
private static final long WORKER_TIMEOUT = secondsToMillis(1);
private static final long MASTER_STUCK_TIMEOUT = secondsToMillis(60);
private static final long GAP_RECOVERY_TIMEOUT = secondsToMillis(2);
private static final long LARGE_GAP_SIZE = 5;
@Resource
@Qualifier("syncStates")
private Map<SyncStateName, SyncState> syncStates;
private SyncState state;
private final Object stateMutex = new Object();
/**
* block which gap recovery is running for
*/
private BlockWrapper gapBlock;
/**
* true if sync done event was triggered
*/
private boolean syncDone = false;
private BigInteger lowerUsefulDifficulty = BigInteger.ZERO;
private BigInteger highestKnownDifficulty = BigInteger.ZERO;
private ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
@Autowired
Blockchain blockchain;
@Autowired
SyncQueue queue;
@Autowired
NodeManager nodeManager;
@Autowired
EthereumListener ethereumListener;
@Autowired
PeersPool pool;
@Autowired
ChannelManager channelManager;
public void init() {
// make it asynchronously
new Thread(new Runnable() {
@Override
public void run() {
// sync queue
queue.init();
if (!CONFIG.isSyncEnabled()) {
logger.info("Sync Manager: OFF");
return;
}
logger.info("Sync Manager: ON");
// set IDLE state at the beginning
state = syncStates.get(IDLE);
updateDifficulties();
changeState(initialState());
addBestKnownNodeListener();
worker.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
updateDifficulties();
removeUselessPeers();
fillUpPeersPool();
maintainState();
} catch (Throwable t) {
t.printStackTrace();
logger.error("Exception in main sync worker", t);
}
}
}, WORKER_TIMEOUT, WORKER_TIMEOUT, TimeUnit.MILLISECONDS);
for (Node node : CONFIG.peerActive()) {
pool.connect(node);
}
if (logger.isInfoEnabled()) {
startLogWorker();
}
}
}).start();
}
public void addPeer(Channel peer) {
if (!CONFIG.isSyncEnabled()) {
return;
}
if (logger.isTraceEnabled()) logger.trace(
"Peer {}: adding",
peer.getPeerIdShort()
);
BigInteger peerTotalDifficulty = peer.getTotalDifficulty();
if (lowerUsefulDifficulty.compareTo(peerTotalDifficulty) > 0) {
if(logger.isInfoEnabled()) logger.info(
"Peer {}: its difficulty lower than ours: {} vs {}, skipping",
Utils.getNodeIdShort(peer.getPeerId()),
peerTotalDifficulty.toString(),
lowerUsefulDifficulty.toString()
);
// TODO report about lower total difficulty
return;
}
if (state.is(HASH_RETRIEVING) && !isIn20PercentRange(highestKnownDifficulty, peerTotalDifficulty)) {
if(logger.isInfoEnabled()) logger.info(
"Peer {}: its chain is better than previously known: {} vs {}, rotate master peer",
Utils.getNodeIdShort(peer.getPeerId()),
peerTotalDifficulty.toString(),
highestKnownDifficulty.toString()
);
// should be synchronized with HASH_RETRIEVING state maintenance
// to avoid double master peer initializing
synchronized (stateMutex) {
startMaster(peer);
}
}
updateHighestKnownDifficulty(peerTotalDifficulty);
pool.add(peer);
}
public void onDisconnect(Channel peer) {
pool.onDisconnect(peer);
}
public void tryGapRecovery(BlockWrapper wrapper) {
if (!isGapRecoveryAllowed(wrapper)) {
return;
}
if (logger.isDebugEnabled()) logger.debug(
"Recovering gap: best.number [{}] vs block.number [{}]",
blockchain.getBestBlock().getNumber(),
wrapper.getNumber()
);
gapBlock = wrapper;
int gap = gapSize(wrapper);
if (gap >= LARGE_GAP_SIZE) {
changeState(HASH_RETRIEVING);
} else {
logger.info("Forcing parent downloading for block.number [{}]", wrapper.getNumber());
queue.addHash(wrapper.getParentHash());
}
}
public void notifyNewBlockImported(BlockWrapper wrapper) {
if (syncDone) {
return;
}
if (!wrapper.isSolidBlock()) {
syncDone = true;
onSyncDone();
logger.debug("NEW block.number [{}] imported", wrapper.getNumber());
} else if (logger.isInfoEnabled()) {
logger.debug(
"NEW block.number [{}] block.minsSinceReceiving [{}] exceeds import time limit, continue sync",
wrapper.getNumber(),
wrapper.timeSinceReceiving() / 1000 / 60
);
}
}
public boolean isSyncDone() {
return syncDone;
}
private int gapSize(BlockWrapper block) {
Block bestBlock = blockchain.getBestBlock();
return (int) (block.getNumber() - bestBlock.getNumber());
}
private void onSyncDone() {
channelManager.onSyncDone();
ethereumListener.onSyncDone();
logger.info("Main synchronization is finished");
}
private boolean isGapRecoveryAllowed(BlockWrapper block) {
// hashes are not downloaded yet, recovery doesn't make sense at all
if (state.is(HASH_RETRIEVING)) {
return false;
}
// gap for this block is being recovered
if (block.equals(gapBlock) && !state.is(IDLE)) {
logger.trace("Gap recovery is already in progress for block.number [{}]", gapBlock.getNumber());
return false;
}
// ALL blocks are downloaded, we definitely have a gap
if (queue.isHashesEmpty()) {
return true;
}
// if blocks downloading is in progress
// and import fails during some period of time
// then we assume that faced with a gap
// but anyway NEW blocks must wait until SyncManager becomes idle
if (!block.isNewBlock()) {
return block.timeSinceFail() > GAP_RECOVERY_TIMEOUT;
} else {
return state.is(IDLE);
}
}
void changeState(SyncStateName newStateName) {
SyncState newState = syncStates.get(newStateName);
if (state == newState) {
return;
}
logger.info("Changing state from {} to {}", state, newState);
synchronized (stateMutex) {
newState.doOnTransition();
state = newState;
}
}
boolean isPeerStuck(Channel peer) {
SyncStatistics stats = peer.getSyncStats();
return stats.millisSinceLastUpdate() > MASTER_STUCK_TIMEOUT
|| stats.getEmptyResponsesCount() > 0;
}
void startMaster(Channel master) {
pool.changeState(IDLE);
if (gapBlock != null) {
int gap = gapSize(gapBlock);
master.setMaxHashesAsk(gap > CONFIG.maxHashesAsk() ? CONFIG.maxHashesAsk() : gap);
queue.setBestHash(gapBlock.getHash());
} else {
master.setMaxHashesAsk(CONFIG.maxHashesAsk());
queue.clearHashes();
queue.setBestHash(master.getBestHash());
}
master.changeSyncState(HASH_RETRIEVING);
if (logger.isInfoEnabled()) logger.info(
"Peer {}: {} initiated, best known hash [{}], askLimit [{}]",
master.getPeerIdShort(),
state,
Hex.toHexString(queue.getBestHash()),
master.getMaxHashesAsk()
);
}
private void updateDifficulties() {
updateLowerUsefulDifficulty(blockchain.getTotalDifficulty());
updateHighestKnownDifficulty(blockchain.getTotalDifficulty());
}
private void updateLowerUsefulDifficulty(BigInteger difficulty) {
if (difficulty.compareTo(lowerUsefulDifficulty) > 0) {
lowerUsefulDifficulty = difficulty;
}
}
private void updateHighestKnownDifficulty(BigInteger difficulty) {
if (difficulty.compareTo(highestKnownDifficulty) > 0) {
highestKnownDifficulty = difficulty;
}
}
private SyncStateName initialState() {
if (queue.hasSolidBlocks()) {
logger.info("It seems that BLOCK_RETRIEVING was interrupted, starting from this state now");
return BLOCK_RETRIEVING;
} else {
return HASH_RETRIEVING;
}
}
private void addBestKnownNodeListener() {
nodeManager.addDiscoverListener(
new DiscoverListener() {
@Override
public void nodeAppeared(NodeHandler handler) {
if (logger.isTraceEnabled()) logger.trace(
"Peer {}: new best chain peer discovered: {} vs {}",
handler.getNode().getHexIdShort(),
handler.getNodeStatistics().getEthTotalDifficulty(),
highestKnownDifficulty
);
pool.connect(handler.getNode());
}
@Override
public void nodeDisappeared(NodeHandler handler) {
}
},
new Functional.Predicate<NodeStatistics>() {
@Override
public boolean test(NodeStatistics nodeStatistics) {
if (nodeStatistics.getEthTotalDifficulty() == null) {
return false;
}
return !isIn20PercentRange(highestKnownDifficulty, nodeStatistics.getEthTotalDifficulty());
}
}
);
}
// WORKER
private void startLogWorker() {
Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
pool.logActivePeers();
pool.logBannedPeers();
logger.info("\nState {}\n", state);
}
}, 0, 30, TimeUnit.SECONDS);
}
private void removeUselessPeers() {
List<Channel> removed = new ArrayList<>();
for (Channel peer : pool) {
if (peer.hasBlocksLack()) {
logger.info("Peer {}: has no more blocks, removing", Utils.getNodeIdShort(peer.getPeerId()));
removed.add(peer);
updateLowerUsefulDifficulty(peer.getTotalDifficulty());
}
}
pool.removeAll(removed);
}
private void fillUpPeersPool() {
int lackSize = CONFIG.syncPeerCount() - pool.activeCount();
if(lackSize <= 0) {
return;
}
Set<String> nodesInUse = pool.nodesInUse();
List<NodeHandler> newNodes = nodeManager.getBestEthNodes(nodesInUse, lowerUsefulDifficulty, lackSize);
if (pool.isEmpty() && newNodes.isEmpty()) {
newNodes = nodeManager.getBestEthNodes(nodesInUse, BigInteger.ZERO, lackSize);
}
if (logger.isTraceEnabled()) {
logDiscoveredNodes(newNodes);
}
for(NodeHandler n : newNodes) {
pool.connect(n.getNode());
}
}
private void logDiscoveredNodes(List<NodeHandler> nodes) {
StringBuilder sb = new StringBuilder();
for(NodeHandler n : nodes) {
sb.append(Utils.getNodeIdShort(Hex.toHexString(n.getNode().getId())));
sb.append(", ");
}
if(sb.length() > 0) {
sb.delete(sb.length() - 2, sb.length());
}
logger.trace(
"Node list obtained from discovery: {}",
nodes.size() > 0 ? sb.toString() : "empty"
);
}
private void maintainState() {
synchronized (stateMutex) {
state.doMaintain();
}
}
}
|
package etomica.util.numerical;
import etomica.util.FunctionDifferentiable;
public class BrentMethodwDerivative {
public BrentMethodwDerivative(){
}
public double[] dbrent(double[] x, FunctionDifferentiable function, double tol){
double xmin = 0.0;
int ITMAX = 100;
double ZEPS = 1e-9;
int iter;
boolean ok1, ok2;
double u;
double a,b,d1,d2,du,dv,dw,dx;
double d = 0.0;
double e = 0.0;
double fu,fv,fw,fx,olde,tol1,tol2,u1,u2,v,w,xm;
double ax = x[0];
double bx = x[1];
double cx = x[2];
/*
* to make sure that a and b are in ascending order
*/
a = (ax < cx ? ax: cx);
b = (ax > cx ? ax: cx);
double axe;
axe = w = v = bx;
fw= fv = fx = function.f(axe);
dw= dv = dx = function.df(1, axe);
int counter=0;
double diff =0.0;
double prevDiff =0.0;
for (iter=0; iter<ITMAX; iter++){
xm = 0.5*(a+b);
tol1 = tol*Math.abs(axe)+ZEPS;
tol2 = 2.0*tol1;
System.out.println("<dbrent> ****iter: " + iter +" " +Math.abs(axe-xm) +" " +0.02*(tol2-0.5*(b-a)));
//Bail out if it can't find a minimum
diff = (xm - axe);
if(Math.abs(diff - prevDiff)<1e-12){
++counter;
if(counter>=5){
xmin = axe;
System.out.println("you bailed [(xm - axe) constant for 5 times] condition");
counter =0;
return new double[]{xmin, fx};
}
} else {
prevDiff = diff;
counter =0;
}
if(Math.abs(axe-xm) <= 0.02*(tol2-0.5*(b-a))){
xmin = axe;
System.out.println("you bailed (axe-xm)<tol2");
return new double[]{xmin, fx};
}
if(Math.abs(e) > tol1){
d1 = 2.0*(b-a);
d2 = d1;
if(dw != dx) {d1 = (w-axe)*dx/(dx-dw);} //Secant Method with one point
if(dv != dx) {d2 = (v-axe)*dx/(dx-dv);} // another Second Method
u1 = axe+d1;
u2 = axe+d2;
ok1 = (a-u1)*(u1-b) > 0.0 && dx*d1 <= 0.0;
ok2 = (a-u2)*(u2-b) > 0.0 && dx*d2 <= 0.0;
olde = e;
e = d;
/*
* Take the acceptable d only;
* but if double d's are acceptable, only pick the smallest d
*/
if(ok1 || ok2){
if(ok1 && ok2){
d = (Math.abs(d1) < Math.abs(d2) ? d1:d2);
} else if (ok1) {
d = d1;
} else {
d = d2;
}
if (Math.abs(d) <= Math.abs(0.5*olde)){
u = axe + d;
if (xm-axe >= 0){
d = Math.abs(tol1);
} else {
d = - Math.abs(tol1);
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
if (Math.abs(d) >= tol1){
u = axe+d;
fu = function.f(u);
} else {
if (d >= 0){
u = axe + Math.abs(tol1);
} else {
u = axe - Math.abs(tol1);
}
fu = function.f(u);
/*
* If the minimum step in the downhill direction takes us uphill,
* then we are done.
*/
if (fu > fx){
xmin = axe;
System.out.println("bailled at (fu > fx)");
return new double[] {xmin, fx};
}
}
du = function.df(1, u);
if (fu <= fx){
if (u >= axe){
a = axe;
} else {
b = axe;
}
v = w;
fv = fw;
dv = dw;
w = axe;
fw = fx;
dw = dx;
axe = u;
fx = fu;
dx = du;
} else {
if (u < v){
a = u;
} else{
b = u;
}
if (fu <= fw || w == axe){
v = w;
fv = fw;
dv = dw;
w = u;
fw = fu;
dw = du;
} else if(fu<fv || v==axe || v==w) {
v = u;
fv = fu;
dv = du;
}
}
}
throw new RuntimeException("Too many iterations in dbrent method!!!");
}
}
|
package sc.iview;
import bdv.BigDataViewer;
import bdv.cache.CacheControl;
import bdv.tools.brightness.ConverterSetup;
import bdv.util.AxisOrder;
import bdv.util.RandomAccessibleIntervalSource;
import bdv.util.RandomAccessibleIntervalSource4D;
import bdv.util.volatiles.VolatileView;
import bdv.util.volatiles.VolatileViewData;
import bdv.viewer.Source;
import bdv.viewer.SourceAndConverter;
import cleargl.GLVector;
import com.formdev.flatlaf.FlatLightLaf;
import com.intellij.ui.tabs.JBTabsPosition;
import com.intellij.ui.tabs.TabInfo;
import com.intellij.ui.tabs.impl.JBEditorTabs;
import graphics.scenery.Box;
import graphics.scenery.*;
import graphics.scenery.backends.RenderedImage;
import graphics.scenery.backends.Renderer;
import graphics.scenery.backends.opengl.OpenGLRenderer;
import graphics.scenery.backends.vulkan.VulkanRenderer;
import graphics.scenery.controls.InputHandler;
import graphics.scenery.controls.OpenVRHMD;
import graphics.scenery.controls.TrackerInput;
import graphics.scenery.controls.behaviours.ArcballCameraControl;
import graphics.scenery.controls.behaviours.FPSCameraControl;
import graphics.scenery.controls.behaviours.MovementCommand;
import graphics.scenery.controls.behaviours.SelectCommand;
import graphics.scenery.utils.*;
import graphics.scenery.volumes.Colormap;
import graphics.scenery.volumes.RAIVolume;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.Volume;
import io.scif.SCIFIOService;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function3;
import net.imagej.Dataset;
import net.imagej.ImageJService;
import net.imagej.axis.CalibratedAxis;
import net.imagej.axis.DefaultAxisType;
import net.imagej.axis.DefaultLinearAxis;
import net.imagej.interval.CalibratedRealInterval;
import net.imagej.lut.LUTService;
import net.imagej.ops.OpService;
import net.imagej.units.UnitService;
import net.imglib2.Cursor;
import net.imglib2.RandomAccess;
import net.imglib2.*;
import net.imglib2.display.ColorTable;
import net.imglib2.img.Img;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.numeric.ARGBType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.view.Views;
import org.jetbrains.annotations.NotNull;
import org.joml.Quaternionf;
import org.joml.Vector2f;
import org.joml.Vector3f;
import org.lwjgl.system.Platform;
import org.scijava.Context;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.io.IOService;
import org.scijava.log.LogLevel;
import org.scijava.log.LogService;
import org.scijava.menu.MenuService;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.service.SciJavaService;
import org.scijava.thread.ThreadService;
import org.scijava.ui.behaviour.Behaviour;
import org.scijava.ui.behaviour.ClickBehaviour;
import org.scijava.ui.behaviour.InputTrigger;
import org.scijava.ui.swing.menu.SwingJMenuBarCreator;
import org.scijava.util.ColorRGB;
import org.scijava.util.Colors;
import org.scijava.util.VersionUtils;
import sc.iview.commands.view.NodePropertyEditor;
import sc.iview.controls.behaviours.*;
import sc.iview.event.NodeActivatedEvent;
import sc.iview.event.NodeAddedEvent;
import sc.iview.event.NodeChangedEvent;
import sc.iview.event.NodeRemovedEvent;
import sc.iview.process.MeshConverter;
import sc.iview.ui.ContextPopUpNodeChooser;
import sc.iview.ui.REPLPane;
import sc.iview.vector.JOMLVector3;
import sc.iview.vector.Vector3;
import tpietzsch.example2.VolumeViewerOptions;
import javax.imageio.ImageIO;
import javax.script.ScriptException;
import javax.swing.*;
import java.awt.Image;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Main SciView class.
*
* @author Kyle Harrington
*/
// we suppress unused warnings here because @Parameter-annotated fields
// get updated automatically by SciJava.
@SuppressWarnings({"unused", "WeakerAccess"})
public class SciView extends SceneryBase implements CalibratedRealInterval<CalibratedAxis> {
public static final ColorRGB DEFAULT_COLOR = Colors.LIGHTGRAY;
private final SceneryPanel[] sceneryPanel = { null };
/**
* Mouse controls for FPS movement and Arcball rotation
*/
protected AnimatedCenteringBeforeArcBallControl targetArcball;
protected FPSCameraControl fpsControl;
/**
* The floor that orients the user in the scene
*/
protected Node floor;
protected boolean vrActive = false;
/**
* The primary camera/observer in the scene
*/
Camera camera = null;
/**
* Geometry/Image information of scene
*/
private CalibratedAxis[] axes;
@Parameter
private LogService log;
@Parameter
private MenuService menus;
@Parameter
private IOService io;
@Parameter
private OpService ops;
@Parameter
private EventService eventService;
@Parameter
private DisplayService displayService;
@Parameter
private LUTService lutService;
@Parameter
private ThreadService threadService;
@Parameter
private ObjectService objectService;
@Parameter
private UnitService unitService;
/**
* Queue keeps track of the currently running animations
**/
private Queue<Future> animations;
/**
* Animation pause tracking
**/
private boolean animating;
/**
* This tracks the actively selected Node in the scene
*/
private Node activeNode = null;
/**
* Speeds for input controls
*/
public ControlsParameters controlsParameters = new ControlsParameters();
private Display<?> scijavaDisplay;
private SplashLabel splashLabel;
private SceneryJPanel panel;
private JSplitPane mainSplitPane;
private JSplitPane inspector;
private JSplitPane interpreterSplitPane;
private REPLPane interpreterPane;
private NodePropertyEditor nodePropertyEditor;
private ArrayList<PointLight> lights;
private Stack<HashMap<String, Object>> controlStack;
private JFrame frame;
private Predicate<? super Node> notAbstractNode = (Predicate<Node>) node -> !( (node instanceof Camera) || (node instanceof Light) || (node==getFloor()));
private boolean isClosed = false;
private Function<Node,List<Node>> notAbstractBranchingFunction = node -> node.getChildren().stream().filter(notAbstractNode).collect(Collectors.toList());
// If true, then when a new node is added to the scene, the camera will refocus on this node by default
private boolean centerOnNewNodes;
// If true, then when a new node is added the thread will block until the node is added to the scene. This is required for
// centerOnNewNodes
private boolean blockOnNewNodes;
private PointLight headlight;
public SciView( Context context ) {
super( "SciView", 1280, 720, false, context );
context.inject( this );
}
public SciView( String applicationName, int windowWidth, int windowHeight ) {
super( applicationName, windowWidth, windowHeight, false );
}
public boolean isClosed() {
return isClosed;
}
public InputHandler publicGetInputHandler() {
return getInputHandler();
}
/**
* Toggle video recording with scenery's video recording mechanism
* Note: this video recording may skip frames because it is asynchronous
*/
public void toggleRecordVideo() {
if( getRenderer() instanceof OpenGLRenderer )
((OpenGLRenderer)getRenderer()).recordMovie();
else
((VulkanRenderer)getRenderer()).recordMovie();
}
/**
* Toggle video recording with scenery's video recording mechanism
* Note: this video recording may skip frames because it is asynchronous
*
* @param filename destination for saving video
* @param overwrite should the file be replaced, otherwise a unique incrementing counter will be appended
*/
public void toggleRecordVideo(String filename, boolean overwrite) {
if( getRenderer() instanceof OpenGLRenderer )
((OpenGLRenderer)getRenderer()).recordMovie(filename, overwrite);
else
((VulkanRenderer)getRenderer()).recordMovie(filename, overwrite);
}
/**
* This pushes the current input setup onto a stack that allows them to be restored with restoreControls.
* It stacks in particular: all keybindings, all Behaviours, and all step sizes and mouse sensitivities
* (which are held together in {@link ControlsParameters}).
*
* <em>Word of warning:</em> The stashing memorizes <em>references only</em> on currently used controls
* (such as, e.g., {@link MovementCommand}, {@link FPSCameraControl} or {@link NodeTranslateControl}),
* it <em>does not</em> create an extra copy of any control. That said, if you modify any control
* object despite it was already stashed with this method, the change will be visible in the "stored"
* control and will not go away after the restore... To be on the safe side for now at least, <em>create
* new and modified</em> controls rather than directly changing them.
*/
public void stashControls() {
final InputHandler inputHandler = getInputHandler();
if (inputHandler == null) {
getLogger().error( "InputHandler is null, cannot store controls" );
return;
}
final HashMap<String, Object> controlState = new HashMap<>();
//behaviours:
for ( String actionName: inputHandler.getAllBehaviours() )
controlState.put( STASH_BEHAVIOUR_KEY+actionName, inputHandler.getBehaviour(actionName) );
//bindings:
for ( String actionName: inputHandler.getAllBehaviours() )
for ( InputTrigger trigger : inputHandler.getKeyBindings(actionName) )
controlState.put( STASH_BINDING_KEY+actionName, trigger.toString() );
//finally, stash the control parameters
controlState.put( STASH_CONTROLSPARAMS_KEY, controlsParameters );
//...and stash it!
controlStack.push(controlState);
}
/**
* This pops/restores the previously stashed controls. Emits a warning if there are no stashed controls.
* It first clears all controls, and then resets in particular: all keybindings, all Behaviours,
* and all step sizes and mouse sensitivities (which are held together in {@link ControlsParameters}).
*
* <em>Some recent changes may not be removed</em> with this restore --
* see discussion in the docs of {@link SciView#stashControls()} for more details.
*/
public void restoreControls() {
if (controlStack.empty()) {
getLogger().warn("Not restoring controls, the controls stash stack is empty!");
return;
}
final InputHandler inputHandler = getInputHandler();
if (inputHandler == null) {
getLogger().error( "InputHandler is null, cannot restore controls" );
return;
}
//clear the input handler entirely
for ( String actionName : inputHandler.getAllBehaviours() ) {
inputHandler.removeKeyBinding( actionName );
inputHandler.removeBehaviour( actionName );
}
//retrieve the most recent stash with controls
final HashMap<String, Object> controlState = controlStack.pop();
for (Map.Entry<String, Object> control : controlState.entrySet()) {
String key;
if (control.getKey().startsWith(STASH_BEHAVIOUR_KEY)) {
//processing behaviour
key = control.getKey().substring(STASH_BEHAVIOUR_KEY.length());
inputHandler.addBehaviour( key, (Behaviour)control.getValue() );
}
else
if (control.getKey().startsWith(STASH_BINDING_KEY)) {
//processing key binding
key = control.getKey().substring(STASH_BINDING_KEY.length());
inputHandler.addKeyBinding( key, (String)control.getValue() );
}
else
if (control.getKey().startsWith(STASH_CONTROLSPARAMS_KEY)) {
//processing mouse sensitivities and step sizes...
controlsParameters = (ControlsParameters)control.getValue();
}
}
}
private static final String STASH_BEHAVIOUR_KEY = "behaviour:";
private static final String STASH_BINDING_KEY = "binding:";
private static final String STASH_CONTROLSPARAMS_KEY = "parameters:";
public ArrayList<PointLight> getLights() {
return lights;
}
/**
* Reset the scene to initial conditions
*/
public void reset() {
// Initialize the 3D axes
axes = new CalibratedAxis[3];
axes[0] = new DefaultLinearAxis(new DefaultAxisType("X", true), "um", 1);
axes[1] = new DefaultLinearAxis(new DefaultAxisType("Y", true), "um", 1);
axes[2] = new DefaultLinearAxis(new DefaultAxisType("Z", true), "um", 1);
// Remove everything except camera
Node[] toRemove = getSceneNodes( n -> !( n instanceof Camera ) );
for( Node n : toRemove ) {
deleteNode(n, false);
}
// Setup camera
Camera cam;
if( getCamera() == null ) {
cam = new DetachedHeadCamera();
this.camera = cam;
cam.setPosition(new Vector3f(0.0f, 1.65f, 0.0f));
getScene().addChild( cam );
} else {
cam = getCamera();
}
cam.setPosition( new Vector3f( 0.0f, 1.65f, 5.0f ) );
cam.perspectiveCamera( 50.0f, getWindowWidth(), getWindowHeight(), 0.1f, 1000.0f );
// Setup lights
Vector3f[] tetrahedron = new Vector3f[4];
tetrahedron[0] = new Vector3f( 1.0f, 0f, -1.0f/(float)Math.sqrt(2.0f) );
tetrahedron[1] = new Vector3f( -1.0f,0f,-1.0f/(float)Math.sqrt(2.0) );
tetrahedron[2] = new Vector3f( 0.0f,1.0f,1.0f/(float)Math.sqrt(2.0) );
tetrahedron[3] = new Vector3f( 0.0f,-1.0f,1.0f/(float)Math.sqrt(2.0) );
lights = new ArrayList<>();
for( int i = 0; i < 4; i++ ) {// TODO allow # initial lights to be customizable?
PointLight light = new PointLight(150.0f);
light.setPosition( tetrahedron[i].mul(25.0f) );
light.setEmissionColor( new Vector3f( 1.0f, 1.0f, 1.0f ) );
light.setIntensity( 1.0f );
lights.add( light );
//camera.addChild( light );
getScene().addChild( light );
}
// Make a headlight for the camera
headlight = new PointLight(150.0f);
headlight.setPosition( new Vector3f(0f, 0f, -1f).mul(25.0f) );
headlight.setEmissionColor( new Vector3f( 1.0f, 1.0f, 1.0f ) );
headlight.setIntensity( 0.5f );
headlight.setName("headlight");
Icosphere lightSphere = new Icosphere(1.0f, 2);
headlight.addChild(lightSphere);
lightSphere.getMaterial().setDiffuse(headlight.getEmissionColor());
lightSphere.getMaterial().setSpecular(headlight.getEmissionColor());
lightSphere.getMaterial().setAmbient(headlight.getEmissionColor());
lightSphere.getMaterial().setWireframe(true);
lightSphere.setVisible(false);
//lights.add( light );
camera.setNearPlaneDistance(0.01f);
camera.setFarPlaneDistance(1000.0f);
camera.addChild( headlight );
floor = new InfinitePlane();//new Box( new Vector3f( 500f, 0.2f, 500f ) );
((InfinitePlane)floor).setType(InfinitePlane.Type.Grid);
floor.setName( "Floor" );
getScene().addChild( floor );
}
/**
* Initialization of SWING and scenery. Also triggers an initial population of lights/camera in the scene
*/
@SuppressWarnings("restriction") @Override public void init() {
// Darcula dependency went missing from maven repo, factor it out
// if(Boolean.parseBoolean(System.getProperty("sciview.useDarcula", "false"))) {
// try {
// BasicLookAndFeel darcula = new DarculaLaf();
// UIManager.setLookAndFeel(darcula);
// } catch (Exception e) {
// getLogger().info("Could not load Darcula Look and Feel");
final String logLevel = System.getProperty("scenery.LogLevel", "info");
log.setLevel(LogLevel.value(logLevel));
LogbackUtils.setLogLevel(null, logLevel);
System.getProperties().stringPropertyNames().forEach(name -> {
if(name.startsWith("scenery.LogLevel")) {
LogbackUtils.setLogLevel("", System.getProperty(name, "info"));
}
});
// determine imagej-launcher version and to disable Vulkan if XInitThreads() fix
// is not deployed
try {
final Class<?> launcherClass = Class.forName("net.imagej.launcher.ClassLauncher");
String versionString = VersionUtils.getVersion(launcherClass);
if (versionString != null && ExtractsNatives.Companion.getPlatform() == ExtractsNatives.Platform.LINUX) {
versionString = versionString.substring(0, 5);
final Version launcherVersion = new Version(versionString);
final Version nonWorkingVersion = new Version("4.0.5");
if (launcherVersion.compareTo(nonWorkingVersion) <= 0
&& !Boolean.parseBoolean(System.getProperty("sciview.DisableLauncherVersionCheck", "false"))) {
getLogger().info("imagej-launcher version smaller or equal to non-working version (" + versionString + " vs. 4.0.5), disabling Vulkan as rendering backend. Disable check by setting 'scenery.DisableLauncherVersionCheck' system property to 'true'.");
System.setProperty("scenery.Renderer", "OpenGLRenderer");
} else {
getLogger().info("imagej-launcher version bigger that non-working version (" + versionString + " vs. 4.0.5), all good.");
}
}
} catch (ClassNotFoundException cnfe) {
// Didn't find the launcher, so we're probably good.
getLogger().info("imagej-launcher not found, not touching renderer preferences.");
}
// TODO: check for jdk 8 v. jdk 11 on linux and choose renderer accordingly
if( Platform.get() == Platform.LINUX ) {
String version = System.getProperty("java.version");
if( version.startsWith("1.") ) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if (dot != -1) {
version = version.substring(0, dot);
}
}
// If Linux and JDK 8, then use OpenGLRenderer
if( version.equals("8") )
System.setProperty("scenery.Renderer", "OpenGLRenderer");
}
int x, y;
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = screenSize.width/2 - getWindowWidth()/2;
y = screenSize.height/2 - getWindowHeight()/2;
} catch(HeadlessException e) {
x = 10;
y = 10;
}
frame = new JFrame("SciView");
frame.setLayout(new BorderLayout(0, 0));
frame.setSize(getWindowWidth(), getWindowHeight());
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nodePropertyEditor = new NodePropertyEditor( this );
final JPanel p = new JPanel(new BorderLayout(0, 0));
panel = new SceneryJPanel();
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
final JMenuBar swingMenuBar = new JMenuBar();
new SwingJMenuBarCreator().createMenus(menus.getMenu("SciView"), swingMenuBar);
frame.setJMenuBar(swingMenuBar);
p.setLayout(new OverlayLayout(p));
p.setBackground(new Color(50, 48, 47));
p.add(panel, BorderLayout.CENTER);
panel.setVisible(true);
nodePropertyEditor.getComponent(); // Initialize node property panel
JTree inspectorTree = nodePropertyEditor.getTree();
inspectorTree.setToggleClickCount(0);// This disables expanding menus on double click
JPanel inspectorProperties = nodePropertyEditor.getProps();
JBEditorTabs tp = new JBEditorTabs(null);
tp.setTabsPosition(JBTabsPosition.right);
tp.setSideComponentVertical(true);
inspector = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane( inspectorTree ),
new JScrollPane( inspectorProperties ));
inspector.setDividerLocation( getWindowHeight() / 3 );
inspector.setContinuousLayout(true);
inspector.setBorder(BorderFactory.createEmptyBorder());
inspector.setDividerSize(1);
ImageIcon inspectorIcon = getScaledImageIcon(this.getClass().getResource("toolbox.png"), 16, 16);
TabInfo tiInspector = new TabInfo(inspector, inspectorIcon);
tiInspector.setText("");
tp.addTab(tiInspector);
// We need to get the surface scale here before initialising scenery's renderer, as
// the information is needed already at initialisation time.
final AffineTransform dt = frame.getGraphicsConfiguration().getDefaultTransform();
final Vector2f surfaceScale = new Vector2f((float)dt.getScaleX(), (float)dt.getScaleY());
getSettings().set("Renderer.SurfaceScale", surfaceScale);
interpreterPane = new REPLPane(getScijavaContext());
interpreterPane.getComponent().setBorder(BorderFactory.createEmptyBorder());
ImageIcon interpreterIcon = getScaledImageIcon(this.getClass().getResource("terminal.png"), 16, 16);
TabInfo tiREPL = new TabInfo(interpreterPane.getComponent(), interpreterIcon);
tiREPL.setText("");
tp.addTab(tiREPL);
tp.addTabMouseListener(new MouseListener() {
private boolean hidden = false;
private int previousPosition = 0;
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2) {
toggleSidebar();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
initializeInterpreter();
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
p,
tp.getComponent()
);
mainSplitPane.setDividerLocation(frame.getSize().width - 36);
mainSplitPane.setBorder(BorderFactory.createEmptyBorder());
mainSplitPane.setDividerSize(1);
mainSplitPane.setResizeWeight(0.9);
sidebarHidden = true;
//frame.add(mainSplitPane, BorderLayout.CENTER);
frame.add(mainSplitPane, BorderLayout.CENTER);
SciView sciView = this;
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
getLogger().debug("Closing SciView window.");
close();
getScijavaContext().service(SciViewService.class).close(sciView);
isClosed = true;
}
});
splashLabel = new SplashLabel();
frame.setGlassPane(splashLabel);
frame.getGlassPane().setVisible(true);
frame.getGlassPane().requestFocusInWindow();
// frame.getGlassPane().setBackground(new java.awt.Color(50, 48, 47, 255));
frame.setVisible(true);
sceneryPanel[0] = panel;
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0]) );
getHub().add( SceneryElement.Renderer, getRenderer() );
reset();
animations = new LinkedList<>();
controlStack = new Stack<>();
SwingUtilities.invokeLater(() -> {
try {
while (!getSceneryRenderer().getFirstImageReady()) {
getLogger().debug("Waiting for renderer initialisation");
Thread.sleep(300);
}
Thread.sleep(200);
} catch (InterruptedException e) {
getLogger().error("Renderer construction interrupted.");
}
nodePropertyEditor.rebuildTree();
getLogger().info("Done initializing SciView");
// subscribe to Node{Added, Removed, Changed} events happens automagically owing to the annotations
frame.getGlassPane().setVisible(false);
panel.setVisible(true);
// install hook to keep inspector updated on external changes (scripting, etc)
getScene().getOnNodePropertiesChanged().put("updateInspector",
node -> {
if( node == nodePropertyEditor.getCurrentNode() ) {
nodePropertyEditor.updateProperties(node);
}
return null;
});
// Enable push rendering by default
getRenderer().setPushMode( true );
sciView.getCamera().setPosition(1.65, 1);
});
}
private boolean sidebarHidden = false;
private int previousSidebarPosition = 0;
public boolean toggleSidebar() {
if(!sidebarHidden) {
previousSidebarPosition = mainSplitPane.getDividerLocation();
// TODO: remove hard-coded tab width
mainSplitPane.setDividerLocation(frame.getSize().width - 36);
sidebarHidden = true;
} else {
if(previousSidebarPosition == 0) {
previousSidebarPosition = getWindowWidth()/3 * 2;
}
mainSplitPane.setDividerLocation(previousSidebarPosition);
sidebarHidden = false;
}
return sidebarHidden;
}
private ImageIcon getScaledImageIcon(final URL resource, int width, int height) {
final ImageIcon first = new ImageIcon(resource);
final Image image = first.getImage();
BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(first.getImage(), 0, 0, width, height, null);
g2.dispose();
return new ImageIcon(resizedImg);
}
private void initializeInterpreter() {
String startupCode = "";
startupCode = new Scanner(SciView.class.getResourceAsStream("startup.py"), "UTF-8").useDelimiter("\\A").next();
interpreterPane.getREPL().getInterpreter().getBindings().put("sciView", this);
try {
interpreterPane.getREPL().getInterpreter().eval(startupCode);
} catch (ScriptException e) {
e.printStackTrace();
}
}
/*
* Completely close the SciView window + cleanup
*/
public void closeWindow() {
frame.dispose();
}
/*
* Return the default floor object
*/
public Node getFloor() {
return floor;
}
/*
* Set the default floor object
*/
public void setFloor( Node n ) {
floor = n;
}
/**
* Return the current SceneryJPanel. This is necessary for custom context menus
* @return panel the current SceneryJPanel
*/
public SceneryJPanel getSceneryJPanel() {
return panel;
}
/*
* Return true if the scene has been initialized
*/
public boolean isInitialized() {
return sceneInitialized();
}
/*
* Return the current camera that is rendering the scene
*/
public Camera getCamera() {
return camera;
}
/*
* Return the SciJava Display that contains SciView
*/
public Display<?> getDisplay() {
return scijavaDisplay;
}
/*
* Set the SciJava Display
*/
public void setDisplay( Display<?> display ) {
scijavaDisplay = display;
}
/*
* Get the InputHandler that is managing mouse, input, VR controls, etc.
*/
public InputHandler getSceneryInputHandler() {
return getInputHandler();
}
/*
* Return a bounding box around a subgraph of the scenegraph
*/
public OrientedBoundingBox getSubgraphBoundingBox( Node n ) {
Function<Node,List<Node>> predicate = node -> node.getChildren();
return getSubgraphBoundingBox(n,predicate);
}
/*
* Return a bounding box around a subgraph of the scenegraph
*/
public OrientedBoundingBox getSubgraphBoundingBox( Node n, Function<Node,List<Node>> branchFunction ) {
if(n.getBoundingBox() == null && n.getChildren().size() != 0) {
return n.getMaximumBoundingBox().asWorld();
}
List<Node> branches = branchFunction.apply(n);
if( branches.size() == 0 ) {
if( n.getBoundingBox() == null )
return null;
else
return n.getBoundingBox().asWorld();
}
OrientedBoundingBox bb = n.getMaximumBoundingBox();
for( Node c : branches ){
OrientedBoundingBox cBB = getSubgraphBoundingBox(c, branchFunction);
if( cBB != null )
bb = bb.expand(bb, cBB);
}
return bb;
}
/**
* Place the scene into the center of camera view, and zoom in/out such
* that the whole scene is in the view (everything would be visible if it
* would not be potentially occluded).
*/
public void fitCameraToScene() {
centerOnNode(getScene());
//TODO: smooth zoom in/out VLADO vlado Vlado
}
/**
* Place the scene into the center of camera view.
*/
public void centerOnScene() {
centerOnNode(getScene());
}
/**
* Place the active node into the center of camera view.
*/
public void centerOnActiveNode() {
if (activeNode == null) return;
centerOnNode(activeNode);
}
/**
* Place the specified node into the center of camera view.
*/
public void centerOnNode( Node currentNode ) {
if (currentNode == null) {
log.info("Cannot center on null node.");
return;
}
//center the on the same spot as ArcBall does
centerOnPosition( currentNode.getMaximumBoundingBox().getBoundingSphere().getOrigin() );
}
/**
* Center the camera on the specified Node
*/
public void centerOnPosition( Vector3f currentPos ) {
//current and desired directions in world coords
final Vector3f currViewDir = new Vector3f(camera.getTarget()).sub(camera.getPosition());
final Vector3f wantViewDir = new Vector3f(currentPos).sub(camera.getPosition());
if (wantViewDir.lengthSquared() < 0.01)
{
//ill defined task, happens typically when cam is inside the node which we want center on
log.info("Camera is on the spot you want to look at. Please, move the camera away first.");
return;
}
//current and desired directions as the camera sees them
camera.getTransformation().transformDirection(currViewDir).normalize();
camera.getTransformation().transformDirection(wantViewDir).normalize();
//we gonna rotate directly to match the current view direction with the desired one,
//which means to rotate by this angle:
float totalDeltaAng = (float)Math.acos( currViewDir.dot(wantViewDir) );
//if the needed angle is less than 2 deg, we do nothing...
if (totalDeltaAng < 0.035) return;
//here's the axis along which we will rotate
if (totalDeltaAng < 3.13) currViewDir.cross(wantViewDir);
else currViewDir.set(camera.getUp());
//NB: if the angle is nearly 180 deg, there is infinite number of axes that
// allow the required "flip" to happen (and cross() did not choose any),
// so we provide own rotation axis: a vertical axis
//animation options: control delay between animation frames -- fluency
final long rotPausePerStep = 30; //miliseconds
//animation options: control max number of steps -- upper limit on total time for animation
final int rotMaxSteps = 999999; //effectively disabled....
//animation options: the hardcoded 5 deg (0.087 rad) -- smoothness
//how many steps when max update/move is 5 deg
int rotSteps = (int)Math.ceil( Math.abs(totalDeltaAng) / 0.087 );
if (rotSteps > rotMaxSteps) rotSteps = rotMaxSteps;
log.debug("centering by deltaAng="+ 180.0f*totalDeltaAng/3.14159f+" deg over "+rotSteps+" steps");
//angular progress aux variables
float angCurPos = 0, angNextPos, angDelta;
camera.setTargeted(false);
for (int i = 1; i <= rotSteps; ++i) {
//this emulates ease-in ease-out animation, both vars are in [0:1]
float timeProgress = (float)i / rotSteps;
float angProgress = ((timeProgress *= 2) <= 1 ? //two cubics connected smoothly into S-shape curve from [0,0] to [1,1]
timeProgress * timeProgress * timeProgress :
(timeProgress -= 2) * timeProgress * timeProgress + 2) / 2;
angNextPos = angProgress * totalDeltaAng; //where I should be by now
angDelta = angNextPos - angCurPos; //how much I must travel to get there
angCurPos = angNextPos; //suppose we already got there...
new Quaternionf().rotateAxis(-angDelta,currViewDir).mul(camera.getRotation(),camera.getRotation());
try {
Thread.sleep(rotPausePerStep);
} catch (InterruptedException e) {
i = rotSteps;
}
}
}
//a couple of shortcut methods to readout controls params
public float getFPSSpeedSlow() {
return controlsParameters.getFpsSpeedSlow();
}
public float getFPSSpeedFast() {
return controlsParameters.getFpsSpeedFast();
}
public float getFPSSpeedVeryFast() {
return controlsParameters.getFpsSpeedVeryFast();
}
public float getMouseSpeed() {
return controlsParameters.getMouseSpeedMult();
}
public float getMouseScrollSpeed() {
return controlsParameters.getMouseScrollMult();
}
//a couple of setters with scene sensible boundary checks
public void setFPSSpeedSlow( float slowSpeed ) {
controlsParameters.setFpsSpeedSlow( paramWithinBounds(slowSpeed, FPSSPEED_MINBOUND_SLOW,FPSSPEED_MAXBOUND_SLOW) );
}
public void setFPSSpeedFast( float fastSpeed ) {
controlsParameters.setFpsSpeedFast( paramWithinBounds(fastSpeed, FPSSPEED_MINBOUND_FAST,FPSSPEED_MAXBOUND_FAST) );
}
public void setFPSSpeedVeryFast( float veryFastSpeed ) {
controlsParameters.setFpsSpeedVeryFast( paramWithinBounds(veryFastSpeed, FPSSPEED_MINBOUND_VERYFAST,FPSSPEED_MAXBOUND_VERYFAST) );
}
public void setFPSSpeed( float newBaseSpeed ) {
// we don't want to escape bounds checking
// (so we call "our" methods rather than directly the controlsParameters)
setFPSSpeedSlow( 1f * newBaseSpeed );
setFPSSpeedFast( 20f * newBaseSpeed );
setFPSSpeedVeryFast( 500f * newBaseSpeed );
//report what's been set in the end
log.debug( "FPS speeds: slow=" + controlsParameters.getFpsSpeedSlow()
+ ", fast=" + controlsParameters.getFpsSpeedFast()
+ ", very fast=" + controlsParameters.getFpsSpeedVeryFast() );
}
public void setMouseSpeed( float newSpeed ) {
controlsParameters.setMouseSpeedMult( paramWithinBounds(newSpeed, MOUSESPEED_MINBOUND,MOUSESPEED_MAXBOUND) );
log.debug( "Mouse movement speed: " + controlsParameters.getMouseSpeedMult() );
}
public void setMouseScrollSpeed( float newSpeed ) {
controlsParameters.setMouseScrollMult( paramWithinBounds(newSpeed, MOUSESCROLL_MINBOUND,MOUSESCROLL_MAXBOUND) );
log.debug( "Mouse scroll speed: " + controlsParameters.getMouseScrollMult() );
}
//bounds for the controls
public static final float FPSSPEED_MINBOUND_SLOW = 0.01f;
public static final float FPSSPEED_MAXBOUND_SLOW = 30.0f;
public static final float FPSSPEED_MINBOUND_FAST = 0.2f;
public static final float FPSSPEED_MAXBOUND_FAST = 600f;
public static final float FPSSPEED_MINBOUND_VERYFAST = 10f;
public static final float FPSSPEED_MAXBOUND_VERYFAST = 2000f;
public static final float MOUSESPEED_MINBOUND = 0.1f;
public static final float MOUSESPEED_MAXBOUND = 3.0f;
public static final float MOUSESCROLL_MINBOUND = 0.3f;
public static final float MOUSESCROLL_MAXBOUND = 10.0f;
private float paramWithinBounds(float param, final float minBound, final float maxBound)
{
if( param < minBound ) param = minBound;
else if( param > maxBound ) param = maxBound;
return param;
}
public void setObjectSelectionMode() {
Function3<Scene.RaycastResult, Integer, Integer, Unit> selectAction = (nearest,x,y) -> {
if( !nearest.getMatches().isEmpty() ) {
// copy reference on the last object picking result into "public domain"
// (this must happen before the ContextPopUpNodeChooser menu!)
objectSelectionLastResult = nearest;
// Setup the context menu for this picking
// (in the menu, the user will chose node herself)
new ContextPopUpNodeChooser(this).show(panel,x,y);
}
return Unit.INSTANCE;
};
setObjectSelectionMode(selectAction);
}
public Scene.RaycastResult objectSelectionLastResult;
/*
* Set the action used during object selection
*/
public void setObjectSelectionMode(Function3<Scene.RaycastResult, Integer, Integer, Unit> selectAction) {
final InputHandler h = getInputHandler();
List<Class<?>> ignoredObjects = new ArrayList<>();
ignoredObjects.add( BoundingGrid.class );
ignoredObjects.add( Camera.class ); //do not mess with "scene params", allow only "scene data" to be selected
ignoredObjects.add( DetachedHeadCamera.class );
ignoredObjects.add( DirectionalLight.class );
ignoredObjects.add( PointLight.class );
if(h == null) {
getLogger().error("InputHandler is null, cannot change object selection mode.");
return;
}
h.addBehaviour( "node: choose one from the view panel",
new SelectCommand( "objectSelector", getRenderer(), getScene(),
() -> getScene().findObserver(), false, ignoredObjects,
selectAction ) );
h.addKeyBinding( "node: choose one from the view panel", "double-click button1" );
}
/*
* Initial configuration of the scenery InputHandler
* This is automatically called and should not be used directly
*/
@Override public void inputSetup() {
final InputHandler h = getInputHandler();
if ( h == null ) {
getLogger().error( "InputHandler is null, cannot run input setup." );
return;
}
//when we get here, the Behaviours and key bindings from scenery are already in place
//possibly, disable some (unused?) controls from scenery
/*
h.removeBehaviour( "gamepad_camera_control");
h.removeKeyBinding("gamepad_camera_control");
h.removeBehaviour( "gamepad_movement_control");
h.removeKeyBinding("gamepad_movement_control");
*/
// node-selection and node-manipulation (translate & rotate) controls
setObjectSelectionMode();
final NodeTranslateControl nodeTranslateControl = new NodeTranslateControl(this);
h.addBehaviour( "node: move selected one left, right, up, or down", nodeTranslateControl);
h.addKeyBinding( "node: move selected one left, right, up, or down", "ctrl button1" );
h.addBehaviour( "node: move selected one closer or further away", nodeTranslateControl);
h.addKeyBinding( "node: move selected one closer or further away", "ctrl scroll" );
h.addBehaviour( "node: rotate selected one", new NodeRotateControl(this) );
h.addKeyBinding( "node: rotate selected one", "ctrl shift button1" );
// within-scene navigation: ArcBall and FPS
enableArcBallControl();
enableFPSControl();
// whole-scene rolling
h.addBehaviour( "view: rotate (roll) clock-wise", new SceneRollControl(this,+0.05f) ); //2.8 deg
h.addKeyBinding("view: rotate (roll) clock-wise", "R");
h.addBehaviour( "view: rotate (roll) counter clock-wise", new SceneRollControl(this,-0.05f) );
h.addKeyBinding("view: rotate (roll) counter clock-wise", "shift R");
h.addBehaviour( "view: rotate (roll) with mouse", h.getBehaviour("view: rotate (roll) clock-wise"));
h.addKeyBinding("view: rotate (roll) with mouse", "ctrl button3");
// adjusters of various controls sensitivities
h.addBehaviour( "moves: step size decrease", (ClickBehaviour)(x,y) -> setFPSSpeed( getFPSSpeedSlow() - 0.01f ) );
h.addKeyBinding("moves: step size decrease", "MINUS");
h.addBehaviour( "moves: step size increase", (ClickBehaviour)(x,y) -> setFPSSpeed( getFPSSpeedSlow() + 0.01f ) );
h.addKeyBinding("moves: step size increase", "EQUALS" );
h.addBehaviour( "mouse: move sensitivity decrease", (ClickBehaviour)(x,y) -> setMouseSpeed( getMouseSpeed() - 0.02f ) );
h.addKeyBinding("mouse: move sensitivity decrease", "M MINUS");
h.addBehaviour( "mouse: move sensitivity increase", (ClickBehaviour)(x,y) -> setMouseSpeed( getMouseSpeed() + 0.02f ) );
h.addKeyBinding("mouse: move sensitivity increase", "M EQUALS" );
h.addBehaviour( "mouse: scroll sensitivity decrease", (ClickBehaviour)(x,y) -> setMouseScrollSpeed( getMouseScrollSpeed() - 0.3f ) );
h.addKeyBinding("mouse: scroll sensitivity decrease", "S MINUS");
h.addBehaviour( "mouse: scroll sensitivity increase", (ClickBehaviour)(x,y) -> setMouseScrollSpeed( getMouseScrollSpeed() + 0.3f ) );
h.addKeyBinding("mouse: scroll sensitivity increase", "S EQUALS" );
// help window
h.addBehaviour( "show help", new showHelpDisplay() );
h.addKeyBinding("show help", "F1" );
}
/*
* Change the control mode to circle around the active object in an arcball
*/
private void enableArcBallControl() {
final InputHandler h = getInputHandler();
if ( h == null ) {
getLogger().error( "InputHandler is null, cannot setup arcball control." );
return;
}
Vector3f target;
if( getActiveNode() == null ) {
target = new Vector3f( 0, 0, 0 );
} else {
target = getActiveNode().getPosition();
}
//setup ArcballCameraControl from scenery, register it with SciView's controlsParameters
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
targetArcball = new AnimatedCenteringBeforeArcBallControl( "view: rotate it around selected node", cameraSupplier,
getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight(), target );
targetArcball.setMaximumDistance( Float.MAX_VALUE );
controlsParameters.registerArcballCameraControl( targetArcball );
h.addBehaviour( "view: rotate around selected node", targetArcball );
h.addKeyBinding( "view: rotate around selected node", "shift button1" );
h.addBehaviour( "view: zoom outward or toward selected node", targetArcball );
h.addKeyBinding( "view: zoom outward or toward selected node", "shift scroll" );
}
/*
* A wrapping class for the {@ArcballCameraControl} that calls {@link CenterOnPosition()}
* before the actual Arcball camera movement takes place. This way, the targeted node is
* first smoothly brought into the centre along which Arcball is revolving, preventing
* from sudden changes of view (and lost of focus from the user.
*/
class AnimatedCenteringBeforeArcBallControl extends ArcballCameraControl {
//a bunch of necessary c'tors (originally defined in the ArcballCameraControl class)
public AnimatedCenteringBeforeArcBallControl(@NotNull String name, @NotNull Function0<? extends Camera> n, int w, int h, @NotNull Function0<? extends Vector3f> target) {
super(name, n, w, h, target);
}
public AnimatedCenteringBeforeArcBallControl(@NotNull String name, @NotNull Supplier<Camera> n, int w, int h, @NotNull Supplier<Vector3f> target) {
super(name, n, w, h, target);
}
public AnimatedCenteringBeforeArcBallControl(@NotNull String name, @NotNull Function0<? extends Camera> n, int w, int h, @NotNull Vector3f target) {
super(name, n, w, h, target);
}
public AnimatedCenteringBeforeArcBallControl(@NotNull String name, @NotNull Supplier<Camera> n, int w, int h, @NotNull Vector3f target) {
super(name, n, w, h, target);
}
@Override
public void init( int x, int y )
{
centerOnPosition( targetArcball.getTarget().invoke() );
super.init(x,y);
}
@Override
public void scroll(double wheelRotation, boolean isHorizontal, int x, int y)
{
centerOnPosition( targetArcball.getTarget().invoke() );
super.scroll(wheelRotation,isHorizontal,x,y);
}
}
/*
* Enable FPS style controls
*/
private void enableFPSControl() {
final InputHandler h = getInputHandler();
if ( h == null ) {
getLogger().error( "InputHandler is null, cannot setup fps control." );
return;
}
// Mouse look around (Lclick) and move around (Rclick)
//setup FPSCameraControl from scenery, register it with SciView's controlsParameters
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
fpsControl = new FPSCameraControl( "view: freely look around", cameraSupplier, getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight() );
controlsParameters.registerFpsCameraControl( fpsControl );
h.addBehaviour( "view: freely look around", fpsControl );
h.addKeyBinding( "view: freely look around", "button1" );
//slow and fast camera motion
h.addBehaviour( "move_withMouse_back/forward/left/right", new CameraTranslateControl( this, 1f ) );
h.addKeyBinding( "move_withMouse_back/forward/left/right", "button3" );
//fast and very fast camera motion
h.addBehaviour( "move_withMouse_back/forward/left/right_fast", new CameraTranslateControl( this, 10f ) );
h.addKeyBinding( "move_withMouse_back/forward/left/right_fast", "shift button3" );
// Keyboard move around (WASD keys)
//override 'WASD' from Scenery
MovementCommand mcW,mcA,mcS,mcD;
mcW = new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
mcS = new MovementCommand( "move_backward", "back", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
mcA = new MovementCommand( "move_left", "left", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
mcD = new MovementCommand( "move_right", "right", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
controlsParameters.registerSlowStepMover( mcW );
controlsParameters.registerSlowStepMover( mcS );
controlsParameters.registerSlowStepMover( mcA );
controlsParameters.registerSlowStepMover( mcD );
h.addBehaviour( "move_forward", mcW );
h.addBehaviour( "move_back", mcS );
h.addBehaviour( "move_left", mcA );
h.addBehaviour( "move_right", mcD );
// 'WASD' keys are registered already in scenery
//override shift+'WASD' from Scenery
mcW = new MovementCommand( "move_forward_fast", "forward", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
mcS = new MovementCommand( "move_backward_fast", "back", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
mcA = new MovementCommand( "move_left_fast", "left", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
mcD = new MovementCommand( "move_right_fast", "right", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
controlsParameters.registerFastStepMover( mcW );
controlsParameters.registerFastStepMover( mcS );
controlsParameters.registerFastStepMover( mcA );
controlsParameters.registerFastStepMover( mcD );
h.addBehaviour( "move_forward_fast", mcW );
h.addBehaviour( "move_back_fast", mcS );
h.addBehaviour( "move_left_fast", mcA );
h.addBehaviour( "move_right_fast", mcD );
// shift+'WASD' keys are registered already in scenery
//define additionally shift+ctrl+'WASD'
mcW = new MovementCommand( "move_forward_veryfast", "forward", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
mcS = new MovementCommand( "move_back_veryfast", "back", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
mcA = new MovementCommand( "move_left_veryfast", "left", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
mcD = new MovementCommand( "move_right_veryfast", "right", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
controlsParameters.registerVeryFastStepMover( mcW );
controlsParameters.registerVeryFastStepMover( mcS );
controlsParameters.registerVeryFastStepMover( mcA );
controlsParameters.registerVeryFastStepMover( mcD );
h.addBehaviour( "move_forward_veryfast", mcW );
h.addBehaviour( "move_back_veryfast", mcS );
h.addBehaviour( "move_left_veryfast", mcA );
h.addBehaviour( "move_right_veryfast", mcD );
h.addKeyBinding( "move_forward_veryfast", "ctrl shift W" );
h.addKeyBinding( "move_back_veryfast", "ctrl shift S" );
h.addKeyBinding( "move_left_veryfast", "ctrl shift A" );
h.addKeyBinding( "move_right_veryfast", "ctrl shift D" );
// Keyboard only move up/down (XC keys)
//[[ctrl]+shift]+'XC'
mcW = new MovementCommand( "move_up", "up", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
mcS = new MovementCommand( "move_down", "down", () -> getScene().findObserver(), controlsParameters.getFpsSpeedSlow() );
controlsParameters.registerSlowStepMover( mcW );
controlsParameters.registerSlowStepMover( mcS );
h.addBehaviour( "move_up", mcW );
h.addBehaviour( "move_down", mcS );
h.addKeyBinding( "move_up", "C" );
h.addKeyBinding( "move_down", "X" );
mcW = new MovementCommand( "move_up_fast", "up", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
mcS = new MovementCommand( "move_down_fast", "down", () -> getScene().findObserver(), controlsParameters.getFpsSpeedFast() );
controlsParameters.registerFastStepMover( mcW );
controlsParameters.registerFastStepMover( mcS );
h.addBehaviour( "move_up_fast", mcW );
h.addBehaviour( "move_down_fast", mcS );
h.addKeyBinding( "move_up_fast", "shift C" );
h.addKeyBinding( "move_down_fast", "shift X" );
mcW = new MovementCommand( "move_up_veryfast", "up", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
mcS = new MovementCommand( "move_down_veryfast", "down", () -> getScene().findObserver(), controlsParameters.getFpsSpeedVeryFast() );
controlsParameters.registerVeryFastStepMover( mcW );
controlsParameters.registerVeryFastStepMover( mcS );
h.addBehaviour( "move_up_veryfast", mcW );
h.addBehaviour( "move_down_veryfast", mcS );
h.addKeyBinding( "move_up_veryfast", "ctrl shift C" );
h.addKeyBinding( "move_down_veryfast", "ctrl shift X" );
}
/**
* Add a box to the scene with default parameters
* @return the Node corresponding to the box
*/
public Node addBox() {
return addBox( new JOMLVector3( 0.0f, 0.0f, 0.0f ) );
}
/**
* Add a box at the specific position and unit size
* @param position position to put the box
* @return the Node corresponding to the box
*/
public Node addBox( Vector3 position ) {
return addBox( position, new JOMLVector3( 1.0f, 1.0f, 1.0f ) );
}
/**
* Add a box at the specified position and with the specified size
* @param position position to put the box
* @param size size of the box
* @return the Node corresponding to the box
*/
public Node addBox( Vector3 position, Vector3 size ) {
return addBox( position, size, DEFAULT_COLOR, false );
}
/**
* Add a box at the specified position with specified size, color, and normals on the inside/outside
* @param position position to put the box
* @param size size of the box
* @param color color of the box
* @param inside are normals inside the box?
* @return the Node corresponding to the box
*/
public Node addBox( final Vector3 position, final Vector3 size, final ColorRGB color,
final boolean inside ) {
// TODO: use a material from the current palate by default
final Material boxmaterial = new Material();
boxmaterial.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
boxmaterial.setDiffuse( Utils.convertToVector3f( color ) );
boxmaterial.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
final Box box = new Box( JOMLVector3.convert( size ), inside );
box.setMaterial( boxmaterial );
box.setPosition( JOMLVector3.convert( position ) );
return addNode( box );
}
/**
* Add a unit sphere at the origin
* @return the Node corresponding to the sphere
*/
public Node addSphere() {
return addSphere( new JOMLVector3( 0.0f, 0.0f, 0.0f ), 1 );
}
/**
* Add a sphere at the specified position with a given radius
* @param position position to put the sphere
* @param radius radius of the sphere
* @return the Node corresponding to the sphere
*/
public Node addSphere( Vector3 position, float radius ) {
return addSphere( position, radius, DEFAULT_COLOR );
}
/**
* Add a sphere at the specified positoin with a given radius and color
* @param position position to put the sphere
* @param radius radius the sphere
* @param color color of the sphere
* @return the Node corresponding to the sphere
*/
public Node addSphere( final Vector3 position, final float radius, final ColorRGB color ) {
final Material material = new Material();
material.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( Utils.convertToVector3f( color ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( JOMLVector3.convert( position ) );
return addNode( sphere );
}
/**
* Add a Cylinder at the given position with radius, height, and number of faces/segments
* @param position position of the cylinder
* @param radius radius of the cylinder
* @param height height of the cylinder
* @param num_segments number of segments to represent the cylinder
* @return the Node corresponding to the cylinder
*/
public Node addCylinder( final Vector3 position, final float radius, final float height, final int num_segments ) {
final Cylinder cyl = new Cylinder( radius, height, num_segments );
cyl.setPosition( JOMLVector3.convert( position ) );
return addNode( cyl );
}
/**
* Add a Cone at the given position with radius, height, and number of faces/segments
* @param position position to put the cone
* @param radius radius of the cone
* @param height height of the cone
* @param num_segments number of segments used to represent cone
* @return the Node corresponding to the cone
*/
public Node addCone( final Vector3 position, final float radius, final float height, final int num_segments ) {
final Cone cone = new Cone( radius, height, num_segments, new Vector3f(0,0,1) );
cone.setPosition( JOMLVector3.convert( position ) );
return addNode( cone );
}
/**
* Add a Line from 0,0,0 to 1,1,1
* @return the Node corresponding to the line
*/
public Node addLine() {
return addLine( new JOMLVector3( 0.0f, 0.0f, 0.0f ), new JOMLVector3( 1.0f, 1.0f, 1.0f ) );
}
/**
* Add a line from start to stop
* @param start start position of line
* @param stop stop position of line
* @return the Node corresponding to the line
*/
public Node addLine( Vector3 start, Vector3 stop ) {
return addLine( start, stop, DEFAULT_COLOR );
}
/**
* Add a line from start to stop with the given color
* @param start start position of line
* @param stop stop position of line
* @param color color of line
* @return the Node corresponding to the line
*/
public Node addLine( Vector3 start, Vector3 stop, ColorRGB color ) {
return addLine( new Vector3[] { start, stop }, color, 0.1f );
}
/**
* Add a multi-segment line that goes through the supplied points with a single color and edge width
* @param points points along line including first and terminal points
* @param color color of line
* @param edgeWidth width of line segments
* @return the Node corresponding to the line
*/
public Node addLine( final Vector3[] points, final ColorRGB color, final double edgeWidth ) {
final Material material = new Material();
material.setAmbient( new Vector3f( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( Utils.convertToVector3f( color ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
final Line line = new Line( points.length );
for( final Vector3 pt : points ) {
line.addPoint( JOMLVector3.convert( pt ) );
}
line.setEdgeWidth( ( float ) edgeWidth );
line.setMaterial( material );
line.setPosition( JOMLVector3.convert( points[0] ) );
return addNode( line );
}
/**
* Add a PointLight source at the origin
* @return a Node corresponding to the PointLight
*/
public Node addPointLight() {
final Material material = new Material();
material.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new Vector3f( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
final PointLight light = new PointLight( 5.0f );
light.setMaterial( material );
light.setPosition( new Vector3f( 0.0f, 0.0f, 0.0f ) );
lights.add(light);
return addNode( light );
}
/**
* Position all lights that were initialized by default around the scene in a circle at Y=0
*/
public void surroundLighting() {
OrientedBoundingBox bb = getSubgraphBoundingBox(getScene(), notAbstractBranchingFunction);
OrientedBoundingBox.BoundingSphere boundingSphere = bb.getBoundingSphere();
// Choose a good y-position, then place lights around the cross-section through this plane
float y = 0;
Vector3f c = boundingSphere.getOrigin();
float r = boundingSphere.getRadius();
for( int k = 0; k < lights.size(); k++ ) {
PointLight light = lights.get(k);
float x = (float) (c.x() + r * Math.cos( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.size()) ));
float z = (float) (c.y() + r * Math.sin( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.size()) ));
light.setLightRadius( 2 * r );
light.setPosition( new Vector3f( x, y, z ) );
}
}
/**
* Write a scenery mesh as an stl to the given file
* @param filename filename of the stl
* @param scMesh mesh to save
*/
public void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ( "facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() +
"\n" ).getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() +
"\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch( FileNotFoundException e ) {
e.printStackTrace();
} catch( IOException e ) {
e.printStackTrace();
}
}
/**
* Return the default point size to use for point clouds
* @return default point size used for point clouds
*/
public float getDefaultPointSize() {
return 0.025f;
}
/**
* Create an array of normal vectors from a set of vertices corresponding to triangles
*
* @param verts vertices to use for computing normals, assumed to be ordered as triangles
* @return array of normals
*/
public float[] makeNormalsFromVertices( ArrayList<RealPoint> verts ) {
float[] normals = new float[verts.size()];// div3 * 3coords
for( int k = 0; k < verts.size(); k += 3 ) {
Vector3f v1 = new Vector3f( verts.get( k ).getFloatPosition( 0 ),
verts.get( k ).getFloatPosition( 1 ),
verts.get( k ).getFloatPosition( 2 ) );
Vector3f v2 = new Vector3f( verts.get( k + 1 ).getFloatPosition( 0 ),
verts.get( k + 1 ).getFloatPosition( 1 ),
verts.get( k + 1 ).getFloatPosition( 2 ) );
Vector3f v3 = new Vector3f( verts.get( k + 2 ).getFloatPosition( 0 ),
verts.get( k + 2 ).getFloatPosition( 1 ),
verts.get( k + 2 ).getFloatPosition( 2 ) );
Vector3f a = v2.sub( v1 );
Vector3f b = v3.sub( v1 );
Vector3f n = a.cross( b ).normalize();
normals[k / 3] = n.get( 0 );
normals[k / 3 + 1] = n.get( 1 );
normals[k / 3 + 2] = n.get( 2 );
}
return normals;
}
/**
* Open a file specified by the source path. The file can be anything that SciView knows about: mesh, volume, point cloud
* @param source string of a data source
* @throws IOException
*/
public void open( final String source ) throws IOException {
if(source.endsWith(".xml")) {
addNode(Volume.Companion.fromXML(source, getHub(), new VolumeViewerOptions()));
return;
}
final Object data = io.open( source );
if( data instanceof net.imagej.mesh.Mesh ) addMesh( ( net.imagej.mesh.Mesh ) data );
else if( data instanceof Mesh ) addMesh( ( Mesh ) data );
else if( data instanceof PointCloud ) addPointCloud( ( PointCloud ) data );
else if( data instanceof Dataset ) addVolume( ( Dataset ) data );
else if( data instanceof RandomAccessibleInterval ) addVolume( ( ( RandomAccessibleInterval ) data ), source );
else if( data instanceof List ) {
final List<?> list = ( List<?> ) data;
if( list.isEmpty() ) {
throw new IllegalArgumentException( "Data source '" + source + "' appears empty." );
}
final Object element = list.get( 0 );
if( element instanceof RealLocalizable ) {
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
@SuppressWarnings("unchecked") final List<? extends RealLocalizable> points = ( List<? extends RealLocalizable> ) list;
addPointCloud( points, source );
} else {
final String type = element == null ? "<null>" : element.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source +
"' contains elements of unknown type '" + type + "'" );
}
} else {
final String type = data == null ? "<null>" : data.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source +
"' contains data of unknown type '" + type + "'" );
}
}
/**
* Add the given points to the scene as a PointCloud
* @param points points to use in a PointCloud
* @return a Node corresponding to the PointCloud
*/
public Node addPointCloud( Collection<? extends RealLocalizable> points ) {
return addPointCloud( points, "PointCloud" );
}
/**
* Add the given points to the scene as a PointCloud with a given name
* @param points points to use in a PointCloud
* @param name name of the PointCloud
* @return
*/
public Node addPointCloud( final Collection<? extends RealLocalizable> points,
final String name ) {
final float[] flatVerts = new float[points.size() * 3];
int k = 0;
for( final RealLocalizable point : points ) {
flatVerts[k * 3] = point.getFloatPosition( 0 );
flatVerts[k * 3 + 1] = point.getFloatPosition( 1 );
flatVerts[k * 3 + 2] = point.getFloatPosition( 2 );
k++;
}
final PointCloud pointCloud = new PointCloud( getDefaultPointSize(), name );
final Material material = new Material();
final FloatBuffer vBuffer = BufferUtils.allocateFloat( flatVerts.length * 4 );
final FloatBuffer nBuffer = BufferUtils.allocateFloat( 0 );
vBuffer.put( flatVerts );
vBuffer.flip();
pointCloud.setVertices( vBuffer );
pointCloud.setNormals( nBuffer );
pointCloud.setIndices( BufferUtils.allocateInt( 0 ) );
pointCloud.setupPointCloud();
material.setAmbient( new Vector3f( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( new Vector3f( 1.0f, 1.0f, 1.0f ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
pointCloud.setMaterial( material );
pointCloud.setPosition( new Vector3f( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
/**
* Add a PointCloud to the scene
* @param pointCloud existing PointCloud to add to scene
* @return a Node corresponding to the PointCloud
*/
public Node addPointCloud( final PointCloud pointCloud ) {
pointCloud.setupPointCloud();
pointCloud.getMaterial().setAmbient( new Vector3f( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setDiffuse( new Vector3f( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
pointCloud.setPosition( new Vector3f( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
/**
* Add a Node to the scene and publish it to the eventservice
* @param n node to add to scene
* @return a Node corresponding to the Node
*/
public Node addNode( final Node n ) {
return addNode(n, true);
}
/**
* Add Node n to the scene and set it as the active node/publish it to the event service if activePublish is true
* @param n node to add to scene
* @param activePublish flag to specify whether the node becomes active *and* is published in the inspector/services
* @return a Node corresponding to the Node
*/
public Node addNode( final Node n, final boolean activePublish ) {
getScene().addChild( n );
objectService.addObject(n);
if( blockOnNewNodes ) {
blockWhile(sciView -> (sciView.find(n.getName()) == null), 20);
//System.out.println("find(name) " + find(n.getName()) );
}
// Set new node as active and centered?
setActiveNode(n);
if( centerOnNewNodes ) centerOnNode(n);
if( activePublish ) eventService.publish(new NodeAddedEvent(n));
return n;
}
/**
* Add a scenery Mesh to the scene
* @param scMesh scenery mesh to add to scene
* @return a Node corresponding to the mesh
*/
public Node addMesh( final Mesh scMesh ) {
final Material material = new Material();
material.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new Vector3f( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
scMesh.setMaterial( material );
scMesh.setPosition( new Vector3f( 0.0f, 0.0f, 0.0f ) );
objectService.addObject(scMesh);
return addNode( scMesh );
}
/**
* Add an ImageJ mesh to the scene
* @param mesh net.imagej.mesh to add to scene
* @return a Node corresponding to the mesh
*/
public Node addMesh( net.imagej.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.toScenery( mesh );
return addMesh( scMesh );
}
/**
* [Deprecated: use deleteNode]
* Remove a Mesh from the scene
* @param scMesh mesh to remove from scene
*/
public void removeMesh( Mesh scMesh ) {
getScene().removeChild( scMesh );
}
/**
* @return a Node corresponding to the currently active node
*/
public Node getActiveNode() {
return activeNode;
}
/**
* Activate the node (without centering view on it). The node becomes a target
* of the Arcball camera movement, will become subject of the node dragging
* (ctrl[+shift]+mouse-left-click-and-drag), will be selected in the scene graph
* inspector (the {@link NodePropertyEditor})
* and {@link sc.iview.event.NodeActivatedEvent} will be published.
*
* @param n existing node that should become active focus of this SciView
* @return the currently active node
*/
public Node setActiveNode( Node n ) {
if( activeNode == n ) return activeNode;
activeNode = n;
targetArcball.setTarget( n == null ? () -> new Vector3f( 0, 0, 0 ) : () -> n.getMaximumBoundingBox().getBoundingSphere().getOrigin());
nodePropertyEditor.trySelectNode( activeNode );
eventService.publish( new NodeActivatedEvent( activeNode ) );
return activeNode;
}
/**
* Activate the node, and center the view on it.
* @param n
* @return the currently active node
*/
public Node setActiveCenteredNode( Node n ) {
//activate...
Node ret = setActiveNode(n);
//...and center it
if (ret != null) centerOnNode(ret);
return ret;
}
@EventHandler
protected void onNodeAdded(NodeAddedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeRemoved(NodeRemovedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeChanged(NodeChangedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeActivated(NodeActivatedEvent event) {
// TODO: add listener code for node activation, if necessary
// NOTE: do not update property window here, this will lead to a loop.
}
public void toggleInspectorWindow()
{
toggleSidebar();
}
public void setInspectorWindowVisibility(boolean visible)
{
// inspector.setVisible(visible);
// if( visible )
// mainSplitPane.setDividerLocation(getWindowWidth()/4 * 3);
// else
// mainSplitPane.setDividerLocation(getWindowWidth());
}
public void setInterpreterWindowVisibility(boolean visible)
{
// interpreterPane.getComponent().setVisible(visible);
// if( visible )
// interpreterSplitPane.setDividerLocation(getWindowHeight()/10 * 6);
// else
// interpreterSplitPane.setDividerLocation(getWindowHeight());
}
/**
* Create an animation thread with the given fps speed and the specified action
* @param fps frames per second at which this action should be run
* @param action Runnable that contains code to run fps times per second
* @return a Future corresponding to the thread
*/
public synchronized Future<?> animate(int fps, Runnable action ) {
// TODO: Make animation speed less laggy and more accurate.
final int delay = 1000 / fps;
Future<?> thread = threadService.run(() -> {
while (animating) {
action.run();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
}
});
animations.add( thread );
animating = true;
return thread;
}
/**
* Stop all animations
*/
public synchronized void stopAnimation() {
animating = false;
while( !animations.isEmpty() ) {
animations.peek().cancel( true );
animations.remove();
}
}
/**
* Take a screenshot and save it to the default scenery location
*/
public void takeScreenshot() {
getRenderer().screenshot();
}
/**
* Take a screenshot and save it to the specified path
* @param path path for saving the screenshot
*/
public void takeScreenshot( String path ) {
getRenderer().screenshot( path, false );
}
/**
* Take a screenshot and return it as an Img
* @return an Img of type UnsignedByteType
*/
public Img<UnsignedByteType> getScreenshot() {
RenderedImage screenshot = getSceneryRenderer().requestScreenshot();
BufferedImage image = new BufferedImage(screenshot.getWidth(), screenshot.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
byte[] imgData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(screenshot.getData(), 0, imgData, 0, screenshot.getData().length);
Img<UnsignedByteType> img = null;
File tmpFile = null;
try {
tmpFile = File.createTempFile("sciview-", "-tmp.png");
ImageIO.write(image, "png", tmpFile);
img = (Img<UnsignedByteType>)io.open(tmpFile.getAbsolutePath());
tmpFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
/**
* Take a screenshot and return it as an Img
* @return an Img of type UnsignedByteType
*/
public Img<ARGBType> getARGBScreenshot() {
Img<UnsignedByteType> screenshot = getScreenshot();
return Utils.convertToARGB(screenshot);
}
/**
* @param name The name of the node to find.
* @return the node object or null, if the node has not been found.
*/
public Node find(final String name) {
final Node n = getScene().find(name);
if(n == null) {
getLogger().warn("Node with name " + name + " not found.");
}
return n;
}
/**
* @return an array of all nodes in the scene except Cameras and PointLights
*/
public Node[] getSceneNodes() {
return getSceneNodes( n -> !( n instanceof Camera ) && !( n instanceof PointLight ) );
}
/**
* Get a list of nodes filtered by filter predicate
* @param filter, a predicate that filters the candidate nodes
* @return all nodes that match the predicate
*/
public Node[] getSceneNodes( Predicate<? super Node> filter ) {
return getScene().getChildren().stream().filter( filter ).toArray( Node[]::new );
}
/**
* @return an array of all Node's in the scene
*/
public Node[] getAllSceneNodes() {
return getSceneNodes( n -> true );
}
/**
* Delete the current active node
*/
public void deleteActiveNode() {
deleteNode( getActiveNode() );
}
/**
* Delete the specified node, this event is published
* @param node node to delete from scene
*/
public void deleteNode( Node node ) {
deleteNode( node, true );
}
/**
* Delete a specified node and control whether the event is published
* @param node node to delete from scene
* @param activePublish whether the deletion should be published
*/
public void deleteNode( Node node, boolean activePublish ) {
for( Node child : node.getChildren() ) {
deleteNode(child, activePublish);
}
objectService.removeObject(node);
node.getParent().removeChild( node );
if (activeNode == node) setActiveNode(null); //maintain consistency
if( activePublish ) eventService.publish(new NodeRemovedEvent(node));
}
/**
* Dispose the current scenery renderer, hub, and other scenery things
*/
public void dispose() {
List<Node> objs = objectService.getObjects(Node.class);
for( Node obj : objs ) {
objectService.removeObject(obj);
}
getScijavaContext().service(SciViewService.class).close(this);
this.close();
}
public void close() {
super.close();
frame.dispose();
}
/**
* Move the current active camera to the specified position
* @param position position to move the camera to
*/
public void moveCamera( float[] position ) {
getCamera().setPosition( new Vector3f( position[0], position[1], position[2] ) );
}
/**
* Move the current active camera to the specified position
* @param position position to move the camera to
*/
public void moveCamera( double[] position ) {
getCamera().setPosition( new Vector3f( ( float ) position[0], ( float ) position[1], ( float ) position[2] ) );
}
/**
* Get the current application name
* @return a String of the application name
*/
public String getName() {
return getApplicationName();
}
/**
* Add a child to the scene. you probably want addNode
* @param node node to add as a child to the scene
*/
public void addChild( Node node ) {
getScene().addChild( node );
}
/**
* Add a Dataset to the scene as a volume. Voxel resolution and name are extracted from the Dataset itself
* @param image image to add as a volume
* @return a Node corresponding to the Volume
*/
public Node addVolume( Dataset image ) {
float[] voxelDims = new float[image.numDimensions()];
for( int d = 0; d < voxelDims.length; d++ ) {
double inValue = image.axis(d).averageScale(0, 1);
if( image.axis(d).unit() == null )
voxelDims[d] = (float) inValue;
else
voxelDims[d] = (float) unitService.value( inValue, image.axis(d).unit(), axis(d).unit() );
}
return addVolume( image, voxelDims );
}
/**
* Add a Dataset as a Volume with the specified voxel dimensions
* @param image image to add as a volume
* @param voxelDimensions dimensions of voxels in volume
* @return a Node corresponding to the Volume
*/
@SuppressWarnings({ "rawtypes", "unchecked" }) public Node addVolume( Dataset image, float[] voxelDimensions ) {
return addVolume( ( RandomAccessibleInterval ) image.getImgPlus(), image.getName(),
voxelDimensions );
}
/**
* Add a RandomAccessibleInterval to the image
* @param image image to add as a volume
* @param name name of image
* @param extra, kludge argument to prevent matching issues
* @param <T> pixel type of image
* @return a Node corresponding to the volume
*/
public <T extends RealType<T>> Node addVolume( RandomAccessibleInterval<T> image, String name, String extra ) {
return addVolume( image, name, 1, 1, 1 );
}
/**
* Add a RandomAccessibleInterval to the image
* @param image image to add as a volume
* @param <T> pixel type of image
* @return a Node corresponding to the volume
*/
public <T extends RealType<T>> Node addVolume(RandomAccessibleInterval<T> image, String name) {
return addVolume(image, name, 1f, 1f, 1f);
}
/**
* Add a RandomAccessibleInterval to the image
* @param image image to add as a volume
* @param <T> pixel type of image
* @return a Node corresponding to the volume
*/
public <T extends RealType<T>> Node addVolume( RandomAccessibleInterval<T> image, float[] voxelDimensions ) {
long[] pos = new long[]{10, 10, 10};
return addVolume( image, "volume", voxelDimensions );
}
/**
* Add an IterableInterval as a Volume
* @param image
* @param <T>
* @return a Node corresponding to the Volume
*/
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image ) throws Exception {
if( image instanceof RandomAccessibleInterval ) {
return addVolume((RandomAccessibleInterval) image, "Volume");
} else {
throw new Exception("Unsupported Volume type:" + image);
}
}
/**
* Add an IterableInterval as a Volume
* @param image image to add as a volume
* @param name name of image
* @param <T> pixel type of image
* @return a Node corresponding to the Volume
*/
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name ) throws Exception {
if( image instanceof RandomAccessibleInterval ) {
return addVolume( (RandomAccessibleInterval) image, name, 1, 1, 1 );
} else {
throw new Exception("Unsupported Volume type:" + image);
}
}
/**
* Set the colormap using an ImageJ LUT name
* @param n node to apply colormap to
* @param lutName name of LUT according to imagej LUTService
*/
public void setColormap( Node n, String lutName ) {
try {
setColormap( n, lutService.loadLUT( lutService.findLUTs().get( lutName ) ) );
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Set the ColorMap of node n to the supplied colorTable
* @param n node to apply colortable to
* @param colorTable ColorTable to use
*/
public void setColormap( Node n, ColorTable colorTable ) {
final int copies = 16;
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
4 * colorTable.getLength() * copies );// Num bytes * num components * color map length * height of color map texture
final byte[] tmp = new byte[4 * colorTable.getLength()];
for( int k = 0; k < colorTable.getLength(); k++ ) {
for( int c = 0; c < colorTable.getComponentCount(); c++ ) {
// TODO this assumes numBits is 8, could be 16
tmp[4 * k + c] = ( byte ) colorTable.get( c, k );
}
if( colorTable.getComponentCount() == 3 ) {
tmp[4 * k + 3] = (byte)255;
}
}
for( int i = 0; i < copies; i++ ) {
byteBuffer.put(tmp);
}
byteBuffer.flip();
n.getMetadata().put("sciviewColormap", colorTable);
if(n instanceof Volume) {
((Volume) n).setColormap(Colormap.fromColorTable(colorTable));
n.setDirty(true);
n.setNeedsUpdate(true);
}
}
/**
* Adss a SourceAndConverter to the scene.
*
* @param sac The SourceAndConverter to add
* @param name Name of the dataset
* @param voxelDimensions Array with voxel dimensions.
* @param <T> Type of the dataset.
* @return THe node corresponding to the volume just added.
*/
public <T extends RealType<T>> Node addVolume(SourceAndConverter<T> sac,
int numTimepoints,
String name,
float... voxelDimensions ) {
List<SourceAndConverter<T>> sources = new ArrayList<>();
sources.add(sac);
return addVolume(sources, numTimepoints, name, voxelDimensions);
}
/**
* Add an IterableInterval to the image with the specified voxelDimensions and name
* This version of addVolume does most of the work
* @param image image to add as a volume
* @param name name of image
* @param voxelDimensions dimensions of voxel in volume
* @param <T> pixel type of image
* @return a Node corresponding to the Volume
*/
public <T extends RealType<T>> Node addVolume( RandomAccessibleInterval<T> image, String name,
float... voxelDimensions ) {
//log.debug( "Add Volume " + name + " image: " + image );
long[] dimensions = new long[image.numDimensions()];
image.dimensions( dimensions );
long[] minPt = new long[image.numDimensions()];
// Get type at min point
RandomAccess<T> imageRA = image.randomAccess();
image.min(minPt);
imageRA.setPosition(minPt);
T voxelType = imageRA.get().createVariable();
ArrayList<ConverterSetup> converterSetups = new ArrayList();
ArrayList<RandomAccessibleInterval<T>> stacks = AxisOrder.splitInputStackIntoSourceStacks(image, AxisOrder.getAxisOrder(AxisOrder.DEFAULT, image, false));
AffineTransform3D sourceTransform = new AffineTransform3D();
ArrayList<SourceAndConverter<T>> sources = new ArrayList();
int numTimepoints = 1;
for (RandomAccessibleInterval stack : stacks) {
Source<T> s;
if (stack.numDimensions() > 3) {
numTimepoints = (int) (stack.max(3) + 1);
s = new RandomAccessibleIntervalSource4D<T>(stack, voxelType, sourceTransform, name);
} else {
s = new RandomAccessibleIntervalSource<T>(stack, voxelType, sourceTransform, name);
}
SourceAndConverter<T> source = BigDataViewer.wrapWithTransformedSource(
new SourceAndConverter<T>(s, BigDataViewer.createConverterToARGB(voxelType)));
converterSetups.add(BigDataViewer.createConverterSetup(source, Volume.Companion.getSetupId().getAndIncrement()));
sources.add(source);
}
Node v = addVolume(sources, numTimepoints, name, voxelDimensions);
v.getMetadata().put("RandomAccessibleInterval", image);
return v;
}
/**
* Adds a SourceAndConverter to the scene.
*
* This method actually instantiates the volume.
*
* @param sources The list of SourceAndConverter to add
* @param name Name of the dataset
* @param voxelDimensions Array with voxel dimensions.
* @param <T> Type of the dataset.
* @return THe node corresponding to the volume just added.
*/
public <T extends RealType<T>> Node addVolume(List<SourceAndConverter<T>> sources,
ArrayList<ConverterSetup> converterSetups,
int numTimepoints,
String name,
float... voxelDimensions ) {
CacheControl cacheControl = null;
// RandomAccessibleInterval<T> image =
// ((RandomAccessibleIntervalSource4D) sources.get(0).getSpimSource()).
// .getSource(0, 0);
RandomAccessibleInterval<T> image = sources.get(0).getSpimSource().getSource(0, 0);
if (image instanceof VolatileView) {
VolatileViewData<T, Volatile<T>> viewData = ((VolatileView<T, Volatile<T>>) image).getVolatileViewData();
cacheControl = viewData.getCacheControl();
}
long[] dimensions = new long[image.numDimensions()];
image.dimensions( dimensions );
long[] minPt = new long[image.numDimensions()];
// Get type at min point
RandomAccess<T> imageRA = image.randomAccess();
image.min(minPt);
imageRA.setPosition(minPt);
T voxelType = imageRA.get().createVariable();
System.out.println("addVolume " + image.numDimensions() + " interval " + ((Interval) image) );
//int numTimepoints = 1;
if( image.numDimensions() > 3 ) {
numTimepoints = (int) image.dimension(3);
}
Volume.VolumeDataSource.RAISource<T> ds = new Volume.VolumeDataSource.RAISource<T>(voxelType, sources, converterSetups, numTimepoints, cacheControl);
VolumeViewerOptions options = new VolumeViewerOptions();
Volume v = new RAIVolume(ds, options, getHub());
v.setName(name);
v.getMetadata().put("sources", sources);
TransferFunction tf = v.getTransferFunction();
float rampMin = 0f;
float rampMax = 0.1f;
tf.clear();
tf.addControlPoint(0.0f, 0.0f);
tf.addControlPoint(rampMin, 0.0f);
tf.addControlPoint(1.0f, rampMax);
BoundingGrid bg = new BoundingGrid();
bg.setNode(v);
return addNode(v);
}
/**
* Block while predicate is true
*
* @param predicate predicate function that returns true as long as this function should block
* @param waitTime wait time before predicate re-evaluation
*/
private void blockWhile(Function<SciView, Boolean> predicate, int waitTime) {
while( predicate.apply(this) ) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Adds a SourceAndConverter to the scene.
*
* @param sources The list of SourceAndConverter to add
* @param name Name of the dataset
* @param voxelDimensions Array with voxel dimensions.
* @param <T> Type of the dataset.
* @return THe node corresponding to the volume just added.
*/
public <T extends RealType<T>> Node addVolume(List<SourceAndConverter<T>> sources,
int numTimepoints,
String name,
float... voxelDimensions ) {
int setupId = 0;
ArrayList<ConverterSetup> converterSetups = new ArrayList<>();
for( SourceAndConverter source: sources ) {
converterSetups.add(BigDataViewer.createConverterSetup(source, setupId++));
}
return addVolume(sources, converterSetups, numTimepoints, name, voxelDimensions);
}
/**
* Update a volume with the given IterableInterval.
* This method actually populates the volume
* @param image image to update into volume
* @param name name of image
* @param voxelDimensions dimensions of voxel in volume
* @param v existing volume to update
* @param <T> pixel type of image
* @return a Node corresponding to the input volume
*/
public <T extends RealType<T>> Node updateVolume( IterableInterval<T> image, String name,
float[] voxelDimensions, Volume v ) {
List<SourceAndConverter<T>> sacs = (List<SourceAndConverter<T>>) v.getMetadata().get("sources");
RandomAccessibleInterval<T> source = sacs.get(0).getSpimSource().getSource(0, 0);// hard coded to timepoint and mipmap 0
Cursor<T> sCur = Views.iterable(source).cursor();
Cursor<T> iCur = image.cursor();
while( sCur.hasNext() ) {
sCur.fwd();
iCur.fwd();
sCur.get().set(iCur.get());
}
v.getVolumeManager().notifyUpdate(v);
v.getVolumeManager().requestRepaint();
//v.getCacheControls().clear();
//v.setDirty( true );
v.setNeedsUpdate( true );
//v.setNeedsUpdateWorld( true );
return v;
}
/**
*
* @return whether PushMode is currently active
*/
public boolean getPushMode() {
return getRenderer().getPushMode();
}
/**
* Set the status of PushMode, which only updates the render panel when there is a change in the scene
* @param push true if push mode should be used
* @return current PushMode status
*/
public boolean setPushMode( boolean push ) {
getRenderer().setPushMode( push );
return getRenderer().getPushMode();
}
public ArcballCameraControl getTargetArcball() {
return targetArcball;
}
@Override
protected void finalize() {
stopAnimation();
}
public Settings getScenerySettings() {
return this.getSettings();
}
public Statistics getSceneryStatistics() {
return this.getStats();
}
public Renderer getSceneryRenderer() {
return this.getRenderer();
}
/**
* Enable VR rendering
*/
public void toggleVRRendering() {
vrActive = !vrActive;
Camera cam = getScene().getActiveObserver();
if(!(cam instanceof DetachedHeadCamera)) {
return;
}
TrackerInput ti = null;
boolean hmdAdded = false;
if (!getHub().has(SceneryElement.HMDInput)) {
try {
final OpenVRHMD hmd = new OpenVRHMD(false, true);
if(hmd.initializedAndWorking()) {
getHub().add(SceneryElement.HMDInput, hmd);
ti = hmd;
} else {
getLogger().warn("Could not initialise VR headset, just activating stereo rendering.");
}
hmdAdded = true;
} catch (Exception e) {
getLogger().error("Could not add OpenVRHMD: " + e.toString());
}
} else {
ti = getHub().getWorkingHMD();
}
if(vrActive && ti != null) {
((DetachedHeadCamera) cam).setTracker(ti);
} else {
((DetachedHeadCamera) cam).setTracker(null);
}
getRenderer().setPushMode(false);
// we need to force reloading the renderer as the HMD might require device or instance extensions
if(getRenderer() instanceof VulkanRenderer && hmdAdded) {
replaceRenderer(getRenderer().getClass().getSimpleName(), true, true);
getRenderer().toggleVR();
while(!getRenderer().getInitialized()/* || !getRenderer().getFirstImageReady()*/) {
getLogger().debug("Waiting for renderer reinitialisation");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
getRenderer().toggleVR();
}
}
/**
* Utility function to generate GLVector in cases like usage from Python
* @param x x coord
* @param y y coord
* @param z z coord
* @return a GLVector of x,y,z
*/
static public GLVector getGLVector(float x, float y, float z) {
return new GLVector(x, y, z);
}
/**
* Set the rotation of Node N by generating a quaternion from the supplied arguments
* @param n node to set rotation for
* @param x x coord of rotation quat
* @param y y coord of rotation quat
* @param z z coord of rotation quat
* @param w w coord of rotation quat
*/
public void setRotation(Node n, float x, float y, float z, float w) {
n.setRotation(new Quaternionf(x,y,z,w));
}
public void setScale(Node n, float x, float y, float z) {
n.setScale(new Vector3f(x,y,z));
}
public void setColor(Node n, float x, float y, float z, float w) {
Vector3f col = new Vector3f(x, y, z);
n.getMaterial().setAmbient(col);
n.getMaterial().setDiffuse(col);
n.getMaterial().setSpecular(col);
}
public void setPosition(Node n, float x, float y, float z) {
n.setPosition(new Vector3f(x,y,z));
}
public void addWindowListener(WindowListener wl) {
frame.addWindowListener(wl);
}
@Override
public CalibratedAxis axis(int i) {
return axes[i];
}
@Override
public void axes(CalibratedAxis[] calibratedAxes) {
axes = calibratedAxes;
}
@Override
public void setAxis(CalibratedAxis calibratedAxis, int i) {
axes[i] = calibratedAxis;
}
@Override
public double realMin(int i) {
return Double.NEGATIVE_INFINITY;
}
@Override
public void realMin(double[] doubles) {
for( int i = 0; i < doubles.length; i++ ) {
doubles[i] = Double.NEGATIVE_INFINITY;
}
}
@Override
public void realMin(RealPositionable realPositionable) {
for( int i = 0; i < realPositionable.numDimensions(); i++ ) {
realPositionable.move(Double.NEGATIVE_INFINITY, i);
}
}
@Override
public double realMax(int i) {
return Double.POSITIVE_INFINITY;
}
@Override
public void realMax(double[] doubles) {
for( int i = 0; i < doubles.length; i++ ) {
doubles[i] = Double.POSITIVE_INFINITY;
}
}
@Override
public void realMax(RealPositionable realPositionable) {
for( int i = 0; i < realPositionable.numDimensions(); i++ ) {
realPositionable.move(Double.POSITIVE_INFINITY, i);
}
}
@Override
public int numDimensions() {
return axes.length;
}
public void setCamera(Camera camera) {
this.camera = camera;
setActiveObserver(camera);
}
public void setActiveObserver(Camera screenshotCam) {
getScene().setActiveObserver(screenshotCam);
}
public Camera getActiveObserver() {
return getScene().getActiveObserver();
}
public void setCenterOnNewNodes(boolean centerOnNewNodes) {
this.centerOnNewNodes = centerOnNewNodes;
}
public boolean getCenterOnNewNodes() {
return centerOnNewNodes;
}
public void setBlockOnNewNodes(boolean blockOnNewNodes) {
this.blockOnNewNodes = blockOnNewNodes;
}
public boolean getBlockOnNewNodes() {
return blockOnNewNodes;
}
public class TransparentSlider extends JSlider {
public TransparentSlider() {
// Important, we taking over the filling of the
// component...
setOpaque(false);
setBackground(Color.DARK_GRAY);
setForeground(Color.LIGHT_GRAY);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.9f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
class showHelpDisplay implements ClickBehaviour {
@Override public void click( int x, int y ) {
StringBuilder helpString = new StringBuilder("SciView help:\n\n");
for( InputTrigger trigger : getInputHandler().getAllBindings().keySet() ) {
helpString.append(trigger).append("\t-\t").append(getInputHandler().getAllBindings().get(trigger)).append("\n");
}
// HACK: Make the console pop via stderr.
// Later, we will use a nicer dialog box or some such.
log.warn(helpString.toString());
}
}
/**
* Return a list of all nodes that match a given predicate function
* @param nodeMatchPredicate, returns true if a node is a match
* @return list of nodes that match the predicate
*/
public List<Node> findNodes(Function1<Node, Boolean> nodeMatchPredicate) {
return getScene().discover(getScene(), nodeMatchPredicate, false);
}
/*
* Convenience function for getting a string of info about a Node
*/
public String nodeInfoString(Node n) {
return "Node name: " + n.getName() + " Node type: " + n.getNodeType() + " To String: " + n;
}
/**
* Static launching method
*
* @return a newly created SciView
*/
public static SciView create() throws Exception {
SceneryBase.xinitThreads();
FlatLightLaf.install();
try {
UIManager.setLookAndFeel( new FlatLightLaf() );
} catch( Exception ex ) {
System.err.println( "Failed to initialize Flat Light LaF, falling back to Swing default." );
}
System.setProperty( "scijava.log.level:sc.iview", "debug" );
Context context = new Context( ImageJService.class, SciJavaService.class, SCIFIOService.class, ThreadService.class);
SciViewService sciViewService = context.service( SciViewService.class );
SciView sciView = sciViewService.getOrCreateActiveSciView();
return sciView;
}
/**
* Static launching method
* [DEPRECATED] use SciView.create() instead
*
* @return a newly created SciView
*/
@Deprecated
public static SciView createSciView() throws Exception {
return create();
}
}
|
package etomica.potential;
/**
* Interface for a potential capable of return bond torsion energies and derivatives.
* Because it only takes cos(theta), the u(-theta) = u(theta) and du/dtheta = 0 at
* theta=0 and theta=pi.
*/
public interface IPotentialBondTorsion {
/**
* Returns the energy for the given value of cos(theta).
*/
double u(double costheta);
/**
* Returns the energy (u) and du/d(cos(theta)) (du) as out parameters for the
* given value of cos(theta).
*/
void udu(double costheta, double[] u, double[] du);
}
|
package etomica.util.numerical;
import etomica.util.FunctionDifferentiable;
public class BrentMethodwDerivative {
public BrentMethodwDerivative(){
}
public double[] dbrent(double[] x, FunctionDifferentiable function, double tol){
double xmin = 0.0;
int ITMAX = 100;
double ZEPS = 1e-9;
int iter;
boolean ok1, ok2;
double u;
double a,b,d1,d2,du,dv,dw,dx;
double d = 0.0;
double e = 0.0;
double fu,fv,fw,fx,olde,tol1,tol2,u1,u2,v,w,xm;
double ax = x[0];
double bx = x[1];
double cx = x[2];
/*
* to make sure that a and b are in ascending order
*/
a = (ax < cx ? ax: cx);
b = (ax > cx ? ax: cx);
double axe;
axe = w = v = bx;
fw= fv = fx = function.f(axe);
dw= dv = dx = function.df(1, axe);
int counter=0;
double diff =0.0;
double prevDiff =0.0;
for (iter=0; iter<ITMAX; iter++){
xm = 0.5*(a+b);
tol1 = tol*Math.abs(axe)+ZEPS;
tol2 = 2.0*tol1;
//Bail out if it can't find a minimum
diff = (xm - axe);
if(Math.abs(diff - prevDiff)<1e-12){
++counter;
if(counter>=5){
xmin = axe;
System.out.println(" <dbrent> you bailed [(xm - axe) constant for 5 times] condition");
counter =0;
return new double[]{xmin, fx};
}
} else {
prevDiff = diff;
counter =0;
}
if(Math.abs(axe-xm) <= 0.02*(tol2-0.5*(b-a))){
xmin = axe;
System.out.println(" <dbrent> you bailed (axe-xm)<tol2");
return new double[]{xmin, fx};
}
if(Math.abs(e) > tol1){
d1 = 2.0*(b-a);
d2 = d1;
if(dw != dx) {d1 = (w-axe)*dx/(dx-dw);} //Secant Method with one point
if(dv != dx) {d2 = (v-axe)*dx/(dx-dv);} // another Second Method
u1 = axe+d1;
u2 = axe+d2;
ok1 = (a-u1)*(u1-b) > 0.0 && dx*d1 <= 0.0;
ok2 = (a-u2)*(u2-b) > 0.0 && dx*d2 <= 0.0;
olde = e;
e = d;
/*
* Take the acceptable d only;
* but if double d's are acceptable, only pick the smallest d
*/
if(ok1 || ok2){
if(ok1 && ok2){
d = (Math.abs(d1) < Math.abs(d2) ? d1:d2);
} else if (ok1) {
d = d1;
} else {
d = d2;
}
if (Math.abs(d) <= Math.abs(0.5*olde)){
u = axe + d;
if (xm-axe >= 0){
d = Math.abs(tol1);
} else {
d = - Math.abs(tol1);
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
} else {
d = 0.5*(e=(dx >= 0.0 ? a-axe : b-axe));
}
if (Math.abs(d) >= tol1){
u = axe+d;
fu = function.f(u);
} else {
if (d >= 0){
u = axe + Math.abs(tol1);
} else {
u = axe - Math.abs(tol1);
}
fu = function.f(u);
/*
* If the minimum step in the downhill direction takes us uphill,
* then we are done.
*/
if (fu > fx){
xmin = axe;
System.out.println(" <dbrent> bailed at (fu > fx)");
return new double[] {xmin, fx};
}
}
du = function.df(1, u);
if (fu <= fx){
if (u >= axe){
a = axe;
} else {
b = axe;
}
v = w;
fv = fw;
dv = dw;
w = axe;
fw = fx;
dw = dx;
axe = u;
fx = fu;
dx = du;
} else {
if (u < v){
a = u;
} else{
b = u;
}
if (fu <= fw || w == axe){
v = w;
fv = fw;
dv = dw;
w = u;
fw = fu;
dw = du;
} else if(fu<fv || v==axe || v==w) {
v = u;
fv = fu;
dv = du;
}
}
}
throw new RuntimeException("Too many iterations in dbrent method!!!");
}
}
|
package sc.iview;
import cleargl.GLTypeEnum;
import cleargl.GLVector;
import com.bulenkov.darcula.DarculaLaf;
import com.jogamp.opengl.math.Quaternion;
import coremem.enums.NativeTypeEnum;
import graphics.scenery.Box;
import graphics.scenery.*;
import graphics.scenery.backends.RenderedImage;
import graphics.scenery.backends.Renderer;
import graphics.scenery.backends.opengl.OpenGLRenderer;
import graphics.scenery.backends.vulkan.VulkanRenderer;
import graphics.scenery.controls.InputHandler;
import graphics.scenery.controls.OpenVRHMD;
import graphics.scenery.controls.TrackerInput;
import graphics.scenery.controls.behaviours.ArcballCameraControl;
import graphics.scenery.controls.behaviours.FPSCameraControl;
import graphics.scenery.controls.behaviours.MovementCommand;
import graphics.scenery.controls.behaviours.SelectCommand;
import graphics.scenery.utils.*;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.Volume;
import graphics.scenery.volumes.bdv.BDVVolume;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import net.imagej.Dataset;
import net.imagej.lut.LUTService;
import net.imagej.ops.OpService;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.RealLocalizable;
import net.imglib2.RealPoint;
import net.imglib2.display.ColorTable;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.view.Views;
import org.scijava.Context;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.io.IOService;
import org.scijava.log.LogLevel;
import org.scijava.log.LogService;
import org.scijava.menu.MenuService;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.thread.ThreadService;
import org.scijava.ui.behaviour.ClickBehaviour;
import org.scijava.ui.behaviour.InputTrigger;
import org.scijava.ui.swing.menu.SwingJMenuBarCreator;
import org.scijava.util.ColorRGB;
import org.scijava.util.Colors;
import org.scijava.util.VersionUtils;
import sc.iview.commands.view.NodePropertyEditor;
import sc.iview.controls.behaviours.CameraTranslateControl;
import sc.iview.controls.behaviours.NodeTranslateControl;
import sc.iview.event.NodeActivatedEvent;
import sc.iview.event.NodeAddedEvent;
import sc.iview.event.NodeChangedEvent;
import sc.iview.event.NodeRemovedEvent;
import sc.iview.process.MeshConverter;
import sc.iview.vector.ClearGLVector3;
import sc.iview.vector.Vector3;
import tpietzsch.example2.VolumeViewerOptions;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.basic.BasicLookAndFeel;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
// we suppress unused warnings here because @Parameter-annotated fields
// get updated automatically by SciJava.
@SuppressWarnings({"unused", "WeakerAccess"})
public class SciView extends SceneryBase {
public static final ColorRGB DEFAULT_COLOR = Colors.LIGHTGRAY;
private final SceneryPanel[] sceneryPanel = { null };
/**
* Mouse controls for FPS movement and Arcball rotation
*/
protected ArcballCameraControl targetArcball;
protected FPSCameraControl fpsControl;
/**
* The floor that orients the user in the scene
*/
protected Node floor;
protected boolean vrActive = false;
/**
* The primary camera/observer in the scene
*/
Camera camera = null;
@Parameter
private LogService log;
@Parameter
private MenuService menus;
@Parameter
private IOService io;
@Parameter
private OpService ops;
@Parameter
private EventService eventService;
@Parameter
private DisplayService displayService;
@Parameter
private LUTService lutService;
@Parameter
private ThreadService threadService;
@Parameter
private ObjectService objectService;
/**
* Queue keeps track of the currently running animations
**/
private Queue<Future> animations;
/**
* Animation pause tracking
**/
private boolean animating;
/**
* This tracks the actively selected Node in the scene
*/
private Node activeNode = null;
/**
* Speeds for input controls
*/
private float fpsScrollSpeed = 0.05f;
private float mouseSpeedMult = 0.25f;
private Display<?> scijavaDisplay;
private JLabel splashLabel;
private SceneryJPanel panel;
private JSplitPane mainSplitPane;
private JSplitPane inspector;
private NodePropertyEditor nodePropertyEditor;
private ArrayList<PointLight> lights;
private Stack<HashMap<String, Object>> controlStack;
private JFrame frame;
private Predicate<? super Node> notAbstractNode = new Predicate<Node>() {
@Override
public boolean test(Node node) {
return !( (node instanceof Camera) || (node instanceof Light) || (node==getFloor()));
}
};
private boolean isClosed = false;
private Function<Node,List<Node>> notAbstractBranchingFunction = node -> node.getChildren().stream().filter(notAbstractNode).collect(Collectors.toList());
public SciView( Context context ) {
super( "SciView", 1280, 720, false, context );
context.inject( this );
}
public SciView( String applicationName, int windowWidth, int windowHeight ) {
super( applicationName, windowWidth, windowHeight, false );
}
static public GLVector getGLVector(float x, float y, float z) {
return new GLVector(x, y, z);
}
public boolean isClosed() {
return isClosed;
}
public InputHandler publicGetInputHandler() {
return getInputHandler();
}
public void toggleRecordVideo() {
if( getRenderer() instanceof OpenGLRenderer )
((OpenGLRenderer)getRenderer()).recordMovie();
else
((VulkanRenderer)getRenderer()).recordMovie();
}
public void stashControls() {
// This pushes the current input setup onto a stack that allows them to be restored with restoreControls
HashMap<String, Object> controlState = new HashMap<String, Object>();
controlStack.push(controlState);
}
public void restoreControls() {
// This pops/restores the previously stashed controls. Emits a warning if there are no stashed controlls
HashMap<String, Object> controlState = controlStack.pop();
// This isnt how it should work
setObjectSelectionMode();
resetFPSInputs();
}
/*
* Place the camera such that all objects in the scene are within the field of view
*/
public void fitCameraToScene() {
centerOnNode(getScene());
}
/*
* Reset the scene to initial conditions
*/
public void reset() {
// Remove everything except camera
Node[] toRemove = getSceneNodes( n -> !( n instanceof Camera ) );
for( Node n : toRemove ) {
deleteNode(n, false);
}
// Add initial objects
GLVector[] tetrahedron = new GLVector[4];
tetrahedron[0] = new GLVector( 1.0f, 0f, -1.0f/(float)Math.sqrt(2.0f) );
tetrahedron[1] = new GLVector( -1.0f,0f,-1.0f/(float)Math.sqrt(2.0) );
tetrahedron[2] = new GLVector( 0.0f,1.0f,1.0f/(float)Math.sqrt(2.0) );
tetrahedron[3] = new GLVector( 0.0f,-1.0f,1.0f/(float)Math.sqrt(2.0) );
lights = new ArrayList<PointLight>();
for( int i = 0; i < 4; i++ ) {// TODO allow # initial lights to be customizable?
PointLight light = new PointLight(150.0f);
light.setPosition( tetrahedron[i].times(25.0f) );
light.setEmissionColor( new GLVector( 1.0f, 1.0f, 1.0f ) );
light.setIntensity( 1.0f );
lights.add( light );
getScene().addChild( light );
}
Camera cam;
if( getCamera() == null ) {
cam = new DetachedHeadCamera();
this.camera = cam;
getScene().addChild( cam );
} else {
cam = getCamera();
}
cam.setPosition( new GLVector( 0.0f, 5.0f, 5.0f ) );
cam.perspectiveCamera( 50.0f, getWindowWidth(), getWindowHeight(), 0.1f, 1000.0f );
cam.setActive( true );
floor = new Box( new GLVector( 500f, 0.2f, 500f ) );
floor.setName( "Floor" );
floor.setPosition( new GLVector( 0f, -1f, 0f ) );
floor.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
getScene().addChild( floor );
}
/*
* Initialization of SWING and scenery. Also triggers an initial population of lights/camera in the scene
*/
@SuppressWarnings("restriction") @Override public void init() {
if(Boolean.parseBoolean(System.getProperty("sciview.useDarcula", "false"))) {
try {
BasicLookAndFeel darcula = new DarculaLaf();
UIManager.setLookAndFeel(darcula);
} catch (Exception e) {
getLogger().info("Could not load Darcula Look and Feel");
}
}
log.setLevel(LogLevel.WARN);
LogbackUtils.setLogLevel(null, System.getProperty("scenery.LogLevel", "info"));
// determine imagej-launcher version and to disable Vulkan if XInitThreads() fix
// is not deployed
try {
final Class<?> launcherClass = Class.forName("net.imagej.launcher.ClassLauncher");
String versionString = VersionUtils.getVersion(launcherClass);
if (versionString != null && ExtractsNatives.Companion.getPlatform() == ExtractsNatives.Platform.LINUX) {
versionString = versionString.substring(0, 5);
final Version launcherVersion = new Version(versionString);
final Version nonWorkingVersion = new Version("4.0.5");
if (launcherVersion.compareTo(nonWorkingVersion) <= 0
&& !Boolean.parseBoolean(System.getProperty("sciview.DisableLauncherVersionCheck", "false"))) {
getLogger().info("imagej-launcher version smaller or equal to non-working version (" + versionString + " vs. 4.0.5), disabling Vulkan as rendering backend. Disable check by setting 'scenery.DisableLauncherVersionCheck' system property to 'true'.");
System.setProperty("scenery.Renderer", "OpenGLRenderer");
} else {
getLogger().info("imagej-launcher version bigger that non-working version (" + versionString + " vs. 4.0.5), all good.");
}
}
} catch (ClassNotFoundException cnfe) {
// Didn't find the launcher, so we're probably good.
getLogger().info("imagej-launcher not found, not touching renderer preferences.");
}
int x, y;
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = screenSize.width/2 - getWindowWidth()/2;
y = screenSize.height/2 - getWindowHeight()/2;
} catch(HeadlessException e) {
x = 10;
y = 10;
}
frame = new JFrame("SciView");
frame.setLayout(new BorderLayout(0, 0));
frame.setSize(getWindowWidth(), getWindowHeight());
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nodePropertyEditor = new NodePropertyEditor( this );
final JPanel p = new JPanel(new BorderLayout(0, 0));
panel = new SceneryJPanel();
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
final JMenuBar swingMenuBar = new JMenuBar();
new SwingJMenuBarCreator().createMenus(menus.getMenu("SciView"), swingMenuBar);
frame.setJMenuBar(swingMenuBar);
// frame.addComponentListener(new ComponentAdapter() {
// @Override
// public void componentResized(ComponentEvent componentEvent) {
// super.componentResized(componentEvent);
// panel.setSize(componentEvent.getComponent().getWidth(), componentEvent.getComponent().getHeight());
BufferedImage splashImage;
try {
splashImage = ImageIO.read(this.getClass().getResourceAsStream("sciview-logo.png"));
} catch (IOException e) {
getLogger().warn("Could not read splash image 'sciview-logo.png'");
splashImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
}
final String sceneryVersion = SceneryBase.class.getPackage().getImplementationVersion();
final String sciviewVersion = SciView.class.getPackage().getImplementationVersion();
final String versionString;
if(sceneryVersion == null || sciviewVersion == null) {
versionString = "";
} else {
versionString = "\n\nsciview " + sciviewVersion + " / scenery " + sceneryVersion;
}
splashLabel = new JLabel(versionString,
new ImageIcon(splashImage.getScaledInstance(500, 200, java.awt.Image.SCALE_SMOOTH)),
SwingConstants.CENTER);
splashLabel.setBackground(new java.awt.Color(50, 48, 47));
splashLabel.setForeground(new java.awt.Color(78, 76, 75));
splashLabel.setOpaque(true);
splashLabel.setVerticalTextPosition(JLabel.BOTTOM);
splashLabel.setHorizontalTextPosition(JLabel.CENTER);
p.setLayout(new OverlayLayout(p));
p.setBackground(new java.awt.Color(50, 48, 47));
p.add(panel, BorderLayout.CENTER);
panel.setVisible(true);
nodePropertyEditor.getComponent(); // Initialize node property panel
JTree inspectorTree = nodePropertyEditor.getTree();
inspectorTree.setToggleClickCount(0);// This disables expanding menus on double click
JPanel inspectorProperties = nodePropertyEditor.getProps();
inspector = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane( inspectorTree ),
new JScrollPane( inspectorProperties ));
inspector.setDividerLocation( getWindowHeight() / 3 );
inspector.setContinuousLayout(true);
inspector.setBorder(BorderFactory.createEmptyBorder());
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
p,
inspector
);
mainSplitPane.setDividerLocation( getWindowWidth()/3 * 2 );
mainSplitPane.setBorder(BorderFactory.createEmptyBorder());
frame.add(mainSplitPane, BorderLayout.CENTER);
SciView sciView = this;
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
getLogger().debug("Closing SciView window.");
close();
getScijavaContext().service(SciViewService.class).close(sciView);
isClosed = true;
}
});
frame.setGlassPane(splashLabel);
frame.getGlassPane().setVisible(true);
// frame.getGlassPane().setBackground(new java.awt.Color(50, 48, 47, 255));
frame.setVisible(true);
sceneryPanel[0] = panel;
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0]) );
// Enable push rendering by default
getRenderer().setPushMode( true );
getHub().add( SceneryElement.Renderer, getRenderer() );
reset();
animations = new LinkedList<>();
controlStack = new Stack<>();
SwingUtilities.invokeLater(() -> {
try {
while (!getSceneryRenderer().getFirstImageReady()) {
getLogger().debug("Waiting for renderer initialisation");
Thread.sleep(300);
}
Thread.sleep(200);
} catch (InterruptedException e) {
getLogger().error("Renderer construction interrupted.");
}
nodePropertyEditor.rebuildTree();
frame.getGlassPane().setVisible(false);
getLogger().info("Done initializing SciView");
// subscribe to Node{Added, Removed, Changed} events
eventService.subscribe(this);
});
// install hook to keep inspector updated on external changes (scripting, etc)
getScene().getOnNodePropertiesChanged().put("updateInspector",
node -> {
if( node == nodePropertyEditor.getCurrentNode() ) {
nodePropertyEditor.updateProperties(node);
}
return null;
});
}
/*
* Completely close the SciView window + cleanup
*/
public void closeWindow() {
frame.dispose();
}
/*
* Return the default floor object
*/
public Node getFloor() {
return floor;
}
/*
* Set the default floor object
*/
public void setFloor( Node n ) {
floor = n;
}
/*
* Return true if the scene has been initialized
*/
public boolean isInitialized() {
return sceneInitialized();
}
/*
* Return the current camera that is rendering the scene
*/
public Camera getCamera() {
return camera;
}
/*
* Return the SciJava Display that contains SciView
*/
public Display<?> getDisplay() {
return scijavaDisplay;
}
/*
* Set the SciJava Display
*/
public void setDisplay( Display<?> display ) {
scijavaDisplay = display;
}
/*
* Center the camera on the scene such that all objects are within the field of view
*/
public void centerOnScene() {
centerOnNode(getScene());
}
/*
* Get the InputHandler that is managing mouse, input, VR controls, etc.
*/
public InputHandler getSceneryInputHandler() {
return getInputHandler();
}
/*
* Return a bounding box around a subgraph of the scenegraph
*/
public OrientedBoundingBox getSubgraphBoundingBox( Node n ) {
Function<Node,List<Node>> predicate = node -> node.getChildren();
return getSubgraphBoundingBox(n,predicate);
}
/*
* Return a bounding box around a subgraph of the scenegraph
*/
public OrientedBoundingBox getSubgraphBoundingBox( Node n, Function<Node,List<Node>> branchFunction ) {
if(n.getBoundingBox() == null && n.getChildren().size() == 0) {
return n.getMaximumBoundingBox().asWorld();
}
List<Node> branches = branchFunction.apply(n);
if( branches.size() == 0 ) {
if( n.getBoundingBox() == null )
return null;
else
return n.getBoundingBox().asWorld();
}
OrientedBoundingBox bb = n.getMaximumBoundingBox();
for( Node c : branches ){
OrientedBoundingBox cBB = getSubgraphBoundingBox(c, branchFunction);
if( cBB != null )
bb = bb.expand(bb, cBB);
}
return bb;
}
/*
* Center the camera on the specified Node
*/
public void centerOnNode( Node currentNode ) {
centerOnNode(currentNode,notAbstractBranchingFunction);
}
/*
* Center the camera on the specified Node
*/
public void centerOnNode( Node currentNode, Function<Node,List<Node>> branchFunction ) {
if( currentNode == null ) return;
OrientedBoundingBox bb = getSubgraphBoundingBox(currentNode, branchFunction);
//log.debug("Centering on: " + currentNode + " bb: " + bb.getMin() + " to " + bb.getMax());
if( bb == null ) return;
getCamera().setTarget( bb.getBoundingSphere().getOrigin() );
getCamera().setTargeted( true );
// Set forward direction to point from camera at active node
GLVector forward = bb.getBoundingSphere().getOrigin().minus( getCamera().getPosition() ).normalize().times( -1 );
float distance = (float) (bb.getBoundingSphere().getRadius() / Math.tan( getCamera().getFov() / 360 * java.lang.Math.PI ));
// Solve for the proper rotation
Quaternion rotation = new Quaternion().setLookAt( forward.toFloatArray(),
new GLVector(0,1,0).toFloatArray(),
new GLVector(1,0,0).toFloatArray(),
new GLVector( 0,1,0).toFloatArray(),
new GLVector( 0, 0, 1).toFloatArray() );
getCamera().setRotation( rotation.invert().normalize() );
getCamera().setPosition( bb.getBoundingSphere().getOrigin().plus( getCamera().getForward().times( distance * -1 ) ) );
getCamera().setDirty(true);
getCamera().setNeedsUpdate(true);
}
public float getFPSSpeed() {
return fpsScrollSpeed;
}
public void setFPSSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 30.0f ) newspeed = 30.0f;
fpsScrollSpeed = newspeed;
//log.debug( "FPS scroll speed: " + fpsScrollSpeed );
}
public float getMouseSpeed() {
return mouseSpeedMult;
}
public void setMouseSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 3.0f ) newspeed = 3.0f;
mouseSpeedMult = newspeed;
//log.debug( "Mouse speed: " + mouseSpeedMult );
}
/*
* Reset the input handler to first-person-shooter (FPS) style controls
*/
public void resetFPSInputs() {
InputHandler h = getInputHandler();
if(h == null) {
getLogger().error("InputHandler is null, cannot change bindings.");
return;
}
h.addBehaviour( "move_forward_scroll",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_forward",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_back",
new MovementCommand( "move_back", "back", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_left",
new MovementCommand( "move_left", "left", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_right",
new MovementCommand( "move_right", "right", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_up",
new MovementCommand( "move_up", "up", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addBehaviour( "move_down",
new MovementCommand( "move_down", "down", () -> getScene().findObserver(),
getFPSSpeed() ) );
h.addKeyBinding( "move_forward_scroll", "scroll" );
}
public void setObjectSelectionMode() {
Function1<? super List<Scene.RaycastResult>, Unit> selectAction = nearest -> {
if( !nearest.isEmpty() ) {
setActiveNode( nearest.get( 0 ).getNode() );
nodePropertyEditor.trySelectNode( getActiveNode() );
log.debug( "Selected node: " + getActiveNode().getName() );
}
return Unit.INSTANCE;
};
setObjectSelectionMode(selectAction);
}
/*
* Set the action used during object selection
*/
public void setObjectSelectionMode(Function1<? super List<Scene.RaycastResult>, Unit> selectAction) {
final InputHandler h = getInputHandler();
List<Class<?>> ignoredObjects = new ArrayList<>();
ignoredObjects.add( BoundingGrid.class );
if(h == null) {
getLogger().error("InputHandler is null, cannot change object selection mode.");
return;
}
h.addBehaviour( "object_selection_mode",
new SelectCommand( "objectSelector", getRenderer(), getScene(),
() -> getScene().findObserver(), false, ignoredObjects,
selectAction ) );
h.addKeyBinding( "object_selection_mode", "double-click button1" );
}
/*
* Initial configuration of the scenery InputHandler
* This is automatically called and should not be used directly
*/
@Override public void inputSetup() {
final InputHandler h = getInputHandler();
if(h == null) {
getLogger().error("InputHandler is null, cannot run input setup.");
return;
}
// TODO: Maybe get rid of this?
h.useDefaultBindings( "" );
// Mouse controls
setObjectSelectionMode();
NodeTranslateControl nodeTranslate = new NodeTranslateControl(this, 0.0005f);
h.addBehaviour( "mouse_control_nodetranslate", nodeTranslate );
h.addKeyBinding( "mouse_control_nodetranslate", "ctrl button1" );
h.addBehaviour( "scroll_nodetranslate", nodeTranslate );
h.addKeyBinding( "scroll_nodetranslate", "ctrl scroll" );
h.addBehaviour("move_up_slow", new MovementCommand("move_up", "up", () -> getScene().findObserver(), fpsScrollSpeed ) );
h.addBehaviour("move_down_slow", new MovementCommand("move_down", "down", () -> getScene().findObserver(), fpsScrollSpeed ) );
h.addBehaviour("move_up_fast", new MovementCommand("move_up", "up", () -> getScene().findObserver(), 1.0f ) );
h.addBehaviour("move_down_fast", new MovementCommand("move_down", "down", () -> getScene().findObserver(), 1.0f ) );
h.addKeyBinding("move_up_slow", "X");
h.addKeyBinding("move_down_slow", "C");
h.addKeyBinding("move_up_fast", "shift X");
h.addKeyBinding("move_down_fast", "shift C");
enableArcBallControl();
enableFPSControl();
// Extra keyboard controls
h.addBehaviour( "show_help", new showHelpDisplay() );
h.addKeyBinding( "show_help", "U" );
h.addBehaviour( "enable_decrease", new enableDecrease() );
h.addKeyBinding( "enable_decrease", "M" );
h.addBehaviour( "enable_increase", new enableIncrease() );
h.addKeyBinding( "enable_increase", "N" );
//float veryFastSpeed = getScene().getMaximumBoundingBox().getBoundingSphere().getRadius()/50f;
float veryFastSpeed = 100f;
h.addBehaviour("move_forward_veryfast", new MovementCommand("move_forward", "forward", () -> getScene().findObserver(), veryFastSpeed));
h.addBehaviour("move_back_veryfast", new MovementCommand("move_back", "back", () -> getScene().findObserver(), veryFastSpeed));
h.addBehaviour("move_left_veryfast", new MovementCommand("move_left", "left", () -> getScene().findObserver(), veryFastSpeed));
h.addBehaviour("move_right_veryfast", new MovementCommand("move_right", "right", () -> getScene().findObserver(), veryFastSpeed));
h.addBehaviour("move_up_veryfast", new MovementCommand("move_up", "up", () -> getScene().findObserver(), veryFastSpeed));
h.addBehaviour("move_down_veryfast", new MovementCommand("move_down", "down", () -> getScene().findObserver(), veryFastSpeed));
h.addKeyBinding("move_forward_veryfast", "ctrl shift W");
h.addKeyBinding("move_back_veryfast", "ctrl shift S");
h.addKeyBinding("move_left_veryfast", "ctrl shift A");
h.addKeyBinding("move_right_veryfast", "ctrl shift D");
h.addKeyBinding("move_up_veryfast", "ctrl shift X");
h.addKeyBinding("move_down_veryfast", "ctrl shift C");
}
/*
* Change the control mode to circle around the active object in an arcball
*/
private void enableArcBallControl() {
final InputHandler h = getInputHandler();
if(h == null) {
getLogger().error("InputHandler is null, cannot setup arcball.");
return;
}
GLVector target;
if( getActiveNode() == null ) {
target = new GLVector( 0, 0, 0 );
} else {
target = getActiveNode().getPosition();
}
float mouseSpeed = 0.25f;
mouseSpeed = getMouseSpeed();
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
targetArcball = new ArcballCameraControl( "mouse_control_arcball", cameraSupplier,
getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight(), target );
targetArcball.setMaximumDistance( Float.MAX_VALUE );
targetArcball.setMouseSpeedMultiplier( mouseSpeed );
targetArcball.setScrollSpeedMultiplier( 0.05f );
targetArcball.setDistance( getCamera().getPosition().minus( target ).magnitude() );
// FIXME: Swing seems to have issues with shift-scroll actions, so we change
// this to alt-scroll here for the moment.
h.addBehaviour( "mouse_control_arcball", targetArcball );
h.addKeyBinding( "mouse_control_arcball", "shift button1" );
h.addBehaviour( "scroll_arcball", targetArcball );
h.addKeyBinding( "scroll_arcball", "shift scroll" );
}
/*
* Enable FPS style controls
*/
private void enableFPSControl() {
final InputHandler h = getInputHandler();
if(h == null) {
getLogger().error("InputHandler is null, cannot setup fps control.");
return;
}
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
fpsControl = new FPSCameraControl( "mouse_control", cameraSupplier, getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight() );
h.addBehaviour( "mouse_control", fpsControl );
h.addKeyBinding( "mouse_control", "button1" );
h.addBehaviour( "mouse_control_cameratranslate", new CameraTranslateControl( this, 0.002f ) );
h.addKeyBinding( "mouse_control_cameratranslate", "button2" );
resetFPSInputs();
}
public Node addBox() {
return addBox( new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addBox( Vector3 position ) {
return addBox( position, new ClearGLVector3( 1.0f, 1.0f, 1.0f ) );
}
public Node addBox( Vector3 position, Vector3 size ) {
return addBox( position, size, DEFAULT_COLOR, false );
}
public Node addBox( final Vector3 position, final Vector3 size, final ColorRGB color,
final boolean inside ) {
// TODO: use a material from the current palate by default
final Material boxmaterial = new Material();
boxmaterial.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
boxmaterial.setDiffuse( Utils.convertToGLVector( color ) );
boxmaterial.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Box box = new Box( ClearGLVector3.convert( size ), inside );
box.setMaterial( boxmaterial );
box.setPosition( ClearGLVector3.convert( position ) );
return addNode( box );
}
public Node addSphere() {
return addSphere( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), 1 );
}
public Node addSphere( Vector3 position, float radius ) {
return addSphere( position, radius, DEFAULT_COLOR );
}
public Node addSphere( final Vector3 position, final float radius, final ColorRGB color ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( Utils.convertToGLVector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( ClearGLVector3.convert( position ) );
return addNode( sphere );
}
public Node addCylinder( final Vector3 position, final float radius, final float height, final int num_segments ) {
final Cylinder cyl = new Cylinder( radius, height, num_segments );
cyl.setPosition( ClearGLVector3.convert( position ) );
return addNode( cyl );
}
public Node addCone( final Vector3 position, final float radius, final float height, final int num_segments ) {
final Cone cone = new Cone( radius, height, num_segments, new GLVector(0,0,1) );
cone.setPosition( ClearGLVector3.convert( position ) );
return addNode( cone );
}
public Node addLine() {
return addLine( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addLine( Vector3 start, Vector3 stop ) {
return addLine( start, stop, DEFAULT_COLOR );
}
public Node addLine( Vector3 start, Vector3 stop, ColorRGB color ) {
return addLine( new Vector3[] { start, stop }, color, 0.1f );
}
public Node addLine( final Vector3[] points, final ColorRGB color, final double edgeWidth ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( Utils.convertToGLVector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Line line = new Line( points.length );
for( final Vector3 pt : points ) {
line.addPoint( ClearGLVector3.convert( pt ) );
}
line.setEdgeWidth( ( float ) edgeWidth );
line.setMaterial( material );
line.setPosition( ClearGLVector3.convert( points[0] ) );
return addNode( line );
}
public Node addPointLight() {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final PointLight light = new PointLight( 5.0f );
light.setMaterial( material );
light.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
lights.add(light);
return addNode( light );
}
public void surroundLighting() {
OrientedBoundingBox bb = getSubgraphBoundingBox(getScene(), notAbstractBranchingFunction);
OrientedBoundingBox.BoundingSphere boundingSphere = bb.getBoundingSphere();
// Choose a good y-position, then place lights around the cross-section through this plane
float y = 0;
GLVector c = boundingSphere.getOrigin();
float r = boundingSphere.getRadius();
for( int k = 0; k < lights.size(); k++ ) {
PointLight light = lights.get(k);
float x = (float) (c.x() + r * Math.cos( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.size()) ));
float z = (float) (c.y() + r * Math.sin( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.size()) ));
light.setLightRadius( 2 * r );
light.setPosition( new GLVector( x, y, z ) );
}
}
public void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ( "facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() +
"\n" ).getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() +
"\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch( FileNotFoundException e ) {
e.printStackTrace();
} catch( IOException e ) {
e.printStackTrace();
}
}
public float getDefaultPointSize() {
return 0.025f;
}
/*
* Create an array of normal vectors from a set of vertices corresponding to triangles
*/
public float[] makeNormalsFromVertices( ArrayList<RealPoint> verts ) {
float[] normals = new float[verts.size()];// div3 * 3coords
for( int k = 0; k < verts.size(); k += 3 ) {
GLVector v1 = new GLVector( verts.get( k ).getFloatPosition( 0 ),
verts.get( k ).getFloatPosition( 1 ),
verts.get( k ).getFloatPosition( 2 ) );
GLVector v2 = new GLVector( verts.get( k + 1 ).getFloatPosition( 0 ),
verts.get( k + 1 ).getFloatPosition( 1 ),
verts.get( k + 1 ).getFloatPosition( 2 ) );
GLVector v3 = new GLVector( verts.get( k + 2 ).getFloatPosition( 0 ),
verts.get( k + 2 ).getFloatPosition( 1 ),
verts.get( k + 2 ).getFloatPosition( 2 ) );
GLVector a = v2.minus( v1 );
GLVector b = v3.minus( v1 );
GLVector n = a.cross( b ).getNormalized();
normals[k / 3] = n.get( 0 );
normals[k / 3 + 1] = n.get( 1 );
normals[k / 3 + 2] = n.get( 2 );
}
return normals;
}
public void open( final String source ) throws IOException {
if(source.endsWith(".xml")) {
addBDVVolume(source);
return;
}
final Object data = io.open( source );
if( data instanceof net.imagej.mesh.Mesh ) addMesh( ( net.imagej.mesh.Mesh ) data );
else if( data instanceof graphics.scenery.Mesh ) addMesh( ( graphics.scenery.Mesh ) data );
else if( data instanceof graphics.scenery.PointCloud ) addPointCloud( ( graphics.scenery.PointCloud ) data );
else if( data instanceof Dataset ) addVolume( ( Dataset ) data );
else if( data instanceof IterableInterval ) addVolume( ( ( IterableInterval ) data ), source );
else if( data instanceof List ) {
final List<?> list = ( List<?> ) data;
if( list.isEmpty() ) {
throw new IllegalArgumentException( "Data source '" + source + "' appears empty." );
}
final Object element = list.get( 0 );
if( element instanceof RealLocalizable ) {
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
@SuppressWarnings("unchecked") final List<? extends RealLocalizable> points = ( List<? extends RealLocalizable> ) list;
addPointCloud( points, source );
} else {
final String type = element == null ? "<null>" : element.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source +
"' contains elements of unknown type '" + type + "'" );
}
} else {
final String type = data == null ? "<null>" : data.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source +
"' contains data of unknown type '" + type + "'" );
}
}
public Node addPointCloud( Collection<? extends RealLocalizable> points ) {
return addPointCloud( points, "PointCloud" );
}
public Node addPointCloud( final Collection<? extends RealLocalizable> points,
final String name ) {
final float[] flatVerts = new float[points.size() * 3];
int k = 0;
for( final RealLocalizable point : points ) {
flatVerts[k * 3] = point.getFloatPosition( 0 );
flatVerts[k * 3 + 1] = point.getFloatPosition( 1 );
flatVerts[k * 3 + 2] = point.getFloatPosition( 2 );
k++;
}
final PointCloud pointCloud = new PointCloud( getDefaultPointSize(), name );
final Material material = new Material();
final FloatBuffer vBuffer = BufferUtils.allocateFloat( flatVerts.length * 4 );
final FloatBuffer nBuffer = BufferUtils.allocateFloat( 0 );
vBuffer.put( flatVerts );
vBuffer.flip();
pointCloud.setVertices( vBuffer );
pointCloud.setNormals( nBuffer );
pointCloud.setIndices( BufferUtils.allocateInt( 0 ) );
pointCloud.setupPointCloud();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setMaterial( material );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addPointCloud( final PointCloud pointCloud ) {
pointCloud.setupPointCloud();
pointCloud.getMaterial().setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addNode( final Node n ) {
return addNode(n, true);
}
public Node addNode( final Node n, final boolean activePublish ) {
getScene().addChild( n );
if( activePublish ) {
// setActiveNode(n);
// if (floor.getVisible())
// updateFloorPosition();
eventService.publish(new NodeAddedEvent(n));
}
return n;
}
public Node addMesh( final Mesh scMesh ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
scMesh.setMaterial( material );
scMesh.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
objectService.addObject(scMesh);
return addNode( scMesh );
}
public Node addMesh( net.imagej.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.toScenery( mesh );
return addMesh( scMesh );
}
public void removeMesh( Mesh scMesh ) {
getScene().removeChild( scMesh );
}
public Node getActiveNode() {
return activeNode;
}
public Node setActiveNode( Node n ) {
if( activeNode == n ) return activeNode;
activeNode = n;
targetArcball.setTarget( n == null ? () -> new GLVector( 0, 0, 0 ) : () -> n.getMaximumBoundingBox().getBoundingSphere().getOrigin());
eventService.publish( new NodeActivatedEvent( activeNode ) );
return activeNode;
}
@EventHandler
protected void onNodeAdded(NodeAddedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeRemoved(NodeRemovedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeChanged(NodeChangedEvent event) {
nodePropertyEditor.rebuildTree();
}
@EventHandler
protected void onNodeActivated(NodeActivatedEvent event) {
// TODO: add listener code for node activation, if necessary
// NOTE: do not update property window here, this will lead to a loop.
}
public void toggleInspectorWindow()
{
boolean currentlyVisible = inspector.isVisible();
if(currentlyVisible) {
inspector.setVisible(false);
mainSplitPane.setDividerLocation(getWindowWidth());
}
else {
inspector.setVisible(true);
mainSplitPane.setDividerLocation(getWindowWidth()/4 * 3);
}
}
public synchronized Future<?> animate(int fps, Runnable action ) {
// TODO: Make animation speed less laggy and more accurate.
final int delay = 1000 / fps;
Future<?> thread = threadService.run(() -> {
while (animating) {
action.run();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
}
});
animations.add( thread );
animating = true;
return thread;
}
public synchronized void stopAnimation() {
animating = false;
while( !animations.isEmpty() ) {
animations.peek().cancel( true );
animations.remove();
}
}
public void takeScreenshot() {
getRenderer().screenshot();
}
public void takeScreenshot( String path ) {
getRenderer().screenshot( path, false );
}
public Img<UnsignedByteType> getScreenshot() {
RenderedImage screenshot = getSceneryRenderer().requestScreenshot();
BufferedImage image = new BufferedImage(screenshot.getWidth(), screenshot.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
byte[] imgData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(screenshot.getData(), 0, imgData, 0, screenshot.getData().length);
Img<UnsignedByteType> img = null;
File tmpFile = null;
try {
tmpFile = File.createTempFile("sciview-", "-tmp.png");
ImageIO.write(image, "png", tmpFile);
img = (Img<UnsignedByteType>)io.open(tmpFile.getAbsolutePath());
tmpFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
public Node[] getSceneNodes() {
return getSceneNodes( n -> !( n instanceof Camera ) && !( n instanceof PointLight ) );
}
public Node[] getSceneNodes( Predicate<? super Node> filter ) {
return getScene().getChildren().stream().filter( filter ).toArray( Node[]::new );
}
public Node[] getAllSceneNodes() {
return getSceneNodes( n -> true );
}
public void deleteActiveNode() {
deleteNode( getActiveNode() );
}
public void deleteNode( Node node ) {
deleteNode( node, true );
}
public void deleteNode( Node node, boolean activePublish ) {
for( Node child : node.getChildren() ) {
deleteNode(child, activePublish);
}
node.getParent().removeChild( node );
if( activePublish ) {
eventService.publish(new NodeRemovedEvent(node));
if (activeNode == node) setActiveNode(null);
}
}
public void dispose() {
// Close the Scenery renderer, hub, and other scenery things
this.close();
}
public void moveCamera( float[] position ) {
getCamera().setPosition( new GLVector( position[0], position[1], position[2] ) );
}
public void moveCamera( double[] position ) {
getCamera().setPosition( new GLVector( ( float ) position[0], ( float ) position[1], ( float ) position[2] ) );
}
public String getName() {
return getApplicationName();
}
public void addChild( Node node ) {
getScene().addChild( node );
}
public Node addVolume( Dataset image ) {
float[] voxelDims = new float[image.numDimensions()];
for( int d = 0; d < voxelDims.length; d++ ) {
voxelDims[d] = ( float ) image.axis( d ).averageScale( 0, 1 );
}
return addVolume( image, voxelDims );
}
public Node addBDVVolume( String source ) {
//getSettings().set("Renderer.HDR.Exposure", 20.0f);
final VolumeViewerOptions opts = new VolumeViewerOptions();
opts.maxCacheSizeInMB(Integer.parseInt(System.getProperty("scenery.BDVVolume.maxCacheSize", "512")));
final BDVVolume v = new BDVVolume(source, opts);
v.setScale(new GLVector(0.01f, 0.01f, 0.01f));
v.setBoundingBox(v.generateBoundingBox());
getScene().addChild(v);
setActiveNode(v);
v.goToTimePoint(0);
eventService.publish( new NodeAddedEvent( v ) );
return v;
}
@SuppressWarnings({ "rawtypes", "unchecked" }) public Node addVolume( Dataset image,
float[] voxelDimensions ) {
return addVolume( ( IterableInterval ) Views.flatIterable( image.getImgPlus() ), image.getName(),
voxelDimensions );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image ) {
return addVolume( image, "Volume" );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name ) {
return addVolume( image, name, 1, 1, 1 );
}
public void setColormap( Node n, ColorTable colorTable ) {
final int copies = 16;
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
4 * colorTable.getLength() * copies );// Num bytes * num components * color map length * height of color map texture
final byte[] tmp = new byte[4 * colorTable.getLength()];
for( int k = 0; k < colorTable.getLength(); k++ ) {
for( int c = 0; c < colorTable.getComponentCount(); c++ ) {
// TODO this assumes numBits is 8, could be 16
tmp[4 * k + c] = ( byte ) colorTable.get( c, k );
}
if( colorTable.getComponentCount() == 3 ) {
tmp[4 * k + 3] = (byte)255;
}
}
for( int i = 0; i < copies; i++ ) {
byteBuffer.put(tmp);
}
byteBuffer.flip();
n.getMetadata().put("sciviewColormap", colorTable);
if(n instanceof Volume) {
((Volume) n).getColormaps().put("sciviewColormap",
new Volume.Colormap.ColormapBuffer(new GenericTexture("colorTable",
new GLVector(colorTable.getLength(), copies, 1.0f), 4,
GLTypeEnum.UnsignedByte,
byteBuffer,
// don't repeat the color map
false, false, false)));
((Volume) n).setColormap("sciviewColormap");
}
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name,
float... voxelDimensions ) {
//log.debug( "Add Volume" );
long[] dimensions = new long[3];
image.dimensions( dimensions );
Volume v = new Volume();
getScene().addChild( v );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
float minVal, maxVal;
if( voxelType == UnsignedByteType.class ) {
minVal = 0;
maxVal = 255;
} else if( voxelType == UnsignedShortType.class ) {
minVal = 0;
maxVal = 65535;
} else if( voxelType == FloatType.class ) {
minVal = 0;
maxVal = 1;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
updateVolume( image, name, voxelDimensions, v );
v.setTrangemin( minVal );
v.setTrangemax( maxVal );
v.setTransferFunction(TransferFunction.ramp(0.0f, 0.4f));
try {
setColormap( v, lutService.loadLUT( lutService.findLUTs().get( "WCIF/ICA.lut" ) ) );
} catch( IOException e ) {
e.printStackTrace();
}
setActiveNode( v );
eventService.publish( new NodeAddedEvent( v ) );
return v;
}
public <T extends RealType<T>> Node updateVolume( IterableInterval<T> image, String name,
float[] voxelDimensions, Volume v ) {
//log.debug( "Update Volume" );
long[] dimensions = new long[3];
image.dimensions( dimensions );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
int bytesPerVoxel = image.firstElement().getBitsPerPixel() / 8;
NativeTypeEnum nType;
if( voxelType == UnsignedByteType.class ) {
nType = NativeTypeEnum.UnsignedByte;
} else if( voxelType == UnsignedShortType.class ) {
nType = NativeTypeEnum.UnsignedShort;
} else if( voxelType == FloatType.class ) {
nType = NativeTypeEnum.Float;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
// Make and populate a ByteBuffer with the content of the Dataset
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
( int ) ( bytesPerVoxel * dimensions[0] * dimensions[1] * dimensions[2] ) );
Cursor<T> cursor = image.cursor();
while( cursor.hasNext() ) {
cursor.fwd();
if( voxelType == UnsignedByteType.class ) {
byteBuffer.put( ( byte ) ( ( ( UnsignedByteType ) cursor.get() ).get() ) );
} else if( voxelType == UnsignedShortType.class ) {
byteBuffer.putShort( ( short ) Math.abs( ( ( UnsignedShortType ) cursor.get() ).getShort() ) );
} else if( voxelType == FloatType.class ) {
byteBuffer.putFloat( ( ( FloatType ) cursor.get() ).get() );
}
}
byteBuffer.flip();
v.readFromBuffer( name, byteBuffer, dimensions[0], dimensions[1], dimensions[2], voxelDimensions[0],
voxelDimensions[1], voxelDimensions[2], nType, bytesPerVoxel );
v.setDirty( true );
v.setNeedsUpdate( true );
v.setNeedsUpdateWorld( true );
return v;
}
public boolean getPushMode() {
return getRenderer().getPushMode();
}
public boolean setPushMode( boolean push ) {
getRenderer().setPushMode( push );
return getRenderer().getPushMode();
}
public ArcballCameraControl getTargetArcball() {
return targetArcball;
}
@Override
protected void finalize() {
stopAnimation();
}
public Settings getScenerySettings() {
return this.getSettings();
}
public Statistics getSceneryStats() {
return this.getStats();
}
public Renderer getSceneryRenderer() {
return this.getRenderer();
}
public void toggleVRRendering() {
vrActive = !vrActive;
Camera cam = getScene().getActiveObserver();
if(!(cam instanceof DetachedHeadCamera)) {
return;
}
TrackerInput ti = null;
boolean hmdAdded = false;
if (!getHub().has(SceneryElement.HMDInput)) {
try {
final OpenVRHMD hmd = new OpenVRHMD(false, true);
if(hmd.initializedAndWorking()) {
getHub().add(SceneryElement.HMDInput, hmd);
ti = hmd;
} else {
getLogger().warn("Could not initialise VR headset, just activating stereo rendering.");
}
hmdAdded = true;
} catch (Exception e) {
getLogger().error("Could not add OpenVRHMD: " + e.toString());
}
} else {
ti = getHub().getWorkingHMD();
}
if(vrActive && ti != null) {
((DetachedHeadCamera) cam).setTracker(ti);
} else {
((DetachedHeadCamera) cam).setTracker(null);
}
getRenderer().setPushMode(false);
// we need to force reloading the renderer as the HMD might require device or instance extensions
if(getRenderer() instanceof VulkanRenderer && hmdAdded) {
replaceRenderer(getRenderer().getClass().getSimpleName(), true, true);
getRenderer().toggleVR();
while(!getRenderer().getInitialized() || !getRenderer().getFirstImageReady()) {
getLogger().debug("Waiting for renderer reinitialisation");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
getRenderer().toggleVR();
}
}
public void setPosition(Node n, float x, float y, float z) {
n.setPosition(new GLVector(x,y,z));
}
public void addWindowListener(WindowListener wl) {
frame.addWindowListener(wl);
}
public class TransparentSlider extends JSlider {
public TransparentSlider() {
// Important, we taking over the filling of the
// component...
setOpaque(false);
setBackground(java.awt.Color.DARK_GRAY);
setForeground(java.awt.Color.LIGHT_GRAY);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.9f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
class enableIncrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() + 0.5f );
setMouseSpeed( getMouseSpeed() + 0.05f );
//log.debug( "Increasing FPS scroll Speed" );
resetFPSInputs();
}
}
class enableDecrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() - 0.1f );
setMouseSpeed( getMouseSpeed() - 0.05f );
//log.debug( "Decreasing FPS scroll Speed" );
resetFPSInputs();
}
}
class showHelpDisplay implements ClickBehaviour {
@Override public void click( int x, int y ) {
String helpString = "SciView help:\n\n";
for( InputTrigger trigger : getInputHandler().getAllBindings().keySet() ) {
helpString += trigger + "\t-\t" + getInputHandler().getAllBindings().get( trigger ) + "\n";
}
// HACK: Make the console pop via stderr.
// Later, we will use a nicer dialog box or some such.
log.warn( helpString );
}
}
public String nodeInfoString(Node n) {
return "Node name: " + n.getName() + " Node type: " + n.getNodeType() + " To String: " + n;
}
}
|
package org.bimserver;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.bimserver.cache.ClashDetectionCache;
import org.bimserver.cache.CompareCache;
import org.bimserver.cache.DiskCacheManager;
import org.bimserver.database.BimDatabase;
import org.bimserver.database.BimDatabaseException;
import org.bimserver.database.BimDatabaseSession;
import org.bimserver.database.BimDeadlockException;
import org.bimserver.database.Database;
import org.bimserver.database.DatabaseRestartRequiredException;
import org.bimserver.database.berkeley.BerkeleyColumnDatabase;
import org.bimserver.database.berkeley.DatabaseInitException;
import org.bimserver.database.migrations.InconsistentModelsException;
import org.bimserver.database.query.conditions.AttributeCondition;
import org.bimserver.database.query.conditions.Condition;
import org.bimserver.database.query.literals.StringLiteral;
import org.bimserver.deserializers.EmfDeserializerFactory;
import org.bimserver.interfaces.objects.SVersion;
import org.bimserver.logging.CustomFileAppender;
import org.bimserver.longaction.LongActionManager;
import org.bimserver.mail.MailSystem;
import org.bimserver.models.ifc2x3.Ifc2x3Package;
import org.bimserver.models.log.AccessMethod;
import org.bimserver.models.log.LogFactory;
import org.bimserver.models.log.ServerStarted;
import org.bimserver.models.store.Deserializer;
import org.bimserver.models.store.IfcEngine;
import org.bimserver.models.store.ObjectIDM;
import org.bimserver.models.store.Serializer;
import org.bimserver.models.store.ServerInfo;
import org.bimserver.models.store.ServerState;
import org.bimserver.models.store.StoreFactory;
import org.bimserver.models.store.StorePackage;
import org.bimserver.notifications.NotificationsManager;
import org.bimserver.pb.server.ProtocolBuffersServer;
import org.bimserver.pb.server.ServiceFactoryRegistry;
import org.bimserver.plugins.Plugin;
import org.bimserver.plugins.PluginChangeListener;
import org.bimserver.plugins.PluginContext;
import org.bimserver.plugins.PluginException;
import org.bimserver.plugins.PluginManager;
import org.bimserver.plugins.ResourceFetcher;
import org.bimserver.plugins.deserializers.DeserializerPlugin;
import org.bimserver.plugins.ifcengine.IfcEnginePlugin;
import org.bimserver.plugins.objectidms.ObjectIDMPlugin;
import org.bimserver.plugins.serializers.SerializerPlugin;
import org.bimserver.serializers.EmfSerializerFactory;
import org.bimserver.shared.NotificationInterface;
import org.bimserver.shared.ServiceInterface;
import org.bimserver.shared.exceptions.ServerException;
import org.bimserver.shared.exceptions.ServiceException;
import org.bimserver.shared.meta.SService;
import org.bimserver.shared.pb.ProtocolBuffersMetaData;
import org.bimserver.shared.pb.ReflectiveRpcChannel;
import org.bimserver.templating.TemplateEngine;
import org.bimserver.utils.CollectionUtils;
import org.bimserver.version.VersionChecker;
import org.bimserver.webservices.Service;
import org.bimserver.webservices.ServiceInterfaceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Main class to start a BIMserver
*/
public class BimServer {
private Logger LOGGER;
private GregorianCalendar serverStartTime;
private BimDatabase bimDatabase;
private JobScheduler bimScheduler;
private LongActionManager longActionManager;
private ServiceInterface systemService;
private SettingsManager settingsManager;
private EmfSerializerFactory emfSerializerFactory;
private EmfDeserializerFactory emfDeserializerFactory;
private MergerFactory mergerFactory;
private PluginManager pluginManager;
private MailSystem mailSystem;
private DiskCacheManager diskCacheManager;
private ServerInfoManager serverInfoManager;
private ServiceInterfaceFactory serviceFactory;
private VersionChecker versionChecker;
private TemplateEngine templateEngine;
private ClashDetectionCache clashDetectionCache;
private NotificationsManager notificationsManager;
private CompareCache compareCache;
private ProtocolBuffersMetaData protocolBuffersMetaData;
private SService serviceInterfaceService;
private SService notificationInterfaceService;
private EmbeddedWebServer embeddedWebServer;
private final BimServerConfig config;
private ProtocolBuffersServer protocolBuffersServer;
private CommandLine commandLine;
/**
* Create a new BIMserver
*
* @param homeDir
* A directory where the user can store instance specific
* configuration files
* @param resourceFetcher
* A resource fetcher
*/
public BimServer(BimServerConfig config) {
this.config = config;
try {
if (config.getHomeDir() != null) {
initHomeDir();
}
fixLogging();
LOGGER = LoggerFactory.getLogger(BimServer.class);
LOGGER.info("Starting BIMserver");
if (config.getHomeDir() != null) {
LOGGER.info("Using \"" + config.getHomeDir().getAbsolutePath() + "\" as homedir");
} else {
LOGGER.info("Not using a homedir");
}
serverInfoManager = new ServerInfoManager();
UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof OutOfMemoryError) {
serverInfoManager.setOutOfMemory();
LOGGER.error("", e);
} else if (e instanceof Error) {
serverInfoManager.setErrorMessage(e.getMessage());
LOGGER.error("", e);
}
}
};
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
versionChecker = new VersionChecker(config.getResourceFetcher());
try {
pluginManager = new PluginManager(config.getHomeDir(), config.getClassPath());
pluginManager.addPluginChangeListener(new PluginChangeListener() {
@Override
public void pluginStateChanged(PluginContext pluginContext, boolean enabled) {
// Reflect this change also in the database
Condition pluginCondition = new AttributeCondition(StorePackage.eINSTANCE.getPlugin_Name(), new StringLiteral(pluginContext.getPlugin().getClass()
.getName()));
BimDatabaseSession session = bimDatabase.createSession();
try {
Map<Long, org.bimserver.models.store.Plugin> pluginsFound = session.query(pluginCondition, org.bimserver.models.store.Plugin.class, false, null);
if (pluginsFound.size() == 0) {
LOGGER.error("Error changing plugin-state in database, plugin " + pluginContext.getPlugin().getClass().getName() + " not found");
} else if (pluginsFound.size() == 1) {
org.bimserver.models.store.Plugin pluginFound = pluginsFound.values().iterator().next();
pluginFound.setEnabled(pluginContext.isEnabled());
session.store(pluginFound);
} else {
LOGGER.error("Error, too many plugin-objects found in database for name " + pluginContext.getPlugin().getClass().getName());
}
session.commit();
} catch (BimDatabaseException e) {
LOGGER.error("", e);
} catch (BimDeadlockException e) {
LOGGER.error("", e);
} finally {
session.close();
}
}
});
pluginManager.loadPlugin(ObjectIDMPlugin.class, "Internal", "Internal", new SchemaFieldObjectIDMPlugin());
pluginManager.loadPlugin(ObjectIDMPlugin.class, "Internal", "Internal", new TestObjectIDMPlugin());
} catch (Exception e) {
LOGGER.error("", e);
}
clashDetectionCache = new ClashDetectionCache();
compareCache = new CompareCache();
if (config.isStartEmbeddedWebServer()) {
embeddedWebServer = new EmbeddedWebServer(this);
}
} catch (Throwable e) {
if (LOGGER == null) {
e.printStackTrace();
}
LOGGER.error("", e);
serverInfoManager.setErrorMessage(e.getMessage());
}
}
public void start() throws DatabaseInitException, BimDatabaseException, PluginException, DatabaseRestartRequiredException, ServerException {
try {
SVersion localVersion = versionChecker.getLocalVersion();
if (localVersion != null) {
LOGGER.info("Version: " + localVersion.getMajor() + "." + localVersion.getMinor() + "." + localVersion.getRevision() + " - " + localVersion.getDate());
} else {
LOGGER.info("Unknown version");
}
pluginManager.initAllLoadedPlugins();
serverStartTime = new GregorianCalendar();
longActionManager = new LongActionManager();
Set<Ifc2x3Package> packages = CollectionUtils.singleSet(Ifc2x3Package.eINSTANCE);
templateEngine = new TemplateEngine();
templateEngine.init(config.getResourceFetcher().getResource("templates/"));
File databaseDir = new File(config.getHomeDir(), "database");
BerkeleyColumnDatabase columnDatabase = new BerkeleyColumnDatabase(databaseDir);
bimDatabase = new Database(this, packages, columnDatabase);
try {
bimDatabase.init();
} catch (DatabaseRestartRequiredException e) {
bimDatabase.close();
columnDatabase = new BerkeleyColumnDatabase(databaseDir);
bimDatabase = new Database(this, packages, columnDatabase);
try {
bimDatabase.init();
} catch (InconsistentModelsException e1) {
LOGGER.error("", e);
serverInfoManager.setServerState(ServerState.FATAL_ERROR);
serverInfoManager.setErrorMessage("Inconsistent models");
}
} catch (InconsistentModelsException e) {
LOGGER.error("", e);
serverInfoManager.setServerState(ServerState.FATAL_ERROR);
serverInfoManager.setErrorMessage("Inconsistent models");
}
protocolBuffersMetaData = new ProtocolBuffersMetaData();
try {
protocolBuffersMetaData.load(config.getResourceFetcher().getResource("service.desc"));
protocolBuffersMetaData.load(config.getResourceFetcher().getResource("notification.desc"));
} catch (IOException e) {
LOGGER.error("", e);
}
serviceInterfaceService = new SService(ServiceInterface.class);
notificationInterfaceService = new SService(NotificationInterface.class);
notificationsManager = new NotificationsManager(this);
notificationsManager.start();
settingsManager = new SettingsManager(bimDatabase);
serverInfoManager.init(this);
serverInfoManager.update();
emfSerializerFactory = new EmfSerializerFactory();
emfDeserializerFactory = new EmfDeserializerFactory();
if (serverInfoManager.getServerState() == ServerState.MIGRATION_REQUIRED) {
serverInfoManager.registerStateChangeListener(new StateChangeListener() {
@Override
public void stateChanged(ServerState oldState, ServerState newState) {
if (oldState == ServerState.MIGRATION_REQUIRED && newState == ServerState.RUNNING) {
try {
initDatabaseDependantItems();
} catch (BimDatabaseException e) {
LOGGER.error("", e);
}
}
}
});
} else {
initDatabaseDependantItems();
}
mailSystem = new MailSystem(settingsManager);
serviceFactory = new ServiceInterfaceFactory(this);
if (config.isStartEmbeddedWebServer()) {
embeddedWebServer.start();
}
diskCacheManager = new DiskCacheManager(new File(config.getHomeDir(), "cache"), settingsManager);
mergerFactory = new MergerFactory(settingsManager);
setSystemService(serviceFactory.newService(AccessMethod.INTERNAL, "internal"));
try {
if (!((Service) getSystemService()).loginAsSystem()) {
throw new RuntimeException("System user not found");
}
} catch (ServiceException e) {
LOGGER.error("", e);
}
bimScheduler = new JobScheduler(this);
bimScheduler.start();
try {
ServiceFactoryRegistry serviceFactoryRegistry = new ServiceFactoryRegistry();
serviceFactoryRegistry.registerServiceFactory(serviceFactory);
protocolBuffersServer = new ProtocolBuffersServer(protocolBuffersMetaData, serviceFactoryRegistry, settingsManager.getSettings().getProtocolBuffersPort());
protocolBuffersServer.registerService(new ReflectiveRpcChannel(serviceFactory, protocolBuffersMetaData, new SService(ServiceInterface.class)));
protocolBuffersServer.start();
} catch (Exception e) {
LOGGER.error("", e);
}
ServerStarted serverStarted = LogFactory.eINSTANCE.createServerStarted();
serverStarted.setDate(new Date());
serverStarted.setAccessMethod(AccessMethod.INTERNAL);
serverStarted.setExecutor(null);
BimDatabaseSession session = bimDatabase.createSession();
try {
session.store(serverStarted);
session.commit();
} catch (BimDeadlockException e) {
throw new BimDatabaseException(e);
} finally {
session.close();
}
if (config.isStartCommandLine()) {
commandLine = new CommandLine(this);
commandLine.start();
}
LOGGER.info("Done starting BIMserver");
} catch (Throwable e) {
serverInfoManager.setErrorMessage(e.getMessage());
LOGGER.error("", e);
}
}
/*
* Serializers, deserializers, ifcengines etc... all have counterparts as
* objects in the database for configuration purposes, this methods syncs
* both versions
*/
private void createDatabaseObjects() throws BimDeadlockException, BimDatabaseException, PluginException {
BimDatabaseSession session = bimDatabase.createSession();
ObjectIDM defaultObjectIDM = null;
for (ObjectIDMPlugin objectIDMPlugin : pluginManager.getAllObjectIDMPlugins(true)) {
String name = objectIDMPlugin.getDefaultObjectIDMName();
Condition condition = new AttributeCondition(StorePackage.eINSTANCE.getObjectIDM_Name(), new StringLiteral(name));
ObjectIDM found = session.querySingle(condition, ObjectIDM.class, false, null);
if (found == null) {
ObjectIDM objectIDM = StoreFactory.eINSTANCE.createObjectIDM();
objectIDM.setName(name);
objectIDM.setClassName(objectIDMPlugin.getClass().getName());
objectIDM.setEnabled(true);
if (objectIDMPlugin.getClass() == SchemaFieldObjectIDMPlugin.class) {
defaultObjectIDM = objectIDM;
}
session.store(objectIDM);
} else {
if (objectIDMPlugin.getClass() == SchemaFieldObjectIDMPlugin.class) {
defaultObjectIDM = found;
}
}
}
IfcEngine defaultIfcEngine = null;
for (IfcEnginePlugin ifcEnginePlugin : pluginManager.getAllIfcEnginePlugins(true)) {
String name = ifcEnginePlugin.getDefaultIfcEngineName();
Condition condition = new AttributeCondition(StorePackage.eINSTANCE.getIfcEngine_Name(), new StringLiteral(name));
IfcEngine found = session.querySingle(condition, IfcEngine.class, false, null);
if (found == null) {
IfcEngine ifcEngine = StoreFactory.eINSTANCE.createIfcEngine();
ifcEngine.setClassName(ifcEnginePlugin.getClass().getName());
ifcEngine.setName(name);
ifcEngine.setEnabled(true);
ifcEngine.setActive(false);
session.store(ifcEngine);
defaultIfcEngine = ifcEngine;
} else {
defaultIfcEngine = found;
}
}
for (SerializerPlugin serializerPlugin : pluginManager.getAllSerializerPlugins(true)) {
String name = serializerPlugin.getDefaultSerializerName();
Condition condition = new AttributeCondition(StorePackage.eINSTANCE.getSerializer_Name(), new StringLiteral(name));
Serializer found = session.querySingle(condition, Serializer.class, false, null);
if (found == null) {
Serializer serializer = StoreFactory.eINSTANCE.createSerializer();
serializer.setClassName(serializerPlugin.getClass().getName());
serializer.setName(name);
serializer.setEnabled(true);
serializer.setDescription(serializerPlugin.getDescription());
serializer.setContentType(serializerPlugin.getDefaultContentType());
serializer.setExtension(serializerPlugin.getDefaultExtension());
serializer.setObjectIDM(defaultObjectIDM);
serializer.setIfcEngine(defaultIfcEngine);
session.store(serializer);
}
}
for (DeserializerPlugin deserializerPlugin : pluginManager.getAllDeserializerPlugins(true)) {
String name = deserializerPlugin.getDefaultDeserializerName();
Condition condition = new AttributeCondition(StorePackage.eINSTANCE.getDeserializer_Name(), new StringLiteral(name));
Deserializer found = session.querySingle(condition, Deserializer.class, false, null);
if (found == null) {
Deserializer deserializer = StoreFactory.eINSTANCE.createDeserializer();
deserializer.setClassName(deserializerPlugin.getClass().getName());
deserializer.setName(name);
deserializer.setEnabled(true);
deserializer.setDescription(deserializerPlugin.getDescription());
session.store(deserializer);
}
}
session.store(defaultObjectIDM);
session.store(defaultIfcEngine);
Collection<Plugin> allPlugins = pluginManager.getAllPlugins(false);
for (Plugin plugin : allPlugins) {
Condition pluginCondition = new AttributeCondition(StorePackage.eINSTANCE.getPlugin_Name(), new StringLiteral(plugin.getClass().getName()));
Map<Long, org.bimserver.models.store.Plugin> results = session.query(pluginCondition, org.bimserver.models.store.Plugin.class, false, null);
if (results.size() == 0) {
org.bimserver.models.store.Plugin pluginObject = StoreFactory.eINSTANCE.createPlugin();
pluginObject.setName(plugin.getClass().getName());
pluginObject.setEnabled(true); // New plugins are enabled by
// default
session.store(pluginObject);
} else if (results.size() == 1) {
org.bimserver.models.store.Plugin pluginObject = results.values().iterator().next();
pluginManager.getPluginContext(plugin).setEnabled(pluginObject.getEnabled());
} else {
LOGGER.error("Multiple plugin objects found with the same name: " + plugin.getClass().getName());
}
}
session.commit();
}
private void initDatabaseDependantItems() throws BimDatabaseException {
getEmfSerializerFactory().init(pluginManager, bimDatabase);
getEmfDeserializerFactory().init(pluginManager, bimDatabase);
try {
createDatabaseObjects();
} catch (BimDeadlockException e) {
throw new BimDatabaseException(e);
} catch (PluginException e) {
throw new BimDatabaseException(e);
}
}
public File getHomeDir() {
return config.getHomeDir();
}
public SettingsManager getSettingsManager() {
return settingsManager;
}
public LongActionManager getLongActionManager() {
return longActionManager;
}
private void fixLogging() throws IOException {
File file = new File(config.getHomeDir(), "logs/bimserver.log");
CustomFileAppender appender = new CustomFileAppender(file);
System.out.println("Logging to: " + file.getAbsolutePath());
Enumeration<?> currentLoggers = LogManager.getCurrentLoggers();
LogManager.getRootLogger().addAppender(appender);
while (currentLoggers.hasMoreElements()) {
Object nextElement = currentLoggers.nextElement();
org.apache.log4j.Logger logger2 = (org.apache.log4j.Logger) nextElement;
logger2.addAppender(appender);
}
}
private void initHomeDir() throws IOException {
String[] filesToCheck = new String[] { "logs", "tmp", "log4j.xml", "templates" };
if (!config.getHomeDir().exists()) {
config.getHomeDir().mkdir();
}
if (config.getHomeDir().exists() && config.getHomeDir().isDirectory()) {
for (String fileToCheck : filesToCheck) {
File sourceFile = config.getResourceFetcher().getFile(fileToCheck);
if (sourceFile != null && sourceFile.exists()) {
File destFile = new File(config.getHomeDir(), fileToCheck);
if (!destFile.exists()) {
if (sourceFile.isDirectory()) {
destFile.mkdir();
for (File f : sourceFile.listFiles()) {
if (f.isFile()) {
FileUtils.copyFile(f, new File(destFile, f.getName()));
}
}
} else {
FileUtils.copyFile(sourceFile, destFile);
}
}
}
}
}
}
public BimDatabase getDatabase() {
return bimDatabase;
}
public ResourceFetcher getResourceFetcher() {
return config.getResourceFetcher();
}
public GregorianCalendar getServerStartTime() {
return serverStartTime;
}
public void setSystemService(ServiceInterface systemService) {
this.systemService = systemService;
}
public ServiceInterface getSystemService() {
return systemService;
}
public MergerFactory getMergerFactory() {
return mergerFactory;
}
public void stop() {
LOGGER.info("Stopping BIMserver");
if (bimDatabase != null) {
bimDatabase.close();
}
if (bimScheduler != null) {
bimScheduler.close();
}
if (longActionManager != null) {
longActionManager.shutdown();
}
if (notificationsManager != null) {
notificationsManager.shutdown();
}
if (embeddedWebServer != null) {
embeddedWebServer.shutdown();
}
if (protocolBuffersServer != null) {
protocolBuffersServer.shutdown();
}
if (commandLine != null) {
commandLine.shutdown();
}
}
public PluginManager getPluginManager() {
return pluginManager;
}
public MailSystem getMailSystem() {
return mailSystem;
}
public EmfSerializerFactory getEmfSerializerFactory() {
return emfSerializerFactory;
}
public EmfDeserializerFactory getEmfDeserializerFactory() {
return emfDeserializerFactory;
}
public DiskCacheManager getDiskCacheManager() {
return diskCacheManager;
}
public String getClassPath() {
return config.getClassPath();
}
public ServerInfo getServerInfo() {
return serverInfoManager.getServerInfo();
}
public ServiceInterfaceFactory getServiceFactory() {
return serviceFactory;
}
public VersionChecker getVersionChecker() {
return versionChecker;
}
public TemplateEngine getTemplateEngine() {
return templateEngine;
}
public ClashDetectionCache getClashDetectionCache() {
return clashDetectionCache;
}
public CompareCache getCompareCache() {
return compareCache;
}
public NotificationsManager getNotificationsManager() {
return notificationsManager;
}
public ServerInfoManager getServerInfoManager() {
return serverInfoManager;
}
public SService getServiceInterfaceService() {
return serviceInterfaceService;
}
public ProtocolBuffersMetaData getProtocolBuffersMetaData() {
return protocolBuffersMetaData;
}
public BimServerConfig getConfig() {
return config;
}
public EmbeddedWebServer getEmbeddedWebServer() {
return embeddedWebServer;
}
public SService getNotificationInterfaceService() {
return notificationInterfaceService;
}
}
|
package util;
import org.apache.maven.toolchain.Toolchain;
import java.io.File;
/**
* Utilities to aid with finding Java's location
*
* @author C. Dessonville
*/
public class JavaLocator {
public static String findExecutableFromToolchain(Toolchain toolchain) {
String javaExec = null;
if (toolchain != null) {
javaExec = toolchain.findTool("java");
}
if (javaExec == null) {
String javaHome = System.getenv("JAVA_HOME");
if (javaHome == null) {
javaHome = System.getProperty("java.home"); // fallback to JRE
}
if (javaHome == null) {
throw new IllegalStateException("Couldn't locate java, try setting JAVA_HOME environment variable.");
}
javaExec = javaHome + File.separator + "bin" + File.separator + "java";
}
return javaExec;
}
static String findHomeFromToolchain(Toolchain toolchain) {
String executable = findExecutableFromToolchain(toolchain);
File executableParent = new File(executable).getParentFile();
if (executableParent == null) {
return null;
}
return executableParent.getParent();
}
}
|
// P i c t u r e V i e w //
// This software is released under the terms of the GNU General Public //
// to report bugs & suggestions. //
package omr.sheet;
import omr.score.PagePoint;
import omr.ui.ScrollView;
import omr.ui.Rubber;
import omr.ui.RubberZoomedPanel;
import omr.ui.Zoom;
import omr.util.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.List;
/**
* Class <code>PictureView</code> defines the view dedicated to the display
* of the picture bitmap of a music sheet.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class PictureView
extends ScrollView
{
private static final Logger logger = Logger.getLogger(PictureView.class);
// The displayed view
private final MyView view;
// Link with sheet
private final Sheet sheet;
// PictureView //
/**
* Create a new <code>PictureView</code> instance, dedicated to a
* sheet.
*
* @param sheet the related sheet
*/
public PictureView (Sheet sheet)
{
view = new MyView();
if (logger.isDebugEnabled()) {
logger.debug("creating PictureView on " + sheet);
}
this.sheet = sheet;
// Insert view
setView(view);
if (logger.isDebugEnabled()) {
logger.debug("PictureView ready");
}
}
// getView //
public MyView getView()
{
return view;
}
// getSheet //
/**
* Report the sheet this view is related to
*
* @return the related sheet
*/
public Sheet getSheet ()
{
return sheet;
}
// close //
/**
* Close the view, by removing it from the containing sheet tabbed
* pane.
*/
public void close ()
{
///Main.getJui().sheetPane.close(this);
}
// showRelatedScore //
/**
* If the sheet-related score exists, then display the score view in
* the score display. Focus is determined as the corresponding point in
* score/score display as the provided image point (or of the current
* sheet image point if a null image point is provided)
*/
public void showRelatedScore ()
{
// // Do we have the corresponding score ?
// final Score score = sheet.getScore();
// if (logger.isDebugEnabled()) {
// logger.debug("showRelatedScore: " + score);
// if (score != null) {
// Main.getJui().scorePane.showScoreView(score.getView());
// } else {
// Main.getJui().scorePane.showScoreView(null);
}
// toString //
/**
* A readable description of this view
*
* @return a name based on the sheet this view is dedicated to
*/
@Override
public String toString ()
{
return "{PictureView " + sheet.getPath() + "}";
}
// getPixel //
/**
* Report the pixel level at the designated point.
*
* @param pt the designated point
* @return the pixel level (0->255) or -1 if info is not available, for
* example because the designated point is outside the image boundaries
*/
@Override
public int getPixel (Point pt)
{
// Make sure the picture is available
Picture picture = sheet.getPicture();
// Check that we are not pointing outside the image
if ((pt.x < picture.getWidth()) && (pt.y < picture.getHeight())) {
return picture.getPixel(pt.x, pt.y);
} else {
return -1;
}
}
// MyView //
private class MyView
extends RubberZoomedPanel
{
// render //
@Override
public void render (Graphics g)
{
// Render the picture image
sheet.getPicture().render(g, getZoom().getRatio());
}
// pointSelected //
/**
* Point designation. Registered observers are notified of the
* Point and Pixel informations.
*
* @param e the mouse event
* @param pt the selected point in model pixel coordinates
*/
@Override
public void pointSelected (MouseEvent e,
Point pt)
{
// We use a specific version which displays the pixel level
notifyObservers(pt, getPixel(pt));
}
}
}
|
package com.ctrip.ops.sysdev.filters;
import java.util.*;
import com.ctrip.ops.sysdev.baseplugin.BaseFilter;
import org.apache.log4j.Logger;
public class FlatMetric extends BaseFilter {
private static final Logger logger = Logger.getLogger(FlatMetric.class.getName());
private int windowSize;
private String key;
private String value;
private Map<Object, Map<Object, Integer>> metric;
private long lastEmitTime;
public FlatMetric(Map config) {
super(config);
}
protected void prepare() {
this.key = (String) config.get("key");
this.value = (String) config.get("value");
this.windowSize = (int) config.get("windowSize") * 1000;
this.processExtraEventsFunc = true;
this.metric = new HashMap();
this.lastEmitTime = System.currentTimeMillis();
}
@Override
protected Map filter(final Map event) {
if (event.containsKey(this.key) && event.containsKey(this.value)) {
Object keyValue = event.get(this.key);
Object valueValue = event.get(this.value);
HashMap set = (HashMap) this.metric.get(keyValue);
if (set == null) {
set = new HashMap();
set.put(valueValue, 1);
} else {
if (set.containsKey(valueValue)) {
int count = (int) set.get(valueValue);
set.put(valueValue, count + 1);
} else {
set.put(valueValue, 1);
}
}
this.metric.put(keyValue, set);
}
return event;
}
@Override
public List<Map<String, Object>> filterExtraEvents(Map event) {
if (System.currentTimeMillis() < this.windowSize + this.lastEmitTime) {
return null;
}
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
Iterator<Map.Entry<Object, Map<Object, Integer>>> it = this.metric.entrySet().iterator();
this.lastEmitTime = System.currentTimeMillis();
while (it.hasNext()) {
Map.Entry<Object, Map<Object, Integer>> o = it.next();
final Object keyValue = o.getKey();
final Map ValueValue = (Map) o.getValue();
Iterator<Map.Entry<Object, Integer>> vvit = ValueValue.entrySet().iterator();
while (vvit.hasNext()) {
Map.Entry<Object, Integer> vvitentry = vvit.next();
events.add(new HashMap<String, Object>() {{
this.put(key, keyValue);
this.put(value, vvitentry.getKey());
this.put("count", vvitentry.getValue());
this.put("@timestamp", lastEmitTime);
}});
}
}
this.metric = new HashMap();
return events;
}
}
|
package org.opennms.netmgt.provision;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.RWSConfig;
import org.opennms.netmgt.config.RancidAdapterConfig;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsCategory;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.model.events.EventForwarder;
import org.opennms.netmgt.model.events.EventSubscriptionService;
import org.opennms.netmgt.model.events.annotations.EventHandler;
import org.opennms.netmgt.model.events.annotations.EventListener;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.rancid.ConnectionProperties;
import org.opennms.rancid.RWSClientApi;
import org.opennms.rancid.RancidApiException;
import org.opennms.rancid.RancidNode;
import org.opennms.rancid.RancidNodeAuthentication;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
/**
* A Rancid provisioning adapter for integration with OpenNMS Provisoning daemon API.
*
* @author <a href="mailto:[email protected]">Guglielmo Incisa</a>
* @author <a href="mailto:[email protected]">Antonio Russo</a>
*
*/
@EventListener(name="RancidProvisioningAdapter:Listener")
public class RancidProvisioningAdapter extends SimpleQueuedProvisioningAdapter implements InitializingBean, org.opennms.netmgt.model.events.EventListener {
private NodeDao m_nodeDao;
private volatile EventForwarder m_eventForwarder;
private volatile EventSubscriptionService m_eventSubscriptionService;
private RWSConfig m_rwsConfig;
private RancidAdapterConfig m_rancidAdapterConfig;
private ConnectionProperties m_cp;
private List<String> m_rancid_categories;
private TransactionTemplate m_template;
public TransactionTemplate getTemplate() {
return m_template;
}
public void setTemplate(TransactionTemplate template) {
m_template = template;
}
private static final String MESSAGE_PREFIX = "Rancid provisioning failed: ";
private static final String ADAPTER_NAME="RancidProvisioningAdapter";
private static final String RANCID_COMMENT="node provisioned by opennms";
public static final String NAME = "RancidProvisioningAdapter";
private volatile static ConcurrentMap<Integer, RancidNode> m_onmsNodeRancidNodeMap;
@Override
@Transactional
AdapterOperationSchedule createScheduleForNode(final int nodeId, AdapterOperationType adapterOperationType) {
log().debug("Scheduling: " + adapterOperationType + " for nodeid: " + nodeId);
if (adapterOperationType.equals(AdapterOperationType.CONFIG_CHANGE)) {
updateRancidNodeState(nodeId, true);
String ipaddress = (String) m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
return getSuitableIpForRancid(nodeId);
}
});
long initialDelay = m_rancidAdapterConfig.getDelay(ipaddress);
int retries = m_rancidAdapterConfig.getRetries(ipaddress);
log().debug("Setting initialDelay(sec): " + initialDelay);
log().debug("Setting retries(sec): " + retries);
return new AdapterOperationSchedule(initialDelay,60, retries, TimeUnit.SECONDS);
}
return new AdapterOperationSchedule();
}
public void afterPropertiesSet() throws Exception {
RWSClientApi.init();
Assert.notNull(m_rwsConfig, "Rancid Provisioning Adapter requires RWSConfig property to be set.");
m_cp = getRWSConnection();
Assert.notNull(m_nodeDao, "Rancid Provisioning Adapter requires nodeDao property to be set.");
createMessageSelectorAndSubscribe();
getRancidCategories();
m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
buildRancidNodeMap();
return null;
}
});
}
private void getRancidCategories() {
try {
m_rancid_categories = RWSClientApi.getRWSResourceDeviceTypesPatternList(m_cp).getResource();
} catch (RancidApiException e) {
ConnectionProperties cp = getStandByRWSConnection();
if (cp != null) {
try {
m_rancid_categories = RWSClientApi.getRWSResourceDeviceTypesPatternList(m_cp).getResource();
} catch (RancidApiException e1) {
log().error("Rancid provisioning Adapter was not able to retieve rancid categories from RWS server");
m_rancid_categories = new ArrayList<String>();
m_rancid_categories.add("cisco");
}
}
}
}
private void buildRancidNodeMap() {
List<OnmsNode> nodes = m_nodeDao.findAllProvisionedNodes();
m_onmsNodeRancidNodeMap = new ConcurrentHashMap<Integer, RancidNode>(nodes.size());
for (OnmsNode onmsNode : nodes) {
RancidNode rNode = getSuitableRancidNode(onmsNode);
if (rNode != null) {
m_onmsNodeRancidNodeMap.putIfAbsent(onmsNode.getId(), rNode);
}
}
}
private ConnectionProperties getRWSConnection() {
return m_rwsConfig.getBase();
}
private ConnectionProperties getStandByRWSConnection() {
return m_rwsConfig.getNextStandBy();
}
public void doAdd(int nodeId, ConnectionProperties cp, boolean retry) throws ProvisioningAdapterException {
log().debug("RANCID PROVISIONING ADAPTER CALLED addNode: nodeid: " + nodeId);
try {
OnmsNode node = m_nodeDao.get(nodeId);
Assert.notNull(node, "Rancid Provisioning Adapter addNode method failed to return node for given nodeId:"+nodeId);
RancidNode rNode = getSuitableRancidNode(node);
if (m_onmsNodeRancidNodeMap.containsValue(rNode)) {
log().warn("Rancid Provisioning Adapter: Error Duplicate node: " + node);
ProvisioningAdapterException e = new ProvisioningAdapterException("Duplicate node has been provided: "+node);
sendAndThrow(nodeId, e);
return;
}
rNode.setStateUp(true);
RWSClientApi.createRWSRancidNode(cp, rNode);
RWSClientApi.createOrUpdateRWSAuthNode(cp, rNode.getAuth());
m_onmsNodeRancidNodeMap.put(Integer.valueOf(nodeId), rNode);
} catch (ProvisioningAdapterException ae) {
sendAndThrow(nodeId, ae);
} catch (Exception e) {
cp = getStandByRWSConnection();
if (retry && cp != null) {
log().info("Rancid Provisioning Adapter: retry Add on standByConn: " + cp.getUrl());
doAdd(nodeId, cp, false);
} else {
sendAndThrow(nodeId, e);
}
}
}
public void doUpdate(int nodeId, ConnectionProperties cp, boolean retry) throws ProvisioningAdapterException {
log().debug("RANCID PROVISIONING ADAPTER CALLED updateNode: nodeid: " + nodeId);
try {
OnmsNode node = m_nodeDao.get(nodeId);
Assert.notNull(node, "Rancid Provisioning Adapter update Node method failed to return node for given nodeId:"+nodeId);
RancidNode rNewNode = getSuitableRancidNode(node);
// The node should exists onmsNodeRancidNodeMap
if (m_onmsNodeRancidNodeMap.containsKey(Integer.valueOf(nodeId))) {
RancidNode rCurrentNode = m_onmsNodeRancidNodeMap.get(Integer.valueOf(nodeId));
// set the state to the suitable state
rNewNode.setStateUp(rCurrentNode.isStateUp());
// delete the current node if it is different
if (!rCurrentNode.equals(rNewNode)) {
try {
RWSClientApi.deleteRWSRancidNode(cp, rCurrentNode);
RWSClientApi.deleteRWSAuthNode(cp, rCurrentNode.getAuth());
} catch (Exception e) {
log().error("RANCID PROVISIONING ADAPTER Failed to delete node: " + nodeId + " Exception: " + e.getMessage());
}
}
} else {
rNewNode.setStateUp(true);
}
RWSClientApi.createOrUpdateRWSRancidNode(cp, rNewNode);
RWSClientApi.createOrUpdateRWSAuthNode(cp, rNewNode.getAuth());
m_onmsNodeRancidNodeMap.replace(node.getId(), rNewNode);
} catch (Exception e) {
cp = getStandByRWSConnection();
if (retry && cp != null) {
log().info("Rancid Provisioning Adapter: retry Update on standByConn: " + cp.getUrl());
doUpdate(nodeId, cp, false);
} else {
sendAndThrow(nodeId, e);
}
}
}
public void doDelete(int nodeId,ConnectionProperties cp, boolean retry) throws ProvisioningAdapterException {
log().debug("RANCID PROVISIONING ADAPTER CALLED deleteNode: nodeid: " + nodeId);
/*
* The work to maintain the hashmap boils down to needing to do deletes, so
* here we go.
*/
try {
if (m_onmsNodeRancidNodeMap.containsKey(Integer.valueOf(nodeId))) {
RancidNode rNode = m_onmsNodeRancidNodeMap.get(Integer.valueOf(nodeId));
RWSClientApi.deleteRWSRancidNode(cp, rNode);
RWSClientApi.deleteRWSAuthNode(cp, rNode.getAuth());
m_onmsNodeRancidNodeMap.remove(Integer.valueOf(nodeId));
} else {
log().warn("No node found in nodeRancid Map for nodeid: " + nodeId);
}
} catch (Exception e) {
cp = getStandByRWSConnection();
if (retry && cp != null) {
log().info("Rancid Provisioning Adapter: retry Delete on standByConn: " + cp.getUrl());
doDelete(nodeId, cp, false);
} else {
sendAndThrow(nodeId, e);
}
}
}
public void doNodeConfigChanged(int nodeId,ConnectionProperties cp, boolean retry) throws ProvisioningAdapterException {
log().debug("RANCID PROVISIONING ADAPTER CALLED DoNodeConfigChanged: nodeid: " + nodeId);
if (m_onmsNodeRancidNodeMap.containsKey(Integer.valueOf(nodeId))) {
updateConfiguration(nodeId,m_onmsNodeRancidNodeMap.get(Integer.valueOf(nodeId)),cp, retry);
} else {
log().warn("No node found in nodeRancid Map for nodeid: " + nodeId);
}
}
private void updateConfiguration(int nodeid, RancidNode rNode,ConnectionProperties cp, boolean retry) throws ProvisioningAdapterException {
log().debug("Updating Rancid Router.db configuration: node: " + rNode.getDeviceName() + " type: " + rNode.getDeviceType() + " group: " + rNode.getGroup());
try {
RWSClientApi.updateRWSRancidNode(cp, rNode);
} catch (Exception e) {
cp = getStandByRWSConnection();
if (retry && cp != null) {
log().info("Rancid Provisioning Adapter: retry update on standByConn: " + cp.getUrl());
updateConfiguration(nodeid, rNode, cp, false);
} else {
sendAndThrow(nodeid, e);
}
}
}
private void sendAndThrow(int nodeId, Exception e) {
log().debug("RANCID PROVISIONING ADAPTER CALLED sendAndThrow: nodeid: " + nodeId);
log().debug("RANCID PROVISIONING ADAPTER CALLED sendAndThrow: Exception: " + e.getMessage());
Event event = buildEvent(EventConstants.PROVISIONING_ADAPTER_FAILED, nodeId).addParam("reason", MESSAGE_PREFIX+e.getLocalizedMessage()).getEvent();
m_eventForwarder.sendNow(event);
throw new ProvisioningAdapterException(MESSAGE_PREFIX, e);
}
private EventBuilder buildEvent(String uei, int nodeId) {
EventBuilder builder = new EventBuilder(uei, "Provisioner", new Date());
builder.setNodeid(nodeId);
return builder;
}
public NodeDao getNodeDao() {
return m_nodeDao;
}
public void setNodeDao(NodeDao dao) {
m_nodeDao = dao;
}
public void setEventForwarder(EventForwarder eventForwarder) {
m_eventForwarder = eventForwarder;
}
public EventForwarder getEventForwarder() {
return m_eventForwarder;
}
private static Category log() {
return ThreadCategory.getInstance(RancidProvisioningAdapter.class);
}
public RWSConfig getRwsConfig() {
return m_rwsConfig;
}
public void setRwsConfig(RWSConfig rwsConfig) {
m_rwsConfig = rwsConfig;
}
public RancidAdapterConfig getRancidAdapterConfig() {
return m_rancidAdapterConfig;
}
public void setRancidAdapterConfig(RancidAdapterConfig rancidAdapterConfig) {
m_rancidAdapterConfig = rancidAdapterConfig;
}
public String getName() {
return ADAPTER_NAME;
}
private String getSuitableIpForRancid(OnmsNode node){
OnmsIpInterface primaryInterface = node.getPrimaryInterface();
if (primaryInterface == null) {
Set<OnmsIpInterface> ipInterfaces = node.getIpInterfaces();
for (OnmsIpInterface onmsIpInterface : ipInterfaces) {
return onmsIpInterface.getIpAddress();
}
}
return primaryInterface.getIpAddress();
}
private String getSuitableIpForRancid(Integer nodeId) {
return getSuitableIpForRancid(m_nodeDao.get(nodeId));
}
private RancidNode getSuitableRancidNode(OnmsNode node) {
//The group should be the foreign source of the node
String group = node.getForeignSource();
if (group == null) return null;
RancidNode r_node = new RancidNode(group, node.getLabel());
String ipaddress = getSuitableIpForRancid(node);
if (m_rancidAdapterConfig.useCategories(ipaddress)) {
r_node.setDeviceType(getTypeFromCategories(node));
} else {
r_node.setDeviceType(getTypeFromSysObjectId(node.getSysObjectId()));
}
r_node.setStateUp(true);
r_node.setComment(RANCID_COMMENT);
r_node.setAuth(getSuitableRancidNodeAuthentication(node));
return r_node;
}
private String getTypeFromSysObjectId(String sysoid) {
String rancidType = m_rancidAdapterConfig.getType(sysoid);
log().debug("Rancid configuration file: Rancid devicetype found: " + rancidType);
return rancidType;
}
private String getTypeFromCategories(OnmsNode node) {
log().debug("Using Categories to get Rancid devicetype for node: " + node.getLabel());
for (String rancidType: m_rancid_categories) {
for (OnmsCategory nodecategory: node.getCategories()) {
if (nodecategory.getName().equalsIgnoreCase(rancidType)) {
log().debug("Found Matching Category: Rancid devicetype found: " + rancidType);
return rancidType;
}
}
}
log().warn("No Matching Category found: trying to get devicetype using config file");
return getTypeFromCategories(node);
}
private RancidNodeAuthentication getSuitableRancidNodeAuthentication(OnmsNode node) {
// RancidAutentication
RancidNodeAuthentication r_auth_node = new RancidNodeAuthentication();
r_auth_node.setDeviceName(node.getLabel());
OnmsAssetRecord asset_node = node.getAssetRecord();
if (asset_node.getUsername() != null) {
r_auth_node.setUser(asset_node.getUsername());
}
if (asset_node.getPassword() != null) {
r_auth_node.setPassword(asset_node.getPassword());
}
if (asset_node.getEnable() != null) {
r_auth_node.setEnablePass(asset_node.getEnable());
}
if (asset_node.getAutoenable() != null) {
r_auth_node.setAutoEnable(asset_node.getAutoenable().equals(OnmsAssetRecord.AUTOENABLED));
}
if (asset_node.getConnection() != null) {
r_auth_node.setConnectionMethod(asset_node.getConnection());
} else {
r_auth_node.setConnectionMethod("telnet");
}
return r_auth_node;
}
@Override
public boolean isNodeReady(final AdapterOperation op) {
boolean ready = true;
if (op.getType() == AdapterOperationType.CONFIG_CHANGE) {
String ipaddress = (String) m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
return getSuitableIpForRancid(op.getNodeId());
}
});
ready =
m_rancidAdapterConfig.isCurTimeInSchedule(ipaddress);
}
log().debug("is Node Ready: " + ready + " For Operation " + op.getType() + " for node: " + op.getNodeId());
return ready;
}
@Override
public void processPendingOperationForNode(final AdapterOperation op) throws ProvisioningAdapterException {
log().debug("Procession Operation: " + op.getType() + " for node: " + op.getNodeId() );
if (op.getType() == AdapterOperationType.ADD) {
m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
doAdd(op.getNodeId(),m_cp,true);
return null;
}
});
} else if (op.getType() == AdapterOperationType.UPDATE) {
m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
doUpdate(op.getNodeId(),m_cp,true);
return null;
}
});
} else if (op.getType() == AdapterOperationType.DELETE) {
m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
doDelete(op.getNodeId(),m_cp,true);
return null;
}
});
} else if (op.getType() == AdapterOperationType.CONFIG_CHANGE) {
m_template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
doNodeConfigChanged(op.getNodeId(),m_cp,true);
return null;
}
});
}
}
@EventHandler(uei = EventConstants.RANCID_DOWNLOAD_FAILURE_UEI)
public void handleRancidDownLoadFailure(Event e) {
log().debug("get Event uei/id: " + e.getUei() + "/" + e.getDbid());
if (e.hasNodeid()) {
int nodeId = Long.valueOf(e.getNodeid()).intValue();
if (m_onmsNodeRancidNodeMap.containsKey(Integer.valueOf(nodeId))) {
updateRancidNodeState(nodeId, false);
} else {
log().warn("node does not exist with nodeid: " + e.getNodeid());
}
}
}
@EventHandler(uei = EventConstants.RANCID_DOWNLOAD_SUCCESS_UEI)
public void handleRancidDownLoadSuccess(Event e) {
log().debug("get Event uei/id: " + e.getUei() + "/" + e.getDbid());
if (e.hasNodeid() ) {
int nodeId = Long.valueOf(e.getNodeid()).intValue();
if (m_onmsNodeRancidNodeMap.containsKey(Integer.valueOf(nodeId))) {
updateRancidNodeState(nodeId, false);
} else {
log().warn("node does not exist with nodeid: " + e.getNodeid());
}
}
}
@EventHandler(uei = EventConstants.RANCID_GROUP_PROCESSING_COMPLETED_UEI)
public void handleRancidGroupProcessingCompleted(Event e) {
log().debug("get Event uei/id: " + e.getUei() + "/" + e.getDbid());
if (e.getParms() != null ) {
Iterator<Parm> ite = e.getParms().iterateParm();
while (ite.hasNext()) {
Parm parm = ite.next();
if (parm.getParmName().equals("rancidGroupName")) {
updateGroupConfiguration(parm.getValue().getContent());
break;
}
}
}
}
private void updateGroupConfiguration(String group) {
Iterator<Integer> ite = m_onmsNodeRancidNodeMap.keySet().iterator();
while (ite.hasNext()) {
Integer nodeId = ite.next();
RancidNode rnode = m_onmsNodeRancidNodeMap.get(nodeId);
if (group.equals(rnode.getGroup())) {
updateConfiguration(nodeId.intValue(), rnode, m_cp, true);
}
}
}
private void updateRancidNodeState(int nodeid, boolean up) {
RancidNode rnode = m_onmsNodeRancidNodeMap.get(Integer.valueOf(nodeid));
rnode.setStateUp(up);
m_onmsNodeRancidNodeMap.put(nodeid, rnode);
}
public EventSubscriptionService getEventSubscriptionService() {
return m_eventSubscriptionService;
}
public void setEventSubscriptionService(
EventSubscriptionService eventSubscriptionService) {
m_eventSubscriptionService = eventSubscriptionService;
}
public void onEvent(Event e) {
if (e == null)
return;
if (e.getUei().equals(EventConstants.RANCID_DOWNLOAD_FAILURE_UEI))
handleRancidDownLoadFailure(e);
else if (e.getUei().equals(EventConstants.RANCID_DOWNLOAD_SUCCESS_UEI))
handleRancidDownLoadSuccess(e);
else if (e.getUei().equals(EventConstants.RANCID_GROUP_PROCESSING_COMPLETED_UEI))
handleRancidGroupProcessingCompleted(e);
}
private void createMessageSelectorAndSubscribe() {
List<String> ueiList = new ArrayList<String>();
ueiList.add(EventConstants.RANCID_DOWNLOAD_FAILURE_UEI);
ueiList.add(EventConstants.RANCID_DOWNLOAD_SUCCESS_UEI);
ueiList.add(EventConstants.RANCID_GROUP_PROCESSING_COMPLETED_UEI);
getEventSubscriptionService().addEventListener(this, ueiList);
}
}
|
package com.izforge.izpack.installer.container.impl;
import javax.swing.*;
import com.izforge.izpack.api.exception.IzPackException;
import com.izforge.izpack.installer.gui.SplashScreen;
import org.picocontainer.Characteristics;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.injectors.ProviderAdapter;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.exception.ContainerException;
import com.izforge.izpack.api.resource.Messages;
import com.izforge.izpack.gui.GUIPrompt;
import com.izforge.izpack.gui.log.Log;
import com.izforge.izpack.installer.container.provider.GUIInstallDataProvider;
import com.izforge.izpack.installer.container.provider.IconsProvider;
import com.izforge.izpack.installer.container.provider.IzPanelsProvider;
import com.izforge.izpack.installer.gui.DefaultNavigator;
import com.izforge.izpack.installer.gui.InstallerController;
import com.izforge.izpack.installer.gui.InstallerFrame;
import com.izforge.izpack.installer.language.LanguageDialog;
import com.izforge.izpack.installer.multiunpacker.MultiVolumeUnpackerHelper;
import com.izforge.izpack.installer.unpacker.GUIPackResources;
import com.izforge.izpack.installer.unpacker.IUnpacker;
/**
* GUI Installer container.
*/
public class GUIInstallerContainer extends InstallerContainer
{
/**
* Constructs a <tt>GUIInstallerContainer</tt>.
*
* @throws ContainerException if initialisation fails
*/
public GUIInstallerContainer()
{
initialise();
}
/**
* Constructs a <tt>GUIInstallerContainer</tt>.
* <p/>
* This constructor is provided for testing purposes.
*
* @param container the underlying container
* @throws ContainerException if initialisation fails
*/
protected GUIInstallerContainer(MutablePicoContainer container)
{
initialise(container);
}
/**
* Registers components with the container.
*
* @param pico the container
*/
@Override
protected void registerComponents(MutablePicoContainer pico)
{
super.registerComponents(pico);
pico
.addAdapter(new ProviderAdapter(new GUIInstallDataProvider()))
.addAdapter(new ProviderAdapter(new IzPanelsProvider()))
.addAdapter(new ProviderAdapter(new IconsProvider()));
pico
.addComponent(GUIPrompt.class)
.addComponent(InstallerController.class)
.addComponent(DefaultNavigator.class)
.addComponent(InstallerFrame.class)
.addComponent(Log.class)
.addComponent(GUIPackResources.class)
.addComponent(MultiVolumeUnpackerHelper.class)
.addComponent(SplashScreen.class)
.as(Characteristics.USE_NAMES).addComponent(LanguageDialog.class);
}
/**
* Resolve components.
*
* @param pico the container
*/
@Override
protected void resolveComponents(final MutablePicoContainer pico)
{
super.resolveComponents(pico);
InstallData installdata = pico.getComponent(InstallData.class);
pico
.addConfig("title", getTitle(installdata)); // Configuration of title parameter in InstallerFrame
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run()
{
InstallerFrame frame = pico.getComponent(InstallerFrame.class);
IUnpacker unpacker = pico.getComponent(IUnpacker.class);
frame.setUnpacker(unpacker);
}
});
}
catch (Exception exception)
{
throw new IzPackException(exception);
}
}
private String getTitle(InstallData installData)
{
// Use a alternate message if defined.
final String key = "installer.reversetitle";
Messages messages = installData.getMessages();
String message = messages.get(key);
// message equal to key -> no message defined.
if (message.equals(key))
{
message = messages.get("installer.title") + " " + installData.getInfo().getAppName();
}
else
{
// Attention! The alternate message has to contain the whole message including
// $APP_NAME and may be $APP_VER.
message = installData.getVariables().replace(message);
}
return message;
}
}
|
package org.jenkinsci.plugins.pipeline.maven.publishers;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import hudson.tasks.junit.JUnitResultArchiver;
import hudson.tasks.junit.TestDataPublisher;
import hudson.tasks.junit.TestResultAction;
import hudson.tasks.junit.pipeline.JUnitResultsStepExecution;
import hudson.tasks.test.PipelineTestDetails;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenSpyLogProcessor;
import org.jenkinsci.plugins.pipeline.maven.MavenPublisher;
import org.jenkinsci.plugins.pipeline.maven.util.XmlUtils;
import org.jenkinsci.plugins.workflow.actions.WarningAction;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.w3c.dom.Element;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* @author <a href="mailto:[email protected]">Cyrille Le Clerc</a>
*/
public class JunitTestsPublisher extends MavenPublisher {
private static final Logger LOGGER = Logger.getLogger(JunitTestsPublisher.class.getName());
private static final String APACHE_GROUP_ID = "org.apache.maven.plugins";
private static final String TYCHO_GROUP_ID = "org.eclipse.tycho";
private static final String KARMA_GROUP_ID = "com.kelveden";
private static final String SUREFIRE_ID = "maven-surefire-plugin";
private static final String FAILSAFE_ID = "maven-failsafe-plugin";
private static final String TYCHO_ID = "tycho-surefire-plugin";
private static final String KARMA_ID = "maven-karma-plugin";
private static final String SUREFIRE_GOAL = "test";
private static final String FAILSAFE_GOAL = "integration-test";
private static final String TYCHO_GOAL = "test";
private static final String KARMA_GOAL = "start";
private static final long serialVersionUID = 1L;
/**
* If true, retain a suite's complete stdout/stderr even if this is huge and the suite passed.
*
* @see JUnitResultArchiver#isKeepLongStdio()
*/
private boolean keepLongStdio;
/**
* @see JUnitResultArchiver#getHealthScaleFactor()
*/
@CheckForNull
private Double healthScaleFactor;
private boolean ignoreAttachments;
@DataBoundConstructor
public JunitTestsPublisher() {
}
/*
<ExecutionEvent type="MojoStarted" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-02-03 10:15:12.554">
<project baseDir="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy" file="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy/pom.xml" groupId="org.jenkins-ci.plugins" name="Maven Spy for the Pipeline Maven Integration Plugin" artifactId="pipeline-maven-spy" version="2.0-SNAPSHOT">
<build outputDirectory="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy/target/classes"/>
</project>
<plugin executionId="default-test" goal="test" groupId="org.apache.maven.plugins" artifactId="maven-surefire-plugin" version="2.19.1">
<additionalClasspathElements>${maven.test.additionalClasspath}</additionalClasspathElements>
<argLine>${argLine}</argLine>
<basedir>${basedir}</basedir>
<childDelegation>${childDelegation}</childDelegation>
<classesDirectory>${project.build.outputDirectory}</classesDirectory>
<classpathDependencyExcludes>${maven.test.dependency.excludes}</classpathDependencyExcludes>
<debugForkedProcess>${maven.surefire.debug}</debugForkedProcess>
<dependenciesToScan>${dependenciesToScan}</dependenciesToScan>
<disableXmlReport>${disableXmlReport}</disableXmlReport>
<enableAssertions>${enableAssertions}</enableAssertions>
<excludedGroups>${excludedGroups}</excludedGroups>
<excludesFile>${surefire.excludesFile}</excludesFile>
<failIfNoSpecifiedTests>${surefire.failIfNoSpecifiedTests}</failIfNoSpecifiedTests>
<failIfNoTests>${failIfNoTests}</failIfNoTests>
<forkCount>1C</forkCount>
<forkMode>${forkMode}</forkMode>
<forkedProcessTimeoutInSeconds>${surefire.timeout}</forkedProcessTimeoutInSeconds>
<groups>${groups}</groups>
<includesFile>${surefire.includesFile}</includesFile>
<junitArtifactName>${junitArtifactName}</junitArtifactName>
<jvm>${jvm}</jvm>
<localRepository>${localRepository}</localRepository>
<objectFactory>${objectFactory}</objectFactory>
<parallel>${parallel}</parallel>
<parallelMavenExecution>${session.parallel}</parallelMavenExecution>
<parallelOptimized>${parallelOptimized}</parallelOptimized>
<parallelTestsTimeoutForcedInSeconds>${surefire.parallel.forcedTimeout}</parallelTestsTimeoutForcedInSeconds>
<parallelTestsTimeoutInSeconds>${surefire.parallel.timeout}</parallelTestsTimeoutInSeconds>
<perCoreThreadCount>${perCoreThreadCount}</perCoreThreadCount>
<pluginArtifactMap>${plugin.artifactMap}</pluginArtifactMap>
<pluginDescriptor>${plugin}</pluginDescriptor>
<printSummary>${surefire.printSummary}</printSummary>
<projectArtifactMap>${project.artifactMap}</projectArtifactMap>
<redirectTestOutputToFile>${maven.test.redirectTestOutputToFile}</redirectTestOutputToFile>
<remoteRepositories>${project.pluginArtifactRepositories}</remoteRepositories>
<reportFormat>${surefire.reportFormat}</reportFormat>
<reportNameSuffix>${surefire.reportNameSuffix}</reportNameSuffix>
<reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
<rerunFailingTestsCount>${surefire.rerunFailingTestsCount}</rerunFailingTestsCount>
<reuseForks>true</reuseForks>
<runOrder>${surefire.runOrder}</runOrder>
<shutdown>${surefire.shutdown}</shutdown>
<skip>${maven.test.skip}</skip>
<skipAfterFailureCount>${surefire.skipAfterFailureCount}</skipAfterFailureCount>
<skipExec>${maven.test.skip.exec}</skipExec>
<skipTests>${skipTests}</skipTests>
<suiteXmlFiles>${surefire.suiteXmlFiles}</suiteXmlFiles>
<systemProperties/>
<test>${test}</test>
<testClassesDirectory>${project.build.testOutputDirectory}</testClassesDirectory>
<testFailureIgnore>${maven.test.failure.ignore}</testFailureIgnore>
<testNGArtifactName>${testNGArtifactName}</testNGArtifactName>
<testSourceDirectory>${project.build.testSourceDirectory}</testSourceDirectory>
<threadCount>${threadCount}</threadCount>
<threadCountClasses>${threadCountClasses}</threadCountClasses>
<threadCountMethods>${threadCountMethods}</threadCountMethods>
<threadCountSuites>${threadCountSuites}</threadCountSuites>
<trimStackTrace>${trimStackTrace}</trimStackTrace>
<useFile>${surefire.useFile}</useFile>
<useManifestOnlyJar>${surefire.useManifestOnlyJar}</useManifestOnlyJar>
<useSystemClassLoader>${surefire.useSystemClassLoader}</useSystemClassLoader>
<useUnlimitedThreads>${useUnlimitedThreads}</useUnlimitedThreads>
<workingDirectory>${basedir}</workingDirectory>
<project>${project}</project>
<session>${session}</session>
</plugin>
</ExecutionEvent>
<ExecutionEvent type="MojoSucceeded" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-02-03 10:15:13.274">
<project baseDir="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy" file="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy/pom.xml" groupId="org.jenkins-ci.plugins" name="Maven Spy for the Pipeline Maven Integration Plugin" artifactId="pipeline-maven-spy" version="2.0-SNAPSHOT">
<build directory="/Users/cleclerc/git/jenkins/pipeline-maven-plugin/maven-spy/target"/>
</project>
<plugin executionId="default-test" goal="test" groupId="org.apache.maven.plugins" artifactId="maven-surefire-plugin" version="2.19.1">
<reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
</plugin>
</ExecutionEvent>
*/
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
TaskListener listener = context.get(TaskListener.class);
if (listener == null) {
LOGGER.warning("TaskListener is NULL, default to stderr");
listener = new StreamBuildListener((OutputStream) System.err);
}
try {
Class.forName("hudson.tasks.junit.JUnitResultArchiver");
} catch (ClassNotFoundException e) {
listener.getLogger().print("[withMaven] Jenkins ");
listener.hyperlink("http://wiki.jenkins-ci.org/display/JENKINS/JUnit+Plugin", "JUnit Plugin");
listener.getLogger().print(" not found, don't display " + APACHE_GROUP_ID + ":" + SUREFIRE_ID + ":" + SUREFIRE_GOAL);
listener.getLogger().print(" nor " + APACHE_GROUP_ID + ":" + FAILSAFE_ID + ":" + FAILSAFE_GOAL + " results in pipeline screen.");
return;
}
List<Element> sureFireTestEvents = XmlUtils.getExecutionEventsByPlugin(mavenSpyLogsElt, APACHE_GROUP_ID, SUREFIRE_ID, SUREFIRE_GOAL, "MojoSucceeded", "MojoFailed");
List<Element> failSafeTestEvents = XmlUtils.getExecutionEventsByPlugin(mavenSpyLogsElt, APACHE_GROUP_ID, FAILSAFE_ID, FAILSAFE_GOAL, "MojoSucceeded", "MojoFailed");
List<Element> tychoTestEvents = XmlUtils.getExecutionEventsByPlugin(mavenSpyLogsElt, TYCHO_GROUP_ID, TYCHO_ID, TYCHO_GOAL, "MojoSucceeded", "MojoFailed");
List<Element> karmaTestEvents = XmlUtils.getExecutionEventsByPlugin(mavenSpyLogsElt, KARMA_GROUP_ID, KARMA_ID, KARMA_GOAL, "MojoSucceeded", "MojoFailed");
executeReporter(context, listener, sureFireTestEvents, APACHE_GROUP_ID + ":" + SUREFIRE_ID + ":" + SUREFIRE_GOAL);
executeReporter(context, listener, failSafeTestEvents, APACHE_GROUP_ID + ":" + FAILSAFE_ID + ":" + FAILSAFE_GOAL);
executeReporter(context, listener, tychoTestEvents, APACHE_GROUP_ID + ":" + TYCHO_ID + ":" + TYCHO_GOAL);
executeReporter(context, listener, karmaTestEvents, KARMA_GROUP_ID + ":" + KARMA_ID + ":" + KARMA_GOAL);
}
private void executeReporter(StepContext context, TaskListener listener, List<Element> testEvents, String goal) throws IOException, InterruptedException {
FilePath workspace = context.get(FilePath.class);
final String fileSeparatorOnAgent = XmlUtils.getFileSeparatorOnRemote(workspace);
Run run = context.get(Run.class);
Launcher launcher = context.get(Launcher.class);
if (testEvents.isEmpty()) {
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - No " + goal + " execution found");
}
return;
}
List<String> testResultsList = new ArrayList<>();
for (Element testEvent : testEvents) {
Element pluginElt = XmlUtils.getUniqueChildElement(testEvent, "plugin");
Element reportsDirectoryElt = XmlUtils.getUniqueChildElementOrNull(pluginElt, "reportsDirectory");
Element projectElt = XmlUtils.getUniqueChildElement(testEvent, "project");
MavenArtifact mavenArtifact = XmlUtils.newMavenArtifact(projectElt);
MavenSpyLogProcessor.PluginInvocation pluginInvocation = XmlUtils.newPluginInvocation(pluginElt);
if (reportsDirectoryElt == null) {
listener.getLogger().println("[withMaven] No <reportsDirectory> element found for <plugin> in " + XmlUtils.toString(testEvent));
continue;
}
String reportsDirectory = reportsDirectoryElt.getTextContent().trim();
if (reportsDirectory.contains("${project.build.directory}")) {
String projectBuildDirectory = XmlUtils.getProjectBuildDirectory(projectElt);
if (projectBuildDirectory == null || projectBuildDirectory.isEmpty()) {
listener.getLogger().println("[withMaven] '${project.build.directory}' found for <project> in " + XmlUtils.toString(testEvent));
continue;
}
reportsDirectory = reportsDirectory.replace("${project.build.directory}", projectBuildDirectory);
} else if (reportsDirectory.contains("${basedir}")) {
String baseDir = projectElt.getAttribute("baseDir");
if (baseDir.isEmpty()) {
listener.getLogger().println("[withMaven] '${basedir}' found for <project> in " + XmlUtils.toString(testEvent));
continue;
}
reportsDirectory = reportsDirectory.replace("${basedir}", baseDir);
}
reportsDirectory = XmlUtils.getPathInWorkspace(reportsDirectory, workspace);
String testResults = reportsDirectory + fileSeparatorOnAgent + "*.xml";
listener.getLogger().println("[withMaven] junitPublisher - Archive test results for Maven artifact " + mavenArtifact.getId() + " generated by " +
pluginInvocation.getId() + ": " + testResults);
if (testResultsList.contains(testResults)) {
if (LOGGER.isLoggable(Level.FINER)) {
listener.getLogger().println("[withMaven] junitPublisher - Ignore already added testResults " + testResults);
}
} else {
testResultsList.add(testResults);
}
}
String testResults = String.join(",", testResultsList);
JUnitResultArchiver archiver = new JUnitResultArchiver(testResults);
if (healthScaleFactor != null) {
archiver.setHealthScaleFactor(this.healthScaleFactor);
}
archiver.setKeepLongStdio(this.keepLongStdio);
// even if "org.apache.maven.plugins:maven-surefire-plugin@test" succeeds, it maybe with "-DskipTests" and thus not have any test results.
archiver.setAllowEmptyResults(true);
if (Boolean.TRUE.equals(this.ignoreAttachments)) {
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - Ignore junit test attachments");
}
} else {
String className = "hudson.plugins.junitattachments.AttachmentPublisher";
try {
TestDataPublisher attachmentPublisher = (TestDataPublisher) Class.forName(className).newInstance();
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - Publish junit test attachments...");
}
archiver.setTestDataPublishers(Collections.singletonList(attachmentPublisher));
} catch(ClassNotFoundException e){
listener.getLogger().print("[withMaven] junitPublisher - Jenkins ");
listener.hyperlink("https://wiki.jenkins-ci.org/display/JENKINS/JUnit+Attachments+Plugin", "JUnit Attachments Plugin");
listener.getLogger().print(" not found, can't publish test attachments.");
} catch (IllegalAccessException|InstantiationException e) {
PrintWriter err = listener.error("[withMaven] junitPublisher - Failure to publish test attachments, exception instantiating '" + className + "'");
e.printStackTrace(err);
}
}
try {
// see hudson.tasks.junit.pipeline.JUnitResultsStepExecution.run
FlowNode node = context.get(FlowNode.class);
String nodeId = node.getId();
List<FlowNode> enclosingBlocks = JUnitResultsStepExecution.getEnclosingStagesAndParallels(node);
PipelineTestDetails pipelineTestDetails = new PipelineTestDetails();
pipelineTestDetails.setNodeId(nodeId);
pipelineTestDetails.setEnclosingBlocks(JUnitResultsStepExecution.getEnclosingBlockIds(enclosingBlocks));
pipelineTestDetails.setEnclosingBlockNames(JUnitResultsStepExecution.getEnclosingBlockNames(enclosingBlocks));
if (LOGGER.isLoggable(Level.FINER)) {
listener.getLogger().println("[withMaven] junitPublisher - collect test reports: testResults=" + archiver.getTestResults() + ", healthScaleFactor=" + archiver.getHealthScaleFactor());
}
TestResultAction testResultAction = JUnitResultArchiver.parseAndAttach(archiver, pipelineTestDetails, run, workspace, launcher, listener);
if (testResultAction == null) {
// no unit test results found
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - no unit test results found, ignore");
}
} else if (testResultAction.getResult().getFailCount() == 0) {
// unit tests are all successful
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - unit tests are all successful");
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] junitPublisher - " + testResultAction.getResult().getFailCount() + " unit test failure(s) found, mark job as unstable");
}
node.addAction(new WarningAction(Result.UNSTABLE).withMessage(testResultAction.getResult().getFailCount() + " unit test failure(s) found"));
run.setResult(Result.UNSTABLE);
}
} catch (RuntimeException e) {
listener.error("[withMaven] junitPublisher - Silently ignore exception archiving JUnit results:" + testResults + ": " + e);
LOGGER.log(Level.WARNING, "Exception processing " + testResults, e);
}
}
public boolean getIgnoreAttachments() {
return ignoreAttachments;
}
@DataBoundSetter
public void setIgnoreAttachments(boolean ignoreAttachments) {
this.ignoreAttachments = ignoreAttachments;
}
public boolean isKeepLongStdio() {
return keepLongStdio;
}
@DataBoundSetter
public void setKeepLongStdio(boolean keepLongStdio) {
this.keepLongStdio = keepLongStdio;
}
@CheckForNull
public Double getHealthScaleFactor() {
return healthScaleFactor;
}
@DataBoundSetter
public void setHealthScaleFactor(@Nullable Double healthScaleFactor) {
this.healthScaleFactor = healthScaleFactor;
}
@Override
public String toString() {
return "JunitTestsPublisher[" +
"disabled=" + isDisabled() + "," +
"healthScaleFactor=" + (healthScaleFactor == null ? "" : healthScaleFactor) + "," +
"keepLongStdio=" + keepLongStdio + "," +
"ignoreAttachments=" + ignoreAttachments +
']';
}
/**
* Don't use the symbol "junit", it would collide with hudson.tasks.junit.JUnitResultArchiver
*/
@Symbol("junitPublisher")
@Extension
public static class DescriptorImpl extends MavenPublisher.DescriptorImpl {
@Nonnull
@Override
public String getDisplayName() {
return "Junit Publisher";
}
@Override
public int ordinal() {
return 10;
}
@Nonnull
@Override
public String getSkipFileName() {
return ".skip-publish-junit-results";
}
}
}
|
package com.foilen.smalltools.filesystemupdatewatcher;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.foilen.smalltools.exception.SmallToolsException;
import com.foilen.smalltools.tools.AssertTools;
/**
* This class is looking at any changes made to any file in the directory and their sub-directory if needed.
*
* On initialization, it creates a separate thread that will call the observers when new events are ready.
*
* Default:
* <ul>
* <li>recursive = false</li>
* </ul>
*/
public class FileSystemUpdateWatcher extends Thread {
// Options
private Path basePath;
private boolean recursive = false;
// Internals
private boolean initialized = false;
private WatchService fsWatchService;
private List<FileSystemUpdateHandler> fileSystemUpdateHandlers = new ArrayList<>();
private Map<WatchKey, Path> pathByKey = new HashMap<WatchKey, Path>();
public FileSystemUpdateWatcher(File basePath) {
this.basePath = basePath.toPath();
}
public FileSystemUpdateWatcher(Path basePath) {
this.basePath = basePath;
}
public FileSystemUpdateWatcher(String basePath) {
this.basePath = Paths.get(basePath);
}
/**
* Add an handler.
*
* @param fileSystemUpdateHandler
* the handler
* @return this
*/
public FileSystemUpdateWatcher addHandler(FileSystemUpdateHandler fileSystemUpdateHandler) {
fileSystemUpdateHandlers.add(fileSystemUpdateHandler);
return this;
}
/**
* Call after setting this object to make it work.
*
* @return this
*/
public FileSystemUpdateWatcher init() {
AssertTools.assertFalse(initialized, "Already initialized");
AssertTools.assertFalse(fileSystemUpdateHandlers.isEmpty(), "There are no handlers");
// Register the directories
try {
fsWatchService = FileSystems.getDefault().newWatchService();
registerRecursively(basePath);
} catch (IOException e) {
throw new SmallToolsException(e);
}
// Start the watch thread
start();
initialized = true;
return this;
}
/**
* Tells if the watch is recursive.
*
* @return recursive
*/
public boolean isRecursive() {
return recursive;
}
/**
* Register a new path to check.
*
* @param path
* the path
*/
protected void register(Path path) {
File directory = path.toFile();
AssertTools.assertTrue(directory.exists(), "The directory must exists prior to watching. Path: " + path);
AssertTools.assertTrue(directory.isDirectory(), "The path must be a directory. Path: " + path);
try {
WatchKey key = path.register(fsWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
pathByKey.put(key, path);
} catch (IOException e) {
throw new SmallToolsException(e);
}
}
/**
* Register a new path to check and all its children if it is set recursive.
*
* @param path
* the path
*/
private void registerRecursively(Path path) {
register(path);
File file = path.toFile();
if (recursive && file.isDirectory()) {
// Go through sub-folders
for (File sub : file.listFiles()) {
if (sub.isDirectory()) {
registerRecursively(sub.toPath());
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public void run() {
for (;;) {
// Wait for the next event
WatchKey key;
try {
key = fsWatchService.take();
} catch (InterruptedException e) {
throw new SmallToolsException(e);
}
// Go through all the events
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
// Check the path
Path completePath = pathByKey.get(key).resolve(pathEvent.context());
File completeFile = completePath.toFile();
// Check the event
WatchEvent.Kind<Path> kind = pathEvent.kind();
if (StandardWatchEventKinds.OVERFLOW.equals(kind)) {
continue;
} else if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
// Check if is a directory and we want to register it
if (recursive && Files.isDirectory(completePath, LinkOption.NOFOLLOW_LINKS)) {
registerRecursively(completePath);
}
for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
handler.created(completeFile);
}
} else if (StandardWatchEventKinds.ENTRY_MODIFY.equals(kind)) {
for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
handler.modified(completeFile);
}
} else if (StandardWatchEventKinds.ENTRY_DELETE.equals(kind)) {
for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
handler.deleted(completeFile);
}
}
}
// Reset
if (!key.reset()) {
pathByKey.remove(key);
}
}
}
/**
* Change the recursive parameter.
*
* @param recursive
* true to watch the subfolders as well
* @return this
*/
public FileSystemUpdateWatcher setRecursive(boolean recursive) {
AssertTools.assertFalse(initialized, "Cannot set recursive when already initialized");
this.recursive = recursive;
return this;
}
}
|
package org.languagetool.rules.spelling.morfologik;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.Categories;
import org.languagetool.rules.ITSIssueType;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.SuggestedReplacement;
import org.languagetool.rules.spelling.SpellingCheckRule;
import org.languagetool.rules.spelling.suggestions.SuggestionsChanges;
import org.languagetool.rules.spelling.suggestions.SuggestionsOrderer;
import org.languagetool.rules.spelling.suggestions.SuggestionsOrdererFeatureExtractor;
import org.languagetool.rules.spelling.suggestions.XGBoostSuggestionsOrderer;
import org.languagetool.rules.translation.TranslationEntry;
import org.languagetool.rules.translation.Translator;
import org.languagetool.tools.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.languagetool.JLanguageTool.*;
public abstract class MorfologikSpellerRule extends SpellingCheckRule {
private static Logger logger = LoggerFactory.getLogger(MorfologikSpellerRule.class);
protected MorfologikMultiSpeller speller1;
protected MorfologikMultiSpeller speller2;
protected MorfologikMultiSpeller speller3;
protected Locale conversionLocale;
protected final Language motherTongue;
protected final GlobalConfig globalConfig;
private final SuggestionsOrderer suggestionsOrderer;
private final boolean runningExperiment;
private boolean ignoreTaggedWords = false;
private boolean checkCompound = false;
private Pattern compoundRegex = Pattern.compile("-");
private final UserConfig userConfig;
static final int MAX_FREQUENCY_FOR_SPLITTING = 21; //0..21
/**
* Get the filename, e.g., <tt>/resource/pl/spelling.dict</tt>.
*/
public abstract String getFileName();
@Override
public abstract String getId();
public MorfologikSpellerRule(ResourceBundle messages, Language language) throws IOException {
this(messages, language, null);
}
public MorfologikSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig) throws IOException {
this(messages, language, userConfig, Collections.emptyList());
}
public MorfologikSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
this(messages, language, null, userConfig, altLanguages, null, null);
}
public MorfologikSpellerRule(ResourceBundle messages, Language language, GlobalConfig globalConfig, UserConfig userConfig,
List<Language> altLanguages, LanguageModel languageModel, Language motherTongue) throws IOException {
super(messages, language, userConfig, altLanguages, languageModel);
this.globalConfig = globalConfig;
this.userConfig = userConfig;
this.motherTongue = motherTongue;
super.setCategory(Categories.TYPOS.getCategory(messages));
this.conversionLocale = conversionLocale != null ? conversionLocale : Locale.getDefault();
init();
setLocQualityIssueType(ITSIssueType.Misspelling);
if (SuggestionsChanges.isRunningExperiment("NewSuggestionsOrderer")) {
suggestionsOrderer = new SuggestionsOrdererFeatureExtractor(language, this.languageModel);
runningExperiment = true;
} else {
runningExperiment = false;
suggestionsOrderer = new XGBoostSuggestionsOrderer(language, languageModel);
}
}
@Override
public String getDescription() {
return messages.getString("desc_spelling");
}
public void setLocale(Locale locale) {
conversionLocale = locale;
}
/**
* Skip words that are known in the POS tagging dictionary, assuming they
* cannot be incorrect.
*/
public void setIgnoreTaggedWords() {
ignoreTaggedWords = true;
}
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace();
if (initSpellers()) return toRuleMatchArray(ruleMatches);
int idx = -1;
for (AnalyzedTokenReadings token : tokens) {
idx++;
if (canBeIgnored(tokens, idx, token)) {
continue;
}
int startPos = token.getStartPos();
// if we use token.getToken() we'll get ignored characters inside and speller will choke
String word = token.getAnalyzedToken(0).getToken();
int newRuleIdx = ruleMatches.size();
if (tokenizingPattern() == null) {
ruleMatches.addAll(getRuleMatches(word, startPos, sentence, ruleMatches, idx, tokens));
} else {
int index = 0;
Matcher m = tokenizingPattern().matcher(word);
while (m.find()) {
String match = word.subSequence(index, m.start()).toString();
ruleMatches.addAll(getRuleMatches(match, startPos + index, sentence, ruleMatches, idx, tokens));
index = m.end();
}
if (index == 0) { // tokenizing char not found
ruleMatches.addAll(getRuleMatches(word, startPos, sentence, ruleMatches, idx, tokens));
} else {
ruleMatches.addAll(getRuleMatches(word.subSequence(index, word.length()).toString(), startPos + index, sentence, ruleMatches, idx, tokens));
}
}
if (ruleMatches.size() > newRuleIdx) {
// matches added for current token - need to adjust for hidden characters
int hiddenCharOffset = token.getToken().length() - word.length();
if (hiddenCharOffset > 0) {
for (int i = newRuleIdx; i < ruleMatches.size(); i++) {
RuleMatch ruleMatch = ruleMatches.get(i);
if( token.getEndPos() < ruleMatch.getToPos() ) // done by multi-token speller, no need to adjust
continue;
ruleMatch.setOffsetPosition(ruleMatch.getFromPos(), ruleMatch.getToPos()+hiddenCharOffset);
}
}
}
}
return toRuleMatchArray(ruleMatches);
}
@Nullable
protected Translator getTranslator(GlobalConfig globalConfig) throws IOException {
return null;
}
private boolean initSpellers() throws IOException {
if (speller1 == null) {
String binaryDict = null;
if (getDataBroker().resourceExists(getFileName()) || Paths.get(getFileName()).toFile().exists()) {
binaryDict = getFileName();
}
if (binaryDict != null) {
initSpeller(binaryDict);
} else {
// should not happen, as we only configure this rule (or rather its subclasses)
// when we have the resources:
return true;
}
}
return false;
}
private void initSpeller(String binaryDict) throws IOException {
List<String> plainTextDicts = new ArrayList<>();
String languageVariantPlainTextDict = null;
if (getSpellingFileName() != null && getDataBroker().resourceExists(getSpellingFileName())) {
plainTextDicts.add(getSpellingFileName());
}
for (String fileName : getAdditionalSpellingFileNames()) {
if (getDataBroker().resourceExists(fileName)) {
plainTextDicts.add(fileName);
}
}
if (getLanguageVariantSpellingFileName() != null && getDataBroker().resourceExists(getLanguageVariantSpellingFileName())) {
languageVariantPlainTextDict = getLanguageVariantSpellingFileName();
}
speller1 = new MorfologikMultiSpeller(binaryDict, plainTextDicts, languageVariantPlainTextDict, userConfig, 1);
speller2 = new MorfologikMultiSpeller(binaryDict, plainTextDicts, languageVariantPlainTextDict, userConfig, 2);
speller3 = new MorfologikMultiSpeller(binaryDict, plainTextDicts, languageVariantPlainTextDict, userConfig, 3);
setConvertsCase(speller1.convertsCase());
}
private boolean canBeIgnored(AnalyzedTokenReadings[] tokens, int idx, AnalyzedTokenReadings token) throws IOException {
return token.isSentenceStart() ||
token.isImmunized() ||
token.isIgnoredBySpeller() ||
isUrl(token.getToken()) ||
isEMail(token.getToken()) ||
(ignoreTaggedWords && token.isTagged() && !isProhibited(token.getToken())) ||
ignoreToken(tokens, idx);
}
/**
* @since 4.8
*/
@Experimental
@Override
public boolean isMisspelled(String word) throws IOException {
initSpellers();
return isMisspelled(speller1, word);
}
/**
* @return true if the word is misspelled
* @since 2.4
*/
protected boolean isMisspelled(MorfologikMultiSpeller speller, String word) {
if (!speller.isMisspelled(word)) {
return false;
}
if (checkCompound && compoundRegex.matcher(word).find()) {
String[] words = compoundRegex.split(word);
for (String singleWord: words) {
if (speller.isMisspelled(singleWord)) {
return true;
}
}
return false;
}
return true;
}
protected int getFrequency(MorfologikMultiSpeller speller, String word) {
return speller.getFrequency(word);
}
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException {
// We create only one rule match.
// Several rule matches on the same word or words can not be shown to the user.
List<RuleMatch> ruleMatches = new ArrayList<>();
RuleMatch ruleMatch = null;
if (!isMisspelled(speller1, word) && !isProhibited(word)) {
return ruleMatches;
}
//the current word is already dealt with in the previous match, so do nothing
if (ruleMatchesSoFar.size() > 0 && ruleMatchesSoFar.get(ruleMatchesSoFar.size() - 1).getToPos() > startPos) {
return ruleMatches;
}
String beforeSuggestionStr = ""; //to be added before the suggestion if there is a suggestion for a split word
String afterSuggestionStr = ""; //to be added after
// Check for split word with previous word
if (idx > 0) {
String prevWord = tokens[idx - 1].getToken();
if (prevWord.length() > 0 && !prevWord.matches(".*\\d.*")
&& getFrequency(speller1, prevWord) < MAX_FREQUENCY_FOR_SPLITTING) {
int prevStartPos = tokens[idx - 1].getStartPos();
// "thanky ou" -> "thank you"
String sugg1a = prevWord.substring(0, prevWord.length() - 1);
String sugg1b = prevWord.substring(prevWord.length() - 1) + word;
if (sugg1a.length() > 1 && sugg1b.length() > 2 && !isMisspelled(speller1, sugg1a)
&& !isMisspelled(speller1, sugg1b)
&& getFrequency(speller1, sugg1a) + getFrequency(speller1, sugg1b) > getFrequency(speller1, prevWord)) {
ruleMatch = createWrongSplitMatch(sentence, ruleMatchesSoFar, startPos, word, sugg1a, sugg1b, prevStartPos);
beforeSuggestionStr = prevWord + " ";
}
// "than kyou" -> "thank you" ; but not "She awaked" -> "Shea waked"
String sugg2a = prevWord + word.substring(0, 1);
String sugg2b = word.substring(1);
if (sugg2a.length() > 1 && sugg2b.length() > 2 && !isMisspelled(speller1, sugg2a)
&& !isMisspelled(speller1, sugg2b)) {
if (ruleMatch == null) {
if (getFrequency(speller1, sugg2a) + getFrequency(speller1, sugg2b) > getFrequency(speller1, prevWord)) {
ruleMatch = createWrongSplitMatch(sentence, ruleMatchesSoFar, startPos, word, sugg2a, sugg2b,
prevStartPos);
beforeSuggestionStr = prevWord + " ";
}
} else {
ruleMatch.addSuggestedReplacement((sugg2a + " " + sugg2b).trim());
}
}
// "g oing-> "going"
String sugg = prevWord + word;
if (word.equals(word.toLowerCase()) && !isMisspelled(speller1, sugg)) {
if (ruleMatch == null) {
if (getFrequency(speller1, sugg) >= getFrequency(speller1, prevWord)) {
ruleMatch = new RuleMatch(this, sentence, prevStartPos, startPos + word.length(),
messages.getString("spelling"), messages.getString("desc_spelling_short"));
beforeSuggestionStr = prevWord + " ";
ruleMatch.setSuggestedReplacement(sugg);
}
} else {
ruleMatch.addSuggestedReplacement(sugg);
}
}
if (ruleMatch != null && isMisspelled(speller1, prevWord)) {
ruleMatches.add(ruleMatch);
return ruleMatches;
}
}
}
// Check for split word with next word
if (ruleMatch == null && idx < tokens.length - 1) {
String nextWord = tokens[idx + 1].getToken();
if (nextWord.length() > 0 && !nextWord.matches(".*\\d.*")
&& getFrequency(speller1, nextWord) < MAX_FREQUENCY_FOR_SPLITTING) {
int nextStartPos = tokens[idx + 1].getStartPos();
String sugg1a = word.substring(0, word.length() - 1);
String sugg1b = word.substring(word.length() - 1) + nextWord;
if (sugg1a.length() > 1 && sugg1b.length() > 2 && !isMisspelled(speller1, sugg1a) && !isMisspelled(speller1, sugg1b) &&
getFrequency(speller1, sugg1a) + getFrequency(speller1, sugg1b) > getFrequency(speller1, nextWord)) {
ruleMatch = createWrongSplitMatch(sentence, ruleMatchesSoFar, nextStartPos, nextWord, sugg1a, sugg1b, startPos);
afterSuggestionStr = " " + nextWord;
}
String sugg2a = word + nextWord.substring(0, 1);
String sugg2b = nextWord.substring(1);
if (sugg2a.length() > 1 && sugg2b.length() > 2 && !isMisspelled(speller1, sugg2a) && !isMisspelled(speller1, sugg2b)) {
if (ruleMatch == null) {
if (getFrequency(speller1, sugg2a) + getFrequency(speller1, sugg2b) > getFrequency(speller1, nextWord)) {
ruleMatch = createWrongSplitMatch(sentence, ruleMatchesSoFar, nextStartPos, nextWord, sugg2a, sugg2b, startPos);
afterSuggestionStr = " " + nextWord;
}
} else {
ruleMatch.addSuggestedReplacement((sugg2a + " " + sugg2b).trim());
}
}
String sugg = word + nextWord;
if (nextWord.equals(nextWord.toLowerCase()) && !isMisspelled(speller1, sugg)) {
if (ruleMatch == null) {
if (getFrequency(speller1, sugg) >= getFrequency(speller1, nextWord)) {
ruleMatch = new RuleMatch(this, sentence, startPos, nextStartPos + nextWord.length(),
messages.getString("spelling"), messages.getString("desc_spelling_short"));
afterSuggestionStr = " " + nextWord;
ruleMatch.setSuggestedReplacement(sugg);
}
} else {
ruleMatch.addSuggestedReplacement(sugg);
}
}
if (ruleMatch != null && isMisspelled(speller1, nextWord)) {
ruleMatches.add(ruleMatch);
return ruleMatches;
}
}
}
int translationSuggestionCount = 0;
boolean preventFurtherSuggestions = false;
Translator translator = getTranslator(globalConfig);
if (translator != null && ruleMatch == null && motherTongue != null &&
language.getShortCode().equals("en") && motherTongue.getShortCode().equals("de")) {
List<PhraseToTranslate> phrasesToTranslate = new ArrayList<>();
if (idx + 1 < tokens.length) {
String nextWord = tokens[idx + 1].getToken();
if (isMisspelled(nextWord)) {
phrasesToTranslate.add(new PhraseToTranslate(word + " " + nextWord, tokens[idx + 1].getEndPos()));
}
}
phrasesToTranslate.add(new PhraseToTranslate(word, startPos + word.length()));
for (PhraseToTranslate phraseToTranslate : phrasesToTranslate) {
List<TranslationEntry> translations = translator.translate(phraseToTranslate.phrase, motherTongue.getShortCode(), language.getShortCode());
if (translations.size() > 0) {
logger.info("Translated: " + word); // privacy: logging a single word without IP address etc. is okay
ruleMatch = new RuleMatch(this, sentence, startPos, phraseToTranslate.endPos, translator.getMessage());
ruleMatch.setType(RuleMatch.Type.Hint);
ruleMatch.setSuggestedReplacements(new ArrayList<>());
List<SuggestedReplacement> l = new ArrayList<>();
String prevWord = idx > 0 ? tokens[idx-1].getToken() : null;
for (TranslationEntry translation : translations) {
for (String s : translation.getL2()) {
String suffix = translator.getTranslationSuffix(s);
SuggestedReplacement repl = new SuggestedReplacement(translator.cleanTranslationForReplace(s, prevWord), String.join(", ", translation.getL1()), suffix.isEmpty() ? null : suffix);
repl.setType(SuggestedReplacement.SuggestionType.Translation);
l.add(repl);
}
}
List<SuggestedReplacement> mergedRepl = mergeSuggestionsWithSameTranslation(l);
if (mergedRepl.size() > 0) {
ruleMatch.setSuggestedReplacementObjects(mergedRepl);
translationSuggestionCount = mergedRepl.size();
if (phraseToTranslate.phrase.contains(" ")) {
preventFurtherSuggestions = true; // mark gets extended, so suggestions for the original marker won't make sense
}
break; // let's assume the first phrase is the best because it's longer
}
}
}
}
if (ruleMatch == null) {
Language acceptingLanguage = acceptedInAlternativeLanguage(word);
if (acceptingLanguage != null) {
// e.g. "Der Typ ist in UK echt famous" -> could be German 'famos'
ruleMatch = new RuleMatch(this, sentence, startPos, startPos + word.length(),
Tools.i18n(messages, "accepted_in_alt_language", word, messages.getString(acceptingLanguage.getShortCode())));
ruleMatch.setType(RuleMatch.Type.Hint);
} else {
ruleMatch = new RuleMatch(this, sentence, startPos, startPos + word.length(), messages.getString("spelling"),
messages.getString("desc_spelling_short"));
}
}
boolean fullResults = SuggestionsChanges.getInstance() != null &&
SuggestionsChanges.getInstance().getCurrentExperiment() != null &&
(boolean) SuggestionsChanges.getInstance().getCurrentExperiment()
.parameters.getOrDefault("fullSuggestionCandidates", Boolean.FALSE);
if (userConfig == null || userConfig.getMaxSpellingSuggestions() == 0
|| ruleMatchesSoFar.size() <= userConfig.getMaxSpellingSuggestions()) {
List<String> defaultSuggestions = speller1.getSuggestionsFromDefaultDicts(word);
List<String> userSuggestions = speller1.getSuggestionsFromUserDicts(word);
//System.out.println("speller1: " + suggestions);
if (word.length() >= 3 && (fullResults || defaultSuggestions.isEmpty())) {
// speller1 uses a maximum edit distance of 1, it won't find suggestion for "garentee", "greatful" etc.
//System.out.println("speller2: " + speller2.getSuggestions(word));
defaultSuggestions.addAll(speller2.getSuggestionsFromDefaultDicts(word));
userSuggestions.addAll(speller2.getSuggestionsFromUserDicts(word));
if (word.length() >= 5 && (fullResults || defaultSuggestions.isEmpty())) {
//System.out.println("speller3: " + speller3.getSuggestions(word));
defaultSuggestions.addAll(speller3.getSuggestionsFromDefaultDicts(word));
userSuggestions.addAll(speller3.getSuggestionsFromUserDicts(word));
}
}
//System.out.println("getAdditionalTopSuggestions(suggestions, word): " + getAdditionalTopSuggestions(suggestions, word));
defaultSuggestions.addAll(0, getAdditionalTopSuggestions(defaultSuggestions, word));
//System.out.println("getAdditionalSuggestions(suggestions, word): " + getAdditionalSuggestions(suggestions, word));
defaultSuggestions.addAll(getAdditionalSuggestions(defaultSuggestions, word));
if (!(defaultSuggestions.isEmpty() && userSuggestions.isEmpty()) && !preventFurtherSuggestions) {
defaultSuggestions = filterSuggestions(defaultSuggestions, sentence, idx);
filterDupes(userSuggestions);
defaultSuggestions = orderSuggestions(defaultSuggestions, word);
defaultSuggestions = joinBeforeAfterSuggestions(defaultSuggestions, beforeSuggestionStr, afterSuggestionStr);
userSuggestions = joinBeforeAfterSuggestions(userSuggestions, beforeSuggestionStr, afterSuggestionStr);
// use suggestionsOrderer only w/ A/B - Testing or manually enabled experiments
if (runningExperiment) {
addSuggestionsToRuleMatch(word,
userSuggestions, defaultSuggestions, suggestionsOrderer, ruleMatch);
} else if (userConfig != null && userConfig.getAbTest() != null &&
userConfig.getAbTest().equals("SuggestionsRanker") &&
suggestionsOrderer.isMlAvailable() && userConfig.getTextSessionId() != null) {
boolean testingA = userConfig.getTextSessionId() % 2 == 0;
if (testingA) {
addSuggestionsToRuleMatch(word, userSuggestions, defaultSuggestions, null, ruleMatch);
} else {
addSuggestionsToRuleMatch(word, userSuggestions, defaultSuggestions, suggestionsOrderer, ruleMatch);
}
} else {
addSuggestionsToRuleMatch(word, userSuggestions, defaultSuggestions, null, ruleMatch);
}
if (translationSuggestionCount > 0 && ruleMatch.getSuggestedReplacements().size() > translationSuggestionCount) {
RuleMatch newRuleMatch = new RuleMatch(ruleMatch.getRule(), ruleMatch.getSentence(), ruleMatch.getFromPos(), ruleMatch.getToPos(),
messages.getString("spelling") + " Translations to English are also offered.");
newRuleMatch.setSuggestedReplacementObjects(ruleMatch.getSuggestedReplacementObjects());
ruleMatch = newRuleMatch;
}
}
} else {
// limited to save CPU
ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors"));
}
ruleMatches.add(ruleMatch);
return ruleMatches;
}
@NotNull
private List<SuggestedReplacement> mergeSuggestionsWithSameTranslation(List<SuggestedReplacement> l) {
List<SuggestedReplacement> mergedRepl = new ArrayList<>();
Set<String> handledReplacements = new HashSet<>();
for (SuggestedReplacement repl : l) {
List<SuggestedReplacement> sameRepl = l.stream()
.filter(k -> k.getReplacement().equals(repl.getReplacement()))
.filter(k -> k.getSuffix() == null || (k.getSuffix() != null && k.getSuffix().equals(repl.getSuffix())))
.collect(Collectors.toList());
if (sameRepl.size() > 1) {
if (handledReplacements.contains(repl.getReplacement())) {
// skip
} else {
List<String> joinedRepls = new ArrayList<>();
for (SuggestedReplacement r : sameRepl) {
joinedRepls.add("* " + r.getShortDescription());
}
mergedRepl.add(new SuggestedReplacement(repl.getReplacement(), String.join("\n", joinedRepls), repl.getSuffix()));
handledReplacements.add(repl.getReplacement());
}
} else {
mergedRepl.add(repl);
}
}
return mergedRepl;
}
/**
* Get the regular expression pattern used to tokenize
* the words as in the source dictionary. For example,
* it may contain a hyphen, if the words with hyphens are
* not included in the dictionary
* @return A compiled {@link Pattern} that is used to tokenize words or {@code null}.
*/
@Nullable
public Pattern tokenizingPattern() {
return null;
}
protected List<String> orderSuggestions(List<String> suggestions, String word) {
return suggestions;
}
private List<String> orderSuggestions(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) {
List<String> orderedSuggestions;
if (userConfig != null && userConfig.getAbTest() != null && userConfig.getAbTest().equals("SuggestionsOrderer") &&
suggestionsOrderer.isMlAvailable() && userConfig.getTextSessionId() != null) {
boolean logGroup = Math.random() < 0.01;
if (logGroup) {
System.out.print("Running A/B-Test for SuggestionsOrderer ->");
}
if (userConfig.getTextSessionId() % 2 == 0) {
if (logGroup) {
System.out.println("in group A (using new ordering)");
}
orderedSuggestions = suggestionsOrderer.orderSuggestionsUsingModel(suggestions, word, sentence, startPos);
} else {
if (logGroup) {
System.out.println("in group B (using old ordering)");
}
orderedSuggestions = orderSuggestions(suggestions, word);
}
} else {
if (suggestionsOrderer.isMlAvailable()) {
orderedSuggestions = suggestionsOrderer.orderSuggestionsUsingModel(suggestions, word, sentence, startPos);
} else {
orderedSuggestions = orderSuggestions(suggestions, word);
}
}
return orderedSuggestions;
}
/**
* @param checkCompound If true and the word is not in the dictionary
* it will be split (see {@link #setCompoundRegex(String)})
* and each component will be checked separately
* @since 2.4
*/
protected void setCheckCompound(boolean checkCompound) {
this.checkCompound = checkCompound;
}
/**
* @param compoundRegex see {@link #setCheckCompound(boolean)}
* @since 2.4
*/
protected void setCompoundRegex(String compoundRegex) {
this.compoundRegex = Pattern.compile(compoundRegex);
}
/**
* Checks whether a given String consists only of surrogate pairs.
* @param word to be checked
* @since 4.2
*/
protected boolean isSurrogatePairCombination (String word) {
if (word.length() > 1 && word.length() % 2 == 0 && word.codePointCount(0, word.length()) != word.length()) {
// some symbols such as emojis () have a string length that equals 2
boolean isSurrogatePairCombination = true;
for (int i = 0; i < word.length() && isSurrogatePairCombination; i += 2) {
isSurrogatePairCombination &= Character.isSurrogatePair(word.charAt(i), word.charAt(i + 1));
}
return isSurrogatePairCombination;
}
return false;
}
/**
* Ignore surrogate pairs (emojis)
* @since 4.3
* @see org.languagetool.rules.spelling.SpellingCheckRule#ignoreWord(java.lang.String)
*/
@Override
protected boolean ignoreWord(String word) throws IOException {
return super.ignoreWord(word) || isSurrogatePairCombination(word);
}
/**
*
* Join strings before and after a suggestion.
* Used when there is also suggestion for split words
* Ex. to thow > tot how | to throw
*
*/
private List<String> joinBeforeAfterSuggestions(List<String> suggestionsList, String beforeSuggestionStr,
String afterSuggestionStr) {
List<String> newSuggestionsList = new ArrayList<>();
for (String str : suggestionsList) {
newSuggestionsList.add(beforeSuggestionStr + str + afterSuggestionStr);
}
return newSuggestionsList;
}
static class PhraseToTranslate {
String phrase;
int endPos;
PhraseToTranslate(String phrase, int endPos) {
this.phrase = phrase;
this.endPos = endPos;
}
}
}
|
package org.libreplan.web.planner.allocation;
import static org.libreplan.web.I18nHelper._;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.libreplan.business.planner.entities.AggregateOfResourceAllocations;
import org.libreplan.business.planner.entities.AssignmentFunction;
import org.libreplan.business.planner.entities.AssignmentFunction.AssignmentFunctionName;
import org.libreplan.business.planner.entities.CalculatedValue;
import org.libreplan.business.planner.entities.GenericResourceAllocation;
import org.libreplan.business.planner.entities.ManualFunction;
import org.libreplan.business.planner.entities.ResourceAllocation;
import org.libreplan.business.planner.entities.SigmoidFunction;
import org.libreplan.business.planner.entities.SpecificResourceAllocation;
import org.libreplan.business.planner.entities.StretchesFunctionTypeEnum;
import org.libreplan.business.planner.entities.Task;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.business.resources.entities.Criterion;
import org.libreplan.business.workingday.EffortDuration;
import org.libreplan.web.common.EffortDurationBox;
import org.libreplan.web.common.IMessagesForUser;
import org.libreplan.web.common.MessagesForUser;
import org.libreplan.web.common.OnlyOneVisible;
import org.libreplan.web.common.Util;
import org.libreplan.web.planner.allocation.streches.StrechesFunctionConfiguration;
import org.zkoss.ganttz.timetracker.ICellForDetailItemRenderer;
import org.zkoss.ganttz.timetracker.IConvertibleToColumn;
import org.zkoss.ganttz.timetracker.PairOfLists;
import org.zkoss.ganttz.timetracker.TimeTrackedTable;
import org.zkoss.ganttz.timetracker.TimeTrackedTableWithLeftPane;
import org.zkoss.ganttz.timetracker.TimeTracker;
import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter;
import org.zkoss.ganttz.timetracker.TimeTrackerComponentWithoutColumns;
import org.zkoss.ganttz.timetracker.zoom.DetailItem;
import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.ganttz.util.Interval;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Div;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.LayoutRegion;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.api.Column;
public class AdvancedAllocationController extends GenericForwardComposer {
public static class AllocationInput {
private final AggregateOfResourceAllocations aggregate;
private final IAdvanceAllocationResultReceiver resultReceiver;
private final TaskElement task;
public AllocationInput(AggregateOfResourceAllocations aggregate,
TaskElement task,
IAdvanceAllocationResultReceiver resultReceiver) {
Validate.notNull(aggregate);
Validate.notNull(resultReceiver);
Validate.notNull(task);
this.aggregate = aggregate;
this.task = task;
this.resultReceiver = resultReceiver;
}
List<ResourceAllocation<?>> getAllocationsSortedByStartDate() {
return getAggregate().getAllocationsSortedByStartDate();
}
EffortDuration getTotalEffort() {
return getAggregate().getTotalEffort();
}
AggregateOfResourceAllocations getAggregate() {
return aggregate;
}
String getTaskName() {
return task.getName();
}
IAdvanceAllocationResultReceiver getResultReceiver() {
return resultReceiver;
}
Interval calculateInterval() {
List<ResourceAllocation<?>> all = getAllocationsSortedByStartDate();
if (all.isEmpty()) {
return new Interval(task.getStartDate(), task
.getEndDate());
} else {
LocalDate start = min(all.get(0)
.getStartConsideringAssignments(), all.get(0)
.getStartDate());
LocalDate taskEndDate = LocalDate.fromDateFields(task
.getEndDate());
LocalDate end = max(getEnd(all), taskEndDate);
return new Interval(asDate(start), asDate(end));
}
}
private LocalDate min(LocalDate... dates) {
return Collections.min(Arrays.asList(dates), null);
}
private LocalDate max(LocalDate... dates) {
return Collections.max(Arrays.asList(dates), null);
}
private static LocalDate getEnd(List<ResourceAllocation<?>> all) {
ArrayList<ResourceAllocation<?>> reversed = reverse(all);
LocalDate end = reversed.get(0).getEndDate();
ListIterator<ResourceAllocation<?>> listIterator = reversed
.listIterator(1);
while (listIterator.hasNext()) {
ResourceAllocation<?> current = listIterator.next();
if (current.getEndDate().compareTo(end) >= 0) {
end = current.getEndDate();
} else {
return end;
}
}
return end;
}
private static ArrayList<ResourceAllocation<?>> reverse(
List<ResourceAllocation<?>> all) {
ArrayList<ResourceAllocation<?>> reversed = new ArrayList<ResourceAllocation<?>>(
all);
Collections.reverse(reversed);
return reversed;
}
private static Date asDate(LocalDate start) {
return start.toDateMidnight().toDate();
}
}
public interface IAdvanceAllocationResultReceiver {
public Restriction createRestriction();
public void accepted(AggregateOfResourceAllocations modifiedAllocations);
public void cancel();
}
public interface IBack {
public void goBack();
boolean isAdvanceAssignmentOfSingleTask();
}
public abstract static class Restriction {
public interface IRestrictionSource {
EffortDuration getTotalEffort();
LocalDate getStart();
LocalDate getEnd();
CalculatedValue getCalculatedValue();
}
public static Restriction build(IRestrictionSource restrictionSource) {
switch (restrictionSource.getCalculatedValue()) {
case END_DATE:
return Restriction.emptyRestriction();
case NUMBER_OF_HOURS:
return Restriction.onlyAssignOnInterval(restrictionSource
.getStart(), restrictionSource.getEnd());
case RESOURCES_PER_DAY:
return Restriction.emptyRestriction();
default:
throw new RuntimeException("unhandled case: "
+ restrictionSource.getCalculatedValue());
}
}
private static Restriction emptyRestriction() {
return new NoRestriction();
}
private static Restriction onlyAssignOnInterval(LocalDate start,
LocalDate end){
return new OnlyOnIntervalRestriction(start, end);
}
abstract LocalDate limitStartDate(LocalDate startDate);
abstract LocalDate limitEndDate(LocalDate localDate);
abstract boolean isDisabledEditionOn(DetailItem item);
public abstract boolean isInvalidTotalEffort(EffortDuration totalEffort);
public abstract void showInvalidEffort(IMessagesForUser messages,
EffortDuration totalEffort);
public abstract void markInvalidEffort(Row groupingRow,
EffortDuration currentEffort);
}
private static class OnlyOnIntervalRestriction extends Restriction {
private final LocalDate start;
private final LocalDate end;
private OnlyOnIntervalRestriction(LocalDate start, LocalDate end) {
super();
this.start = start;
this.end = end;
}
private org.joda.time.Interval intervalAllowed() {
return new org.joda.time.Interval(start.toDateTimeAtStartOfDay(),
end.toDateTimeAtStartOfDay());
}
@Override
boolean isDisabledEditionOn(DetailItem item) {
return !intervalAllowed().overlaps(
new org.joda.time.Interval(item.getStartDate(), item
.getEndDate()));
}
@Override
public boolean isInvalidTotalEffort(EffortDuration totalEffort) {
return false;
}
@Override
LocalDate limitEndDate(LocalDate argEnd) {
return end.compareTo(argEnd) < 0 ? end : argEnd;
}
@Override
LocalDate limitStartDate(LocalDate argStart) {
return start.compareTo(argStart) > 0 ? start : argStart;
}
@Override
public void showInvalidEffort(IMessagesForUser messages,
EffortDuration totalEffort) {
throw new UnsupportedOperationException();
}
@Override
public void markInvalidEffort(Row groupingRow,
EffortDuration currentEffort) {
throw new UnsupportedOperationException();
}
}
private static class NoRestriction extends Restriction {
@Override
boolean isDisabledEditionOn(DetailItem item) {
return false;
}
@Override
public boolean isInvalidTotalEffort(EffortDuration totalEffort) {
return false;
}
@Override
LocalDate limitEndDate(LocalDate endDate) {
return endDate;
}
@Override
LocalDate limitStartDate(LocalDate startDate) {
return startDate;
}
@Override
public void markInvalidEffort(Row groupingRow,
EffortDuration currentEffort) {
throw new UnsupportedOperationException();
}
@Override
public void showInvalidEffort(IMessagesForUser messages,
EffortDuration totalEffort) {
throw new UnsupportedOperationException();
}
}
private static final int VERTICAL_MAX_ELEMENTS = 25;
private IMessagesForUser messages;
private Component insertionPointTimetracker;
private Div insertionPointLeftPanel;
private LayoutRegion insertionPointRightPanel;
private Button paginationDownButton;
private Button paginationUpButton;
private Button verticalPaginationUpButton;
private Button verticalPaginationDownButton;
private TimeTracker timeTracker;
private PaginatorFilter paginatorFilter;
private Listbox advancedAllocationZoomLevel;
private TimeTrackerComponentWithoutColumns timeTrackerComponent;
private Grid leftPane;
private TimeTrackedTable<Row> table;
private IBack back;
private List<AllocationInput> allocationInputs;
private Component associatedComponent;
private Listbox advancedAllocationHorizontalPagination;
private Listbox advancedAllocationVerticalPagination;
private boolean fixedZoomByUser = false;
private ZoomLevel zoomLevel;
public AdvancedAllocationController(IBack back,
List<AllocationInput> allocationInputs) {
setInputData(back, allocationInputs);
}
private void setInputData(IBack back, List<AllocationInput> allocationInputs) {
Validate.notNull(back);
Validate.noNullElements(allocationInputs);
this.back = back;
this.allocationInputs = allocationInputs;
}
public void reset(IBack back, List<AllocationInput> allocationInputs) {
rowsCached = null;
setInputData(back, allocationInputs);
loadAndInitializeComponents();
}
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
normalLayout = comp.getFellow("normalLayout");
noDataLayout = comp.getFellow("noDataLayout");
onlyOneVisible = new OnlyOneVisible(normalLayout, noDataLayout);
this.associatedComponent = comp;
loadAndInitializeComponents();
Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();");
}
private void loadAndInitializeComponents() {
messages = new MessagesForUser(associatedComponent
.getFellow("messages"));
if (allocationInputs.isEmpty()) {
onlyOneVisible.showOnly(noDataLayout);
} else {
onlyOneVisible.showOnly(normalLayout);
createComponents();
insertComponentsInLayout();
timeTrackerComponent.afterCompose();
table.afterCompose();
}
}
private class PaginatorFilter implements IDetailItemFilter {
private DateTime intervalStart;
private DateTime intervalEnd;
private DateTime paginatorStart;
private DateTime paginatorEnd;
private ZoomLevel zoomLevel = ZoomLevel.DETAIL_ONE;
@Override
public Interval getCurrentPaginationInterval() {
return new Interval(intervalStart.toDate(), intervalEnd.toDate());
}
private Period intervalIncrease() {
switch (zoomLevel) {
case DETAIL_ONE:
return Period.years(5);
case DETAIL_TWO:
return Period.years(5);
case DETAIL_THREE:
return Period.years(2);
case DETAIL_FOUR:
return Period.months(6);
case DETAIL_FIVE:
return Period.weeks(6);
}
return Period.years(5);
}
public void populateHorizontalListbox() {
advancedAllocationHorizontalPagination.getItems().clear();
if (intervalStart != null) {
DateTime itemStart = intervalStart;
DateTime itemEnd = intervalStart.plus(intervalIncrease());
while (intervalEnd.isAfter(itemStart)) {
if (intervalEnd.isBefore(itemEnd)
|| !intervalEnd.isAfter(itemEnd
.plus(intervalIncrease()))) {
itemEnd = intervalEnd;
}
Listitem item = new Listitem(Util.formatDate(itemStart)
+ " - " + Util.formatDate(itemEnd.minusDays(1)));
advancedAllocationHorizontalPagination.appendChild(item);
itemStart = itemEnd;
itemEnd = itemEnd.plus(intervalIncrease());
}
}
advancedAllocationHorizontalPagination
.setDisabled(advancedAllocationHorizontalPagination
.getItems().size() < 2);
advancedAllocationHorizontalPagination.setSelectedIndex(0);
}
public void goToHorizontalPage(int interval) {
if (interval >= 0) {
paginatorStart = intervalStart;
for (int i = 0; i < interval; i++) {
paginatorStart = paginatorStart.plus(intervalIncrease());
}
paginatorEnd = paginatorStart.plus(intervalIncrease());
// Avoid reduced intervals
if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) {
paginatorEnd = intervalEnd;
}
updatePaginationButtons();
}
}
@Override
public Collection<DetailItem> selectsFirstLevel(
Collection<DetailItem> firstLevelDetails) {
ArrayList<DetailItem> result = new ArrayList<DetailItem>();
for (DetailItem each : firstLevelDetails) {
if ((each.getStartDate() == null)
|| !(each.getStartDate().isBefore(paginatorStart))
&& (each.getStartDate().isBefore(paginatorEnd))) {
result.add(each);
}
}
return result;
}
@Override
public Collection<DetailItem> selectsSecondLevel(
Collection<DetailItem> secondLevelDetails) {
ArrayList<DetailItem> result = new ArrayList<DetailItem>();
for (DetailItem each : secondLevelDetails) {
if ((each.getStartDate() == null)
|| !(each.getStartDate().isBefore(paginatorStart))
&& (each.getStartDate().isBefore(paginatorEnd))) {
result.add(each);
}
}
return result;
}
public void next() {
paginatorStart = paginatorStart.plus(intervalIncrease());
paginatorEnd = paginatorEnd.plus(intervalIncrease());
// Avoid reduced last intervals
if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) {
paginatorEnd = paginatorEnd.plus(intervalIncrease());
}
updatePaginationButtons();
}
public void previous() {
paginatorStart = paginatorStart.minus(intervalIncrease());
paginatorEnd = paginatorEnd.minus(intervalIncrease());
updatePaginationButtons();
}
private void updatePaginationButtons() {
paginationDownButton.setDisabled(isFirstPage());
paginationUpButton.setDisabled(isLastPage());
}
public boolean isFirstPage() {
return !(paginatorStart.isAfter(intervalStart));
}
public boolean isLastPage() {
return ((paginatorEnd.isAfter(intervalEnd)) || (paginatorEnd
.isEqual(intervalEnd)));
}
public void setZoomLevel(ZoomLevel detailLevel) {
zoomLevel = detailLevel;
}
public void setInterval(Interval realInterval) {
intervalStart = realInterval.getStart().toDateTimeAtStartOfDay();
intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay();
paginatorStart = intervalStart;
paginatorEnd = intervalStart.plus(intervalIncrease());
if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) {
paginatorEnd = intervalEnd;
}
updatePaginationButtons();
}
@Override
public void resetInterval() {
setInterval(timeTracker.getRealInterval());
}
}
private void createComponents() {
timeTracker = new TimeTracker(addMarginTointerval(), self);
paginatorFilter = new PaginatorFilter();
if (fixedZoomByUser && (zoomLevel != null)) {
timeTracker.setZoomLevel(zoomLevel);
}
paginatorFilter.setZoomLevel(timeTracker.getDetailLevel());
paginatorFilter.setInterval(timeTracker.getRealInterval());
paginationUpButton.setDisabled(isLastPage());
advancedAllocationZoomLevel.setSelectedIndex(timeTracker
.getDetailLevel().ordinal());
timeTracker.setFilter(paginatorFilter);
timeTracker.addZoomListener(new IZoomLevelChangedListener() {
@Override
public void zoomLevelChanged(ZoomLevel detailLevel) {
fixedZoomByUser = true;
zoomLevel = detailLevel;
paginatorFilter.setZoomLevel(detailLevel);
paginatorFilter.setInterval(timeTracker.getRealInterval());
timeTracker.setFilter(paginatorFilter);
populateHorizontalListbox();
Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();");
}
});
timeTrackerComponent = new TimeTrackerComponentWithoutColumns(
timeTracker, "timetrackerheader");
timeTrackedTableWithLeftPane = new TimeTrackedTableWithLeftPane<Row, Row>(
getDataSource(), getColumnsForLeft(), getLeftRenderer(),
getRightRenderer(), timeTracker);
table = timeTrackedTableWithLeftPane.getRightPane();
table.setSclass("timeTrackedTableWithLeftPane");
leftPane = timeTrackedTableWithLeftPane.getLeftPane();
leftPane.setFixedLayout(true);
Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();");
populateHorizontalListbox();
}
public void paginationDown() {
paginatorFilter.previous();
reloadComponent();
advancedAllocationHorizontalPagination
.setSelectedIndex(advancedAllocationHorizontalPagination
.getSelectedIndex() - 1);
}
public void paginationUp() {
paginatorFilter.next();
reloadComponent();
advancedAllocationHorizontalPagination.setSelectedIndex(Math.max(0,
advancedAllocationHorizontalPagination.getSelectedIndex()) + 1);
}
public void goToSelectedHorizontalPage() {
paginatorFilter
.goToHorizontalPage(advancedAllocationHorizontalPagination
.getSelectedIndex());
reloadComponent();
}
private void populateHorizontalListbox() {
advancedAllocationHorizontalPagination.setVisible(true);
paginatorFilter.populateHorizontalListbox();
}
private void reloadComponent() {
timeTrackedTableWithLeftPane.reload();
timeTrackerComponent.recreate();
// Reattach listener for zoomLevel changes. May be optimized
timeTracker.addZoomListener(new IZoomLevelChangedListener() {
@Override
public void zoomLevelChanged(ZoomLevel detailLevel) {
paginatorFilter.setZoomLevel(detailLevel);
paginatorFilter.setInterval(timeTracker.getRealInterval());
timeTracker.setFilter(paginatorFilter);
populateHorizontalListbox();
Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();");
}
});
Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();");
}
public boolean isFirstPage() {
return paginatorFilter.isFirstPage();
}
public boolean isLastPage() {
return paginatorFilter.isLastPage();
}
private void insertComponentsInLayout() {
insertionPointRightPanel.getChildren().clear();
insertionPointRightPanel.appendChild(table);
insertionPointLeftPanel.getChildren().clear();
insertionPointLeftPanel.appendChild(leftPane);
insertionPointTimetracker.getChildren().clear();
insertionPointTimetracker.appendChild(timeTrackerComponent);
}
public void onClick$acceptButton() {
for (AllocationInput allocationInput : allocationInputs) {
EffortDuration totalEffort = allocationInput.getTotalEffort();
Restriction restriction = allocationInput.getResultReceiver()
.createRestriction();
if (restriction.isInvalidTotalEffort(totalEffort)) {
Row groupingRow = groupingRows.get(allocationInput);
restriction.markInvalidEffort(groupingRow, totalEffort);
}
}
back.goBack();
for (AllocationInput allocationInput : allocationInputs) {
allocationInput.getResultReceiver().accepted(allocationInput
.getAggregate());
}
}
public void onClick$saveButton() {
for (AllocationInput allocationInput : allocationInputs) {
EffortDuration totalEffort = allocationInput.getTotalEffort();
Restriction restriction = allocationInput.getResultReceiver()
.createRestriction();
if (restriction.isInvalidTotalEffort(totalEffort)) {
Row groupingRow = groupingRows.get(allocationInput);
restriction.markInvalidEffort(groupingRow, totalEffort);
}
}
for (AllocationInput allocationInput : allocationInputs) {
allocationInput.getResultReceiver().accepted(
allocationInput.getAggregate());
}
try {
Messagebox.show(_("Changes applied"), _("Information"),
Messagebox.OK, Messagebox.INFORMATION);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void onClick$cancelButton() {
back.goBack();
for (AllocationInput allocationInput : allocationInputs) {
allocationInput.getResultReceiver().cancel();
}
}
public ListModel getZoomLevels() {
ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_ONE,
ZoomLevel.DETAIL_TWO, ZoomLevel.DETAIL_THREE,
ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE };
return new SimpleListModel(selectableZoomlevels);
}
public void setZoomLevel(final ZoomLevel zoomLevel) {
timeTracker.setZoomLevel(zoomLevel);
}
public void onClick$zoomIncrease() {
timeTracker.zoomIncrease();
}
public void onClick$zoomDecrease() {
timeTracker.zoomDecrease();
}
private List<Row> rowsCached = null;
private Map<AllocationInput, Row> groupingRows = new HashMap<AllocationInput, Row>();
private OnlyOneVisible onlyOneVisible;
private Component normalLayout;
private Component noDataLayout;
private TimeTrackedTableWithLeftPane<Row, Row> timeTrackedTableWithLeftPane;
private int verticalIndex = 0;
private List<Integer> verticalPaginationIndexes;
private int verticalPage;
private List<Row> getRows() {
if (rowsCached != null) {
return filterRows(rowsCached);
}
rowsCached = new ArrayList<Row>();
int position = 1;
for (AllocationInput allocationInput : allocationInputs) {
if (allocationInput.getAggregate()
.getAllocationsSortedByStartDate().isEmpty()) {
} else {
Row groupingRow = buildGroupingRow(allocationInput);
groupingRow.setDescription(position + " " + allocationInput.getTaskName());
groupingRows.put(allocationInput, groupingRow);
rowsCached.add(groupingRow);
List<Row> genericRows = genericRows(allocationInput);
groupingRow.listenTo(genericRows);
rowsCached.addAll(genericRows);
List<Row> specificRows = specificRows(allocationInput);
groupingRow.listenTo(specificRows);
rowsCached.addAll(specificRows);
position++;
}
}
populateVerticalListbox();
return filterRows(rowsCached);
}
private List<Row> filterRows(List<Row> rows) {
verticalPaginationUpButton.setDisabled(verticalIndex <= 0);
verticalPaginationDownButton
.setDisabled((verticalIndex + VERTICAL_MAX_ELEMENTS) >= rows
.size());
if(advancedAllocationVerticalPagination.getChildren().size() >= 2) {
advancedAllocationVerticalPagination.setDisabled(false);
advancedAllocationVerticalPagination.setSelectedIndex(
verticalPage);
}
else {
advancedAllocationVerticalPagination.setDisabled(true);
}
return rows.subList(verticalIndex,
verticalPage + 1 < verticalPaginationIndexes.size() ?
verticalPaginationIndexes.get(verticalPage + 1).intValue() :
rows.size());
}
public void verticalPagedown() {
verticalPage++;
verticalIndex = verticalPaginationIndexes.get(verticalPage);
timeTrackedTableWithLeftPane.reload();
}
public void setVerticalPagedownButtonDisabled(boolean disabled) {
verticalPaginationUpButton.setDisabled(disabled);
}
public void verticalPageup() {
verticalPage
verticalIndex = verticalPaginationIndexes.get(verticalPage);
timeTrackedTableWithLeftPane.reload();
}
public void goToSelectedVerticalPage() {
verticalPage = advancedAllocationVerticalPagination.
getSelectedIndex();
verticalIndex = verticalPaginationIndexes.get(verticalPage);
timeTrackedTableWithLeftPane.reload();
}
public void populateVerticalListbox() {
if (rowsCached != null) {
verticalPaginationIndexes = new ArrayList<Integer>();
advancedAllocationVerticalPagination.getChildren().clear();
for(int i=0; i<rowsCached.size(); i=
correctVerticalPageDownPosition(i+VERTICAL_MAX_ELEMENTS)) {
int endPosition = correctVerticalPageUpPosition(Math.min(
rowsCached.size(), i+VERTICAL_MAX_ELEMENTS) - 1);
String label = rowsCached.get(i).getDescription() + " - " +
rowsCached.get(endPosition).getDescription();
Listitem item = new Listitem();
item.appendChild(new Listcell(label));
advancedAllocationVerticalPagination.appendChild(item);
verticalPaginationIndexes.add(i);
}
if (!rowsCached.isEmpty()) {
advancedAllocationVerticalPagination.setSelectedIndex(0);
}
}
}
private int correctVerticalPageUpPosition(int position) {
int correctedPosition = position;
//moves the pointer up until it finds the previous grouping row
//or the beginning of the list
while(correctedPosition > 0 &&
!rowsCached.get(correctedPosition).isGroupingRow()) {
correctedPosition
}
return correctedPosition;
}
private int correctVerticalPageDownPosition(int position) {
int correctedPosition = position;
//moves the pointer down until it finds the next grouping row
//or the end of the list
while(correctedPosition < rowsCached.size() &&
!rowsCached.get(correctedPosition).isGroupingRow()) {
correctedPosition++;
}
return correctedPosition;
}
private List<Row> specificRows(AllocationInput allocationInput) {
List<Row> result = new ArrayList<Row>();
for (SpecificResourceAllocation specificResourceAllocation : allocationInput.getAggregate()
.getSpecificAllocations()) {
result.add(createSpecificRow(specificResourceAllocation,
allocationInput.getResultReceiver().createRestriction(), allocationInput.task));
}
return result;
}
private Row createSpecificRow(
SpecificResourceAllocation specificResourceAllocation,
Restriction restriction, TaskElement task) {
return Row.createRow(messages, restriction,
specificResourceAllocation.getResource()
.getName(), 1, Arrays
.asList(specificResourceAllocation), specificResourceAllocation
.getResource().getShortDescription(),
specificResourceAllocation.getResource().isLimitingResource(), task);
}
private List<Row> genericRows(AllocationInput allocationInput) {
List<Row> result = new ArrayList<Row>();
for (GenericResourceAllocation genericResourceAllocation : allocationInput.getAggregate()
.getGenericAllocations()) {
result.add(buildGenericRow(genericResourceAllocation,
allocationInput.getResultReceiver().createRestriction(), allocationInput.task));
}
return result;
}
private Row buildGenericRow(
GenericResourceAllocation genericResourceAllocation,
Restriction restriction, TaskElement task) {
return Row.createRow(messages, restriction, Criterion
.getCaptionFor(genericResourceAllocation.getCriterions()), 1, Arrays
.asList(genericResourceAllocation), genericResourceAllocation
.isLimiting(), task);
}
private Row buildGroupingRow(AllocationInput allocationInput) {
Restriction restriction = allocationInput.getResultReceiver()
.createRestriction();
String taskName = allocationInput.getTaskName();
Row groupingRow = Row.createRow(messages, restriction, taskName, 0,
allocationInput.getAllocationsSortedByStartDate(), false, allocationInput.task);
return groupingRow;
}
private ICellForDetailItemRenderer<ColumnOnRow, Row> getLeftRenderer() {
return new ICellForDetailItemRenderer<ColumnOnRow, Row>() {
@Override
public Component cellFor(ColumnOnRow column, Row row) {
return column.cellFor(row);
}
};
}
private List<ColumnOnRow> getColumnsForLeft() {
List<ColumnOnRow> result = new ArrayList<ColumnOnRow>();
result.add(new ColumnOnRow(_("Name")) {
@Override
public Component cellFor(Row row) {
return row.getNameLabel();
}
});
result.add(new ColumnOnRow(_("Efforts"), "50px") {
@Override
public Component cellFor(Row row) {
return row.getAllEffort();
}
});
result.add(new ColumnOnRow(_("Function"), "130px") {
@Override
public Component cellFor(Row row) {
return row.getFunction();
}
});
return result;
}
private Callable<PairOfLists<Row, Row>> getDataSource() {
return new Callable<PairOfLists<Row, Row>>() {
@Override
public PairOfLists<Row, Row> call() {
List<Row> rows = getRows();
return new PairOfLists<Row, Row>(rows, rows);
}
};
}
private ICellForDetailItemRenderer<DetailItem, Row> getRightRenderer() {
return new ICellForDetailItemRenderer<DetailItem, Row>() {
@Override
public Component cellFor(DetailItem item, Row data) {
return data.effortOnInterval(item);
}
};
}
private Interval intervalFromData() {
Interval result = null;
for (AllocationInput each : allocationInputs) {
Interval intervalForInput = each.calculateInterval();
result = result == null ? intervalForInput : result
.coalesce(intervalForInput);
}
return result;
}
private Interval addMarginTointerval() {
Interval interval = intervalFromData();
// No global margin is added by default
return interval;
}
public boolean isAdvancedAllocationOfSingleTask() {
return back.isAdvanceAssignmentOfSingleTask();
}
}
abstract class ColumnOnRow implements IConvertibleToColumn {
private final String columnName;
private String width = null;
ColumnOnRow(String columnName) {
this.columnName = columnName;
}
ColumnOnRow(String columnName, String width) {
this.columnName = columnName;
this.width = width;
}
public abstract Component cellFor(Row row);
@Override
public Column toColumn() {
Column column = new org.zkoss.zul.Column();
column.setLabel(_(columnName));
column.setSclass(columnName.toLowerCase());
if (width != null) {
column.setWidth(width);
}
return column;
}
public String getName() {
return columnName;
}
}
interface CellChangedListener {
public void changeOn(DetailItem detailItem);
public void changeOnGlobal();
}
class Row {
static Row createRow(IMessagesForUser messages,
AdvancedAllocationController.Restriction restriction,
String name, int level,
List<? extends ResourceAllocation<?>> allocations,
String description, boolean limiting, TaskElement task) {
Row newRow = new Row(messages, restriction, name, level, allocations,
limiting, task);
newRow.setDescription(description);
return newRow;
}
static Row createRow(IMessagesForUser messages,
AdvancedAllocationController.Restriction restriction, String name,
int level, List<? extends ResourceAllocation<?>> allocations,
boolean limiting, TaskElement task) {
return new Row(messages, restriction, name, level, allocations,
limiting, task);
}
public void markErrorOnTotal(String message) {
throw new WrongValueException(allEffortInput, message);
}
private EffortDurationBox allEffortInput;
private Label nameLabel;
private List<CellChangedListener> listeners = new ArrayList<CellChangedListener>();
private Map<DetailItem, Component> componentsByDetailItem = new WeakHashMap<DetailItem, Component>();
private String name;
private String description;
private int level;
private final AggregateOfResourceAllocations aggregate;
private final AdvancedAllocationController.Restriction restriction;
private final IMessagesForUser messages;
private final String functionName;
private TaskElement task;
void listenTo(Collection<Row> rows) {
for (Row row : rows) {
listenTo(row);
}
}
void listenTo(Row row) {
row.add(new CellChangedListener() {
@Override
public void changeOnGlobal() {
reloadAllEffort();
reloadEffortsSameRowForDetailItems();
}
@Override
public void changeOn(DetailItem detailItem) {
Component component = componentsByDetailItem.get(detailItem);
if (component == null) {
return;
}
reloadEffortOnInterval(component, detailItem);
reloadAllEffort();
}
});
}
void add(CellChangedListener listener) {
listeners.add(listener);
}
private void fireCellChanged(DetailItem detailItem) {
for (CellChangedListener cellChangedListener : listeners) {
cellChangedListener.changeOn(detailItem);
}
}
private void fireCellChanged() {
for (CellChangedListener cellChangedListener : listeners) {
cellChangedListener.changeOnGlobal();
}
}
Component getAllEffort() {
if (allEffortInput == null) {
allEffortInput = buildSumAllEffort();
reloadAllEffort();
addListenerIfNeeded(allEffortInput);
}
return allEffortInput;
}
private EffortDurationBox buildSumAllEffort() {
EffortDurationBox box = isEffortDurationBoxDisabled() ? EffortDurationBox
.notEditable() : new EffortDurationBox();
box.setWidth("40px");
return box;
}
private void addListenerIfNeeded(Component allEffortComponent) {
if (isEffortDurationBoxDisabled()) {
return;
}
final EffortDurationBox effortDurationBox = (EffortDurationBox) allEffortComponent;
effortDurationBox.addEventListener(Events.ON_CHANGE,
new EventListener() {
@Override
public void onEvent(Event event) {
EffortDuration value = effortDurationBox
.getEffortDurationValue();
ResourceAllocation<?> resourceAllocation = getAllocation();
resourceAllocation
.withPreviousAssociatedResources()
.onIntervalWithinTask(
resourceAllocation.getStartDate(),
resourceAllocation.getEndDate())
.allocate(value);
AssignmentFunction assignmentFunction = resourceAllocation.getAssignmentFunction();
if (assignmentFunction != null) {
assignmentFunction.applyTo(resourceAllocation);
}
fireCellChanged();
reloadEffortsSameRowForDetailItems();
reloadAllEffort();
}
});
}
private boolean isEffortDurationBoxDisabled() {
return isGroupingRow() || isLimiting || task.isUpdatedFromTimesheets();
}
private void reloadEffortsSameRowForDetailItems() {
for (Entry<DetailItem, Component> entry : componentsByDetailItem
.entrySet()) {
reloadEffortOnInterval(entry.getValue(), entry.getKey());
}
}
private void reloadAllEffort() {
if (allEffortInput == null) {
return;
}
EffortDuration allEffort = aggregate.getTotalEffort();
allEffortInput.setValue(allEffort);
Clients.closeErrorBox(allEffortInput);
if (isEffortDurationBoxDisabled()) {
allEffortInput.setDisabled(true);
}
if (restriction.isInvalidTotalEffort(allEffort)) {
restriction.showInvalidEffort(messages, allEffort);
}
}
private Hbox hboxAssigmentFunctionsCombo = null;
Component getFunction() {
if (isGroupingRow()) {
return new Label();
} else if (isLimiting) {
return new Label(_("Queue-based assignment"));
} else {
if (hboxAssigmentFunctionsCombo == null) {
initializeAssigmentFunctionsCombo();
}
return hboxAssigmentFunctionsCombo;
}
}
private AssignmentFunctionListbox assignmentFunctionsCombo = null;
private Button assignmentFunctionsConfigureButton = null;
private void initializeAssigmentFunctionsCombo() {
hboxAssigmentFunctionsCombo = new Hbox();
assignmentFunctionsCombo = new AssignmentFunctionListbox(
functions, getAllocation().getAssignmentFunction());
hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsCombo);
assignmentFunctionsConfigureButton = getAssignmentFunctionsConfigureButton(assignmentFunctionsCombo);
hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsConfigureButton);
// Disable if task is updated from timesheets
assignmentFunctionsCombo.setDisabled(task.isUpdatedFromTimesheets());
assignmentFunctionsConfigureButton.setDisabled(task
.isUpdatedFromTimesheets());
}
class AssignmentFunctionListbox extends Listbox {
private Listitem previousListitem;
public AssignmentFunctionListbox(IAssignmentFunctionConfiguration[] functions,
AssignmentFunction initialValue) {
for (IAssignmentFunctionConfiguration each : functions) {
Listitem listitem = listItem(each);
this.appendChild(listitem);
if (each.isTargetedTo(initialValue)) {
selectItemAndSavePreviousValue(listitem);
}
}
this.addEventListener(Events.ON_SELECT, onSelectListbox());
this.setMold("select");
this.setStyle("font-size: 10px");
}
private void selectItemAndSavePreviousValue(Listitem listitem) {
setSelectedItem(listitem);
previousListitem = listitem;
}
private Listitem listItem(
IAssignmentFunctionConfiguration assignmentFunction) {
Listitem listitem = new Listitem(_(assignmentFunction.getName()));
listitem.setValue(assignmentFunction);
return listitem;
}
private EventListener onSelectListbox() {
return new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) getSelectedItem()
.getValue();
// Cannot apply function if task contains consolidated day assignments
final ResourceAllocation<?> resourceAllocation = getAllocation();
if (function.isSigmoid()
&& !resourceAllocation
.getConsolidatedAssignments().isEmpty()) {
showCannotApplySigmoidFunction();
setSelectedItem(getPreviousListitem());
return;
}
// User didn't accept
if (showConfirmChangeFunctionDialog() != Messagebox.YES) {
setSelectedItem(getPreviousListitem());
return;
}
// Apply assignment function
if (function != null) {
setPreviousListitem(getSelectedItem());
function.applyOn(resourceAllocation);
updateAssignmentFunctionsConfigureButton(
assignmentFunctionsConfigureButton,
function.isConfigurable());
}
}
};
}
private Listitem getPreviousListitem() {
return previousListitem;
}
private void setPreviousListitem(Listitem previousListitem) {
this.previousListitem = previousListitem;
}
private void showCannotApplySigmoidFunction() {
try {
Messagebox
.show(_("Task contains consolidated progress. Cannot apply sigmoid function."),
_("Error"), Messagebox.OK, Messagebox.ERROR);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private int showConfirmChangeFunctionDialog()
throws InterruptedException {
return Messagebox
.show(_("Assignment function will be changed. Are you sure?"),
_("Confirm change"),
Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
}
private void setSelectedFunction(String functionName) {
List<Listitem> children = getChildren();
for (Listitem item : children) {
IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) item
.getValue();
if (function.getName().equals(functionName)) {
setSelectedItem(item);
}
}
}
}
private IAssignmentFunctionConfiguration flat = new IAssignmentFunctionConfiguration() {
@Override
public void goToConfigure() {
throw new UnsupportedOperationException(
"Flat allocation is not configurable");
}
@Override
public String getName() {
return AssignmentFunctionName.FLAT.toString();
}
@Override
public boolean isTargetedTo(AssignmentFunction function) {
return function == null;
}
@Override
public void applyOn(
ResourceAllocation<?> resourceAllocation) {
resourceAllocation.setAssignmentFunctionWithoutApply(null);
resourceAllocation
.withPreviousAssociatedResources()
.onIntervalWithinTask(resourceAllocation.getStartDate(),
resourceAllocation.getEndDate())
.allocate(allEffortInput.getEffortDurationValue());
reloadEfforts();
}
private void reloadEfforts() {
reloadEffortsSameRowForDetailItems();
reloadAllEffort();
fireCellChanged();
}
@Override
public boolean isSigmoid() {
return false;
}
@Override
public boolean isConfigurable() {
return false;
}
};
private IAssignmentFunctionConfiguration manualFunction = new IAssignmentFunctionConfiguration() {
@Override
public void goToConfigure() {
throw new UnsupportedOperationException(
"Manual allocation is not configurable");
}
@Override
public String getName() {
return AssignmentFunctionName.MANUAL.toString();
}
@Override
public boolean isTargetedTo(AssignmentFunction function) {
return function instanceof ManualFunction;
}
@Override
public void applyOn(ResourceAllocation<?> resourceAllocation) {
resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create());
}
@Override
public boolean isSigmoid() {
return false;
}
@Override
public boolean isConfigurable() {
return false;
}
};
private abstract class CommonStrechesConfiguration extends
StrechesFunctionConfiguration {
@Override
protected void assignmentFunctionChanged() {
reloadEffortsSameRowForDetailItems();
reloadAllEffort();
fireCellChanged();
}
@Override
protected ResourceAllocation<?> getAllocation() {
return Row.this.getAllocation();
}
@Override
protected Component getParentOnWhichOpenWindow() {
return allEffortInput.getParent();
}
}
private IAssignmentFunctionConfiguration defaultStrechesFunction = new CommonStrechesConfiguration() {
@Override
protected String getTitle() {
return _("Stretches list");
}
@Override
protected boolean getChartsEnabled() {
return true;
}
@Override
protected StretchesFunctionTypeEnum getType() {
return StretchesFunctionTypeEnum.STRETCHES;
}
@Override
public String getName() {
return AssignmentFunctionName.STRETCHES.toString();
}
};
private IAssignmentFunctionConfiguration strechesWithInterpolation = new CommonStrechesConfiguration() {
@Override
protected String getTitle() {
return _("Stretches with Interpolation");
}
@Override
protected boolean getChartsEnabled() {
return false;
}
@Override
protected StretchesFunctionTypeEnum getType() {
return StretchesFunctionTypeEnum.INTERPOLATED;
}
@Override
public String getName() {
return AssignmentFunctionName.INTERPOLATION.toString();
}
};
private IAssignmentFunctionConfiguration sigmoidFunction = new IAssignmentFunctionConfiguration() {
@Override
public void goToConfigure() {
throw new UnsupportedOperationException(
"Sigmoid function is not configurable");
}
@Override
public String getName() {
return AssignmentFunctionName.SIGMOID.toString();
}
@Override
public boolean isTargetedTo(AssignmentFunction function) {
return function instanceof SigmoidFunction;
}
@Override
public void applyOn(
ResourceAllocation<?> resourceAllocation) {
resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(SigmoidFunction.create());
reloadEfforts();
}
private void reloadEfforts() {
reloadEffortsSameRowForDetailItems();
reloadAllEffort();
fireCellChanged();
}
@Override
public boolean isSigmoid() {
return true;
}
@Override
public boolean isConfigurable() {
return false;
}
};
private IAssignmentFunctionConfiguration[] functions = {
flat,
manualFunction,
defaultStrechesFunction,
strechesWithInterpolation,
sigmoidFunction
};
private boolean isLimiting;
private Button getAssignmentFunctionsConfigureButton(
final Listbox assignmentFunctionsListbox) {
Button button = Util.createEditButton(new EventListener() {
@Override
public void onEvent(Event event) {
IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox
.getSelectedItem().getValue();
configuration.goToConfigure();
}
});
IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox
.getSelectedItem().getValue();
updateAssignmentFunctionsConfigureButton(button,
configuration.isConfigurable());
return button;
}
private void updateAssignmentFunctionsConfigureButton(Button button,
boolean configurable) {
if (configurable) {
button.setTooltiptext(_("Configure"));
button.setDisabled(false);
} else {
button.setTooltiptext(_("Not configurable"));
button.setDisabled(true);
}
}
Component getNameLabel() {
if (nameLabel == null) {
nameLabel = new Label();
nameLabel.setValue(name);
if (!StringUtils.isBlank(description)) {
nameLabel.setTooltiptext(description);
} else {
nameLabel.setTooltiptext(name);
}
nameLabel.setSclass("level" + level);
}
return nameLabel;
}
private Row(IMessagesForUser messages,
AdvancedAllocationController.Restriction restriction, String name,
int level, List<? extends ResourceAllocation<?>> allocations,
boolean limiting, TaskElement task) {
this.messages = messages;
this.restriction = restriction;
this.name = name;
this.level = level;
this.isLimiting = limiting;
this.task = task;
this.aggregate = AggregateOfResourceAllocations
.createFromSatisfied(new ArrayList<ResourceAllocation<?>>(allocations));
this.functionName = getAssignmentFunctionName(allocations);
}
private String getAssignmentFunctionName(
List<? extends ResourceAllocation<?>> allocations) {
AssignmentFunction function = getAssignmentFunction(allocations);
return (function != null) ? function.getName()
: AssignmentFunctionName.FLAT.toString();
}
private AssignmentFunction getAssignmentFunction(
List<? extends ResourceAllocation<?>> allocations) {
if (allocations != null) {
ResourceAllocation<?> allocation = allocations.iterator().next();
return allocation.getAssignmentFunction();
}
return null;
}
private EffortDuration getEffortForDetailItem(DetailItem item) {
DateTime startDate = item.getStartDate();
DateTime endDate = item.getEndDate();
return this.aggregate.effortBetween(startDate.toLocalDate(), endDate
.toLocalDate());
}
Component effortOnInterval(DetailItem item) {
Component result = cannotBeEdited(item) ? new Label()
: disableIfNeeded(item, new EffortDurationBox());
reloadEffortOnInterval(result, item);
componentsByDetailItem.put(item, result);
addListenerIfNeeded(item, result);
return result;
}
private boolean cannotBeEdited(DetailItem item) {
return isGroupingRow() || doesNotIntersectWithTask(item)
|| isBeforeLatestConsolidation(item)
|| task.isUpdatedFromTimesheets();
}
private EffortDurationBox disableIfNeeded(DetailItem item,
EffortDurationBox effortDurationBox) {
effortDurationBox.setDisabled(restriction.isDisabledEditionOn(item));
return effortDurationBox;
}
private void addListenerIfNeeded(final DetailItem item,
final Component component) {
if (cannotBeEdited(item)) {
return;
}
final EffortDurationBox effortBox = (EffortDurationBox) component;
component.addEventListener(Events.ON_CHANGE, new EventListener() {
@Override
public void onEvent(Event event) {
EffortDuration value = effortBox.getEffortDurationValue();
LocalDate startDate = restriction.limitStartDate(item
.getStartDate().toLocalDate());
LocalDate endDate = restriction.limitEndDate(item.getEndDate()
.toLocalDate());
changeAssignmentFunctionToManual();
getAllocation().withPreviousAssociatedResources()
.onIntervalWithinTask(startDate, endDate)
.allocate(value);
fireCellChanged(item);
effortBox.setRawValue(getEffortForDetailItem(item));
reloadAllEffort();
}
});
}
private void changeAssignmentFunctionToManual() {
assignmentFunctionsCombo
.setSelectedFunction(AssignmentFunctionName.MANUAL.toString());
ResourceAllocation<?> allocation = getAllocation();
if (!(allocation.getAssignmentFunction() instanceof ManualFunction)) {
allocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create());
}
}
private void reloadEffortOnInterval(Component component, DetailItem item) {
if (cannotBeEdited(item)) {
Label label = (Label) component;
label.setValue(getEffortForDetailItem(item).toFormattedString());
label.setClass(getLabelClassFor(item));
} else {
EffortDurationBox effortDurationBox = (EffortDurationBox) component;
effortDurationBox.setValue(getEffortForDetailItem(item));
if (isLimiting) {
effortDurationBox.setDisabled(true);
effortDurationBox.setSclass(" limiting");
}
}
}
private String getLabelClassFor(DetailItem item) {
if (isGroupingRow()) {
return "calculated-hours";
}
if (doesNotIntersectWithTask(item)) {
return "unmodifiable-hours";
}
if (isBeforeLatestConsolidation(item)) {
return "consolidated-hours";
}
return "";
}
private boolean doesNotIntersectWithTask(DetailItem item) {
return isBeforeTaskStartDate(item) || isAfterTaskEndDate(item);
}
private boolean isBeforeTaskStartDate(DetailItem item) {
return task.getIntraDayStartDate().compareTo(
item.getEndDate().toLocalDate()) >= 0;
}
private boolean isAfterTaskEndDate(DetailItem item) {
return task.getIntraDayEndDate().compareTo(
item.getStartDate().toLocalDate()) <= 0;
}
private boolean isBeforeLatestConsolidation(DetailItem item) {
if(!((Task)task).hasConsolidations()) {
return false;
}
LocalDate d = ((Task) task).getFirstDayNotConsolidated().getDate();
DateTime firstDayNotConsolidated =
new DateTime(d.getYear(), d.getMonthOfYear(),
d.getDayOfMonth(), 0, 0, 0, 0);
return item.getStartDate().compareTo(firstDayNotConsolidated) < 0;
}
private ResourceAllocation<?> getAllocation() {
if (isGroupingRow()) {
throw new IllegalStateException("is grouping row");
}
return aggregate.getAllocationsSortedByStartDate().get(0);
}
public boolean isGroupingRow() {
return level == 0;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.github.florent37.materialviewpager;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ObservableWebView;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ArgbEvaluator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.github.florent37.materialviewpager.Utils.canScroll;
import static com.github.florent37.materialviewpager.Utils.colorWithAlpha;
import static com.github.florent37.materialviewpager.Utils.dpToPx;
import static com.github.florent37.materialviewpager.Utils.getTheVisibileView;
import static com.github.florent37.materialviewpager.Utils.minMax;
import static com.github.florent37.materialviewpager.Utils.scrollTo;
import static com.github.florent37.materialviewpager.Utils.setBackgroundColor;
import static com.github.florent37.materialviewpager.Utils.setElevation;
import static com.github.florent37.materialviewpager.Utils.setScale;
public class MaterialViewPagerAnimator {
private static final String TAG = MaterialViewPagerAnimator.class.getSimpleName();
public static Boolean ENABLE_LOG = false;
private Context context;
//contains MaterialViewPager subviews references
private MaterialViewPagerHeader mHeader;
//duration of translate header enter animation
private static final int ENTER_TOOLBAR_ANIMATION_DURATION = 600;
//reference to the current MaterialViewPager
protected MaterialViewPager materialViewPager;
//final toolbar layout elevation (if attr viewpager_enableToolbarElevation = true)
public final float elevation;
//max scroll which will be dispatched for all scrollable
public final float scrollMax;
// equals scrollMax in DP (saved to avoir convert to dp anytime I use it)
public final float scrollMaxDp;
protected float lastYOffset = -1; //the current yOffset
protected float lastPercent = 0; //the current Percent
//contains the attributes given to MaterialViewPager from layout
protected MaterialViewPagerSettings settings;
//list of all registered scrollers
protected List<View> scrollViewList = new ArrayList<>();
//save all yOffsets of scrollables
protected HashMap<Object, Integer> yOffsets = new HashMap<>();
//the last headerYOffset during scroll
private float headerYOffset = Float.MAX_VALUE;
//the tmp headerAnimator (not null if animating, else null)
private Object headerAnimator;
boolean followScrollToolbarIsVisible = false;
float firstScrollValue = Float.MIN_VALUE;
boolean justToolbarAnimated = false;
//intial distance between pager & toolbat
float initialDistance = -1;
public MaterialViewPagerAnimator(MaterialViewPager materialViewPager) {
this.settings = materialViewPager.settings;
this.materialViewPager = materialViewPager;
this.mHeader = materialViewPager.materialViewPagerHeader;
this.context = mHeader.getContext();
// initialise the scrollMax to headerHeight, so until the first cell touch the top of the screen
this.scrollMax = this.settings.headerHeight;
//save in into dp once
this.scrollMaxDp = Utils.dpToPx(this.scrollMax, context);
//heightMaxScrollToolbar = context.getResources().getDimension(R.dimen.material_viewpager_padding_top);
elevation = dpToPx(4, context);
}
/**
* When notified for scroll, dispatch it to all registered scrollables
*
* @param source
* @param yOffset
*/
private void dispatchScrollOffset(Object source, float yOffset) {
if (scrollViewList != null) {
for (Object scroll : scrollViewList) {
//do not re-scroll the source
if (scroll != null && scroll != source) {
setScrollOffset(scroll, yOffset);
}
}
}
}
/**
* When notified for scroll, dispatch it to all registered scrollables
*
* @param scroll
* @param yOffset
*/
private void setScrollOffset(Object scroll, float yOffset) {
//do not re-scroll the source
if (scroll != null && yOffset >= 0) {
scrollTo(scroll, yOffset);
//save the current yOffset of the scrollable on the yOffsets hashmap
yOffsets.put(scroll, (int) yOffset);
}
}
/**
* Called when a scroller(RecyclerView/ListView,ScrollView,WebView) scrolled by the user
*
* @param source the scroller
* @param yOffset the scroller current yOffset
*/
public void onMaterialScrolled(Object source, float yOffset) {
//only if yOffset changed
if (yOffset == lastYOffset)
return;
float scrollTop = -yOffset;
{
//parallax scroll of the Background ImageView (the KenBurnsView)
if (mHeader.headerBackground != null) {
if (this.settings.parallaxHeaderFactor != 0)
ViewHelper.setTranslationY(mHeader.headerBackground, scrollTop / this.settings.parallaxHeaderFactor);
if (ViewHelper.getY(mHeader.headerBackground) >= 0)
ViewHelper.setY(mHeader.headerBackground, 0);
}
}
if (ENABLE_LOG)
Log.d("yOffset", "" + yOffset);
//dispatch the new offset to all registered scrollables
dispatchScrollOffset(source, minMax(0, yOffset, scrollMaxDp));
float percent = yOffset / scrollMax;
if(initialDistance == -1)
initialDistance = mHeader.mPagerSlidingTabStrip.getTop() - mHeader.toolbar.getBottom();
//distance between pager & toolbar
float newDistance = ViewHelper.getY(mHeader.mPagerSlidingTabStrip) - mHeader.toolbar.getBottom();
percent = 1 - newDistance/initialDistance;
percent = minMax(0, percent, 1);
{
if (!settings.toolbarTransparent) {
// change color of toolbar & viewpager indicator & statusBaground
setColorPercent(percent);
} else {
if (justToolbarAnimated) {
if (toolbarJoinsTabs())
setColorPercent(1);
else if (lastPercent != percent) {
animateColorPercent(0, 200);
}
}
}
lastPercent = percent; //save the percent
if (mHeader.mPagerSlidingTabStrip != null) { //move the viewpager indicator
//float newY = ViewHelper.getY(mHeader.mPagerSlidingTabStrip) + scrollTop;
if (ENABLE_LOG)
Log.d(TAG, "" + scrollTop);
//mHeader.mPagerSlidingTabStrip.setTranslationY(mHeader.getToolbar().getBottom()-mHeader.mPagerSlidingTabStrip.getY());
if (scrollTop <= 0) {
ViewHelper.setTranslationY(mHeader.mPagerSlidingTabStrip, scrollTop);
ViewHelper.setTranslationY(mHeader.toolbarLayoutBackground, scrollTop);
//when
if (ViewHelper.getY(mHeader.mPagerSlidingTabStrip) < mHeader.getToolbar().getBottom()) {
float ty = mHeader.getToolbar().getBottom() - mHeader.mPagerSlidingTabStrip.getTop();
ViewHelper.setTranslationY(mHeader.mPagerSlidingTabStrip, ty);
ViewHelper.setTranslationY(mHeader.toolbarLayoutBackground, ty);
}
}
}
if (mHeader.mLogo != null) { //move the header logo to toolbar
if (this.settings.hideLogoWithFade) {
ViewHelper.setAlpha(mHeader.mLogo, 1 - percent);
ViewHelper.setTranslationY(mHeader.mLogo, (mHeader.finalTitleY - mHeader.originalTitleY) * percent);
} else {
ViewHelper.setTranslationY(mHeader.mLogo, (mHeader.finalTitleY - mHeader.originalTitleY) * percent);
ViewHelper.setTranslationX(mHeader.mLogo, (mHeader.finalTitleX - mHeader.originalTitleX) * percent);
float scale = (1 - percent) * (1 - mHeader.finalScale) + mHeader.finalScale;
setScale(scale, mHeader.mLogo);
}
}
if (this.settings.hideToolbarAndTitle && mHeader.toolbarLayout != null) {
boolean scrollUp = lastYOffset < yOffset;
if (scrollUp) {
scrollUp(yOffset);
} else {
scrollDown(yOffset);
}
}
}
if (headerAnimator != null && percent < 1) {
if (headerAnimator instanceof ObjectAnimator)
((ObjectAnimator) headerAnimator).cancel();
else if (headerAnimator instanceof android.animation.ObjectAnimator)
((android.animation.ObjectAnimator) headerAnimator).cancel();
headerAnimator = null;
}
lastYOffset = yOffset;
}
private void scrollUp(float yOffset) {
if (ENABLE_LOG)
Log.d(TAG, "scrollUp");
followScrollToolbarLayout(yOffset);
}
private void scrollDown(float yOffset) {
if (ENABLE_LOG)
Log.d(TAG, "scrollDown");
if (yOffset > mHeader.toolbarLayout.getHeight() * 1.5f) {
animateEnterToolbarLayout(yOffset);
} else {
if (headerAnimator != null) {
followScrollToolbarIsVisible = true;
} else {
headerYOffset = Float.MAX_VALUE;
followScrollToolbarLayout(yOffset);
}
}
}
/**
* Change the color of the statusbackground, toolbar, toolbarlayout and pagertitlestrip
* With a color transition animation
*
* @param color the final color
* @param duration the transition color animation duration
*/
public void setColor(int color, int duration) {
ValueAnimator colorAnim = ObjectAnimator.ofInt(mHeader.headerBackground, "backgroundColor", settings.color, color);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setDuration(duration);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
final int animatedValue = (Integer) animation.getAnimatedValue();
int colorAlpha = colorWithAlpha(animatedValue, lastPercent);
mHeader.headerBackground.setBackgroundColor(colorAlpha);
mHeader.statusBackground.setBackgroundColor(colorAlpha);
mHeader.toolbar.setBackgroundColor(colorAlpha);
mHeader.toolbarLayoutBackground.setBackgroundColor(colorAlpha);
mHeader.mPagerSlidingTabStrip.setBackgroundColor(colorAlpha);
//set the new color as MaterialViewPager's color
settings.color = animatedValue;
}
});
colorAnim.start();
}
public void animateColorPercent(float percent, int duration) {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(lastPercent, percent);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setColorPercent((float) animation.getAnimatedValue());
}
});
valueAnimator.setDuration(duration);
valueAnimator.start();
}
public void setColorPercent(float percent) {
// change color of
// toolbar & viewpager indicator & statusBaground
setBackgroundColor(
colorWithAlpha(this.settings.color, percent),
mHeader.statusBackground
);
if (percent >= 1) {
setBackgroundColor(
colorWithAlpha(this.settings.color, percent),
mHeader.toolbar,
mHeader.toolbarLayoutBackground,
mHeader.mPagerSlidingTabStrip
);
} else {
setBackgroundColor(
colorWithAlpha(this.settings.color, 0),
mHeader.toolbar,
mHeader.toolbarLayoutBackground,
mHeader.mPagerSlidingTabStrip
);
}
if (this.settings.enableToolbarElevation && toolbarJoinsTabs())
setElevation(
(percent == 1) ? elevation : 0,
mHeader.toolbar,
mHeader.toolbarLayoutBackground,
mHeader.mPagerSlidingTabStrip,
mHeader.mLogo
);
}
private boolean toolbarJoinsTabs() {
return (mHeader.toolbar.getBottom() == mHeader.mPagerSlidingTabStrip.getTop() + ViewHelper.getTranslationY(mHeader.mPagerSlidingTabStrip));
}
/**
* move the toolbarlayout (containing toolbar & tabs)
* following the current scroll
*/
private void followScrollToolbarLayout(float yOffset) {
if (mHeader.toolbar.getBottom() == 0)
return;
if (toolbarJoinsTabs()) {
if (firstScrollValue == Float.MIN_VALUE)
firstScrollValue = yOffset;
float translationY = firstScrollValue - yOffset;
if (ENABLE_LOG)
Log.d(TAG, "translationY " + translationY);
ViewHelper.setTranslationY(mHeader.toolbarLayout, translationY);
} else {
ViewHelper.setTranslationY(mHeader.toolbarLayout, 0);
justToolbarAnimated = false;
}
followScrollToolbarIsVisible = (ViewHelper.getY(mHeader.toolbarLayout) >= 0);
}
/**
* Animate enter toolbarlayout
*
* @param yOffset
*/
private void animateEnterToolbarLayout(float yOffset) {
if (!followScrollToolbarIsVisible && headerAnimator != null) {
if (headerAnimator instanceof ObjectAnimator)
((ObjectAnimator) headerAnimator).cancel();
else if (headerAnimator instanceof android.animation.ObjectAnimator)
((android.animation.ObjectAnimator) headerAnimator).cancel();
headerAnimator = null;
}
if (headerAnimator == null) {
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
headerAnimator = android.animation.ObjectAnimator.ofFloat(mHeader.toolbarLayout, "translationY", 0).setDuration(ENTER_TOOLBAR_ANIMATION_DURATION);
((android.animation.ObjectAnimator) headerAnimator).addListener(new android.animation.AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(android.animation.Animator animation) {
super.onAnimationEnd(animation);
followScrollToolbarIsVisible = true;
firstScrollValue = Float.MIN_VALUE;
justToolbarAnimated = true;
}
});
((android.animation.ObjectAnimator) headerAnimator).start();
} else {
headerAnimator = ObjectAnimator.ofFloat(mHeader.toolbarLayout, "translationY", 0).setDuration(ENTER_TOOLBAR_ANIMATION_DURATION);
((ObjectAnimator) headerAnimator).addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
followScrollToolbarIsVisible = true;
firstScrollValue = Float.MIN_VALUE;
justToolbarAnimated = true;
}
});
((ObjectAnimator) headerAnimator).start();
}
headerYOffset = yOffset;
}
}
public int getHeaderHeight() {
return this.settings.headerHeight;
}
protected boolean isNewYOffset(int yOffset) {
if (lastYOffset == -1)
return true;
else
return yOffset != lastYOffset;
}
//region register scrollables
/**
* Register a RecyclerView to the current MaterialViewPagerAnimator
* Listen to RecyclerView.OnScrollListener so give to $[onScrollListener] your RecyclerView.OnScrollListener if you already use one
* For loadmore or anything else
*
* @param recyclerView the scrollable
* @param onScrollListener use it if you want to get a callback of the RecyclerView
*/
public void registerRecyclerView(final RecyclerView recyclerView, final RecyclerView.OnScrollListener onScrollListener) {
if (recyclerView != null) {
scrollViewList.add(recyclerView); //add to the scrollable list
yOffsets.put(recyclerView, recyclerView.getScrollY()); //save the initial recyclerview's yOffset (0) into hashmap
//only necessary for recyclerview
//listen to scroll
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
boolean firstZeroPassed;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (onScrollListener != null)
onScrollListener.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (onScrollListener != null)
onScrollListener.onScrolled(recyclerView, dx, dy);
int yOffset = yOffsets.get(recyclerView);
yOffset += dy;
yOffsets.put(recyclerView, yOffset); //save the new offset
//first time you get 0, don't share it to others scrolls
if (yOffset == 0 && !firstZeroPassed) {
firstZeroPassed = true;
return;
}
//only if yOffset changed
if (isNewYOffset(yOffset))
onMaterialScrolled(recyclerView, yOffset);
}
});
recyclerView.post(new Runnable() {
@Override
public void run() {
setScrollOffset(recyclerView, lastYOffset);
}
});
}
}
/**
* Register a ScrollView to the current MaterialViewPagerAnimator
* Listen to ObservableScrollViewCallbacks so give to $[observableScrollViewCallbacks] your ObservableScrollViewCallbacks if you already use one
* For loadmore or anything else
*
* @param scrollView the scrollable
* @param observableScrollViewCallbacks use it if you want to get a callback of the RecyclerView
*/
public void registerScrollView(final ObservableScrollView scrollView, final ObservableScrollViewCallbacks observableScrollViewCallbacks) {
if (scrollView != null) {
scrollViewList.add(scrollView); //add to the scrollable list
if (scrollView.getParent() != null && scrollView.getParent().getParent() != null && scrollView.getParent().getParent() instanceof ViewGroup)
scrollView.setTouchInterceptionViewGroup((ViewGroup) scrollView.getParent().getParent());
scrollView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
boolean firstZeroPassed;
@Override
public void onScrollChanged(int yOffset, boolean b, boolean b2) {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onScrollChanged(yOffset, b, b2);
//first time you get 0, don't share it to others scrolls
if (yOffset == 0 && !firstZeroPassed) {
firstZeroPassed = true;
return;
}
//only if yOffset changed
if (isNewYOffset(yOffset))
onMaterialScrolled(scrollView, yOffset);
}
@Override
public void onDownMotionEvent() {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onDownMotionEvent();
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onUpOrCancelMotionEvent(scrollState);
}
});
scrollView.post(new Runnable() {
@Override
public void run() {
setScrollOffset(scrollView, lastYOffset);
}
});
}
}
/**
* Register a WebView to the current MaterialViewPagerAnimator
* Listen to ObservableScrollViewCallbacks so give to $[observableScrollViewCallbacks] your ObservableScrollViewCallbacks if you already use one
* For loadmore or anything else
*
* @param webView the scrollable
* @param observableScrollViewCallbacks use it if you want to get a callback of the RecyclerView
*/
public void registerWebView(final ObservableWebView webView, final ObservableScrollViewCallbacks observableScrollViewCallbacks) {
if (webView != null) {
if (scrollViewList.isEmpty())
onMaterialScrolled(webView, webView.getCurrentScrollY());
scrollViewList.add(webView); //add to the scrollable list
webView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int yOffset, boolean b, boolean b2) {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onScrollChanged(yOffset, b, b2);
if (isNewYOffset(yOffset))
onMaterialScrolled(webView, yOffset);
}
@Override
public void onDownMotionEvent() {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onDownMotionEvent();
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
if (observableScrollViewCallbacks != null)
observableScrollViewCallbacks.onUpOrCancelMotionEvent(scrollState);
}
});
this.setScrollOffset(webView, -lastYOffset);
}
}
//endregion
public void restoreScroll(float scroll, MaterialViewPagerSettings settings) {
this.settings = settings;
onMaterialScrolled(null, scroll);
}
public void onViewPagerPageChanged() {
scrollDown(lastYOffset);
View visibleView = getTheVisibileView(scrollViewList);
if (!canScroll(visibleView)) {
followScrollToolbarLayout(0);
onMaterialScrolled(visibleView, 0);
}
}
}
|
package org.openlmis.web.view.pdf.requisition;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPRow;
import com.itextpdf.text.pdf.PdfPTable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.openlmis.core.builder.FacilityBuilder;
import org.openlmis.core.domain.Facility;
import org.openlmis.rnr.builder.RnrLineItemBuilder;
import org.openlmis.rnr.domain.LossesAndAdjustmentsType;
import org.openlmis.rnr.domain.Rnr;
import org.openlmis.rnr.domain.RnrColumn;
import org.openlmis.rnr.domain.RnrLineItem;
import org.openlmis.web.controller.RequisitionController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.natpryce.makeiteasy.MakeItEasy.*;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.openlmis.rnr.builder.RequisitionBuilder.defaultRnr;
import static org.openlmis.rnr.builder.RequisitionBuilder.facility;
import static org.openlmis.rnr.builder.RnrTemplateBuilder.defaultRnrTemplate;
@RunWith(MockitoJUnitRunner.class)
public class RequisitionPdfModelTest {
private Map<String, Object> model;
private Rnr requisition;
private RequisitionPdfModel requisitionPdfModel;
private List<LossesAndAdjustmentsType> lossesAndAdjustmentsList;
@Before
public void setUp() throws Exception {
Facility f1 = make(a(FacilityBuilder.defaultFacility, with(FacilityBuilder.name, "F1")));
requisition = spy(make(a(defaultRnr, with(facility, f1))));
model = new HashMap<>();
model.put(RequisitionController.CURRENCY, "$");
model.put(RequisitionController.RNR, requisition);
List<RnrColumn> rnrTemplate = make(a(defaultRnrTemplate)).getRnrColumns();
model.put(RequisitionController.RNR_TEMPLATE, rnrTemplate);
requisitionPdfModel = new RequisitionPdfModel(model);
LossesAndAdjustmentsType additive1 = new LossesAndAdjustmentsType("TRANSFER_IN", "TRANSFER IN", true, 1);
lossesAndAdjustmentsList = asList(additive1);
RnrLineItem.setLossesAndAdjustmentsTypes(lossesAndAdjustmentsList);
}
@Test
public void shouldGetHeader() throws Exception {
PdfPTable header = requisitionPdfModel.getRequisitionHeader();
assertRowValues(header.getRow(0), "Report and Requisition for: Yellow Fever (Central Warehouse)");
assertRowValues(header.getRow(1), "Facility: F1", "Operated By: MOH", "Maximum Stock level: 100", "Emergency Order Point: 50.5");
assertRowValues(header.getRow(2), "levelName: Lusaka", "parentLevelName: Zambia", "Reporting Period: 01/01/2012 - 01/02/2012");
assertThat(header.getSpacingAfter(), is(RequisitionPdfModel.PARAGRAPH_SPACING));
}
@Test
public void shouldGetSummary() throws Exception {
PdfPTable summary = requisitionPdfModel.getSummary();
verify(requisition).fillFullSupplyCost();
verify(requisition).fillNonFullSupplyCost();
assertRowValues(summary.getRow(0), "Summary");
assertRowValues(summary.getRow(1), "Total Cost For Full Supply Items", "$8.00");
assertRowValues(summary.getRow(2), "Total Cost For Non Full Supply Items", "$0.00");
assertRowValues(summary.getRow(3), "Total Cost", "$8.00");
assertRowValues(summary.getRow(4), " ", " ");
assertRowValues(summary.getRow(5), " ", " ");
assertRowValues(summary.getRow(6), "Submitted By: ", "Date: 19/03/2013");
assertRowValues(summary.getRow(7), "Authorized By: ", "Date: ");
}
@Test
public void shouldGetFullSupplyHeader() throws Exception {
Paragraph fullSupplyHeader = requisitionPdfModel.getFullSupplyHeader();
assertThat(fullSupplyHeader.getContent(), is("Full supply products"));
}
@Test
public void shouldGetNonFullSupplyHeader() throws Exception {
Paragraph nonFullSupplyHeader = requisitionPdfModel.getNonFullSupplyHeader();
assertThat(nonFullSupplyHeader.getContent(), is("Non-Full supply products"));
}
@Test
public void shouldGetFullSupplyLineItems() throws Exception {
PdfPTable fullSupplyTable = requisitionPdfModel.getFullSupplyTable();
assertRowValues(fullSupplyTable.getRow(0), "Requested Quantity", "stockOutDays", "stock in hand", "quantity received", "beginning balance", "losses and adjustment");
assertRowValues(fullSupplyTable.getRow(1), " ");
assertRowValues(fullSupplyTable.getRow(2), "C1");
assertRowValues(fullSupplyTable.getRow(3), "6", "3", "4", "3", "10", "1");
assertThat(fullSupplyTable.getRows().size(), is(requisition.getFullSupplyLineItems().size() + 3));
}
@Test
public void shouldGetNonFullSupplyLineItems() throws Exception {
RnrLineItem lineItem = make(a(RnrLineItemBuilder.defaultRnrLineItem));
requisition.add(lineItem, false);
PdfPTable nonFullSupplyTable = requisitionPdfModel.getNonFullSupplyTable();
assertRowValues(nonFullSupplyTable.getRow(0), "Requested Quantity");
assertRowValues(nonFullSupplyTable.getRow(1), " ");
assertRowValues(nonFullSupplyTable.getRow(2), "C1");
assertRowValues(nonFullSupplyTable.getRow(3), "6");
assertThat(nonFullSupplyTable.getRows().size(), is(requisition.getNonFullSupplyLineItems().size() + 3));
}
private void assertRowValues(PdfPRow row, String... cellTexts) {
PdfPCell[] rowCells = row.getCells();
int index = 0;
for (String text : cellTexts) {
assertThat(rowCells[index++].getPhrase().getContent(), is(text));
}
}
}
|
package org.eclipse.persistence.jaxb.compiler;
import java.awt.Image;
import java.beans.Introspector;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttachmentRef;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlInlineBinaryData;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSchemaTypes;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.XmlType.DEFAULT;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import org.eclipse.persistence.exceptions.JAXBException;
import org.eclipse.persistence.internal.descriptors.Namespace;
import org.eclipse.persistence.internal.helper.ClassConstants;
import org.eclipse.persistence.internal.helper.ConversionManager;
import org.eclipse.persistence.internal.jaxb.JaxbClassLoader;
import org.eclipse.persistence.internal.libraries.asm.ClassWriter;
import org.eclipse.persistence.internal.libraries.asm.CodeVisitor;
import org.eclipse.persistence.internal.libraries.asm.Constants;
import org.eclipse.persistence.internal.libraries.asm.Label;
import org.eclipse.persistence.internal.libraries.asm.Type;
import org.eclipse.persistence.internal.libraries.asm.attrs.Annotation;
import org.eclipse.persistence.internal.libraries.asm.attrs.LocalVariableTypeTableAttribute;
import org.eclipse.persistence.internal.libraries.asm.attrs.RuntimeVisibleAnnotations;
import org.eclipse.persistence.internal.libraries.asm.attrs.SignatureAttribute;
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.jaxb.TypeMappingInfo;
import org.eclipse.persistence.jaxb.javamodel.AnnotationProxy;
import org.eclipse.persistence.jaxb.javamodel.Helper;
import org.eclipse.persistence.jaxb.javamodel.JavaClass;
import org.eclipse.persistence.jaxb.javamodel.JavaConstructor;
import org.eclipse.persistence.jaxb.javamodel.JavaField;
import org.eclipse.persistence.jaxb.javamodel.JavaHasAnnotations;
import org.eclipse.persistence.jaxb.javamodel.JavaMethod;
import org.eclipse.persistence.jaxb.javamodel.JavaPackage;
import org.eclipse.persistence.jaxb.javamodel.reflection.JavaFieldImpl;
import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder;
import org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType;
import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation;
import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer;
import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer;
import org.eclipse.persistence.mappings.transformers.AttributeTransformer;
import org.eclipse.persistence.mappings.transformers.FieldTransformer;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLConstants;
import org.eclipse.persistence.oxm.annotations.XmlAccessMethods;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;
import org.eclipse.persistence.oxm.annotations.XmlClassExtractor;
import org.eclipse.persistence.oxm.annotations.XmlContainerProperty;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue;
import org.eclipse.persistence.oxm.annotations.XmlElementsJoinNodes;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import org.eclipse.persistence.oxm.annotations.XmlIsSetNullPolicy;
import org.eclipse.persistence.oxm.annotations.XmlJoinNode;
import org.eclipse.persistence.oxm.annotations.XmlJoinNodes;
import org.eclipse.persistence.oxm.annotations.XmlKey;
import org.eclipse.persistence.oxm.annotations.XmlNullPolicy;
import org.eclipse.persistence.oxm.annotations.XmlParameter;
import org.eclipse.persistence.oxm.annotations.XmlPath;
import org.eclipse.persistence.oxm.annotations.XmlPaths;
import org.eclipse.persistence.oxm.annotations.XmlProperties;
import org.eclipse.persistence.oxm.annotations.XmlProperty;
import org.eclipse.persistence.oxm.annotations.XmlReadOnly;
import org.eclipse.persistence.oxm.annotations.XmlWriteOnly;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;
/**
* INTERNAL:
* <p>
* <b>Purpose:</b>To perform some initial processing of Java classes and JAXB
* 2.0 Annotations and generate meta data that can be used by the Mappings
* Generator and Schema Generator
* <p>
* <b>Responsibilities:</b>
* <ul>
* <li>Generate a map of TypeInfo objects, keyed on class name</li>
* <li>Generate a map of user defined schema types</li>
* <li>Identify any class-based JAXB 2.0 callback methods, and create
* MarshalCallback and UnmarshalCallback objects to wrap them.</li>
* <li>Centralize processing which is common to both Schema Generation and
* Mapping Generation tasks</li>
* <p>
* This class does the initial processing of the JAXB 2.0 Generation. It
* generates meta data that can be used by the later Schema Generation and
* Mapping Generation steps.
*
* @see org.eclipse.persistence.jaxb.compiler.Generator
* @author mmacivor
* @since Oracle TopLink 11.1.1.0.0
*/
public class AnnotationsProcessor {
static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler";
static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart";
private static final String JAVAX_XML_BIND_JAXBELEMENT = "javax.xml.bind.JAXBElement";
private static final String TYPE_METHOD_NAME = "type";
private static final String VALUE_METHOD_NAME = "value";
private static final String ARRAY_PACKAGE_NAME = "jaxb.dev.java.net.array";
private static final String ARRAY_NAMESPACE = "http://jaxb.dev.java.net/array";
private static final String ARRAY_CLASS_NAME_SUFFIX = "Array";
private static final String JAXB_DEV = "jaxb.dev.java.net";
private static final String ORG_W3C_DOM = "org.w3c.dom";
private static final String CREATE = "create";
private static final String ELEMENT_DECL_GLOBAL = "javax.xml.bind.annotation.XmlElementDecl.GLOBAL";
private static final String ELEMENT_DECL_DEFAULT = "\u0000";
private static final String EMPTY_STRING = "";
private static final String JAVA_UTIL_LIST = "java.util.List";
private static final String JAVA_LANG_OBJECT = "java.lang.Object";
private static final String SLASH = "/";
private static final String AT_SIGN = "@";
private static final String SEMI_COLON = ";";
private static final String L = "L";
private static final String ITEM = "item";
private static final String IS_STR = "is";
private static final String GET_STR = "get";
private static final String SET_STR = "set";
private static final Character DOT_CHR = '.';
private static final Character DOLLAR_SIGN_CHR = '$';
private static final Character SLASH_CHR = '/';
private ArrayList<JavaClass> typeInfoClasses;
private HashMap<String, NamespaceInfo> packageToNamespaceMappings;
private HashMap<String, MarshalCallback> marshalCallbacks;
private HashMap<String, QName> userDefinedSchemaTypes;
private HashMap<String, TypeInfo> typeInfo;
private ArrayList<QName> typeQNames;
private HashMap<String, UnmarshalCallback> unmarshalCallbacks;
private HashMap<String, HashMap<QName, ElementDeclaration>> elementDeclarations;
private HashMap<String, ElementDeclaration> xmlRootElements;
private List<ElementDeclaration> localElements;
private HashMap<String, JavaMethod> factoryMethods;
private Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry> xmlRegistries;
private Map<String, Class> arrayClassesToGeneratedClasses;
private Map<Class, JavaClass> generatedClassesToArrayClasses;
private Map<java.lang.reflect.Type, Class> collectionClassesToGeneratedClasses;
private Map<Class, java.lang.reflect.Type> generatedClassesToCollectionClasses;
private Map<JavaClass, TypeMappingInfo> javaClassToTypeMappingInfos;
private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses;
private Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses;
private Map<TypeMappingInfo, QName> typeMappingInfoToSchemaType;
private NamespaceResolver namespaceResolver;
private Helper helper;
private String defaultTargetNamespace;
private JAXBMetadataLogger logger;
private boolean isDefaultNamespaceAllowed;
private boolean hasSwaRef;
public AnnotationsProcessor(Helper helper) {
this.helper = helper;
isDefaultNamespaceAllowed = true;
hasSwaRef = false;
}
/**
* Generate TypeInfo instances for a given array of JavaClasses.
*
* @param classes
*/
void processClassesAndProperties(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
init(classes, typeMappingInfos);
preBuildTypeInfo(classes);
classes = postBuildTypeInfo(classes);
processJavaClasses(null);
processPropertyTypes(this.typeInfoClasses.toArray(new JavaClass[this.typeInfoClasses.size()]));
finalizeProperties();
createElementsForTypeMappingInfo();
}
public void createElementsForTypeMappingInfo() {
if (this.javaClassToTypeMappingInfos != null && !this.javaClassToTypeMappingInfos.isEmpty()) {
Set<JavaClass> classes = this.javaClassToTypeMappingInfos.keySet();
for (JavaClass nextClass : classes) {
TypeMappingInfo nextInfo = this.javaClassToTypeMappingInfos.get(nextClass);
if (nextInfo != null) {
boolean xmlAttachmentRef = false;
String xmlMimeType = null;
java.lang.annotation.Annotation[] annotations = getAnnotations(nextInfo);
Class adapterClass = this.typeMappingInfoToAdapterClasses.get(nextInfo);
Class declJavaType = null;
if (adapterClass != null) {
declJavaType = CompilerHelper.getTypeFromAdapterClass(adapterClass);
}
if (annotations != null) {
for (int j = 0; j < annotations.length; j++) {
java.lang.annotation.Annotation nextAnnotation = annotations[j];
if (nextAnnotation != null) {
if (nextAnnotation instanceof XmlMimeType) {
XmlMimeType javaAnnotation = (XmlMimeType) nextAnnotation;
xmlMimeType = javaAnnotation.value();
} else if (nextAnnotation instanceof XmlAttachmentRef) {
xmlAttachmentRef = true;
if(!this.hasSwaRef) {
this.hasSwaRef = true;
}
}
}
}
}
QName qname = null;
String nextClassName = nextClass.getQualifiedName();
if (declJavaType != null) {
nextClassName = declJavaType.getCanonicalName();
}
if (typeMappingInfoToGeneratedClasses != null) {
Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo);
if (generatedClass != null) {
nextClassName = generatedClass.getCanonicalName();
}
}
TypeInfo nextTypeInfo = typeInfo.get(nextClassName);
if (nextTypeInfo != null) {
qname = new QName(nextTypeInfo.getClassNamespace(), nextTypeInfo.getSchemaTypeName());
} else {
qname = getUserDefinedSchemaTypes().get(nextClassName);
if (qname == null) {
if (nextClassName.equals(ClassConstants.APBYTE.getName()) || nextClassName.equals(Image.class.getName()) || nextClassName.equals(Source.class.getName()) || nextClassName.equals("javax.activation.DataHandler")) {
if (xmlAttachmentRef) {
qname = XMLConstants.SWA_REF_QNAME;
} else {
qname = XMLConstants.BASE_64_BINARY_QNAME;
}
} else if (nextClassName.equals(ClassConstants.OBJECT.getName())) {
qname = XMLConstants.ANY_TYPE_QNAME;
} else if (nextClassName.equals(ClassConstants.XML_GREGORIAN_CALENDAR.getName())) {
qname = XMLConstants.ANY_SIMPLE_TYPE_QNAME;
} else {
Class theClass = helper.getClassForJavaClass(nextClass);
qname = (QName) XMLConversionManager.getDefaultJavaTypes().get(theClass);
}
}
}
if (qname != null) {
typeMappingInfoToSchemaType.put(nextInfo, qname);
}
if (nextInfo.getXmlTagName() != null) {
ElementDeclaration element = new ElementDeclaration(nextInfo.getXmlTagName(), nextClass, nextClass.getQualifiedName(), false);
element.setTypeMappingInfo(nextInfo);
element.setXmlMimeType(xmlMimeType);
element.setXmlAttachmentRef(xmlAttachmentRef);
if (declJavaType != null) {
element.setJavaType(helper.getJavaClass(declJavaType));
}
Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo);
if (generatedClass != null) {
element.setJavaType(helper.getJavaClass(generatedClass));
}
if (nextInfo.getElementScope() == TypeMappingInfo.ElementScope.Global) {
this.getGlobalElements().put(element.getElementName(), element);
} else {
this.localElements.add(element);
}
String rootNamespace = element.getElementName().getNamespaceURI();
if(rootNamespace == null) {
rootNamespace = XMLConstants.EMPTY_STRING;
}
if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) {
isDefaultNamespaceAllowed = false;
}
}
}
}
}
}
/**
* Returns an array of Annotations for a given TypeMappingInfo. This array
* will either be populated from the TypeMappingInfo's array of annotations,
* or based on an xml-element if present. The xml-element will take
* precedence over the annotation array; if there is an xml-element the
* Array of Annotations will be ignored.
*
* @param tmInfo
* @return
*/
private java.lang.annotation.Annotation[] getAnnotations(TypeMappingInfo tmInfo) {
if (tmInfo.getXmlElement() != null) {
ClassLoader loader = helper.getClassLoader();
// create a single ConversionManager for that will be shared by the
// proxy objects
ConversionManager cMgr = new ConversionManager();
cMgr.setLoader(loader);
// unmarshal the node into an XmlElement
org.eclipse.persistence.jaxb.xmlmodel.XmlElement xElt = (org.eclipse.persistence.jaxb.xmlmodel.XmlElement) CompilerHelper.getXmlElement(tmInfo.getXmlElement(), loader);
List annotations = new ArrayList();
// where applicable, a given dynamic proxy will contain a Map of
// method name/return value entries
Map<String, Object> components = null;
// handle @XmlElement: set 'type' method
if (!(xElt.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT"))) {
components = new HashMap();
components.put(TYPE_METHOD_NAME, xElt.getType());
annotations.add(AnnotationProxy.getProxy(components, XmlElement.class, loader, cMgr));
}
// handle @XmlList
if (xElt.isXmlList()) {
annotations.add(AnnotationProxy.getProxy(components, XmlList.class, loader, cMgr));
}
// handle @XmlAttachmentRef
if (xElt.isXmlAttachmentRef()) {
annotations.add(AnnotationProxy.getProxy(components, XmlAttachmentRef.class, loader, cMgr));
}
// handle @XmlMimeType: set 'value' method
if (xElt.getXmlMimeType() != null) {
components = new HashMap();
components.put(VALUE_METHOD_NAME, xElt.getXmlMimeType());
annotations.add(AnnotationProxy.getProxy(components, XmlMimeType.class, loader, cMgr));
}
// handle @XmlJavaTypeAdapter: set 'type' and 'value' methods
if (xElt.getXmlJavaTypeAdapter() != null) {
components = new HashMap();
components.put(TYPE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getType());
components.put(VALUE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getValue());
annotations.add(AnnotationProxy.getProxy(components, XmlJavaTypeAdapter.class, loader, cMgr));
}
// return the newly created array of dynamic proxy objects
return (java.lang.annotation.Annotation[]) annotations.toArray(new java.lang.annotation.Annotation[annotations.size()]);
}
// no xml-element set on the info, (i.e. no xml overrides) so return the
// array of Annotation objects
return tmInfo.getAnnotations();
}
/**
* Initialize maps, lists, etc. Typically called prior to processing a set
* of classes via preBuildTypeInfo, postBuildTypeInfo, processJavaClasses.
*/
void init(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
typeInfoClasses = new ArrayList<JavaClass>();
typeInfo = new HashMap<String, TypeInfo>();
typeQNames = new ArrayList<QName>();
userDefinedSchemaTypes = new HashMap<String, QName>();
if (packageToNamespaceMappings == null) {
packageToNamespaceMappings = new HashMap<String, NamespaceInfo>();
}
this.factoryMethods = new HashMap<String, JavaMethod>();
this.xmlRegistries = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry>();
this.namespaceResolver = new NamespaceResolver();
this.xmlRootElements = new HashMap<String, ElementDeclaration>();
arrayClassesToGeneratedClasses = new HashMap<String, Class>();
collectionClassesToGeneratedClasses = new HashMap<java.lang.reflect.Type, Class>();
generatedClassesToArrayClasses = new HashMap<Class, JavaClass>();
generatedClassesToCollectionClasses = new HashMap<Class, java.lang.reflect.Type>();
typeMappingInfoToGeneratedClasses = new HashMap<TypeMappingInfo, Class>();
typeMappingInfoToSchemaType = new HashMap<TypeMappingInfo, QName>();
elementDeclarations = new HashMap<String, HashMap<QName, ElementDeclaration>>();
HashMap globalElements = new HashMap<QName, ElementDeclaration>();
elementDeclarations.put(XmlElementDecl.GLOBAL.class.getName(), globalElements);
localElements = new ArrayList<ElementDeclaration>();
javaClassToTypeMappingInfos = new HashMap<JavaClass, TypeMappingInfo>();
if (typeMappingInfos != null) {
for (int i = 0; i < typeMappingInfos.length; i++) {
javaClassToTypeMappingInfos.put(classes[i], typeMappingInfos[i]);
}
}
typeMappingInfoToAdapterClasses = new HashMap<TypeMappingInfo, Class>();
if (typeMappingInfos != null) {
for (TypeMappingInfo next : typeMappingInfos) {
java.lang.annotation.Annotation[] annotations = getAnnotations(next);
if (annotations != null) {
for (java.lang.annotation.Annotation nextAnnotation : annotations) {
if (nextAnnotation instanceof XmlJavaTypeAdapter) {
typeMappingInfoToAdapterClasses.put(next, ((XmlJavaTypeAdapter) nextAnnotation).value());
}
}
}
}
}
}
/**
* Process class level annotations only. It is assumed that a call to init()
* has been made prior to calling this method. After the types created via
* this method have been modified (if necessary) postBuildTypeInfo and
* processJavaClasses should be called to finish processing.
*
* @param javaClasses
* @return
*/
public Map<String, TypeInfo> preBuildTypeInfo(JavaClass[] javaClasses) {
for (JavaClass javaClass : javaClasses) {
if (javaClass == null || !shouldGenerateTypeInfo(javaClass) || isXmlRegistry(javaClass) || javaClass.isArray()) {
continue;
}
TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
if (info != null) {
if (info.isPreBuilt()) {
continue;
}
}
if (javaClass.isEnum()) {
info = new EnumTypeInfo(helper);
} else {
info = new TypeInfo(helper);
}
info.setJavaClassName(javaClass.getQualifiedName());
info.setPreBuilt(true);
// handle @XmlTransient
if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) {
info.setXmlTransient(true);
}
// handle @XmlInlineBinaryData
if (helper.isAnnotationPresent(javaClass, XmlInlineBinaryData.class)) {
info.setInlineBinaryData(true);
}
// handle @XmlRootElement
processXmlRootElement(javaClass, info);
// handle @XmlSeeAlso
processXmlSeeAlso(javaClass, info);
NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass);
// handle @XmlType
preProcessXmlType(javaClass, info, packageNamespace);
// handle @XmlAccessorType
preProcessXmlAccessorType(javaClass, info, packageNamespace);
// handle @XmlAccessorOrder
preProcessXmlAccessorOrder(javaClass, info, packageNamespace);
// handle package level @XmlJavaTypeAdapters
processPackageLevelAdapters(javaClass, info);
// handle class level @XmlJavaTypeAdapters
processClassLevelAdapters(javaClass, info);
// handle descriptor customizer
preProcessCustomizer(javaClass, info);
// handle package level @XmlSchemaType(s)
processSchemaTypes(javaClass, info);
// handle class extractor
if (helper.isAnnotationPresent(javaClass, XmlClassExtractor.class)) {
XmlClassExtractor classExtractor = (XmlClassExtractor) helper.getAnnotation(javaClass, XmlClassExtractor.class);
info.setClassExtractorName(classExtractor.value().getName());
}
// handle user properties
if (helper.isAnnotationPresent(javaClass, XmlProperties.class)) {
XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(javaClass, XmlProperties.class);
Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value());
info.setUserProperties(propertiesMap);
} else if (helper.isAnnotationPresent(javaClass, XmlProperty.class)) {
XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(javaClass, XmlProperty.class);
Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty });
info.setUserProperties(propertiesMap);
}
// handle class indicator field name
if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorNode.class)) {
XmlDiscriminatorNode xmlDiscriminatorNode = (XmlDiscriminatorNode) helper.getAnnotation(javaClass, XmlDiscriminatorNode.class);
info.setXmlDiscriminatorNode(xmlDiscriminatorNode.value());
}
// handle class indicator
if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorValue.class)) {
XmlDiscriminatorValue xmlDiscriminatorValue = (XmlDiscriminatorValue) helper.getAnnotation(javaClass, XmlDiscriminatorValue.class);
info.setXmlDiscriminatorValue(xmlDiscriminatorValue.value());
}
typeInfoClasses.add(javaClass);
typeInfo.put(info.getJavaClassName(), info);
}
return typeInfo;
}
/**
* Process any additional classes (i.e. inner classes, @XmlSeeAlso,
* @XmlRegistry, etc.) for a given set of JavaClasses, then complete
* building all of the required TypeInfo objects. This method
* is typically called after init and preBuildTypeInfo have
* been called.
*
* @param javaClasses
* @return updated array of JavaClasses, made up of the original classes
* plus any additional ones
*/
public JavaClass[] postBuildTypeInfo(JavaClass[] javaClasses) {
if (javaClasses.length == 0) {
return javaClasses;
}
// create type info instances for any additional classes
javaClasses = processAdditionalClasses(javaClasses);
preBuildTypeInfo(javaClasses);
updateGlobalElements(javaClasses);
buildTypeInfo(javaClasses);
return javaClasses;
}
/**
* INTERNAL:
*
* Complete building TypeInfo objects for a given set of JavaClass
* instances. This method assumes that init, preBuildTypeInfo, and
* postBuildTypeInfo have been called.
*
* @param allClasses
* @return
*/
private Map<String, TypeInfo> buildTypeInfo(JavaClass[] allClasses) {
for (JavaClass javaClass : allClasses) {
if (javaClass == null) {
continue;
}
TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
if (info == null || info.isPostBuilt()) {
continue;
}
info.setPostBuilt(true);
// handle factory methods
processFactoryMethods(javaClass, info);
NamespaceInfo packageNamespace = getNamespaceInfoForPackage(javaClass);
// handle @XmlAccessorType
postProcessXmlAccessorType(info, packageNamespace);
// handle @XmlType
postProcessXmlType(javaClass, info, packageNamespace);
// handle @XmlEnum
if (info.isEnumerationType()) {
addEnumTypeInfo(javaClass, ((EnumTypeInfo) info));
continue;
}
// process schema type name
processTypeQName(javaClass, info, packageNamespace);
// handle superclass if necessary
JavaClass superClass = (JavaClass) javaClass.getSuperclass();
if (shouldGenerateTypeInfo(superClass)) {
JavaClass[] jClassArray = new JavaClass[] { superClass };
buildNewTypeInfo(jClassArray);
}
// add properties
info.setProperties(getPropertiesForClass(javaClass, info));
// process properties
processTypeInfoProperties(javaClass, info);
// handle @XmlAccessorOrder
postProcessXmlAccessorOrder(info, packageNamespace);
validatePropOrderForInfo(info);
}
return typeInfo;
}
/**
* Perform any final generation and/or validation operations on TypeInfo
* properties.
*
*/
public void finalizeProperties() {
ArrayList<JavaClass> jClasses = getTypeInfoClasses();
for (JavaClass jClass : jClasses) {
TypeInfo tInfo = getTypeInfo().get(jClass.getQualifiedName());
// don't need to validate props on a transient class at this point
if (tInfo.isTransient()) {
continue;
}
if(!jClass.isInterface() && !tInfo.isEnumerationType() && !jClass.isAbstract()) {
if (tInfo.getFactoryMethodName() == null && tInfo.getObjectFactoryClassName() == null) {
JavaConstructor zeroArgConstructor = jClass.getDeclaredConstructor(new JavaClass[] {});
if (zeroArgConstructor == null) {
if(tInfo.isSetXmlJavaTypeAdapter()) {
tInfo.setTransient(true);
} else {
throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodOrConstructorRequired(jClass.getName());
}
}
}
}
// validate XmlValue
if (tInfo.getXmlValueProperty() != null) {
validateXmlValueFieldOrProperty(jClass, tInfo.getXmlValueProperty());
}
for (Property property : tInfo.getPropertyList()) {
// need to check for transient reference class
JavaClass typeClass = property.getActualType();
TypeInfo targetInfo = typeInfo.get(typeClass.getQualifiedName());
if (targetInfo != null && targetInfo.isTransient()) {
throw JAXBException.invalidReferenceToTransientClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
}
// only one XmlValue is allowed per class, and if there is one only XmlAttributes are allowed
if (tInfo.isSetXmlValueProperty()) {
if (property.isXmlValue() && !(tInfo.getXmlValueProperty().getPropertyName().equals(property.getPropertyName()))) {
throw JAXBException.xmlValueAlreadySet(property.getPropertyName(), tInfo.getXmlValueProperty().getPropertyName(), jClass.getName());
}
if (!property.isXmlValue() && !property.isAttribute() && !property.isInverseReference() && !property.isTransient()) {
throw JAXBException.propertyOrFieldShouldBeAnAttribute(property.getPropertyName());
}
}
if(property.isSwaAttachmentRef() && !this.hasSwaRef) {
this.hasSwaRef = true;
}
// validate XmlIDREF
if (property.isXmlIdRef()) {
// the target class must have an associated TypeInfo unless it is Object
if (targetInfo == null && !typeClass.getQualifiedName().equals(JAVA_LANG_OBJECT)) {
throw JAXBException.invalidIDREFClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
}
// if the property is an XmlIDREF, the target must have an XmlID set
if (targetInfo != null && targetInfo.getIDProperty() == null) {
throw JAXBException.invalidIdRef(property.getPropertyName(), typeClass.getQualifiedName());
}
}
// there can only be one XmlID per type info
if (property.isXmlId() && tInfo.getIDProperty() != null && !(tInfo.getIDProperty().getPropertyName().equals(property.getPropertyName()))) {
throw JAXBException.idAlreadySet(property.getPropertyName(), tInfo.getIDProperty().getPropertyName(), jClass.getName());
}
// there can only be one XmlAnyAttribute per type info
if (property.isAnyAttribute() && tInfo.isSetAnyAttributePropertyName() && !(tInfo.getAnyAttributePropertyName().equals(property.getPropertyName()))) {
throw JAXBException.multipleAnyAttributeMapping(jClass.getName());
}
// there can only be one XmlAnyElement per type info
if (property.isAny() && tInfo.isSetAnyElementPropertyName() && !(tInfo.getAnyElementPropertyName().equals(property.getPropertyName()))) {
throw JAXBException.xmlAnyElementAlreadySet(property.getPropertyName(), tInfo.getAnyElementPropertyName(), jClass.getName());
}
// an XmlAttachmentRef can only appear on a DataHandler property
if (property.isSwaAttachmentRef() && !areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) {
throw JAXBException.invalidAttributeRef(property.getPropertyName(), jClass.getQualifiedName());
}
// an XmlElementWrapper can only appear on a Collection or Array
if (property.getXmlElementWrapper() != null) {
if (!isCollectionType(property) && !property.getType().isArray()) {
throw JAXBException.invalidElementWrapper(property.getPropertyName());
}
}
// handle XmlElementRef(s) - validate and build the required ElementDeclaration object
if (property.isReference()) {
processReferenceProperty(property, tInfo, jClass);
}
// handle XmlTransformation - validate transformer class/method
if (property.isXmlTransformation()) {
processXmlTransformationProperty(property);
}
// validate XmlJoinNodes
if (property.isSetXmlJoinNodes()) {
// the target class must have an associated TypeInfo
if (targetInfo == null) {
throw JAXBException.invalidXmlJoinNodeReferencedClass(property.getPropertyName(), typeClass.getQualifiedName());
}
// validate each referencedXmlPath - target TypeInfo should
// have XmlID/XmlKey property with matching XmlPath
if (targetInfo.getIDProperty() == null && targetInfo.getXmlKeyProperties() == null) {
throw JAXBException.noKeyOrIDPropertyOnJoinTarget(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
}
for (org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode : property.getXmlJoinNodes().getXmlJoinNode()) {
String refXPath = xmlJoinNode.getReferencedXmlPath();
if (targetInfo.getIDProperty() != null && refXPath.equals(targetInfo.getIDProperty().getXmlPath())) {
continue;
}
boolean matched = false;
if (targetInfo.getXmlKeyProperties() != null) {
for (Property xmlkeyProperty : targetInfo.getXmlKeyProperties()) {
if (refXPath.equals(xmlkeyProperty.getXmlPath())) {
matched = true;
break;
}
}
}
if (!matched) {
throw JAXBException.invalidReferencedXmlPathOnJoin(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName(), refXPath);
}
}
}
}
}
}
/**
* Process a given TypeInfo instance's properties.
*
* @param info
*/
private void processTypeInfoProperties(JavaClass javaClass, TypeInfo info) {
ArrayList<Property> properties = info.getPropertyList();
for (Property property : properties) {
// handle @XmlID
processXmlID(property, javaClass, info);
// handle @XmlIDREF - validate these properties after processing of
// all types is completed
processXmlIDREF(property);
if(property.isMap()) {
JavaClass keyType = property.getKeyType();
if (shouldGenerateTypeInfo(keyType)) {
JavaClass[] jClassArray = new JavaClass[] { keyType };
buildNewTypeInfo(jClassArray);
}
JavaClass valueType = property.getValueType();
if (shouldGenerateTypeInfo(valueType)) {
JavaClass[] jClassArray = new JavaClass[] { valueType };
buildNewTypeInfo(jClassArray);
}
}
}
}
void processPropertyTypes(JavaClass[] classes) {
for (JavaClass next:classes) {
TypeInfo info = getTypeInfo().get(next.getQualifiedName());
if(info != null) {
for (Property property : info.getPropertyList()) {
if(property.isTransient()) {
continue;
}
JavaClass type = property.getActualType();
if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) {
CompilerHelper.addClassToClassLoader(type, helper.getClassLoader());
JavaClass[] jClassArray = new JavaClass[] { type };
buildNewTypeInfo(jClassArray);
}
if(property.isChoice()) {
processChoiceProperty(property, info, next, type);
for(Property choiceProp:property.getChoiceProperties()) {
type = choiceProp.getActualType();
if (!(this.typeInfo.containsKey(type.getQualifiedName())) && shouldGenerateTypeInfo(type)) {
CompilerHelper.addClassToClassLoader(type, helper.getClassLoader());
JavaClass[] jClassArray = new JavaClass[] { type };
buildNewTypeInfo(jClassArray);
}
}
}
}
}
}
}
/**
* This method was initially designed to handle processing one or more
* JavaClass instances. Over time its functionality has been broken apart
* and handled in different methods. Its sole purpose now is to check for
* callback methods.
*
* @param classes
* this paramater can and should be null as it is not used
*/
public void processJavaClasses(JavaClass[] classes) {
checkForCallbackMethods();
}
/**
* Process any additional classes, such as inner classes, @XmlRegistry or
* from @XmlSeeAlso.
*
* @param classes
* @return
*/
private JavaClass[] processAdditionalClasses(JavaClass[] classes) {
ArrayList<JavaClass> extraClasses = new ArrayList<JavaClass>();
ArrayList<JavaClass> classesToProcess = new ArrayList<JavaClass>();
for (JavaClass jClass : classes) {
Class xmlElementType = null;
JavaClass javaClass = jClass;
TypeMappingInfo tmi = javaClassToTypeMappingInfos.get(javaClass);
if (tmi != null) {
Class adapterClass = this.typeMappingInfoToAdapterClasses.get(tmi);
if (adapterClass != null) {
JavaClass adapterJavaClass = helper.getJavaClass(adapterClass);
JavaClass newType = helper.getJavaClass(Object.class);
// look for marshal method
for (Object nextMethod : adapterJavaClass.getDeclaredMethods()) {
JavaMethod method = (JavaMethod) nextMethod;
if (method.getName().equals("marshal")) {
JavaClass returnType = method.getReturnType();
if (!returnType.getQualifiedName().equals(newType.getQualifiedName())) {
newType = (JavaClass) returnType;
break;
}
}
}
javaClass = newType;
}
java.lang.annotation.Annotation[] annotations = getAnnotations(tmi);
if (annotations != null) {
for (int j = 0; j < annotations.length; j++) {
java.lang.annotation.Annotation nextAnnotation = annotations[j];
if (nextAnnotation != null) {
if (nextAnnotation instanceof XmlElement) {
XmlElement javaAnnotation = (XmlElement) nextAnnotation;
if (javaAnnotation.type() != XmlElement.DEFAULT.class) {
xmlElementType = javaAnnotation.type();
}
}
}
}
}
}
if (areEquals(javaClass, byte[].class) || areEquals(javaClass, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(javaClass, Source.class) || areEquals(javaClass, Image.class) || areEquals(javaClass, JAVAX_MAIL_INTERNET_MIMEMULTIPART)) {
if (tmi == null || tmi.getXmlTagName() == null) {
ElementDeclaration declaration = new ElementDeclaration(null, javaClass, javaClass.getQualifiedName(), false, XmlElementDecl.GLOBAL.class);
declaration.setTypeMappingInfo(tmi);
getGlobalElements().put(null, declaration);
}
} else if (javaClass.isArray()) {
if (!helper.isBuiltInJavaType(javaClass.getComponentType())) {
extraClasses.add(javaClass.getComponentType());
}
Class generatedClass;
if (null == tmi) {
generatedClass = arrayClassesToGeneratedClasses.get(javaClass.getName());
} else {
generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
}
if (generatedClass == null) {
generatedClass = generateWrapperForArrayClass(javaClass, tmi, xmlElementType, extraClasses);
extraClasses.add(helper.getJavaClass(generatedClass));
arrayClassesToGeneratedClasses.put(javaClass.getName(), generatedClass);
}
generatedClassesToArrayClasses.put(generatedClass, javaClass);
typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
} else if (isCollectionType(javaClass)) {
JavaClass componentClass;
if (javaClass.hasActualTypeArguments()) {
componentClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0];
if (!componentClass.isPrimitive()) {
extraClasses.add(componentClass);
}
} else {
componentClass = helper.getJavaClass(Object.class);
}
Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
if (generatedClass == null) {
generatedClass = generateCollectionValue(javaClass, tmi, xmlElementType);
extraClasses.add(helper.getJavaClass(generatedClass));
}
typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
} else if (isMapType(javaClass)) {
JavaClass keyClass;
JavaClass valueClass;
if (javaClass.hasActualTypeArguments()) {
keyClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[0];
if (!helper.isBuiltInJavaType(keyClass)) {
extraClasses.add(keyClass);
}
valueClass = (JavaClass) javaClass.getActualTypeArguments().toArray()[1];
if (!helper.isBuiltInJavaType(valueClass)) {
extraClasses.add(valueClass);
}
} else {
keyClass = helper.getJavaClass(Object.class);
valueClass = helper.getJavaClass(Object.class);
}
Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
if (generatedClass == null) {
generatedClass = generateWrapperForMapClass(javaClass, keyClass, valueClass, tmi);
extraClasses.add(helper.getJavaClass(generatedClass));
}
typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
} else {
// process @XmlRegistry, @XmlSeeAlso and inner classes
processClass(javaClass, classesToProcess);
}
}
// process @XmlRegistry, @XmlSeeAlso and inner classes
for (JavaClass javaClass : extraClasses) {
processClass(javaClass, classesToProcess);
}
return classesToProcess.toArray(new JavaClass[classesToProcess.size()]);
}
/**
* Adds additional classes to the given List, from inner classes,
*
* @XmlRegistry or @XmlSeeAlso.
*
* @param javaClass
* @param classesToProcess
*/
private void processClass(JavaClass javaClass, ArrayList<JavaClass> classesToProcess) {
if (shouldGenerateTypeInfo(javaClass)) {
if (isXmlRegistry(javaClass)) {
this.processObjectFactory(javaClass, classesToProcess);
} else {
classesToProcess.add(javaClass);
// handle @XmlSeeAlso
TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
if (info != null && info.isSetXmlSeeAlso()) {
for (String jClassName : info.getXmlSeeAlso()) {
classesToProcess.add(helper.getJavaClass(jClassName));
}
}
// handle inner classes
for (Iterator<JavaClass> jClassIt = javaClass.getDeclaredClasses().iterator(); jClassIt.hasNext();) {
JavaClass innerClass = jClassIt.next();
if (shouldGenerateTypeInfo(innerClass)) {
CompilerHelper.addClassToClassLoader(innerClass, helper.getClassLoader());
TypeInfo tInfo = typeInfo.get(innerClass.getQualifiedName());
if ((tInfo != null && !tInfo.isTransient()) || !helper.isAnnotationPresent(innerClass, XmlTransient.class)) {
classesToProcess.add(innerClass);
}
}
}
}
}
}
/**
* Process an @XmlSeeAlso annotation. TypeInfo instances will be created for
* each class listed.
*
* @param javaClass
*/
private void processXmlSeeAlso(JavaClass javaClass, TypeInfo info) {
// reflectively load @XmlSeeAlso class to avoid dependency
Class xmlSeeAlsoClass = null;
Method valueMethod = null;
try {
xmlSeeAlsoClass = PrivilegedAccessHelper.getClassForName("javax.xml.bind.annotation.XmlSeeAlso");
valueMethod = PrivilegedAccessHelper.getDeclaredMethod(xmlSeeAlsoClass, "value", new Class[] {});
} catch (ClassNotFoundException ex) {
// Ignore this exception. If SeeAlso isn't available, don't try to
// process
} catch (NoSuchMethodException ex) {
}
if (xmlSeeAlsoClass != null && helper.isAnnotationPresent(javaClass, xmlSeeAlsoClass)) {
Object seeAlso = helper.getAnnotation(javaClass, xmlSeeAlsoClass);
Class[] values = null;
try {
values = (Class[]) PrivilegedAccessHelper.invokeMethod(valueMethod, seeAlso, new Object[] {});
} catch (Exception ex) {
}
List<String> seeAlsoClassNames = new ArrayList<String>();
for (Class next : values) {
seeAlsoClassNames.add(next.getName());
}
info.setXmlSeeAlso(seeAlsoClassNames);
}
}
/**
* Process any factory methods.
*
* @param javaClass
* @param info
*/
private void processFactoryMethods(JavaClass javaClass, TypeInfo info) {
JavaMethod factoryMethod = this.factoryMethods.get(javaClass.getRawName());
if (factoryMethod != null) {
// set up factory method info for mappings.
info.setFactoryMethodName(factoryMethod.getName());
info.setObjectFactoryClassName(factoryMethod.getOwningClass().getRawName());
JavaClass[] paramTypes = factoryMethod.getParameterTypes();
if (paramTypes != null && paramTypes.length > 0) {
String[] paramTypeNames = new String[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
paramTypeNames[i] = paramTypes[i].getRawName();
}
info.setFactoryMethodParamTypes(paramTypeNames);
}
}
}
/**
* Process any package-level @XmlJavaTypeAdapters.
*
* @param javaClass
* @param info
*/
private void processPackageLevelAdapters(JavaClass javaClass, TypeInfo info) {
JavaPackage pack = javaClass.getPackage();
if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapters.class)) {
XmlJavaTypeAdapters adapters = (XmlJavaTypeAdapters) helper.getAnnotation(pack, XmlJavaTypeAdapters.class);
XmlJavaTypeAdapter[] adapterArray = adapters.value();
for (XmlJavaTypeAdapter next : adapterArray) {
processPackageLevelAdapter(next, info);
}
}
if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(pack, XmlJavaTypeAdapter.class);
processPackageLevelAdapter(adapter, info);
}
}
private void processPackageLevelAdapter(XmlJavaTypeAdapter next, TypeInfo info) {
JavaClass adapterClass = helper.getJavaClass(next.value());
JavaClass boundType = helper.getJavaClass(next.type());
if (boundType != null) {
info.addPackageLevelAdapterClass(adapterClass, boundType);
} else {
getLogger().logWarning(JAXBMetadataLogger.INVALID_BOUND_TYPE, new Object[] { boundType, adapterClass });
}
}
/**
* Process any class-level @XmlJavaTypeAdapters.
*
* @param javaClass
* @param info
*/
private void processClassLevelAdapters(JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(javaClass, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(javaClass, XmlJavaTypeAdapter.class);
String boundType = adapter.type().getName();
if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) {
boundType = javaClass.getRawName();
}
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
xja.setValue(adapter.value().getName());
xja.setType(boundType);
info.setXmlJavaTypeAdapter(xja);
}
}
/**
* Process any @XmlSchemaType(s).
*
* @param javaClass
* @param info
*/
private void processSchemaTypes(JavaClass javaClass, TypeInfo info) {
JavaPackage pack = javaClass.getPackage();
if (helper.isAnnotationPresent(pack, XmlSchemaTypes.class)) {
XmlSchemaTypes types = (XmlSchemaTypes) helper.getAnnotation(pack, XmlSchemaTypes.class);
XmlSchemaType[] typeArray = types.value();
for (XmlSchemaType next : typeArray) {
processSchemaType(next);
}
} else if (helper.isAnnotationPresent(pack, XmlSchemaType.class)) {
processSchemaType((XmlSchemaType) helper.getAnnotation(pack, XmlSchemaType.class));
}
}
/**
* Process @XmlRootElement annotation on a given JavaClass.
*
* @param javaClass
* @param info
*/
private void processXmlRootElement(JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(javaClass, XmlRootElement.class)) {
XmlRootElement rootElemAnnotation = (XmlRootElement) helper.getAnnotation(javaClass, XmlRootElement.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = new org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement();
xmlRE.setName(rootElemAnnotation.name());
xmlRE.setNamespace(rootElemAnnotation.namespace());
info.setXmlRootElement(xmlRE);
}
}
/**
* Process @XmlType annotation on a given JavaClass and update the TypeInfo
* for pre-processing. Note that if no @XmlType annotation is present we
* still create a new XmlType an set it on the TypeInfo.
*
* @param javaClass
* @param info
* @param packageNamespace
*/
private void preProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = new org.eclipse.persistence.jaxb.xmlmodel.XmlType();
if (helper.isAnnotationPresent(javaClass, XmlType.class)) {
XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class);
// set name
xmlType.setName(typeAnnotation.name());
// set namespace
xmlType.setNamespace(typeAnnotation.namespace());
// set propOrder
String[] propOrder = typeAnnotation.propOrder();
// handle case where propOrder is an empty array
if (propOrder != null) {
xmlType.getPropOrder();
}
for (String prop : propOrder) {
xmlType.getPropOrder().add(prop);
}
// set factoryClass
Class factoryClass = typeAnnotation.factoryClass();
if (factoryClass == DEFAULT.class) {
xmlType.setFactoryClass("javax.xml.bind.annotation.XmlType.DEFAULT");
} else {
xmlType.setFactoryClass(factoryClass.getCanonicalName());
}
// set factoryMethodName
xmlType.setFactoryMethod(typeAnnotation.factoryMethod());
} else {
// set defaults
xmlType.setName(getSchemaTypeNameForClassName(javaClass.getName()));
xmlType.setNamespace(packageNamespace.getNamespace());
}
info.setXmlType(xmlType);
}
/**
* Process XmlType for a given TypeInfo. Here we assume that the TypeInfo
* has an XmlType set - typically via preProcessXmlType or XmlProcessor
* override.
*
* @param javaClass
* @param info
* @param packageNamespace
*/
private void postProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
// assumes that the TypeInfo has an XmlType set from
org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = info.getXmlType();
// set/validate factoryClass and factoryMethod
String factoryClassName = xmlType.getFactoryClass();
String factoryMethodName = xmlType.getFactoryMethod();
if (factoryClassName.equals("javax.xml.bind.annotation.XmlType.DEFAULT")) {
if (factoryMethodName != null && !factoryMethodName.equals(EMPTY_STRING)) {
// factory method applies to the current class - verify method exists
JavaMethod method = javaClass.getDeclaredMethod(factoryMethodName, new JavaClass[] {});
if (method == null) {
throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodNotDeclared(factoryMethodName, javaClass.getName());
}
info.setFactoryMethodName(factoryMethodName);
}
} else {
if (factoryMethodName == null || factoryMethodName.equals(EMPTY_STRING)) {
throw org.eclipse.persistence.exceptions.JAXBException.factoryClassWithoutFactoryMethod(javaClass.getName());
}
info.setObjectFactoryClassName(factoryClassName);
info.setFactoryMethodName(factoryMethodName);
}
// figure out type name
String typeName = xmlType.getName();
if (typeName.equals(XMLProcessor.DEFAULT)) {
typeName = getSchemaTypeNameForClassName(javaClass.getName());
}
info.setSchemaTypeName(typeName);
// set propOrder
if (xmlType.isSetPropOrder()) {
List<String> props = xmlType.getPropOrder();
if (props.size() == 0) {
info.setPropOrder(new String[0]);
} else if (props.get(0).equals(EMPTY_STRING)) {
info.setPropOrder(new String[] { EMPTY_STRING });
} else {
info.setPropOrder(xmlType.getPropOrder().toArray(new String[xmlType.getPropOrder().size()]));
}
}
// figure out namespace
if (xmlType.getNamespace().equals(XMLProcessor.DEFAULT)) {
info.setClassNamespace(packageNamespace.getNamespace());
} else {
info.setClassNamespace(xmlType.getNamespace());
}
}
/**
* Process @XmlAccessorType annotation on a given JavaClass and update the
* TypeInfo for pre-processing.
*
* @param javaClass
* @param info
* @param packageNamespace
*/
private void preProcessXmlAccessorType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType xmlAccessType;
if (helper.isAnnotationPresent(javaClass, XmlAccessorType.class)) {
XmlAccessorType accessorType = (XmlAccessorType) helper.getAnnotation(javaClass, XmlAccessorType.class);
xmlAccessType = org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(accessorType.value().name());
info.setXmlAccessType(xmlAccessType);
}
}
/**
* Post process XmlAccessorType. In some cases, such as @XmlSeeAlso classes,
* the access type may not have been set
*
* @param info
*/
private void postProcessXmlAccessorType(TypeInfo info, NamespaceInfo packageNamespace) {
if (!info.isSetXmlAccessType()) {
//Check for super class
JavaClass next = helper.getJavaClass(info.getJavaClassName()).getSuperclass();
while(next != null && !(next.getName().equals(JAVA_LANG_OBJECT))) {
TypeInfo parentInfo = this.typeInfo.get(next.getName());
if(parentInfo != null && parentInfo.isSetXmlAccessType()) {
info.setXmlAccessType(parentInfo.getXmlAccessType());
break;
}
next = next.getSuperclass();
}
// use value in package-info.java as last resort - will default if
// not set
info.setXmlAccessType(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.fromValue(packageNamespace.getAccessType().name()));
}
}
/**
* Process package and class @XmlAccessorOrder. Class level annotation
* overrides a package level annotation.
*
* @param javaClass
* @param info
* @param packageNamespace
*/
private void preProcessXmlAccessorOrder(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
XmlAccessorOrder order = null;
// class level annotation overrides package level annotation
if (helper.isAnnotationPresent(javaClass, XmlAccessorOrder.class)) {
order = (XmlAccessorOrder) helper.getAnnotation(javaClass, XmlAccessorOrder.class);
info.setXmlAccessOrder(XmlAccessOrder.fromValue(order.value().name()));
}
}
/**
* Post process XmlAccessorOrder. This method assumes that the given
* TypeInfo has already had its order set (via annotations in
* preProcessXmlAccessorOrder or via xml metadata override in XMLProcessor).
*
* @param javaClass
* @param info
*/
private void postProcessXmlAccessorOrder(TypeInfo info, NamespaceInfo packageNamespace) {
if (!info.isSetXmlAccessOrder()) {
// use value in package-info.java as last resort - will default if
// not set
info.setXmlAccessOrder(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder.fromValue(packageNamespace.getAccessOrder().name()));
}
info.orderProperties();
}
/**
* Process @XmlElement annotation on a given property.
*
* @param property
*/
private void processXmlElement(Property property, TypeInfo info) {
if (helper.isAnnotationPresent(property.getElement(), XmlElement.class)) {
XmlElement element = (XmlElement) helper.getAnnotation(property.getElement(), XmlElement.class);
property.setIsRequired(element.required());
property.setNillable(element.nillable());
if (element.type() != XmlElement.DEFAULT.class && !(property.isSwaAttachmentRef())) {
property.setOriginalType(property.getType());
if (isCollectionType(property.getType())) {
property.setGenericType(helper.getJavaClass(element.type()));
} else {
property.setType(helper.getJavaClass(element.type()));
}
property.setHasXmlElementType(true);
}
// handle default value
if (!element.defaultValue().equals(ELEMENT_DECL_DEFAULT)) {
property.setDefaultValue(element.defaultValue());
}
validateElementIsInPropOrder(info, property.getPropertyName());
}
}
/**
* Process @XmlID annotation on a given property
*
* @param property
* @param info
*/
private void processXmlID(Property property, JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(property.getElement(), XmlID.class)) {
property.setIsXmlId(true);
info.setIDProperty(property);
}
}
/**
* Process @XmlIDREF on a given property.
*
* @param property
*/
private void processXmlIDREF(Property property) {
if (helper.isAnnotationPresent(property.getElement(), XmlIDREF.class)) {
property.setIsXmlIdRef(true);
}
}
/**
* Process @XmlJavaTypeAdapter on a given property.
*
* @param property
* @param propertyType
*/
private void processXmlJavaTypeAdapter(Property property, TypeInfo info, JavaClass javaClass) {
JavaClass adapterClass = null;
JavaClass ptype = property.getActualType();
if (helper.isAnnotationPresent(property.getElement(), XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(property.getElement(), XmlJavaTypeAdapter.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
xja.setValue(adapter.value().getName());
xja.setType(adapter.type().getName());
property.setXmlJavaTypeAdapter(xja);
} else {
TypeInfo ptypeInfo = typeInfo.get(ptype.getQualifiedName());
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter;
if (ptypeInfo == null && shouldGenerateTypeInfo(ptype)) {
if(helper.isAnnotationPresent(ptype, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(ptype, XmlJavaTypeAdapter.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
xja.setValue(adapter.value().getName());
String boundType = adapter.type().getName();
if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) {
boundType = ptype.getRawName();
}
xja.setType(adapter.type().getName());
property.setXmlJavaTypeAdapter(xja);
}
}
if (ptypeInfo != null) {
if (null != (xmlJavaTypeAdapter = ptypeInfo.getXmlJavaTypeAdapter())) {
try {
property.setXmlJavaTypeAdapter(xmlJavaTypeAdapter);
} catch (JAXBException e) {
throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), javaClass.getName());
}
}
}
if (info.getPackageLevelAdaptersByClass().get(ptype.getQualifiedName()) != null && !property.isSetXmlJavaTypeAdapter()) {
adapterClass = info.getPackageLevelAdapterClass(ptype);
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
xja.setValue(adapterClass.getQualifiedName());
xja.setType(ptype.getQualifiedName());
property.setXmlJavaTypeAdapter(xja);
}
}
}
private void removeTypeInfo(String qualifiedName, TypeInfo info) {
this.typeInfo.remove(qualifiedName);
String typeName = info.getSchemaTypeName();
if (typeName != null && !(EMPTY_STRING.equals(typeName))) {
QName typeQName = new QName(info.getClassNamespace(), typeName);
this.typeQNames.remove(typeQName);
}
for(JavaClass next:this.typeInfoClasses) {
if(next.getQualifiedName().equals(info.getJavaClassName())) {
this.typeInfoClasses.remove(next);
break;
}
}
}
/**
* Store a QName (if necessary) based on a given TypeInfo's schema type
* name.
*
* @param javaClass
* @param info
*/
private void processTypeQName(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
String typeName = info.getSchemaTypeName();
if (typeName != null && !(EMPTY_STRING.equals(typeName))) {
QName typeQName = new QName(info.getClassNamespace(), typeName);
boolean containsQName = typeQNames.contains(typeQName);
if (containsQName) {
throw JAXBException.nameCollision(typeQName.getNamespaceURI(), typeQName.getLocalPart());
} else {
typeQNames.add(typeQName);
}
}
}
public boolean shouldGenerateTypeInfo(JavaClass javaClass) {
if (javaClass == null || javaClass.isPrimitive() || javaClass.isAnnotation() || ORG_W3C_DOM.equals(javaClass.getPackageName())) {
return false;
}
if (userDefinedSchemaTypes.get(javaClass.getQualifiedName()) != null) {
return false;
}
if (javaClass.isArray()) {
String javaClassName = javaClass.getName();
if (!(javaClassName.equals(ClassConstants.APBYTE.getName()))) {
return true;
}
}
if (helper.isBuiltInJavaType(javaClass)) {
return false;
}
if (isCollectionType(javaClass) || isMapType(javaClass)) {
return false;
}
return true;
}
public ArrayList<Property> getPropertiesForClass(JavaClass cls, TypeInfo info) {
ArrayList<Property> returnList = new ArrayList<Property>();
if (!info.isTransient()) {
JavaClass superClass = cls.getSuperclass();
if (null != superClass) {
TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName());
while (superClassInfo != null && superClassInfo.isTransient()) {
if (info.getXmlAccessType() == XmlAccessType.FIELD) {
returnList.addAll(getFieldPropertiesForClass(superClass, superClassInfo, false));
} else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) {
returnList.addAll(getPropertyPropertiesForClass(superClass, superClassInfo, false));
} else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) {
returnList.addAll(getPublicMemberPropertiesForClass(superClass, superClassInfo));
} else {
returnList.addAll(getNoAccessTypePropertiesForClass(superClass, superClassInfo));
}
superClass = superClass.getSuperclass();
superClassInfo = typeInfo.get(superClass.getQualifiedName());
}
}
}
if (info.isTransient()) {
returnList.addAll(getNoAccessTypePropertiesForClass(cls, info));
} else if (info.getXmlAccessType() == XmlAccessType.FIELD) {
returnList.addAll(getFieldPropertiesForClass(cls, info, false));
} else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) {
returnList.addAll(getPropertyPropertiesForClass(cls, info, false));
} else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) {
returnList.addAll(getPublicMemberPropertiesForClass(cls, info));
} else {
returnList.addAll(getNoAccessTypePropertiesForClass(cls, info));
}
return returnList;
}
public ArrayList<Property> getFieldPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) {
ArrayList<Property> properties = new ArrayList<Property>();
if (cls == null) {
return properties;
}
for (Iterator<JavaField> fieldIt = cls.getDeclaredFields().iterator(); fieldIt.hasNext();) {
JavaField nextField = fieldIt.next();
int modifiers = nextField.getModifiers();
if (!helper.isAnnotationPresent(nextField, XmlTransient.class)) {
if (!Modifier.isTransient(modifiers) && ((Modifier.isPublic(nextField.getModifiers()) && onlyPublic) || !onlyPublic)) {
if (!Modifier.isStatic(modifiers)) {
Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType());
properties.add(property);
} else if (helper.isAnnotationPresent(nextField, XmlAttribute.class)) {
try {
Property property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType());
Object value = ((JavaFieldImpl) nextField).get(null);
if(value != null) {
String stringValue = (String) XMLConversionManager.getDefaultXMLManager().convertObject(value, String.class, property.getSchemaType());
property.setFixedValue(stringValue);
} else {
property.setWriteOnly(true);
}
properties.add(property);
} catch (ClassCastException e) {
// do Nothing
} catch (IllegalAccessException e) {
// do Nothing
}
}
}
} else {
// If a property is marked transient ensure it doesn't exist in
// the propOrder
List<String> propOrderList = Arrays.asList(info.getPropOrder());
if (propOrderList.contains(nextField.getName())) {
throw JAXBException.transientInProporder(nextField.getName());
}
}
}
return properties;
}
/*
* Create a new Property Object and process the annotations that are common
* to fields and methods
*/
private Property buildNewProperty(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) {
Property property = null;
if (helper.isAnnotationPresent(javaHasAnnotations, XmlElements.class)) {
property = buildChoiceProperty(javaHasAnnotations);
} else if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementRef.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlElementRefs.class)) {
property = buildReferenceProperty(info, javaHasAnnotations, propertyName, ptype);
if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
property.setIsAny(true);
if (anyElement.value() != null) {
property.setDomHandlerClassName(anyElement.value().getName());
}
property.setLax(anyElement.lax());
info.setAnyElementPropertyName(propertyName);
}
} else if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
property = new Property(helper);
property.setIsAny(true);
if (anyElement.value() != null) {
property.setDomHandlerClassName(anyElement.value().getName());
}
property.setLax(anyElement.lax());
info.setAnyElementPropertyName(propertyName);
} else if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) {
property = buildTransformationProperty(javaHasAnnotations, cls);
} else {
property = new Property(helper);
}
property.setPropertyName(propertyName);
property.setElement(javaHasAnnotations);
// if there is a TypeInfo for ptype check it for transient, otherwise
// check the class
TypeInfo pTypeInfo = typeInfo.get(ptype.getQualifiedName());
if ((pTypeInfo != null && !pTypeInfo.isTransient()) || !helper.isAnnotationPresent(ptype, XmlTransient.class)) {
property.setType(ptype);
} else {
JavaClass parent = ptype.getSuperclass();
while (parent != null) {
if (parent.getName().equals(JAVA_LANG_OBJECT)) {
property.setType(parent);
break;
}
// if there is a TypeInfo for parent check it for transient,
// otherwise check the class
TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName());
if ((parentTypeInfo != null && !parentTypeInfo.isTransient()) || !helper.isAnnotationPresent(parent, XmlTransient.class)) {
property.setType(parent);
break;
}
parent = parent.getSuperclass();
}
}
processPropertyAnnotations(info, cls, javaHasAnnotations, property);
if (helper.isAnnotationPresent(javaHasAnnotations, XmlPath.class)) {
XmlPath xmlPath = (XmlPath) helper.getAnnotation(javaHasAnnotations, XmlPath.class);
property.setXmlPath(xmlPath.value());
// set schema name
String schemaName = XMLProcessor.getNameFromXPath(xmlPath.value(), property.getPropertyName(), property.isAttribute());
QName qName;
NamespaceInfo nsInfo = getNamespaceInfoForPackage(cls);
if (nsInfo.isElementFormQualified()) {
qName = new QName(nsInfo.getNamespace(), schemaName);
} else {
qName = new QName(schemaName);
}
property.setSchemaName(qName);
} else {
property.setSchemaName(getQNameForProperty(propertyName, javaHasAnnotations, getNamespaceInfoForPackage(cls), info.getClassNamespace()));
}
ptype = property.getActualType();
if (ptype.isPrimitive()) {
property.setIsRequired(true);
}
// apply class level adapters - don't override property level adapter
if (!property.isSetXmlJavaTypeAdapter()) {
TypeInfo refClassInfo = getTypeInfo().get(ptype.getQualifiedName());
if (refClassInfo != null && refClassInfo.isSetXmlJavaTypeAdapter()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter = null;
try {
xmlJavaTypeAdapter = refClassInfo.getXmlJavaTypeAdapter();
property.setXmlJavaTypeAdapter(refClassInfo.getXmlJavaTypeAdapter());
} catch (JAXBException e) {
throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), cls.getName());
}
}
}
return property;
}
/**
* Build a new 'choice' property. Here, we flag a new property as a 'choice'
* and create/set an XmlModel XmlElements object based on the @XmlElements
* annotation.
*
* Validation and building of the XmlElement properties will be done during
* finalizeProperties in the processChoiceProperty method.
*
* @param javaHasAnnotations
* @return
*/
private Property buildChoiceProperty(JavaHasAnnotations javaHasAnnotations) {
Property choiceProperty = new Property(helper);
choiceProperty.setChoice(true);
boolean isIdRef = helper.isAnnotationPresent(javaHasAnnotations, XmlIDREF.class);
choiceProperty.setIsXmlIdRef(isIdRef);
// build an XmlElement to set on the Property
org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements();
XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value();
for (int i = 0; i < elements.length; i++) {
XmlElement next = elements[i];
org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement();
xmlElement.setDefaultValue(next.defaultValue());
xmlElement.setName(next.name());
xmlElement.setNamespace(next.namespace());
xmlElement.setNillable(next.nillable());
xmlElement.setRequired(next.required());
xmlElement.setType(next.type().getName());
xmlElements.getXmlElement().add(xmlElement);
}
choiceProperty.setXmlElements(xmlElements);
// handle XmlElementsJoinNodes
if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementsJoinNodes.class)) {
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes;
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode;
List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes> xmlJoinNodesList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes>();
List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList = null;
for (XmlJoinNodes xmlJNs : ((XmlElementsJoinNodes) helper.getAnnotation(javaHasAnnotations, XmlElementsJoinNodes.class)).value()) {
xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>();
for (XmlJoinNode xmlJN : xmlJNs.value()) {
xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode();
xmlJoinNode.setXmlPath(xmlJN.xmlPath());
xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath());
xmlJoinNodeList.add(xmlJoinNode);
}
if (xmlJoinNodeList.size() > 0) {
xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes();
xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList);
xmlJoinNodesList.add(xmlJoinNodes);
}
}
choiceProperty.setXmlJoinNodesList(xmlJoinNodesList);
}
return choiceProperty;
}
private Property buildTransformationProperty(JavaHasAnnotations javaHasAnnotations, JavaClass cls) {
Property property = new Property(helper);
org.eclipse.persistence.oxm.annotations.XmlTransformation transformationAnnotation = (org.eclipse.persistence.oxm.annotations.XmlTransformation) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlTransformation.class);
XmlTransformation transformation = new XmlTransformation();
if (transformationAnnotation != null) {
transformation.setOptional(transformationAnnotation.optional());
}
// Read Transformer
org.eclipse.persistence.oxm.annotations.XmlReadTransformer readTransformer = (org.eclipse.persistence.oxm.annotations.XmlReadTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlReadTransformer.class);
if (readTransformer != null) {
org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer xmlReadTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer();
if (!(readTransformer.transformerClass() == AttributeTransformer.class)) {
xmlReadTransformer.setTransformerClass(readTransformer.transformerClass().getName());
} else if (!(readTransformer.method().equals(EMPTY_STRING))) {
xmlReadTransformer.setMethod(readTransformer.method());
}
transformation.setXmlReadTransformer(xmlReadTransformer);
}
// Handle Write Transformers
org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] transformers = null;
if (helper.isAnnotationPresent(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class)) {
org.eclipse.persistence.oxm.annotations.XmlWriteTransformer writeTransformer = (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer) helper.getAnnotation(javaHasAnnotations, org.eclipse.persistence.oxm.annotations.XmlWriteTransformer.class);
transformers = new org.eclipse.persistence.oxm.annotations.XmlWriteTransformer[] { writeTransformer };
} else if (helper.isAnnotationPresent(javaHasAnnotations, XmlWriteTransformers.class)) {
XmlWriteTransformers writeTransformers = (XmlWriteTransformers) helper.getAnnotation(javaHasAnnotations, XmlWriteTransformers.class);
transformers = writeTransformers.value();
}
if (transformers != null) {
for (org.eclipse.persistence.oxm.annotations.XmlWriteTransformer next : transformers) {
org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer xmlWriteTransformer = new org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer();
if (!(next.transformerClass() == FieldTransformer.class)) {
xmlWriteTransformer.setTransformerClass(next.transformerClass().getName());
} else if (!(next.method().equals(EMPTY_STRING))) {
xmlWriteTransformer.setMethod(next.method());
}
xmlWriteTransformer.setXmlPath(next.xmlPath());
transformation.getXmlWriteTransformer().add(xmlWriteTransformer);
}
}
property.setXmlTransformation(transformation);
property.setIsXmlTransformation(true);
return property;
}
/**
* Complete creation of a 'choice' property. Here, a Property is created for
* each XmlElement in the XmlElements list. Validation is performed as well.
* Each created Property is added to the owning Property's list of choice
* properties.
*
* @param choiceProperty
* @param info
* @param cls
* @param propertyType
*/
private void processChoiceProperty(Property choiceProperty, TypeInfo info, JavaClass cls, JavaClass propertyType) {
String propertyName = choiceProperty.getPropertyName();
validateElementIsInPropOrder(info, propertyName);
// validate XmlElementsXmlJoinNodes (if set)
if (choiceProperty.isSetXmlJoinNodesList()) {
// there must be one XmlJoinNodes entry per XmlElement
if (choiceProperty.getXmlElements().getXmlElement().size() != choiceProperty.getXmlJoinNodesList().size()) {
throw JAXBException.incorrectNumberOfXmlJoinNodesOnXmlElements(propertyName, cls.getQualifiedName());
}
}
XmlPath[] paths = null;
if (helper.isAnnotationPresent(choiceProperty.getElement(), XmlPaths.class)) {
XmlPaths pathAnnotation = (XmlPaths) helper.getAnnotation(choiceProperty.getElement(), XmlPaths.class);
paths = pathAnnotation.value();
}
ArrayList<Property> choiceProperties = new ArrayList<Property>();
for (int i = 0; i < choiceProperty.getXmlElements().getXmlElement().size(); i++) {
org.eclipse.persistence.jaxb.xmlmodel.XmlElement next = choiceProperty.getXmlElements().getXmlElement().get(i);
Property choiceProp = new Property(helper);
String name;
String namespace;
// handle XmlPath - if xml-path is set, we ignore name/namespace
if (paths != null && next.getXmlPath() == null) {
// Only set the path, if the path hasn't already been set from xml
XmlPath nextPath = paths[i];
next.setXmlPath(nextPath.value());
}
if (next.getXmlPath() != null) {
choiceProp.setXmlPath(next.getXmlPath());
boolean isAttribute = next.getXmlPath().contains(AT_SIGN);
// validate attribute - must be in nested path, not at root
if (isAttribute && !next.getXmlPath().contains(SLASH)) {
throw JAXBException.invalidXmlPathWithAttribute(propertyName, cls.getQualifiedName(), next.getXmlPath());
}
choiceProp.setIsAttribute(isAttribute);
name = XMLProcessor.getNameFromXPath(next.getXmlPath(), propertyName, isAttribute);
namespace = XMLProcessor.DEFAULT;
} else {
// no xml-path, so use name/namespace from xml-element
name = next.getName();
namespace = next.getNamespace();
}
if (name == null || name.equals(XMLProcessor.DEFAULT)) {
if (next.getJavaAttribute() != null) {
name = next.getJavaAttribute();
} else {
name = propertyName;
}
}
// if the property has xml-idref, the target type of each
// xml-element in the list must have an xml-id property
if (choiceProperty.isXmlIdRef()) {
TypeInfo tInfo = typeInfo.get(next.getType());
if (tInfo == null || !tInfo.isIDSet()) {
throw JAXBException.invalidXmlElementInXmlElementsList(propertyName, name);
}
}
QName qName = null;
if (!namespace.equals(XMLProcessor.DEFAULT)) {
qName = new QName(namespace, name);
} else {
NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(cls);
if (namespaceInfo.isElementFormQualified()) {
qName = new QName(namespaceInfo.getNamespace(), name);
} else {
qName = new QName(name);
}
}
choiceProp.setPropertyName(name);
// figure out the property's type - note that for DEFAULT, if from XML the value will
// be "XmlElement.DEFAULT", and from annotations the value will be "XmlElement$DEFAULT"
if (next.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT") || next.getType().equals("javax.xml.bind.annotation.XmlElement$DEFAULT")) {
choiceProp.setType(propertyType);
} else {
choiceProp.setType(helper.getJavaClass(next.getType()));
}
// handle case of XmlJoinNodes w/XmlElements
if (choiceProperty.isSetXmlJoinNodesList()) {
// assumes one corresponding xml-join-nodes entry per xml-element
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes = choiceProperty.getXmlJoinNodesList().get(i);
if (xmlJoinNodes != null) {
choiceProp.setXmlJoinNodes(xmlJoinNodes);
// set type
if (!xmlJoinNodes.getType().equals(XMLProcessor.DEFAULT)) {
JavaClass pType = helper.getJavaClass(xmlJoinNodes.getType());
if (isCollectionType(choiceProp.getType())) {
choiceProp.setGenericType(pType);
} else {
choiceProp.setType(pType);
}
}
}
}
choiceProp.setSchemaName(qName);
choiceProp.setSchemaType(getSchemaTypeFor(choiceProp.getType()));
choiceProp.setIsXmlIdRef(choiceProperty.isXmlIdRef());
choiceProp.setXmlElementWrapper(choiceProperty.getXmlElementWrapper());
choiceProperties.add(choiceProp);
if (!(this.typeInfo.containsKey(choiceProp.getType().getQualifiedName())) && shouldGenerateTypeInfo(choiceProp.getType())) {
JavaClass[] jClassArray = new JavaClass[] { choiceProp.getType() };
buildNewTypeInfo(jClassArray);
}
}
choiceProperty.setChoiceProperties(choiceProperties);
}
/**
* Build a reference property. Here we will build a list of XML model
* XmlElementRef objects, based on the @XmlElement(s) annotation, to store
* on the Property. Processing of the elements and validation will be
* performed during the finalize property phase via the
* processReferenceProperty method.
*
* @param info
* @param javaHasAnnotations
* @param propertyName
* @param ptype
* @return
*/
private Property buildReferenceProperty(TypeInfo info, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) {
Property property = new Property(helper);
property.setType(ptype);
XmlElementRef[] elementRefs;
XmlElementRef ref = (XmlElementRef) helper.getAnnotation(javaHasAnnotations, XmlElementRef.class);
if (ref != null) {
elementRefs = new XmlElementRef[] { ref };
} else {
XmlElementRefs refs = (XmlElementRefs) helper.getAnnotation(javaHasAnnotations, XmlElementRefs.class);
elementRefs = refs.value();
info.setElementRefsPropertyName(propertyName);
}
List<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef> eltRefs = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef>();
for (XmlElementRef nextRef : elementRefs) {
org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef eltRef = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef();
eltRef.setName(nextRef.name());
eltRef.setNamespace(nextRef.namespace());
eltRef.setType(nextRef.type().getName());
eltRefs.add(eltRef);
}
property.setIsReference(true);
property.setXmlElementRefs(eltRefs);
return property;
}
/**
* Build a reference property.
*
* @param property
* @param info
* @param javaHasAnnotations
* @return
*/
private Property processReferenceProperty(Property property, TypeInfo info, JavaClass cls) {
String propertyName = property.getPropertyName();
validateElementIsInPropOrder(info, propertyName);
for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) {
JavaClass type = property.getType();
String typeName = type.getQualifiedName();
if (isCollectionType(property)) {
if (type.hasActualTypeArguments()) {
type = property.getGenericType();
typeName = type.getQualifiedName();
}
}
// for DEFAULT, if from XML the type will be "XmlElementRef.DEFAULT",
// and from annotations the value will be "XmlElementref$DEFAULT"
if (!(nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef.DEFAULT") || nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef$DEFAULT"))) {
typeName = nextRef.getType();
type = helper.getJavaClass(typeName);
}
boolean missingReference = true;
for (Entry<String, ElementDeclaration> entry : xmlRootElements.entrySet()) {
ElementDeclaration entryValue = entry.getValue();
if (type.isAssignableFrom(entryValue.getJavaType())) {
addReferencedElement(property, entryValue);
missingReference = false;
}
}
if (missingReference) {
String name = nextRef.getName();
String namespace = nextRef.getNamespace();
if (namespace.equals(XMLProcessor.DEFAULT)) {
namespace = EMPTY_STRING;
}
QName qname = new QName(namespace, name);
JavaClass scopeClass = cls;
ElementDeclaration referencedElement = null;
while (!(scopeClass.getName().equals(JAVA_LANG_OBJECT))) {
HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
if (elements != null) {
referencedElement = elements.get(qname);
}
if (referencedElement != null) {
break;
}
scopeClass = scopeClass.getSuperclass();
}
if (referencedElement == null) {
referencedElement = this.getGlobalElements().get(qname);
}
if (referencedElement != null) {
addReferencedElement(property, referencedElement);
} else {
throw org.eclipse.persistence.exceptions.JAXBException.invalidElementRef(property.getPropertyName(), cls.getName());
}
}
}
return property;
}
private void processPropertyAnnotations(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, Property property) {
// Check for mixed context
if (helper.isAnnotationPresent(javaHasAnnotations, XmlMixed.class)) {
info.setMixed(true);
property.setMixedContent(true);
}
if (helper.isAnnotationPresent(javaHasAnnotations, XmlContainerProperty.class)) {
XmlContainerProperty container = (XmlContainerProperty) helper.getAnnotation(javaHasAnnotations, XmlContainerProperty.class);
property.setInverseReferencePropertyName(container.value());
property.setInverseReferencePropertyGetMethodName(container.getMethodName());
property.setInverseReferencePropertySetMethodName(container.setMethodName());
} else if (helper.isAnnotationPresent(javaHasAnnotations, XmlInverseReference.class)) {
XmlInverseReference inverseReference = (XmlInverseReference) helper.getAnnotation(javaHasAnnotations, XmlInverseReference.class);
property.setInverseReferencePropertyName(inverseReference.mappedBy());
TypeInfo targetInfo = this.getTypeInfo().get(property.getActualType().getName());
if (targetInfo != null && targetInfo.getXmlAccessType() == XmlAccessType.PROPERTY) {
String propName = property.getPropertyName();
propName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
property.setInverseReferencePropertyGetMethodName(GET_STR + propName);
property.setInverseReferencePropertySetMethodName(SET_STR + propName);
}
property.setInverseReference(true);
}
processXmlJavaTypeAdapter(property, info, cls);
if (helper.isAnnotationPresent(property.getElement(), XmlAttachmentRef.class) && areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) {
property.setIsSwaAttachmentRef(true);
property.setSchemaType(XMLConstants.SWA_REF_QNAME);
}
processXmlElement(property, info);
//JavaClass ptype = property.getActualType();
if (!(property.isSwaAttachmentRef()) && isMtomAttachment(property)) {
property.setIsMtomAttachment(true);
property.setSchemaType(XMLConstants.BASE_64_BINARY_QNAME);
}
if (helper.isAnnotationPresent(property.getElement(), XmlMimeType.class)) {
property.setMimeType(((XmlMimeType) helper.getAnnotation(property.getElement(), XmlMimeType.class)).value());
}
// set indicator for inlining binary data - setting this to true on a
// non-binary data type won't have any affect
if (helper.isAnnotationPresent(property.getElement(), XmlInlineBinaryData.class) || info.isBinaryDataToBeInlined()) {
property.setisInlineBinaryData(true);
}
// Get schema-type info if specified and set it on the property for
// later use:
if (helper.isAnnotationPresent(property.getElement(), XmlSchemaType.class)) {
XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(property.getElement(), XmlSchemaType.class);
QName schemaTypeQname = new QName(schemaType.namespace(), schemaType.name());
property.setSchemaType(schemaTypeQname);
}
if (helper.isAnnotationPresent(property.getElement(), XmlAttribute.class)) {
property.setIsAttribute(true);
property.setIsRequired(((XmlAttribute) helper.getAnnotation(property.getElement(), XmlAttribute.class)).required());
}
if (helper.isAnnotationPresent(property.getElement(), XmlAnyAttribute.class)) {
if (info.isSetAnyAttributePropertyName()) {
throw org.eclipse.persistence.exceptions.JAXBException.multipleAnyAttributeMapping(cls.getName());
}
if (!property.getType().getName().equals("java.util.Map")) {
throw org.eclipse.persistence.exceptions.JAXBException.anyAttributeOnNonMap(property.getPropertyName());
}
property.setIsAnyAttribute(true);
info.setAnyAttributePropertyName(property.getPropertyName());
}
// Make sure XmlElementWrapper annotation is on a collection or array
if (helper.isAnnotationPresent(property.getElement(), XmlElementWrapper.class)) {
XmlElementWrapper wrapper = (XmlElementWrapper) helper.getAnnotation(property.getElement(), XmlElementWrapper.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper xmlEltWrapper = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper();
xmlEltWrapper.setName(wrapper.name());
xmlEltWrapper.setNamespace(wrapper.namespace());
xmlEltWrapper.setNillable(wrapper.nillable());
xmlEltWrapper.setRequired(wrapper.required());
property.setXmlElementWrapper(xmlEltWrapper);
}
if (helper.isAnnotationPresent(property.getElement(), XmlList.class)) {
// Make sure XmlList annotation is on a collection or array
if (!isCollectionType(property) && !property.getType().isArray()) {
throw JAXBException.invalidList(property.getPropertyName());
}
property.setIsXmlList(true);
}
if (helper.isAnnotationPresent(property.getElement(), XmlValue.class)) {
property.setIsXmlValue(true);
info.setXmlValueProperty(property);
}
if (helper.isAnnotationPresent(property.getElement(), XmlReadOnly.class)) {
property.setReadOnly(true);
}
if (helper.isAnnotationPresent(property.getElement(), XmlWriteOnly.class)) {
property.setWriteOnly(true);
}
if (helper.isAnnotationPresent(property.getElement(), XmlCDATA.class)) {
property.setCdata(true);
}
if (helper.isAnnotationPresent(property.getElement(), XmlAccessMethods.class)) {
XmlAccessMethods accessMethods = (XmlAccessMethods) helper.getAnnotation(property.getElement(), XmlAccessMethods.class);
if (!(accessMethods.getMethodName().equals(EMPTY_STRING))) {
property.setGetMethodName(accessMethods.getMethodName());
}
if (!(accessMethods.setMethodName().equals(EMPTY_STRING))) {
property.setSetMethodName(accessMethods.setMethodName());
}
if (!(property.isMethodProperty())) {
property.setMethodProperty(true);
}
}
// handle user properties
if (helper.isAnnotationPresent(property.getElement(), XmlProperties.class)) {
XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(property.getElement(), XmlProperties.class);
Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value());
property.setUserProperties(propertiesMap);
} else if (helper.isAnnotationPresent(property.getElement(), XmlProperty.class)) {
XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(property.getElement(), XmlProperty.class);
Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty });
property.setUserProperties(propertiesMap);
}
// handle XmlKey
if (helper.isAnnotationPresent(property.getElement(), XmlKey.class)) {
info.addXmlKeyProperty(property);
}
// handle XmlJoinNode(s)
processXmlJoinNodes(property);
processXmlNullPolicy(property);
}
/**
* Process XmlJoinNode(s) for a given Property. An
* org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNode(s) will be
* created/populated using the annotation, and set on the Property for later
* processing.
*
* It is assumed that for a single join node XmlJoinNode will be used, and
* for multiple join nodes XmlJoinNodes will be used.
*
* @param property
* Property that may contain @XmlJoinNodes/@XmlJoinNode
*/
private void processXmlJoinNodes(Property property) {
List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList;
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode;
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes;
// handle XmlJoinNodes
if (helper.isAnnotationPresent(property.getElement(), XmlJoinNodes.class)) {
xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>();
for (XmlJoinNode xmlJN : ((XmlJoinNodes) helper.getAnnotation(property.getElement(), XmlJoinNodes.class)).value()) {
xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode();
xmlJoinNode.setXmlPath(xmlJN.xmlPath());
xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath());
xmlJoinNodeList.add(xmlJoinNode);
}
xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes();
xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList);
property.setXmlJoinNodes(xmlJoinNodes);
}
// handle XmlJoinNode
else if (helper.isAnnotationPresent(property.getElement(), XmlJoinNode.class)) {
XmlJoinNode xmlJN = (XmlJoinNode) helper.getAnnotation(property.getElement(), XmlJoinNode.class);
xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode();
xmlJoinNode.setXmlPath(xmlJN.xmlPath());
xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath());
xmlJoinNodeList = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode>();
xmlJoinNodeList.add(xmlJoinNode);
xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes();
xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList);
property.setXmlJoinNodes(xmlJoinNodes);
}
}
/**
* Responsible for validating transformer settings on a given property.
* Validates that for field transformers either a transformer class OR
* method name is set (not both) and that an xml-path is set. Validates that
* for attribute transformers either a transformer class OR method name is
* set (not both).
*
* @param property
*/
private void processXmlTransformationProperty(Property property) {
if (property.isSetXmlTransformation()) {
XmlTransformation xmlTransformation = property.getXmlTransformation();
// validate transformer(s)
if (xmlTransformation.isSetXmlReadTransformer()) {
// validate read transformer
XmlReadTransformer readTransformer = xmlTransformation.getXmlReadTransformer();
if (readTransformer.isSetTransformerClass()) {
// handle read transformer class
if (readTransformer.isSetMethod()) {
// cannot have both class and method set
throw JAXBException.readTransformerHasBothClassAndMethod(property.getPropertyName());
}
} else {
// handle read transformer method
if (!readTransformer.isSetMethod()) {
// require class or method to be set
throw JAXBException.readTransformerHasNeitherClassNorMethod(property.getPropertyName());
}
}
}
if (xmlTransformation.isSetXmlWriteTransformers()) {
// handle write transformer(s)
for (XmlWriteTransformer writeTransformer : xmlTransformation.getXmlWriteTransformer()) {
// must have an xml-path set
if (!writeTransformer.isSetXmlPath()) {
throw JAXBException.writeTransformerHasNoXmlPath(property.getPropertyName());
}
if (writeTransformer.isSetTransformerClass()) {
// handle write transformer class
if (writeTransformer.isSetMethod()) {
// cannot have both class and method set
throw JAXBException.writeTransformerHasBothClassAndMethod(property.getPropertyName(), writeTransformer.getXmlPath());
}
} else {
// handle write transformer method
if (!writeTransformer.isSetMethod()) {
// require class or method to be set
throw JAXBException.writeTransformerHasNeitherClassNorMethod(property.getPropertyName(), writeTransformer.getXmlPath());
}
}
}
}
}
}
/**
* Compares a JavaModel JavaClass to a Class. Equality is based on the raw
* name of the JavaClass compared to the canonical name of the Class.
*
* @param src
* @param tgt
* @return
*/
protected boolean areEquals(JavaClass src, Class tgt) {
if (src == null || tgt == null) {
return false;
}
return src.getRawName().equals(tgt.getCanonicalName());
}
private void processXmlNullPolicy(Property property) {
if (helper.isAnnotationPresent(property.getElement(), XmlNullPolicy.class)) {
XmlNullPolicy nullPolicy = (XmlNullPolicy) helper.getAnnotation(property.getElement(), XmlNullPolicy.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy();
policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
policy.setIsSetPerformedForAbsentNode(nullPolicy.isSetPerformedForAbsentNode());
policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull()));
policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
property.setNullPolicy(policy);
} else if (helper.isAnnotationPresent(property.getElement(), XmlIsSetNullPolicy.class)) {
XmlIsSetNullPolicy nullPolicy = (XmlIsSetNullPolicy) helper.getAnnotation(property.getElement(), XmlIsSetNullPolicy.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy();
policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
policy.setXsiNilRepresentsNull(new Boolean(nullPolicy.xsiNilRepresentsNull()));
policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
policy.setIsSetMethodName(nullPolicy.isSetMethodName());
for (XmlParameter next : nullPolicy.isSetParameters()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter param = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter();
param.setValue(next.value());
param.setType(next.type().getName());
policy.getIsSetParameter().add(param);
}
property.setNullPolicy(policy);
}
}
/**
* Compares a JavaModel JavaClass to a Class. Equality is based on the raw
* name of the JavaClass compared to the canonical name of the Class.
*
* @param src
* @param tgt
* @return
*/
protected boolean areEquals(JavaClass src, String tgtCanonicalName) {
if (src == null || tgtCanonicalName == null) {
return false;
}
return src.getRawName().equals(tgtCanonicalName);
}
public ArrayList<Property> getPropertyPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic) {
ArrayList<Property> properties = new ArrayList<Property>();
if (cls == null) {
return properties;
}
// First collect all the getters and setters
ArrayList<JavaMethod> propertyMethods = new ArrayList<JavaMethod>();
for (JavaMethod next : new ArrayList<JavaMethod>(cls.getDeclaredMethods())) {
if (((next.getName().startsWith(GET_STR) && next.getName().length() > 3) || (next.getName().startsWith(IS_STR) && next.getName().length() > 2)) && next.getParameterTypes().length == 0 && next.getReturnType() != helper.getJavaClass(java.lang.Void.class)) {
int modifiers = next.getModifiers();
if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) {
propertyMethods.add(next);
}
} else if (next.getName().startsWith(SET_STR) && next.getName().length() > 3 && next.getParameterTypes().length == 1) {
int modifiers = next.getModifiers();
if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic)) {
propertyMethods.add(next);
}
}
}
// Next iterate over the getters and find their setter methods, add
// whichever one is
// annotated to the properties list. If neither is, use the getter
// keep track of property names to avoid processing the same property
// twice (for getter and setter)
ArrayList<String> propertyNames = new ArrayList<String>();
for (int i = 0; i < propertyMethods.size(); i++) {
boolean isPropertyTransient = false;
JavaMethod nextMethod = propertyMethods.get(i);
String propertyName = EMPTY_STRING;
JavaMethod getMethod;
JavaMethod setMethod;
JavaMethod propertyMethod = null;
if (!nextMethod.getName().startsWith(SET_STR)) {
if (nextMethod.getName().startsWith(GET_STR)) {
propertyName = nextMethod.getName().substring(3);
} else if (nextMethod.getName().startsWith(IS_STR)) {
propertyName = nextMethod.getName().substring(2);
}
getMethod = nextMethod;
String setMethodName = SET_STR + propertyName;
// use the JavaBean API to correctly decapitalize the first
// character, if necessary
propertyName = Introspector.decapitalize(propertyName);
JavaClass[] paramTypes = { (JavaClass) getMethod.getReturnType() };
setMethod = cls.getDeclaredMethod(setMethodName, paramTypes);
if (setMethod != null && !setMethod.getAnnotations().isEmpty()) {
// use the set method if it exists and is annotated
if (!helper.isAnnotationPresent(setMethod, XmlTransient.class)) {
propertyMethod = setMethod;
} else {
isPropertyTransient = true;
}
} else {
if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) {
propertyMethod = getMethod;
} else {
isPropertyTransient = true;
}
}
} else {
propertyName = nextMethod.getName().substring(3);
setMethod = nextMethod;
String getMethodName = GET_STR + propertyName;
getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {});
if (getMethod == null) {
// try is instead of get
getMethodName = IS_STR + propertyName;
getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {});
}
if (getMethod != null && !getMethod.getAnnotations().isEmpty()) {
// use the set method if it exists and is annotated
if (!helper.isAnnotationPresent(getMethod, XmlTransient.class)) {
propertyMethod = getMethod;
} else {
isPropertyTransient = true;
}
} else {
if (!helper.isAnnotationPresent(setMethod, XmlTransient.class)) {
propertyMethod = setMethod;
} else {
isPropertyTransient = true;
}
}
// use the JavaBean API to correctly decapitalize the first
// character, if necessary
propertyName = Introspector.decapitalize(propertyName);
}
JavaClass ptype = null;
if (getMethod != null) {
ptype = (JavaClass) getMethod.getReturnType();
} else {
ptype = setMethod.getParameterTypes()[0];
}
if (!propertyNames.contains(propertyName)) {
propertyNames.add(propertyName);
Property property = buildNewProperty(info, cls, propertyMethod, propertyName, ptype);
property.setTransient(isPropertyTransient);
if (getMethod != null) {
property.setOriginalGetMethodName(getMethod.getName());
if (property.getGetMethodName() == null) {
property.setGetMethodName(getMethod.getName());
}
}
if (setMethod != null) {
property.setOriginalSetMethodName(setMethod.getName());
if (property.getSetMethodName() == null) {
property.setSetMethodName(setMethod.getName());
}
}
property.setMethodProperty(true);
if (!helper.isAnnotationPresent(property.getElement(), XmlTransient.class)) {
properties.add(property);
} else {
// If a property is marked transient ensure it doesn't exist
// in the propOrder
List<String> propOrderList = Arrays.asList(info.getPropOrder());
if (propOrderList.contains(propertyName)) {
throw JAXBException.transientInProporder(propertyName);
}
property.setTransient(true);
}
}
}
properties = removeSuperclassProperties(cls, properties);
// default to alphabetical ordering
// RI compliancy
Collections.sort(properties, new PropertyComparitor());
return properties;
}
private ArrayList<Property> removeSuperclassProperties(JavaClass cls, ArrayList<Property> properties) {
ArrayList<Property> revisedProperties = new ArrayList<Property>();
revisedProperties.addAll(properties);
// Check for any get() methods that are overridden in the subclass.
// If we find any, remove the property, because it is already defined on the superclass.
JavaClass superClass = cls.getSuperclass();
if (null != superClass) {
TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName());
if (superClassInfo != null && !superClassInfo.isTransient()) {
for (Property prop : properties) {
for (Property superProp : superClassInfo.getProperties().values()) {
if (superProp.getGetMethodName() != null && superProp.getGetMethodName().equals(prop.getGetMethodName())) {
revisedProperties.remove(prop);
}
}
}
}
}
return revisedProperties;
}
public ArrayList getPublicMemberPropertiesForClass(JavaClass cls, TypeInfo info) {
ArrayList<Property> fieldProperties = getFieldPropertiesForClass(cls, info, false);
ArrayList<Property> methodProperties = getPropertyPropertiesForClass(cls, info, false);
// filter out non-public properties that aren't annotated
ArrayList<Property> publicFieldProperties = new ArrayList<Property>();
ArrayList<Property> publicMethodProperties = new ArrayList<Property>();
for (Property next : fieldProperties) {
if (Modifier.isPublic(((JavaField) next.getElement()).getModifiers())) {
publicFieldProperties.add(next);
} else {
if (hasJAXBAnnotations(next.getElement())) {
publicFieldProperties.add(next);
}
}
}
for (Property next : methodProperties) {
if (next.getElement() != null) {
if (Modifier.isPublic(((JavaMethod) next.getElement()).getModifiers())) {
publicMethodProperties.add(next);
} else {
if (hasJAXBAnnotations(next.getElement())) {
publicMethodProperties.add(next);
}
}
}
}
// Not sure who should win if a property exists for both or the correct
// order
if (publicFieldProperties.size() >= 0 && publicMethodProperties.size() == 0) {
return publicFieldProperties;
} else if (publicMethodProperties.size() > 0 && publicFieldProperties.size() == 0) {
return publicMethodProperties;
} else {
// add any non-duplicate method properties to the collection.
// - in the case of a collision if one is annotated use it,
// otherwise
// use the field.
HashMap fieldPropertyMap = getPropertyMapFromArrayList(publicFieldProperties);
for (int i = 0; i < publicMethodProperties.size(); i++) {
Property next = (Property) publicMethodProperties.get(i);
if (fieldPropertyMap.get(next.getPropertyName()) == null) {
publicFieldProperties.add(next);
}
}
return publicFieldProperties;
}
}
public HashMap getPropertyMapFromArrayList(ArrayList<Property> props) {
HashMap propMap = new HashMap(props.size());
Iterator propIter = props.iterator();
while (propIter.hasNext()) {
Property next = (Property) propIter.next();
propMap.put(next.getPropertyName(), next);
}
return propMap;
}
public ArrayList getNoAccessTypePropertiesForClass(JavaClass cls, TypeInfo info) {
ArrayList<Property> list = new ArrayList<Property>();
if (cls == null) {
return list;
}
// Iterate over the field and method properties. If ANYTHING contains an
// annotation and
// doesn't appear in the other list, add it to the final list
List<Property> fieldProperties = getFieldPropertiesForClass(cls, info, false);
Map<String, Property> fields = new HashMap<String, Property>(fieldProperties.size());
for(Property next : fieldProperties) {
JavaHasAnnotations elem = next.getElement();
if (!hasJAXBAnnotations(elem)) {
next.setTransient(true);
}
list.add(next);
fields.put(next.getPropertyName(), next);
}
List<Property> methodProperties = getPropertyPropertiesForClass(cls, info, false);
for(Property next : methodProperties) {
JavaHasAnnotations elem = next.getElement();
if (hasJAXBAnnotations(elem)) {
// If the property is annotated remove the corresponding field
Property fieldProperty = fields.get(next.getPropertyName());
list.remove(fieldProperty);
list.add(next);
} else {
// If the property is not annotated only add it if there is no
// corresponding field.
next.setTransient(true);
if(fields.get(next.getPropertyName()) == null) {
list.add(next);
}
}
}
return list;
}
/**
* Use name, namespace and type information to setup a user-defined schema
* type. This method will typically be called when processing an
*
* @XmlSchemaType(s) annotation or xml-schema-type(s) metadata.
*
* @param name
* @param namespace
* @param jClassQualifiedName
*/
public void processSchemaType(String name, String namespace, String jClassQualifiedName) {
this.userDefinedSchemaTypes.put(jClassQualifiedName, new QName(namespace, name));
}
public void processSchemaType(XmlSchemaType type) {
JavaClass jClass = helper.getJavaClass(type.type());
if (jClass == null) {
return;
}
processSchemaType(type.name(), type.namespace(), jClass.getQualifiedName());
}
public void addEnumTypeInfo(JavaClass javaClass, EnumTypeInfo info) {
if (javaClass == null) {
return;
}
info.setClassName(javaClass.getQualifiedName());
Class restrictionClass = String.class;
if (helper.isAnnotationPresent(javaClass, XmlEnum.class)) {
XmlEnum xmlEnum = (XmlEnum) helper.getAnnotation(javaClass, XmlEnum.class);
restrictionClass = xmlEnum.value();
}
QName restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass));
info.setRestrictionBase(restrictionBase);
for (Iterator<JavaField> fieldIt = javaClass.getDeclaredFields().iterator(); fieldIt.hasNext();) {
JavaField field = fieldIt.next();
if (field.isEnumConstant()) {
String enumValue = field.getName();
if (helper.isAnnotationPresent(field, XmlEnumValue.class)) {
enumValue = ((XmlEnumValue) helper.getAnnotation(field, XmlEnumValue.class)).value();
}
info.addJavaFieldToXmlEnumValuePair(field.getName(), enumValue);
}
}
//Add a non-named element declaration for each enumeration to trigger class generation
ElementDeclaration elem = new ElementDeclaration(null, javaClass, javaClass.getQualifiedName(), false);
//if(this.javaClassToTypeMappingInfos.get(javaClass) != null) {
//elem.setTypeMappingInfo(this.javaClassToTypeMappingInfos.get(javaClass));
this.getLocalElements().add(elem);
}
private String decapitalize(String javaName) {
char[] name = javaName.toCharArray();
int i = 0;
while (i < name.length && (Character.isUpperCase(name[i]) || !Character.isLetter(name[i]))) {
i++;
}
if (i > 0) {
name[0] = Character.toLowerCase(name[0]);
for (int j = 1; j < i - 1; j++) {
name[j] = Character.toLowerCase(name[j]);
}
return new String(name);
} else {
return javaName;
}
}
public String getSchemaTypeNameForClassName(String className) {
String typeName = EMPTY_STRING;
if (className.indexOf(DOLLAR_SIGN_CHR) != -1) {
typeName = decapitalize(className.substring(className.lastIndexOf(DOLLAR_SIGN_CHR) + 1));
} else {
typeName = decapitalize(className.substring(className.lastIndexOf(DOT_CHR) + 1));
}
// now capitalize any characters that occur after a "break"
boolean inBreak = false;
StringBuffer toReturn = new StringBuffer(typeName.length());
for (int i = 0; i < typeName.length(); i++) {
char next = typeName.charAt(i);
if (Character.isDigit(next)) {
if (!inBreak) {
inBreak = true;
}
toReturn.append(next);
} else {
if (inBreak) {
toReturn.append(Character.toUpperCase(next));
} else {
toReturn.append(next);
}
}
}
return toReturn.toString();
}
public QName getSchemaTypeOrNullFor(JavaClass javaClass) {
if (javaClass == null) {
return null;
}
// check user defined types first
QName schemaType = (QName) userDefinedSchemaTypes.get(javaClass.getQualifiedName());
if (schemaType == null) {
schemaType = (QName) helper.getXMLToJavaTypeMap().get(javaClass.getRawName());
}
return schemaType;
}
public QName getSchemaTypeFor(JavaClass javaClass) {
QName schemaType = getSchemaTypeOrNullFor(javaClass);
if (schemaType == null) {
return XMLConstants.ANY_SIMPLE_TYPE_QNAME;
}
return schemaType;
}
public boolean isCollectionType(Property field) {
return isCollectionType(field.getType());
}
public boolean isCollectionType(JavaClass type) {
if (helper.getJavaClass(java.util.Collection.class).isAssignableFrom(type) || helper.getJavaClass(java.util.List.class).isAssignableFrom(type) || helper.getJavaClass(java.util.Set.class).isAssignableFrom(type)) {
return true;
}
return false;
}
public NamespaceInfo processNamespaceInformation(XmlSchema xmlSchema) {
NamespaceInfo info = new NamespaceInfo();
info.setNamespaceResolver(new NamespaceResolver());
String packageNamespace = null;
if (xmlSchema != null) {
String namespaceMapping = xmlSchema.namespace();
if (!(namespaceMapping.equals(EMPTY_STRING) || namespaceMapping.equals(XMLProcessor.DEFAULT))) {
packageNamespace = namespaceMapping;
} else if (namespaceMapping.equals(XMLProcessor.DEFAULT)) {
packageNamespace = this.defaultTargetNamespace;
}
info.setNamespace(packageNamespace);
XmlNs[] xmlns = xmlSchema.xmlns();
for (int i = 0; i < xmlns.length; i++) {
XmlNs next = xmlns[i];
info.getNamespaceResolver().put(next.prefix(), next.namespaceURI());
}
info.setAttributeFormQualified(xmlSchema.attributeFormDefault() == XmlNsForm.QUALIFIED);
info.setElementFormQualified(xmlSchema.elementFormDefault() == XmlNsForm.QUALIFIED);
// reflectively load XmlSchema class to avoid dependency
try {
Method locationMethod = PrivilegedAccessHelper.getDeclaredMethod(XmlSchema.class, "location", new Class[] {});
String location = (String) PrivilegedAccessHelper.invokeMethod(locationMethod, xmlSchema, new Object[] {});
if (location != null) {
if (location.equals("##generate")) {
location = null;
} else if (location.equals(EMPTY_STRING)) {
location = null;
}
}
info.setLocation(location);
} catch (Exception ex) {
}
} else {
info.setNamespace(defaultTargetNamespace);
}
if (!info.isElementFormQualified() || info.isAttributeFormQualified()) {
isDefaultNamespaceAllowed = false;
}
return info;
}
public HashMap<String, TypeInfo> getTypeInfo() {
return typeInfo;
}
public ArrayList<JavaClass> getTypeInfoClasses() {
return typeInfoClasses;
}
public HashMap<String, QName> getUserDefinedSchemaTypes() {
return userDefinedSchemaTypes;
}
public NamespaceResolver getNamespaceResolver() {
return namespaceResolver;
}
public String getSchemaTypeNameFor(JavaClass javaClass, XmlType xmlType) {
String typeName = EMPTY_STRING;
if (javaClass == null) {
return typeName;
}
if (helper.isAnnotationPresent(javaClass, XmlType.class)) {
// Figure out what kind of type we have
// figure out type name
XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class);
typeName = typeAnnotation.name();
if (typeName.equals("#default")) {
typeName = getSchemaTypeNameForClassName(javaClass.getName());
}
} else {
typeName = getSchemaTypeNameForClassName(javaClass.getName());
}
return typeName;
}
public QName getQNameForProperty(String defaultName, JavaHasAnnotations element, NamespaceInfo namespaceInfo, String uri) {
String name = XMLProcessor.DEFAULT;
String namespace = XMLProcessor.DEFAULT;
QName qName = null;
if (helper.isAnnotationPresent(element, XmlAttribute.class)) {
XmlAttribute xmlAttribute = (XmlAttribute) helper.getAnnotation(element, XmlAttribute.class);
name = xmlAttribute.name();
namespace = xmlAttribute.namespace();
if (name.equals(XMLProcessor.DEFAULT)) {
name = defaultName;
}
if (!namespace.equals(XMLProcessor.DEFAULT)) {
qName = new QName(namespace, name);
isDefaultNamespaceAllowed = false;
} else {
if (namespaceInfo.isAttributeFormQualified()) {
qName = new QName(uri, name);
} else {
qName = new QName(name);
}
}
} else {
if (helper.isAnnotationPresent(element, XmlElement.class)) {
XmlElement xmlElement = (XmlElement) helper.getAnnotation(element, XmlElement.class);
name = xmlElement.name();
namespace = xmlElement.namespace();
}
if (name.equals(XMLProcessor.DEFAULT)) {
name = defaultName;
}
if (!namespace.equals(XMLProcessor.DEFAULT)) {
qName = new QName(namespace, name);
if (namespace.equals(XMLConstants.EMPTY_STRING)) {
isDefaultNamespaceAllowed = false;
}
} else {
if (namespaceInfo.isElementFormQualified()) {
qName = new QName(uri, name);
} else {
qName = new QName(name);
}
}
}
return qName;
}
public HashMap<String, NamespaceInfo> getPackageToNamespaceMappings() {
return packageToNamespaceMappings;
}
/**
* Add a package name/NamespaceInfo entry to the map. This method will
* lazy-load the map if necessary.
*
* @return
*/
public void addPackageToNamespaceMapping(String packageName, NamespaceInfo nsInfo) {
if (packageToNamespaceMappings == null) {
packageToNamespaceMappings = new HashMap<String, NamespaceInfo>();
}
packageToNamespaceMappings.put(packageName, nsInfo);
}
public NamespaceInfo getNamespaceInfoForPackage(JavaClass javaClass) {
String packageName = javaClass.getPackageName();
NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName);
if (packageNamespace == null) {
packageNamespace = getNamespaceInfoForPackage(javaClass.getPackage(), packageName);
}
return packageNamespace;
}
public NamespaceInfo getNamespaceInfoForPackage(JavaPackage pack, String packageName) {
NamespaceInfo packageNamespace = packageToNamespaceMappings.get(packageName);
if (packageNamespace == null) {
XmlSchema xmlSchema = (XmlSchema) helper.getAnnotation(pack, XmlSchema.class);
packageNamespace = processNamespaceInformation(xmlSchema);
// if it's still null, generate based on package name
if (packageNamespace.getNamespace() == null) {
packageNamespace.setNamespace(EMPTY_STRING);
}
if (helper.isAnnotationPresent(pack, XmlAccessorType.class)) {
XmlAccessorType xmlAccessorType = (XmlAccessorType) helper.getAnnotation(pack, XmlAccessorType.class);
packageNamespace.setAccessType(XmlAccessType.fromValue(xmlAccessorType.value().name()));
}
if (helper.isAnnotationPresent(pack, XmlAccessorOrder.class)) {
XmlAccessorOrder xmlAccessorOrder = (XmlAccessorOrder) helper.getAnnotation(pack, XmlAccessorOrder.class);
packageNamespace.setAccessOrder(XmlAccessOrder.fromValue(xmlAccessorOrder.value().name()));
}
packageToNamespaceMappings.put(packageName, packageNamespace);
}
return packageNamespace;
}
private void checkForCallbackMethods() {
for (JavaClass next : typeInfoClasses) {
if (next == null) {
continue;
}
JavaClass unmarshallerCls = helper.getJavaClass(Unmarshaller.class);
JavaClass marshallerCls = helper.getJavaClass(Marshaller.class);
JavaClass objectCls = helper.getJavaClass(Object.class);
JavaClass[] unmarshalParams = new JavaClass[] { unmarshallerCls, objectCls };
JavaClass[] marshalParams = new JavaClass[] { marshallerCls };
UnmarshalCallback unmarshalCallback = null;
MarshalCallback marshalCallback = null;
// look for before unmarshal callback
if (next.getMethod("beforeUnmarshal", unmarshalParams) != null) {
unmarshalCallback = new UnmarshalCallback();
unmarshalCallback.setDomainClassName(next.getQualifiedName());
unmarshalCallback.setHasBeforeUnmarshalCallback();
}
// look for after unmarshal callback
if (next.getMethod("afterUnmarshal", unmarshalParams) != null) {
if (unmarshalCallback == null) {
unmarshalCallback = new UnmarshalCallback();
unmarshalCallback.setDomainClassName(next.getQualifiedName());
}
unmarshalCallback.setHasAfterUnmarshalCallback();
}
// if before/after unmarshal callback was found, add the callback to
// the list
if (unmarshalCallback != null) {
if (this.unmarshalCallbacks == null) {
this.unmarshalCallbacks = new HashMap<String, UnmarshalCallback>();
}
unmarshalCallbacks.put(next.getQualifiedName(), unmarshalCallback);
}
// look for before marshal callback
if (next.getMethod("beforeMarshal", marshalParams) != null) {
marshalCallback = new MarshalCallback();
marshalCallback.setDomainClassName(next.getQualifiedName());
marshalCallback.setHasBeforeMarshalCallback();
}
// look for after marshal callback
if (next.getMethod("afterMarshal", marshalParams) != null) {
if (marshalCallback == null) {
marshalCallback = new MarshalCallback();
marshalCallback.setDomainClassName(next.getQualifiedName());
}
marshalCallback.setHasAfterMarshalCallback();
}
// if before/after marshal callback was found, add the callback to
// the list
if (marshalCallback != null) {
if (this.marshalCallbacks == null) {
this.marshalCallbacks = new HashMap<String, MarshalCallback>();
}
marshalCallbacks.put(next.getQualifiedName(), marshalCallback);
}
}
}
public HashMap<String, MarshalCallback> getMarshalCallbacks() {
return this.marshalCallbacks;
}
public HashMap<String, UnmarshalCallback> getUnmarshalCallbacks() {
return this.unmarshalCallbacks;
}
public JavaClass[] processObjectFactory(JavaClass objectFactoryClass, ArrayList<JavaClass> classes) {
// if there is an xml-registry from XML for this JavaClass, create a map
// of method names to XmlElementDecl objects to simplify processing
// later on in this method
Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl>();
org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg = xmlRegistries.get(objectFactoryClass.getQualifiedName());
if (xmlReg != null) {
// process xml-element-decl entries
for (org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlElementDecl : xmlReg.getXmlElementDecl()) {
// key each element-decl on method name
elemDecls.put(xmlElementDecl.getJavaMethod(), xmlElementDecl);
}
}
Collection methods = objectFactoryClass.getDeclaredMethods();
Iterator methodsIter = methods.iterator();
NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(objectFactoryClass);
while (methodsIter.hasNext()) {
JavaMethod next = (JavaMethod) methodsIter.next();
if (next.getName().startsWith(CREATE)) {
JavaClass type = next.getReturnType();
if (JAVAX_XML_BIND_JAXBELEMENT.equals(type.getName())) {
Object[] actutalTypeArguments = next.getReturnType().getActualTypeArguments().toArray();
if(actutalTypeArguments.length == 0) {
type = helper.getJavaClass(Object.class);
} else {
type = (JavaClass) next.getReturnType().getActualTypeArguments().toArray()[0];
}
} else {
this.factoryMethods.put(next.getReturnType().getRawName(), next);
}
// if there's an XmlElementDecl for this method from XML, use it
// - otherwise look for an annotation
org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlEltDecl = elemDecls.get(next.getName());
if (xmlEltDecl != null || helper.isAnnotationPresent(next, XmlElementDecl.class)) {
QName qname;
QName substitutionHead = null;
String url;
String localName;
String defaultValue = null;
Class scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class;
if (xmlEltDecl != null) {
url = xmlEltDecl.getNamespace();
localName = xmlEltDecl.getName();
String scopeClassName = xmlEltDecl.getScope();
if (!scopeClassName.equals(ELEMENT_DECL_GLOBAL)) {
JavaClass jScopeClass = helper.getJavaClass(scopeClassName);
if (jScopeClass != null) {
scopeClass = helper.getClassForJavaClass(jScopeClass);
if (scopeClass == null) {
scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class;
}
}
}
if (!xmlEltDecl.getSubstitutionHeadName().equals(EMPTY_STRING)) {
String subHeadLocal = xmlEltDecl.getSubstitutionHeadName();
String subHeadNamespace = xmlEltDecl.getSubstitutionHeadNamespace();
if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) {
subHeadNamespace = namespaceInfo.getNamespace();
}
substitutionHead = new QName(subHeadNamespace, subHeadLocal);
}
if (!(xmlEltDecl.getDefaultValue().length() == 1 && xmlEltDecl.getDefaultValue().startsWith(ELEMENT_DECL_DEFAULT))) {
defaultValue = xmlEltDecl.getDefaultValue();
}
} else {
// there was no xml-element-decl for this method in XML,
// so use the annotation
XmlElementDecl elementDecl = (XmlElementDecl) helper.getAnnotation(next, XmlElementDecl.class);
url = elementDecl.namespace();
localName = elementDecl.name();
scopeClass = elementDecl.scope();
if (!elementDecl.substitutionHeadName().equals(EMPTY_STRING)) {
String subHeadLocal = elementDecl.substitutionHeadName();
String subHeadNamespace = elementDecl.substitutionHeadNamespace();
if (subHeadNamespace.equals(XMLProcessor.DEFAULT)) {
subHeadNamespace = namespaceInfo.getNamespace();
}
substitutionHead = new QName(subHeadNamespace, subHeadLocal);
}
if (!(elementDecl.defaultValue().length() == 1 && elementDecl.defaultValue().startsWith(ELEMENT_DECL_DEFAULT))) {
defaultValue = elementDecl.defaultValue();
}
}
if (XMLProcessor.DEFAULT.equals(url)) {
url = namespaceInfo.getNamespace();
}
qname = new QName(url, localName);
boolean isList = false;
if (JAVA_UTIL_LIST.equals(type.getName())) {
isList = true;
if (type.hasActualTypeArguments()) {
type = (JavaClass) type.getActualTypeArguments().toArray()[0];
}
}
ElementDeclaration declaration = new ElementDeclaration(qname, type, type.getQualifiedName(), isList, scopeClass);
if (substitutionHead != null) {
declaration.setSubstitutionHead(substitutionHead);
}
if (defaultValue != null) {
declaration.setDefaultValue(defaultValue);
}
if (helper.isAnnotationPresent(next, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter typeAdapter = (XmlJavaTypeAdapter) helper.getAnnotation(next, XmlJavaTypeAdapter.class);
Class typeAdapterClass = typeAdapter.value();
declaration.setJavaTypeAdapterClass(typeAdapterClass);
Class declJavaType = CompilerHelper.getTypeFromAdapterClass(typeAdapterClass);
declaration.setJavaType(helper.getJavaClass(declJavaType));
declaration.setAdaptedJavaType(type);
}
HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
if (elements == null) {
elements = new HashMap<QName, ElementDeclaration>();
this.elementDeclarations.put(scopeClass.getName(), elements);
}
elements.put(qname, declaration);
}
if (!helper.isBuiltInJavaType(type) && !helper.classExistsInArray(type, classes)) {
classes.add(type);
}
}
}
if (classes.size() > 0) {
return classes.toArray(new JavaClass[classes.size()]);
} else {
return new JavaClass[0];
}
}
/**
* Lazy load and return the map of global elements.
*
* @return
*/
public HashMap<QName, ElementDeclaration> getGlobalElements() {
return this.elementDeclarations.get(XmlElementDecl.GLOBAL.class.getName());
}
public void updateGlobalElements(JavaClass[] classesToProcess) {
// Once all the global element declarations have been created, make sure
// that any ones that have
// a substitution head set are added to the list of substitutable
// elements on the declaration for that
// head.
// Look for XmlRootElement declarations
for (JavaClass javaClass : classesToProcess) {
TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
if (info == null) {
continue;
}
if (!info.isTransient() && info.isSetXmlRootElement()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement();
NamespaceInfo namespaceInfo;
namespaceInfo = getNamespaceInfoForPackage(javaClass);
String elementName = xmlRE.getName();
if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) {
if (javaClass.getName().indexOf(DOLLAR_SIGN_CHR) != -1) {
elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOLLAR_SIGN_CHR) + 1));
} else {
elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOT_CHR) + 1));
}
// TCK Compliancy
if (elementName.length() >= 3) {
int idx = elementName.length() - 1;
char ch = elementName.charAt(idx - 1);
if (Character.isDigit(ch)) {
char lastCh = Character.toUpperCase(elementName.charAt(idx));
elementName = elementName.substring(0, idx) + lastCh;
}
}
}
String rootNamespace = xmlRE.getNamespace();
QName rootElemName = null;
if (rootNamespace.equals(XMLProcessor.DEFAULT)) {
if (namespaceInfo == null) {
rootElemName = new QName(elementName);
} else {
String rootNS = namespaceInfo.getNamespace();
rootElemName = new QName(rootNS, elementName);
if (rootNS.equals(XMLConstants.EMPTY_STRING)) {
isDefaultNamespaceAllowed = false;
}
}
} else {
rootElemName = new QName(rootNamespace, elementName);
if (rootNamespace.equals(XMLConstants.EMPTY_STRING)) {
isDefaultNamespaceAllowed = false;
}
}
ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getQualifiedName(), false);
declaration.setIsXmlRootElement(true);
this.getGlobalElements().put(rootElemName, declaration);
this.xmlRootElements.put(javaClass.getQualifiedName(), declaration);
}
}
Iterator<QName> elementQnames = this.getGlobalElements().keySet().iterator();
while (elementQnames.hasNext()) {
QName next = elementQnames.next();
ElementDeclaration nextDeclaration = this.getGlobalElements().get(next);
QName substitutionHead = nextDeclaration.getSubstitutionHead();
while (substitutionHead != null) {
ElementDeclaration rootDeclaration = this.getGlobalElements().get(substitutionHead);
rootDeclaration.addSubstitutableElement(nextDeclaration);
substitutionHead = rootDeclaration.getSubstitutionHead();
}
}
}
private void addReferencedElement(Property property, ElementDeclaration referencedElement) {
property.addReferencedElement(referencedElement);
if (referencedElement.getSubstitutableElements() != null && referencedElement.getSubstitutableElements().size() > 0) {
for (ElementDeclaration substitutable : referencedElement.getSubstitutableElements()) {
addReferencedElement(property, substitutable);
}
}
}
/**
* Returns true if the field or method passed in is annotated with JAXB
* annotations.
*/
private boolean hasJAXBAnnotations(JavaHasAnnotations elem) {
return (helper.isAnnotationPresent(elem, XmlElement.class) ||
helper.isAnnotationPresent(elem, XmlAttribute.class) ||
helper.isAnnotationPresent(elem, XmlAnyElement.class) ||
helper.isAnnotationPresent(elem, XmlAnyAttribute.class) ||
helper.isAnnotationPresent(elem, XmlValue.class) ||
helper.isAnnotationPresent(elem, XmlElements.class) ||
helper.isAnnotationPresent(elem, XmlElementRef.class) ||
helper.isAnnotationPresent(elem, XmlElementRefs.class) ||
helper.isAnnotationPresent(elem, XmlID.class) ||
helper.isAnnotationPresent(elem, XmlSchemaType.class) ||
helper.isAnnotationPresent(elem, XmlElementWrapper.class) ||
helper.isAnnotationPresent(elem, XmlList.class) ||
helper.isAnnotationPresent(elem, XmlMimeType.class) ||
helper.isAnnotationPresent(elem, XmlIDREF.class) ||
helper.isAnnotationPresent(elem, XmlPath.class) ||
helper.isAnnotationPresent(elem, XmlPaths.class) ||
helper.isAnnotationPresent(elem, XmlInverseReference.class) ||
helper.isAnnotationPresent(elem, XmlReadOnly.class) ||
helper.isAnnotationPresent(elem, XmlWriteOnly.class) ||
helper.isAnnotationPresent(elem, XmlCDATA.class) ||
helper.isAnnotationPresent(elem, XmlAccessMethods.class) ||
helper.isAnnotationPresent(elem, XmlNullPolicy.class));
}
private void validateElementIsInPropOrder(TypeInfo info, String name) {
if (info.isTransient()) {
return;
}
// If a property is marked with XMLElement, XMLElements, XMLElementRef
// or XMLElementRefs
// and propOrder is not empty then it must be in the proporder list
String[] propOrder = info.getPropOrder();
if (propOrder.length > 0) {
if (propOrder.length == 1 && propOrder[0].equals(EMPTY_STRING)) {
return;
}
List<String> propOrderList = Arrays.asList(info.getPropOrder());
if (!propOrderList.contains(name)) {
throw JAXBException.missingPropertyInPropOrder(name);
}
}
}
private void validatePropOrderForInfo(TypeInfo info) {
if (info.isTransient()) {
return;
}
// Ensure that all properties in the propOrder list actually exist
String[] propOrder = info.getPropOrder();
int propOrderLength = propOrder.length;
if (propOrderLength > 0) {
for (int i = 1; i < propOrderLength; i++) {
String nextPropName = propOrder[i];
if (!nextPropName.equals(EMPTY_STRING) && !info.getPropertyNames().contains(nextPropName)) {
throw JAXBException.nonExistentPropertyInPropOrder(nextPropName);
}
}
}
}
private void validateXmlValueFieldOrProperty(JavaClass cls, Property property) {
JavaClass ptype = property.getActualType();
String propName = property.getPropertyName();
JavaClass parent = cls.getSuperclass();
while (parent != null && !(parent.getQualifiedName().equals(JAVA_LANG_OBJECT))) {
TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName());
if (parentTypeInfo != null || shouldGenerateTypeInfo(parent)) {
throw JAXBException.propertyOrFieldCannotBeXmlValue(propName);
}
parent = parent.getSuperclass();
}
QName schemaQName = getSchemaTypeOrNullFor(ptype);
if (schemaQName == null) {
TypeInfo refInfo = typeInfo.get(ptype.getQualifiedName());
if (refInfo != null) {
if (!refInfo.isPostBuilt()) {
postBuildTypeInfo(new JavaClass[] { ptype });
}
} else if (shouldGenerateTypeInfo(ptype)) {
JavaClass[] jClasses = new JavaClass[] { ptype };
buildNewTypeInfo(jClasses);
refInfo = typeInfo.get(ptype.getQualifiedName());
}
if (refInfo != null && !refInfo.isEnumerationType() && refInfo.getXmlValueProperty() == null) {
throw JAXBException.invalidTypeForXmlValueField(propName);
}
}
}
public boolean isMapType(JavaClass type) {
return helper.getJavaClass(java.util.Map.class).isAssignableFrom(type);
}
private Class generateWrapperForMapClass(JavaClass mapClass, JavaClass keyClass, JavaClass valueClass, TypeMappingInfo typeMappingInfo) {
String packageName = JAXB_DEV;
NamespaceResolver combinedNamespaceResolver = new NamespaceResolver();
if (!helper.isBuiltInJavaType(keyClass)) {
String keyPackageName = keyClass.getPackageName();
packageName = packageName + DOT_CHR + keyPackageName;
NamespaceInfo keyNamespaceInfo = getNamespaceInfoForPackage(keyClass);
if (keyNamespaceInfo != null) {
java.util.Vector<Namespace> namespaces = keyNamespaceInfo.getNamespaceResolver().getNamespaces();
for (Namespace n : namespaces) {
combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI());
}
}
}
if (!helper.isBuiltInJavaType(valueClass)) {
String valuePackageName = valueClass.getPackageName();
packageName = packageName + DOT_CHR + valuePackageName;
NamespaceInfo valueNamespaceInfo = getNamespaceInfoForPackage(valueClass);
if (valueNamespaceInfo != null) {
java.util.Vector<Namespace> namespaces = valueNamespaceInfo.getNamespaceResolver().getNamespaces();
for (Namespace n : namespaces) {
combinedNamespaceResolver.put(n.getPrefix(), n.getNamespaceURI());
}
}
}
String namespace = this.defaultTargetNamespace;
if (namespace == null) {
namespace = EMPTY_STRING;
}
NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(mapClass.getPackageName());
if (namespaceInfo == null) {
namespaceInfo = getPackageToNamespaceMappings().get(packageName);
} else {
if (namespaceInfo.getNamespace() != null) {
namespace = namespaceInfo.getNamespace();
}
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
}
if (namespaceInfo == null) {
namespaceInfo = new NamespaceInfo();
namespaceInfo.setNamespace(namespace);
namespaceInfo.setNamespaceResolver(combinedNamespaceResolver);
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
}
int beginIndex = keyClass.getName().lastIndexOf(DOT_CHR) + 1;
String keyName = keyClass.getName().substring(beginIndex);
int dollarIndex = keyName.indexOf(DOLLAR_SIGN_CHR);
if (dollarIndex > -1) {
keyName = keyName.substring(dollarIndex + 1);
}
beginIndex = valueClass.getName().lastIndexOf(DOT_CHR) + 1;
String valueName = valueClass.getName().substring(beginIndex);
dollarIndex = valueName.indexOf(DOLLAR_SIGN_CHR);
if (dollarIndex > -1) {
valueName = valueName.substring(dollarIndex + 1);
}
String collectionClassShortName = mapClass.getRawName().substring(mapClass.getRawName().lastIndexOf(DOT_CHR) + 1);
String suggestedClassName = keyName + valueName + collectionClassShortName;
String qualifiedClassName = packageName + DOT_CHR + suggestedClassName;
qualifiedClassName = getNextAvailableClassName(qualifiedClassName);
String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR);
String internalKeyName = keyClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR);
String internalValueName = valueClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR);
Type mapType = Type.getType(L + mapClass.getRawName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
ClassWriter cw = new ClassWriter(false);
CodeVisitor cv;
cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/MapValue", null, "StringEmployeeMap.java");
// FIELD ATTRIBUTES
RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations();
if (typeMappingInfo != null) {
java.lang.annotation.Annotation[] annotations = typeMappingInfo.getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
java.lang.annotation.Annotation nextAnnotation = annotations[i];
if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) {
String annotationClassName = nextAnnotation.annotationType().getName();
Annotation fieldAttrs1ann0 = new Annotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
fieldAttrs1.annotations.add(fieldAttrs1ann0);
for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) {
try {
Object nextValue = next.invoke(nextAnnotation, new Object[] {});
if (nextValue instanceof Class) {
Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
nextValue = nextType;
}
fieldAttrs1ann0.add(next.getName(), nextValue);
} catch (InvocationTargetException ex) {
// ignore the invocation target exception here.
} catch (IllegalAccessException ex) {
}
}
}
}
}
}
// FIELD ATTRIBUTES
SignatureAttribute fieldAttrs2 = new SignatureAttribute(L + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;");
fieldAttrs1.next = fieldAttrs2;
cw.visitField(Constants.ACC_PUBLIC, "entry", L + mapType.getInternalName() + SEMI_COLON, null, fieldAttrs1);
cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/MapValue", "<init>", "()V");
cv.visitInsn(Constants.RETURN);
cv.visitMaxs(1, 1);
// METHOD ATTRIBUTES
RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations();
Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;");
methodAttrs1.annotations.add(methodAttrs1ann0);
SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;)V");
methodAttrs1.next = methodAttrs2;
cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + mapType.getInternalName() + ";)V", null, methodAttrs1);
Label l0 = new Label();
cv.visitLabel(l0);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitVarInsn(Constants.ALOAD, 1);
cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, "entry", L + mapType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.RETURN);
Label l1 = new Label();
cv.visitLabel(l1);
// CODE ATTRIBUTE
LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute();
cv.visitAttribute(cvAttr);
cv.visitMaxs(2, 2);
// METHOD ATTRIBUTES
methodAttrs1 = new RuntimeVisibleAnnotations();
methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;");
methodAttrs1.annotations.add(methodAttrs1ann0);
methodAttrs2 = new SignatureAttribute("()L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;");
methodAttrs1.next = methodAttrs2;
cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + mapType.getInternalName() + SEMI_COLON, null, methodAttrs1);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "entry", L + mapType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + mapType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitVarInsn(Constants.ALOAD, 1);
cv.visitTypeInsn(Constants.CHECKCAST, mapType.getInternalName());
cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + mapType.getInternalName() + ";)V");
cv.visitInsn(Constants.RETURN);
cv.visitMaxs(2, 2);
// CLASS ATTRIBUTE
RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations();
Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;");
attrann0.add("namespace", namespace);
annotationsAttr.annotations.add(attrann0);
cw.visitAttribute(annotationsAttr);
SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/MapValue<L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;>;");
cw.visitAttribute(attr);
cw.visitEnd();
byte[] classBytes = cw.toByteArray();
return generateClassFromBytes(qualifiedClassName, classBytes);
}
private Class generateWrapperForArrayClass(JavaClass arrayClass, TypeMappingInfo typeMappingInfo, Class xmlElementType, List<JavaClass> classesToProcess) {
JavaClass componentClass = null;
if (typeMappingInfo != null && xmlElementType != null) {
componentClass = helper.getJavaClass(xmlElementType);
} else {
componentClass = arrayClass.getComponentType();
}
if (componentClass.isArray()) {
Class nestedArrayClass = arrayClassesToGeneratedClasses.get(componentClass.getName());
if(nestedArrayClass == null) {
nestedArrayClass = generateWrapperForArrayClass(componentClass, typeMappingInfo, xmlElementType, classesToProcess);
arrayClassesToGeneratedClasses.put(componentClass.getName(), nestedArrayClass);
classesToProcess.add(helper.getJavaClass(nestedArrayClass));
}
return generateArrayValue(arrayClass, componentClass, helper.getJavaClass(nestedArrayClass), typeMappingInfo);
} else {
return generateArrayValue(arrayClass, componentClass, componentClass, typeMappingInfo);
}
}
private Class generateArrayValue(JavaClass arrayClass, JavaClass componentClass, JavaClass nestedClass, TypeMappingInfo typeMappingInfo) {
String packageName;
String qualifiedClassName;
if (componentClass.isArray()) {
packageName = componentClass.getPackageName();
qualifiedClassName = nestedClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX;
} else {
if (componentClass.isPrimitive()) {
packageName = ARRAY_PACKAGE_NAME;
qualifiedClassName = packageName + DOT_CHR + componentClass.getName() + ARRAY_CLASS_NAME_SUFFIX;
} else {
packageName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getPackageName();
if (componentClass.isMemberClass()) {
qualifiedClassName = componentClass.getName();
qualifiedClassName = qualifiedClassName.substring(qualifiedClassName.indexOf(DOLLAR_SIGN_CHR) + 1);
qualifiedClassName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getPackageName() + DOT_CHR + qualifiedClassName + ARRAY_CLASS_NAME_SUFFIX;
} else {
qualifiedClassName = ARRAY_PACKAGE_NAME + DOT_CHR + componentClass.getQualifiedName() + ARRAY_CLASS_NAME_SUFFIX;
}
}
if (componentClass.isPrimitive() || helper.isBuiltInJavaType(componentClass)) {
NamespaceInfo namespaceInfo = getPackageToNamespaceMappings().get(packageName);
if (namespaceInfo == null) {
namespaceInfo = new NamespaceInfo();
namespaceInfo.setNamespace(ARRAY_NAMESPACE);
namespaceInfo.setNamespaceResolver(new NamespaceResolver());
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
}
} else {
NamespaceInfo namespaceInfo = getNamespaceInfoForPackage(componentClass.getPackage(), componentClass.getPackageName());
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
}
}
String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR);
String superClassName;
if (componentClass.isArray()) {
superClassName = "org/eclipse/persistence/internal/jaxb/many/MultiDimensionalArrayValue";
} else {
superClassName = "org/eclipse/persistence/internal/jaxb/many/ArrayValue";
}
ClassWriter cw = new ClassWriter(false);
cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, superClassName, null, null);
CodeVisitor cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitMethodInsn(Constants.INVOKESPECIAL, superClassName, "<init>", "()V");
cv.visitInsn(Constants.RETURN);
cv.visitMaxs(1, 1);
if (componentClass.isArray()) {
cv = cw.visitMethod(Constants.ACC_PROTECTED, "adaptedClass", "()Ljava/lang/Class;", null, null);
cv.visitLdcInsn(Type.getType(L + nestedClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON));
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
}
cv = cw.visitMethod(Constants.ACC_PROTECTED, "componentClass", "()Ljava/lang/Class;", null, null);
JavaClass baseComponentClass = getBaseComponentType(componentClass);
if (baseComponentClass.isPrimitive()) {
cv.visitFieldInsn(Constants.GETSTATIC, getObjectType(baseComponentClass).getQualifiedName().replace(DOT_CHR, SLASH_CHR), "TYPE", "Ljava/lang/Class;");
} else {
cv.visitLdcInsn(Type.getType(L + baseComponentClass.getQualifiedName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON));
}
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
RuntimeVisibleAnnotations getAdaptedValueMethodAnnotations = new RuntimeVisibleAnnotations();
// process any annotations set on the TypeMappingInfo instance
java.lang.annotation.Annotation[] annotations;
if (typeMappingInfo != null && ((annotations = getAnnotations(typeMappingInfo)) != null)) {
for (java.lang.annotation.Annotation nextAnnotation : annotations) {
if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) {
Annotation annotation = new Annotation(L + nextAnnotation.annotationType().getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) {
try {
Object nextValue = next.invoke(nextAnnotation, new Object[] {});
if (nextValue instanceof Class) {
nextValue = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
}
annotation.add(next.getName(), nextValue);
} catch (InvocationTargetException ex) {
} catch (IllegalAccessException ex) {
}
}
getAdaptedValueMethodAnnotations.annotations.add(annotation);
}
}
}
Annotation xmlElementAnnotation = new Annotation("Ljavax/xml/bind/annotation/XmlElement;");
xmlElementAnnotation.add("name", ITEM);
xmlElementAnnotation.add("type", Type.getType(L + getObjectType(nestedClass).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON));
getAdaptedValueMethodAnnotations.annotations.add(xmlElementAnnotation);
cv = cw.visitMethod(Constants.ACC_PUBLIC, "getAdaptedValue", "()Ljava/util/List;", null, getAdaptedValueMethodAnnotations);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, "adaptedValue", "Ljava/util/List;");
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
return generateClassFromBytes(qualifiedClassName, cw.toByteArray());
}
private JavaClass getBaseComponentType(JavaClass javaClass) {
JavaClass componentType = javaClass.getComponentType();
if (null == componentType) {
return javaClass;
}
if (!componentType.isArray()) {
return componentType;
}
return getBaseComponentType(componentType);
}
private JavaClass getObjectType(JavaClass javaClass) {
if (javaClass.isPrimitive()) {
String primitiveClassName = javaClass.getRawName();
Class primitiveClass = getPrimitiveClass(primitiveClassName);
return helper.getJavaClass(getObjectClass(primitiveClass));
}
return javaClass;
}
private Class generateCollectionValue(JavaClass collectionClass, TypeMappingInfo typeMappingInfo, Class xmlElementType) {
JavaClass componentClass;
if (typeMappingInfo != null && xmlElementType != null) {
componentClass = helper.getJavaClass(xmlElementType);
} else if (collectionClass.hasActualTypeArguments()) {
componentClass = ((JavaClass) collectionClass.getActualTypeArguments().toArray()[0]);
} else {
componentClass = helper.getJavaClass(Object.class);
}
if (componentClass.isPrimitive()) {
Class primitiveClass = getPrimitiveClass(componentClass.getRawName());
componentClass = helper.getJavaClass(getObjectClass(primitiveClass));
}
NamespaceInfo namespaceInfo = packageToNamespaceMappings.get(collectionClass.getPackageName());
String namespace = EMPTY_STRING;
if (this.defaultTargetNamespace != null) {
namespace = this.defaultTargetNamespace;
}
NamespaceInfo componentNamespaceInfo = getNamespaceInfoForPackage(componentClass);
String packageName = componentClass.getPackageName();
packageName = "jaxb.dev.java.net." + packageName;
if (namespaceInfo == null) {
namespaceInfo = getPackageToNamespaceMappings().get(packageName);
} else {
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
if (namespaceInfo.getNamespace() != null) {
namespace = namespaceInfo.getNamespace();
}
}
if (namespaceInfo == null) {
if (componentNamespaceInfo != null) {
namespaceInfo = componentNamespaceInfo;
} else {
namespaceInfo = new NamespaceInfo();
namespaceInfo.setNamespaceResolver(new NamespaceResolver());
}
getPackageToNamespaceMappings().put(packageName, namespaceInfo);
}
String name = componentClass.getName();
Type componentType = Type.getType(L + componentClass.getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
String componentTypeInternalName = null;
if (name.equals("[B")) {
name = "byteArray";
componentTypeInternalName = componentType.getInternalName();
} else if (name.equals("[Ljava.lang.Byte;")) {
name = "ByteArray";
componentTypeInternalName = componentType.getInternalName() + SEMI_COLON;
} else {
componentTypeInternalName = L + componentType.getInternalName() + SEMI_COLON;
}
int beginIndex = name.lastIndexOf(DOT_CHR) + 1;
name = name.substring(beginIndex);
int dollarIndex = name.indexOf(DOLLAR_SIGN_CHR);
if (dollarIndex > -1) {
name = name.substring(dollarIndex + 1);
}
String collectionClassRawName = collectionClass.getRawName();
String collectionClassShortName = collectionClassRawName.substring(collectionClassRawName.lastIndexOf(DOT_CHR) + 1);
String suggestedClassName = collectionClassShortName + "Of" + name;
String qualifiedClassName = packageName + DOT_CHR + suggestedClassName;
qualifiedClassName = getNextAvailableClassName(qualifiedClassName);
String className = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(DOT_CHR) + 1);
Type collectionType = Type.getType(L + collectionClassRawName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
String qualifiedInternalClassName = qualifiedClassName.replace(DOT_CHR, SLASH_CHR);
ClassWriter cw = new ClassWriter(false);
CodeVisitor cv;
cw.visit(Constants.V1_5, Constants.ACC_PUBLIC + Constants.ACC_SUPER, qualifiedInternalClassName, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", null, className.replace(DOT_CHR, SLASH_CHR) + ".java");
// FIELD ATTRIBUTES
RuntimeVisibleAnnotations fieldAttrs1 = new RuntimeVisibleAnnotations();
if (typeMappingInfo != null) {
java.lang.annotation.Annotation[] annotations = getAnnotations(typeMappingInfo);
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
java.lang.annotation.Annotation nextAnnotation = annotations[i];
if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) {
String annotationClassName = nextAnnotation.annotationType().getName();
Annotation fieldAttrs1ann0 = new Annotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
fieldAttrs1.annotations.add(fieldAttrs1ann0);
for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) {
try {
Object nextValue = next.invoke(nextAnnotation, new Object[] {});
if (nextValue instanceof Class) {
Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
nextValue = nextType;
}
fieldAttrs1ann0.add(next.getName(), nextValue);
} catch (InvocationTargetException ex) {
// ignore the invocation target exception here.
} catch (IllegalAccessException ex) {
}
}
}
}
}
}
SignatureAttribute fieldAttrs2 = new SignatureAttribute(L + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;");
fieldAttrs1.next = fieldAttrs2;
cw.visitField(Constants.ACC_PUBLIC, ITEM, L + collectionType.getInternalName() + SEMI_COLON, null, fieldAttrs1);
cv = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitMethodInsn(Constants.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/CollectionValue", "<init>", "()V");
cv.visitInsn(Constants.RETURN);
cv.visitMaxs(1, 1);
// METHOD ATTRIBUTES
RuntimeVisibleAnnotations methodAttrs1 = new RuntimeVisibleAnnotations();
Annotation methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;");
methodAttrs1.annotations.add(methodAttrs1ann0);
SignatureAttribute methodAttrs2 = new SignatureAttribute("(L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;)V");
methodAttrs1.next = methodAttrs2;
cv = cw.visitMethod(Constants.ACC_PUBLIC, "setItem", "(L" + collectionType.getInternalName() + ";)V", null, methodAttrs1);
Label l0 = new Label();
cv.visitLabel(l0);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitVarInsn(Constants.ALOAD, 1);
cv.visitFieldInsn(Constants.PUTFIELD, qualifiedInternalClassName, ITEM, L + collectionType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.RETURN);
Label l1 = new Label();
cv.visitLabel(l1);
// CODE ATTRIBUTE
LocalVariableTypeTableAttribute cvAttr = new LocalVariableTypeTableAttribute();
cv.visitAttribute(cvAttr);
cv.visitMaxs(2, 2);
// METHOD ATTRIBUTES
methodAttrs1 = new RuntimeVisibleAnnotations();
methodAttrs1ann0 = new Annotation("Ljavax/xml/bind/annotation/XmlTransient;");
methodAttrs1.annotations.add(methodAttrs1ann0);
methodAttrs2 = new SignatureAttribute("()L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;");
methodAttrs1.next = methodAttrs2;
cv = cw.visitMethod(Constants.ACC_PUBLIC, "getItem", "()L" + collectionType.getInternalName() + SEMI_COLON, null, methodAttrs1);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitFieldInsn(Constants.GETFIELD, qualifiedInternalClassName, ITEM, L + collectionType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "getItem", "()Ljava/lang/Object;", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "getItem", "()L" + collectionType.getInternalName() + SEMI_COLON);
cv.visitInsn(Constants.ARETURN);
cv.visitMaxs(1, 1);
cv = cw.visitMethod(Constants.ACC_PUBLIC + Constants.ACC_BRIDGE + Constants.ACC_SYNTHETIC, "setItem", "(Ljava/lang/Object;)V", null, null);
cv.visitVarInsn(Constants.ALOAD, 0);
cv.visitVarInsn(Constants.ALOAD, 1);
cv.visitTypeInsn(Constants.CHECKCAST, EMPTY_STRING + collectionType.getInternalName() + EMPTY_STRING);
cv.visitMethodInsn(Constants.INVOKEVIRTUAL, qualifiedInternalClassName, "setItem", "(L" + collectionType.getInternalName() + ";)V");
cv.visitInsn(Constants.RETURN);
cv.visitMaxs(2, 2);
// CLASS ATTRIBUTE
RuntimeVisibleAnnotations annotationsAttr = new RuntimeVisibleAnnotations();
Annotation attrann0 = new Annotation("Ljavax/xml/bind/annotation/XmlType;");
attrann0.add("namespace", namespace);
annotationsAttr.annotations.add(attrann0);
cw.visitAttribute(annotationsAttr);
SignatureAttribute attr = new SignatureAttribute("Lorg/eclipse/persistence/internal/jaxb/many/CollectionValue<L" + collectionType.getInternalName() + "<" + componentTypeInternalName + ">;>;");
cw.visitAttribute(attr);
cw.visitEnd();
byte[] classBytes = cw.toByteArray();
return generateClassFromBytes(qualifiedClassName, classBytes);
}
private Class generateClassFromBytes(String className, byte[] classBytes) {
JaxbClassLoader loader = (JaxbClassLoader) helper.getClassLoader();
Class generatedClass = loader.generateClass(className, classBytes);
return generatedClass;
}
/**
* Inner class used for ordering a list of Properties alphabetically by
* property name.
*
*/
class PropertyComparitor implements Comparator<Property> {
public int compare(Property p1, Property p2) {
return p1.getPropertyName().compareTo(p2.getPropertyName());
}
}
private String getNextAvailableClassName(String suggestedName) {
int counter = 1;
return getNextAvailableClassName(suggestedName, suggestedName, counter);
}
private String getNextAvailableClassName(String suggestedBaseName, String suggestedName, int counter) {
Iterator<Class> iter = typeMappingInfoToGeneratedClasses.values().iterator();
while (iter.hasNext()) {
Class nextClass = iter.next();
if (nextClass.getName().equals(suggestedName)) {
counter = counter + 1;
return getNextAvailableClassName(suggestedBaseName, suggestedBaseName + counter, counter);
}
}
return suggestedName;
}
private Class getPrimitiveClass(String primitiveClassName) {
return ConversionManager.getDefaultManager().convertClassNameToClass(primitiveClassName);
}
private Class getObjectClass(Class primitiveClass) {
return ConversionManager.getDefaultManager().getObjectClass(primitiveClass);
}
public Map<java.lang.reflect.Type, Class> getCollectionClassesToGeneratedClasses() {
return collectionClassesToGeneratedClasses;
}
public Map<String, Class> getArrayClassesToGeneratedClasses() {
return arrayClassesToGeneratedClasses;
}
public Map<Class, java.lang.reflect.Type> getGeneratedClassesToCollectionClasses() {
return generatedClassesToCollectionClasses;
}
public Map<Class, JavaClass> getGeneratedClassesToArrayClasses() {
return generatedClassesToArrayClasses;
}
/**
* Convenience method for returning all of the TypeInfo objects for a given
* package name.
*
* This method is inefficient as we need to iterate over the entire typeinfo
* map for each call. We should eventually store the TypeInfos in a Map
* based on package name, i.e.:
*
* Map<String, Map<String, TypeInfo>>
*
* @param packageName
* @return List of TypeInfo objects for a given package name
*/
public Map<String, TypeInfo> getTypeInfosForPackage(String packageName) {
Map<String, TypeInfo> typeInfos = new HashMap<String, TypeInfo>();
ArrayList<JavaClass> jClasses = getTypeInfoClasses();
for (JavaClass jClass : jClasses) {
if (jClass.getPackageName().equals(packageName)) {
String key = jClass.getQualifiedName();
typeInfos.put(key, typeInfo.get(key));
}
}
return typeInfos;
}
/**
* Set namespace override info from XML bindings file. This will typically
* be called from the XMLProcessor.
*
* @param packageToNamespaceMappings
*/
public void setPackageToNamespaceMappings(HashMap<String, NamespaceInfo> packageToNamespaceMappings) {
this.packageToNamespaceMappings = packageToNamespaceMappings;
}
public SchemaTypeInfo addClass(JavaClass javaClass) {
if (javaClass == null) {
return null;
} else if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) {
return null;
}
if (typeInfo == null) {
// this is the first class. Initialize all the properties
this.typeInfoClasses = new ArrayList<JavaClass>();
this.typeInfo = new HashMap<String, TypeInfo>();
this.typeQNames = new ArrayList<QName>();
this.userDefinedSchemaTypes = new HashMap<String, QName>();
this.packageToNamespaceMappings = new HashMap<String, NamespaceInfo>();
this.namespaceResolver = new NamespaceResolver();
}
JavaClass[] jClasses = new JavaClass[] { javaClass };
buildNewTypeInfo(jClasses);
TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
NamespaceInfo namespaceInfo;
String packageName = javaClass.getPackageName();
namespaceInfo = this.packageToNamespaceMappings.get(packageName);
SchemaTypeInfo schemaInfo = new SchemaTypeInfo();
schemaInfo.setSchemaTypeName(new QName(info.getClassNamespace(), info.getSchemaTypeName()));
if (info.isSetXmlRootElement()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement();
String elementName = xmlRE.getName();
if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) {
if (javaClass.getName().indexOf(DOLLAR_SIGN_CHR) != -1) {
elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOLLAR_SIGN_CHR) + 1));
} else {
elementName = Introspector.decapitalize(javaClass.getName().substring(javaClass.getName().lastIndexOf(DOT_CHR) + 1));
}
// TCK Compliancy
if (elementName.length() >= 3) {
int idx = elementName.length() - 1;
char ch = elementName.charAt(idx - 1);
if (Character.isDigit(ch)) {
char lastCh = Character.toUpperCase(elementName.charAt(idx));
elementName = elementName.substring(0, idx) + lastCh;
}
}
}
String rootNamespace = xmlRE.getNamespace();
QName rootElemName = null;
if (rootNamespace.equals(XMLProcessor.DEFAULT)) {
rootElemName = new QName(namespaceInfo.getNamespace(), elementName);
} else {
rootElemName = new QName(rootNamespace, elementName);
}
schemaInfo.getGlobalElementDeclarations().add(rootElemName);
ElementDeclaration declaration = new ElementDeclaration(rootElemName, javaClass, javaClass.getRawName(), false);
this.getGlobalElements().put(rootElemName, declaration);
}
return schemaInfo;
}
/**
* Convenience method which class pre and postBuildTypeInfo for a given set
* of JavaClasses.
*
* @param javaClasses
*/
public void buildNewTypeInfo(JavaClass[] javaClasses) {
preBuildTypeInfo(javaClasses);
postBuildTypeInfo(javaClasses);
processPropertyTypes(javaClasses);
}
/**
* Pre-process a descriptor customizer. Here, the given JavaClass is checked
* for the existence of an @XmlCustomizer annotation.
*
* Note that the post processing of the descriptor customizers will take
* place in MappingsGenerator's generateProject method, after the
* descriptors and mappings have been generated.
*
* @param jClass
* @param tInfo
* @see XmlCustomizer
* @see MappingsGenerator
*/
private void preProcessCustomizer(JavaClass jClass, TypeInfo tInfo) {
XmlCustomizer xmlCustomizer = (XmlCustomizer) helper.getAnnotation(jClass, XmlCustomizer.class);
if (xmlCustomizer != null) {
tInfo.setXmlCustomizer(xmlCustomizer.value().getName());
}
}
/**
* Lazy load the metadata logger.
*
* @return
*/
private JAXBMetadataLogger getLogger() {
if (logger == null) {
logger = new JAXBMetadataLogger();
}
return logger;
}
/**
* Return the Helper object set on this processor.
*
* @return
*/
Helper getHelper() {
return this.helper;
}
public boolean isDefaultNamespaceAllowed() {
return isDefaultNamespaceAllowed;
}
public List<ElementDeclaration> getLocalElements() {
return this.localElements;
}
public Map<TypeMappingInfo, Class> getTypeMappingInfoToGeneratedClasses() {
return this.typeMappingInfoToGeneratedClasses;
}
public Map<TypeMappingInfo, Class> getTypeMappingInfoToAdapterClasses() {
return this.typeMappingInfoToAdapterClasses;
}
/**
* Add an XmlRegistry to ObjectFactory class name pair to the map.
*
* @param factoryClassName
* ObjectFactory class name
* @param xmlReg
* org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry instance
*/
public void addXmlRegistry(String factoryClassName, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg) {
this.xmlRegistries.put(factoryClassName, xmlReg);
}
/**
* Convenience method for determining if a given JavaClass should be
* processed as an ObjectFactory class.
*
* @param javaClass
* @return true if the JavaClass is annotated with @XmlRegistry or the map
* of XmlRegistries contains a key equal to the JavaClass' qualified
* name
*/
private boolean isXmlRegistry(JavaClass javaClass) {
return (helper.isAnnotationPresent(javaClass, XmlRegistry.class) || xmlRegistries.get(javaClass.getQualifiedName()) != null);
}
public Map<TypeMappingInfo, QName> getTypeMappingInfoToSchemaType() {
return this.typeMappingInfoToSchemaType;
}
String getDefaultTargetNamespace() {
return this.defaultTargetNamespace;
}
void setDefaultTargetNamespace(String defaultTargetNamespace) {
this.defaultTargetNamespace = defaultTargetNamespace;
}
public void setDefaultNamespaceAllowed(boolean isDefaultNamespaceAllowed) {
this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed;
}
HashMap<QName, ElementDeclaration> getElementDeclarationsForScope(String scopeClassName) {
return this.elementDeclarations.get(scopeClassName);
}
private Map<Object, Object> createUserPropertiesMap(XmlProperty[] properties) {
Map<Object, Object> propMap = new HashMap<Object, Object>();
for (XmlProperty prop : properties) {
Object pvalue = prop.value();
if (!(prop.valueType() == String.class)) {
pvalue = XMLConversionManager.getDefaultXMLManager().convertObject(prop.value(), prop.valueType());
}
propMap.put(prop.name(), pvalue);
}
return propMap;
}
/**
* Indicates if a given Property represents an MTOM attachment. Will return true
* if the given Property's actual type is one of:
*
* - DataHandler
* - byte[]
* - Byte[]
* - Image
* - Source
* - MimeMultipart
*
* @param property
* @return
*/
public boolean isMtomAttachment(Property property) {
JavaClass ptype = property.getActualType();
return (areEquals(ptype, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(ptype, byte[].class) || areEquals(ptype, Image.class) || areEquals(ptype, Source.class) || areEquals(ptype, JAVAX_MAIL_INTERNET_MIMEMULTIPART));
}
public boolean hasSwaRef() {
return this.hasSwaRef;
}
public void setHasSwaRef(boolean swaRef) {
this.hasSwaRef = swaRef;
}
}
|
package org.nbone;
/**
* IT
* @author thinking
* @since 2015-12-12
*
*/
public interface Constant {
public final static int engine =0;
public final static int default_ =0;
public final static int component =0;
public final static int container =0;
public final static int application =0;
public final static int exception =0;
public final static int framework =0;
public final static int persistence =0;
public final static int delegate =0;
public final static int factory =0;
public final static int entity_manager =0;
public final static int EntityManagerFactory =0;
public final static int uap_integrate_isc =0;
public final static int reference =0;
public final static int develop =0;
public final static int debug =0;
public final static int deploy =0;
public final static int normal =0;
public final static int publish =0;
public final static int release =0;
public final static int configuration =0;
public final static int prefix =0;
public final static int suffix =0;
}
|
package com.yahoo.vespa.hosted.provision.persistence;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationLockException;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.NodeFlavors;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.log.LogLevel;
import com.yahoo.path.Path;
import com.yahoo.transaction.NestedTransaction;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.curator.transaction.CuratorOperations;
import com.yahoo.vespa.curator.transaction.CuratorTransaction;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.node.Status;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Client which reads and writes nodes to a curator database.
* Nodes are stored in files named <code>/provision/v1/[nodestate]/[hostname]</code>.
*
* The responsibility of this class is to turn operations on the level of node states, applications and nodes
* into operations on the level of file paths and bytes.
*
* @author bratseth
*/
public class CuratorDatabaseClient {
private static final Logger log = Logger.getLogger(CuratorDatabaseClient.class.getName());
private static final Path root = Path.fromString("/provision/v1");
private static final Duration defaultLockTimeout = Duration.ofMinutes(1);
private final NodeSerializer nodeSerializer;
private final StringSetSerializer stringSetSerializer = new StringSetSerializer();
private final CuratorDatabase curatorDatabase;
private final Clock clock;
private final Zone zone;
public CuratorDatabaseClient(NodeFlavors flavors, Curator curator, Clock clock, Zone zone) {
this.nodeSerializer = new NodeSerializer(flavors);
this.zone = zone;
boolean useCache = zone.system().equals(SystemName.cd);
this.curatorDatabase = new CuratorDatabase(curator, root, useCache);
this.clock = clock;
initZK();
}
private void initZK() {
curatorDatabase.create(root);
for (Node.State state : Node.State.values())
curatorDatabase.create(toPath(state));
curatorDatabase.create(inactiveJobsPath());
}
/**
* Adds a set of nodes. Rollbacks/fails transaction if any node is not in the expected state.
*/
public List<Node> addNodesInState(List<Node> nodes, Node.State expectedState) {
NestedTransaction transaction = new NestedTransaction();
CuratorTransaction curatorTransaction = curatorDatabase.newCuratorTransactionIn(transaction);
for (Node node : nodes) {
if (node.state() != expectedState)
throw new IllegalArgumentException(node + " is not in the " + node.state() + " state");
curatorTransaction.add(CuratorOperations.create(toPath(node).getAbsolute(), nodeSerializer.toJson(node)));
}
transaction.commit();
for (Node node : nodes)
log.log(LogLevel.INFO, "Added " + node);
return nodes;
}
/**
* Adds a set of nodes in the initial, provisioned state.
*
* @return the given nodes for convenience.
*/
public List<Node> addNodes(List<Node> nodes) {
return addNodesInState(nodes, Node.State.provisioned);
}
/**
* Removes a node.
*
* @param state the current state of the node
* @param hostName the host name of the node to remove
*/
public void removeNode(Node.State state, String hostName) {
Path path = toPath(state, hostName);
NestedTransaction transaction = new NestedTransaction();
CuratorTransaction curatorTransaction = curatorDatabase.newCuratorTransactionIn(transaction);
curatorTransaction.add(CuratorOperations.delete(path.getAbsolute()));
transaction.commit();
log.log(LogLevel.INFO, "Removed: " + state + " node " + hostName);
}
/**
* Writes the given nodes and returns a copy of the incoming nodes in their persisted state.
*
* @param nodes the list of nodes to write
* @param agent the agent causing this change
* @return the nodes in their persisted state
*/
public List<Node> writeTo(List<Node> nodes, Agent agent, Optional<String> reason) {
if (nodes.isEmpty()) return Collections.emptyList();
List<Node> writtenNodes = new ArrayList<>(nodes.size());
try (NestedTransaction nestedTransaction = new NestedTransaction()) {
Map<Node.State, List<Node>> nodesByState = nodes.stream().collect(Collectors.groupingBy(Node::state));
for (Map.Entry<Node.State, List<Node>> entry : nodesByState.entrySet()) {
writtenNodes.addAll(writeTo(entry.getKey(), entry.getValue(), agent, reason, nestedTransaction));
nestedTransaction.commit();
}
}
return writtenNodes;
}
/**
* Writes the given nodes to the given state (whether or not they are already in this state or another),
* and returns a copy of the incoming nodes in their persisted state.
*
* @param toState the state to write the nodes to
* @param nodes the list of nodes to write
* @param agent the agent causing this change
* @return the nodes in their persisted state
*/
public List<Node> writeTo(Node.State toState, List<Node> nodes,
Agent agent, Optional<String> reason) {
try (NestedTransaction nestedTransaction = new NestedTransaction()) {
List<Node> writtenNodes = writeTo(toState, nodes, agent, reason, nestedTransaction);
nestedTransaction.commit();
return writtenNodes;
}
}
public Node writeTo(Node.State toState, Node node, Agent agent, Optional<String> reason) {
return writeTo(toState, Collections.singletonList(node), agent, reason).get(0);
}
/**
* Adds to the given transaction operations to write the given nodes to the given state,
* and returns a copy of the nodes in the state they will have if the transaction is committed.
*
* @param toState the state to write the nodes to
* @param nodes the list of nodes to write
* @param agent the agent causing this change
* @param reason an optional reason to be logged, for humans
* @param transaction the transaction to which write operations are added by this
* @return the nodes in their state as it will be written if committed
*/
public List<Node> writeTo(Node.State toState, List<Node> nodes,
Agent agent, Optional<String> reason,
NestedTransaction transaction) {
if (nodes.isEmpty()) return nodes;
List<Node> writtenNodes = new ArrayList<>(nodes.size());
CuratorTransaction curatorTransaction = curatorDatabase.newCuratorTransactionIn(transaction);
for (Node node : nodes) {
Node newNode = new Node(node.openStackId(), node.ipAddresses(), node.additionalIpAddresses(), node.hostname(),
node.parentHostname(), node.flavor(),
newNodeStatus(node, toState),
toState,
toState.isAllocated() ? node.allocation() : Optional.empty(),
node.history().recordStateTransition(node.state(), toState, agent, clock.instant()),
node.type());
curatorTransaction.add(CuratorOperations.delete(toPath(node).getAbsolute()))
.add(CuratorOperations.create(toPath(toState, newNode.hostname()).getAbsolute(), nodeSerializer.toJson(newNode)));
writtenNodes.add(newNode);
}
transaction.onCommitted(() -> { // schedule logging on commit of nodes which changed state
for (Node node : nodes) {
if (toState != node.state())
log.log(LogLevel.INFO, agent + " moved " + node + " to " + toState + reason.map(s -> ": " + s).orElse(""));
}
});
return writtenNodes;
}
private Status newNodeStatus(Node node, Node.State toState) {
if (node.state() != Node.State.failed && toState == Node.State.failed) return node.status().withIncreasedFailCount();
if (node.state() == Node.State.failed && toState == Node.State.active) return node.status().withDecreasedFailCount(); // fail undo
// Increase reboot generation when node is moved to dirty unless quick reuse is prioritized.
// This gets rid of lingering processes, updates OS packages if necessary and tests that reboot succeeds.
if (node.state() != Node.State.dirty && toState == Node.State.dirty && !needsFastNodeReuse(zone))
return node.status().withReboot(node.status().reboot().withIncreasedWanted());
return node.status();
}
/** In automated test environments, nodes need to be reused quickly to achieve fast test turnaronud time */
private boolean needsFastNodeReuse(Zone zone) {
return zone.environment() == Environment.staging || zone.environment() == Environment.test;
}
/**
* Returns all nodes which are in one of the given states.
* If no states are given this returns all nodes.
*/
public List<Node> getNodes(Node.State ... states) {
List<Node> nodes = new ArrayList<>();
if (states.length == 0)
states = Node.State.values();
for (Node.State state : states) {
for (String hostname : curatorDatabase.getChildren(toPath(state))) {
Optional<Node> node = getNode(hostname, state);
if (node.isPresent()) nodes.add(node.get()); // node might disappear between getChildren and getNode
}
}
return nodes;
}
/**
* Returns all nodes allocated to the given application which are in one of the given states
* If no states are given this returns all nodes.
*/
public List<Node> getNodes(ApplicationId applicationId, Node.State ... states) {
List<Node> nodes = getNodes(states);
nodes.removeIf(node -> ! node.allocation().isPresent() || ! node.allocation().get().owner().equals(applicationId));
return nodes;
}
/**
* Returns a particular node, or empty if this noe is not in any of the given states.
* If no states are given this returns the node if it is present in any state.
*/
public Optional<Node> getNode(String hostname, Node.State ... states) {
if (states.length == 0)
states = Node.State.values();
for (Node.State state : states) {
Optional<byte[]> nodeData = curatorDatabase.getData(toPath(state, hostname));
if (nodeData.isPresent())
return nodeData.map((data) -> nodeSerializer.fromJson(state, data));
}
return Optional.empty();
}
private Path toPath(Node.State nodeState) { return root.append(toDir(nodeState)); }
private Path toPath(Node node) {
return root.append(toDir(node.state())).append(node.hostname());
}
private Path toPath(Node.State nodeState, String nodeName) {
return root.append(toDir(nodeState)).append(nodeName);
}
/** Creates an returns the path to the lock for this application */
private Path lockPath(ApplicationId application) {
Path lockPath =
root
.append("locks")
.append(application.tenant().value())
.append(application.application().value())
.append(application.instance().value());
curatorDatabase.create(lockPath);
return lockPath;
}
private String toDir(Node.State state) {
switch (state) {
case active: return "allocated"; // legacy name
case dirty: return "dirty";
case failed: return "failed";
case inactive: return "deallocated"; // legacy name
case parked : return "parked";
case provisioned: return "provisioned";
case ready: return "ready";
case reserved: return "reserved";
default: throw new RuntimeException("Node state " + state + " does not map to a directory name");
}
}
/** Acquires the single cluster-global, reentrant lock for all non-active nodes */
public Lock lockInactive() {
return lock(root.append("locks").append("unallocatedLock"), defaultLockTimeout);
}
/** Acquires the single cluster-global, reentrant lock for active nodes of this application */
public Lock lock(ApplicationId application) {
return lock(application, defaultLockTimeout);
}
/** Acquires the single cluster-global, reentrant lock with the specified timeout for active nodes of this application */
public Lock lock(ApplicationId application, Duration timeout) {
try {
return lock(lockPath(application), timeout);
}
catch (UncheckedTimeoutException e) {
throw new ApplicationLockException(e);
}
}
private Lock lock(Path path, Duration timeout) {
return curatorDatabase.lock(path, timeout);
}
/**
* Returns a default flavor specific for an application, or empty if not available.
*/
public Optional<String> getDefaultFlavorForApplication(ApplicationId applicationId) {
Optional<byte[]> utf8DefaultFlavor = curatorDatabase.getData(defaultFlavorPath(applicationId));
return utf8DefaultFlavor.map((flavor) -> new String(flavor, StandardCharsets.UTF_8));
}
private Path defaultFlavorPath(ApplicationId applicationId) {
return root.append("defaultFlavor").append(applicationId.serializedForm());
}
public Set<String> readInactiveJobs() {
try {
byte[] data = curatorDatabase.getData(inactiveJobsPath()).get();
if (data.length == 0) return new HashSet<>(); // inactive jobs has never been written
return stringSetSerializer.fromJson(data);
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Error reading inactive jobs, deleting inactive state");
writeInactiveJobs(Collections.emptySet());
return new HashSet<>();
}
}
public void writeInactiveJobs(Set<String> inactiveJobs) {
NestedTransaction transaction = new NestedTransaction();
CuratorTransaction curatorTransaction = curatorDatabase.newCuratorTransactionIn(transaction);
curatorTransaction.add(CuratorOperations.setData(inactiveJobsPath().getAbsolute(),
stringSetSerializer.toJson(inactiveJobs)));
transaction.commit();
}
public Lock lockInactiveJobs() {
return lock(root.append("locks").append("inactiveJobsLock"), defaultLockTimeout);
}
private Path inactiveJobsPath() {
return root.append("inactiveJobs");
}
}
|
package edu.umd.cs.findbugs.classfile.impl;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.IAnalysisEngine;
import edu.umd.cs.findbugs.classfile.IClassAnalysisEngine;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.IClassPath;
import edu.umd.cs.findbugs.classfile.IDatabaseFactory;
import edu.umd.cs.findbugs.classfile.IErrorLogger;
import edu.umd.cs.findbugs.classfile.IMethodAnalysisEngine;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.util.MapCache;
/**
* Implementation of IAnalysisCache.
* This object is responsible for registering class and method analysis engines
* and caching analysis results.
*
* @author David Hovemeyer
*/
public class AnalysisCache implements IAnalysisCache {
// TODO: think about caching policy. Right now, cache everything forever.
// We could emulate the existing behavior by purging
// the least-recently-used class analysis results
// after the max cache size is reached.
private static final int CACHE_SIZE = 5;
private IClassPath classPath;
private IErrorLogger errorLogger;
private Map<Class<?>, IClassAnalysisEngine> classAnalysisEngineMap;
private Map<Class<?>, IMethodAnalysisEngine> methodAnalysisEngineMap;
private Map<Class<?>, IDatabaseFactory<?>> databaseFactoryMap;
private Map<ClassDescriptor, Map<Class<?>, Object>> classAnalysisMap;
private Map<MethodDescriptor, Map<Class<?>, Object>> methodAnalysisMap;
private Map<Class<?>, Object> databaseMap;
static class AnalysisError {
CheckedAnalysisException exception;
public AnalysisError(CheckedAnalysisException exception) {
this.exception = exception;
}
}
AnalysisCache(IClassPath classPath, IErrorLogger errorLogger) {
this.classPath = classPath;
this.errorLogger = errorLogger;
this.classAnalysisEngineMap = new HashMap<Class<?>, IClassAnalysisEngine>();
this.methodAnalysisEngineMap = new HashMap<Class<?>, IMethodAnalysisEngine>();
this.databaseFactoryMap = new HashMap<Class<?>, IDatabaseFactory<?>>();
this.classAnalysisMap = new MapCache<ClassDescriptor, Map<Class<?>,Object>>(CACHE_SIZE);
this.methodAnalysisMap = new MapCache<MethodDescriptor, Map<Class<?>,Object>>(CACHE_SIZE);
this.databaseMap = new HashMap<Class<?>, Object>();
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#getClassPath()
*/
public IClassPath getClassPath() {
return classPath;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#getClassAnalysis(java.lang.Class, edu.umd.cs.findbugs.classfile.ClassDescriptor)
*/
public <E> E getClassAnalysis(Class<E> analysisClass,
ClassDescriptor classDescriptor) throws CheckedAnalysisException {
return analyzeClassOrMethod(
this,
classAnalysisMap,
classAnalysisEngineMap,
classDescriptor,
analysisClass);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#getMethodAnalysis(java.lang.Class, edu.umd.cs.findbugs.classfile.MethodDescriptor)
*/
public <E> E getMethodAnalysis(Class<E> analysisClass,
MethodDescriptor methodDescriptor) throws CheckedAnalysisException {
return analyzeClassOrMethod(
this,
methodAnalysisMap,
methodAnalysisEngineMap,
methodDescriptor,
analysisClass);
}
/**
* Analyze a class or method,
* or get the cached analysis result.
*
* @param <DescriptorType> type of descriptor (class or method)
* @param <E> type of analysis result
* @param analysisCache the IAnalysisCache object
* @param descriptorToAnalysisCacheMap cache of analysis results for this kind of descriptor
* @param engineMap engine map for this kind of descriptor
* @param descriptor the class or method descriptor
* @param analysisClass the analysis result type Class object
* @return the analysis result object
* @throws CheckedAnalysisException if an analysis error occurs
*/
static<DescriptorType, E> E analyzeClassOrMethod(
IAnalysisCache analysisCache,
Map<DescriptorType, Map<Class<?>, Object>> descriptorToAnalysisCacheMap,
Map<Class<?>, ? extends IAnalysisEngine<DescriptorType>> engineMap,
DescriptorType descriptor,
Class<E> analysisClass
) throws CheckedAnalysisException {
// Get the analysis map for the class/method descriptor
Map<Class<?>, Object> analysisMap = descriptorToAnalysisCacheMap.get(descriptor);
if (analysisMap == null) {
// Create empty analysis map and save it
analysisMap = new HashMap<Class<?>, Object>();
descriptorToAnalysisCacheMap.put(descriptor, analysisMap);
}
// See if the analysis has already been performed
Object analysisResult = analysisMap.get(analysisClass);
if (analysisResult == null) {
// Analysis hasn't been performed yet.
// Find an appropriate analysis engine.
IAnalysisEngine<DescriptorType> engine = engineMap.get(analysisClass);
if (engine == null) {
throw new IllegalArgumentException(
"No analysis engine registered to produce " + analysisClass.getName());
}
// Perform the analysis
try {
analysisResult = engine.analyze(analysisCache, descriptor);
} catch (CheckedAnalysisException e) {
// Whoops, an error occurred when performing the analysis.
// Make a note.
analysisResult = new AnalysisError(e);
}
// Save the result
analysisMap.put(analysisClass, analysisResult);
}
// Error occurred?
if (analysisResult instanceof AnalysisError) {
throw ((AnalysisError) analysisResult).exception;
}
// If we could assume a 1.5 or later JVM, the Class.cast()
// method could do this cast without a warning.
return (E) analysisResult;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#registerClassAnalysisEngine(java.lang.Class, edu.umd.cs.findbugs.classfile.IClassAnalysisEngine)
*/
public <E> void registerClassAnalysisEngine(Class<E> analysisResultType,
IClassAnalysisEngine classAnalysisEngine) {
classAnalysisEngineMap.put(analysisResultType, classAnalysisEngine);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#registerMethodAnalysisEngine(java.lang.Class, edu.umd.cs.findbugs.classfile.IMethodAnalysisEngine)
*/
public <E> void registerMethodAnalysisEngine(Class<E> analysisResultType,
IMethodAnalysisEngine methodAnalysisEngine) {
methodAnalysisEngineMap.put(analysisResultType, methodAnalysisEngine);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#registerDatabaseFactory(java.lang.Class, edu.umd.cs.findbugs.classfile.IDatabaseFactory)
*/
public <E> void registerDatabaseFactory(Class<E> databaseClass, IDatabaseFactory<E> databaseFactory) {
databaseFactoryMap.put(databaseClass, databaseFactory);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#getDatabase(java.lang.Class)
*/
public <E> E getDatabase(Class<E> databaseClass) throws CheckedAnalysisException {
Object database = databaseMap.get(databaseClass);
if (database == null) {
try {
// Find the database factory
IDatabaseFactory<?> databaseFactory = databaseFactoryMap.get(databaseClass);
if (databaseFactory == null) {
throw new IllegalArgumentException(
"No database factory registered for " + databaseClass.getName());
}
// Create the database
database = databaseFactory.createDatabase();
} catch (CheckedAnalysisException e) {
// Error - record the analysis error
database = new AnalysisError(e);
}
}
if (database instanceof AnalysisError) {
throw ((AnalysisError)database).exception;
}
// Again, we really should be using Class.cast()
return (E) database;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IAnalysisCache#getErrorLogger()
*/
public IErrorLogger getErrorLogger() {
return errorLogger;
}
}
|
package org.fugerit.java.core.cfg.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.fugerit.java.core.lang.helpers.BooleanUtils;
import org.fugerit.java.core.lang.helpers.ClassHelper;
import org.fugerit.java.core.lang.helpers.StringUtils;
import org.fugerit.java.core.util.collection.ListMapStringKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyHolder extends BasicIdConfigType {
private final static Logger logger = LoggerFactory.getLogger( PropertyHolder.class );
public static final String UNSAFE_TRUE = "true";
public static final String UNSAFE_FALSE = "false";
public static final String UNSAFE_WARN = "warn";
public final static String MODE_CLASS_LOADER = "classloader";
public final static String MODE_CL = "cl";
public final static String MODE_FILE = "file";
/**
* When this mode is used, you must define in PATH reference to other holders in the same catalog, semicolon separated.
* For instace if props-01 and props-02 are two holder in the same catalog :
* path="props01;props-02"
*/
public final static String MODE_MULTI = "multi";
private static final long serialVersionUID = -4759769106837549175L;
private String description;
private String path;
private String mode;
private String xml;
private String unsafe;
private String unsafeMessage;
private Properties props;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
private static void loadWorker( InputStream is, Properties props, boolean xml ) throws IOException {
if ( xml ) {
props.loadFromXML( is );
} else {
props.load( is );
}
}
public static Properties load( String mode, String path, String xml) throws IOException {
return load(mode, path, xml, UNSAFE_FALSE, null );
}
public static Properties load( String mode, String path, String xml, String unsafe, String usafeMessage ) throws IOException {
Properties props = new Properties();
try {
if ( MODE_CLASS_LOADER.equalsIgnoreCase( mode ) || MODE_CL.equalsIgnoreCase( mode ) ) {
try ( InputStream is = ClassHelper.loadFromDefaultClassLoader( path ) ) {
loadWorker( is , props, BooleanUtils.isTrue( xml ) );
} catch (Exception e) {
throw new IOException( e );
}
} else {
try ( InputStream is = new FileInputStream( new File( path ) ) ) {
loadWorker( is , props, BooleanUtils.isTrue( xml ) );
}
}
} catch ( Exception e ) {
if ( UNSAFE_TRUE.equalsIgnoreCase( unsafe ) || UNSAFE_WARN.equalsIgnoreCase( unsafe ) ) {
String unsafeMessage = " ";
if ( StringUtils.isNotEmpty( unsafeMessage ) ) {
unsafeMessage+= unsafeMessage+" ";
}
if ( UNSAFE_WARN.equalsIgnoreCase( unsafe ) ) {
logger.warn( "Error loading unsafe property holder : "+path+unsafe+e );
} else {
logger.warn( "WARNING! Error loading unsafe property holder : "+path+unsafe+e, e );
}
} else {
throw new IOException( "Property holder load error : "+path, e );
}
}
return props;
}
public void init( PropertyCatalog catalog, String catalogId ) throws IOException {
if ( MODE_MULTI.equalsIgnoreCase( this.getMode() ) ) {
Properties multi = new Properties();
String[] data = this.getPath().split( ";" );
for ( String propsId : data ) {
ListMapStringKey<PropertyHolder> parent = catalog.getListMap( catalogId );
PropertyHolder current = parent.get( propsId );
Properties currentProps = current.getInnerProps();
for ( Object key : currentProps.keySet() ) {
String k = key.toString();
String oldValue = multi.getProperty( k );
String newValue = currentProps.getProperty( k );
if ( oldValue != null ) {
logger.info( "Override property '{}' from '{}' to '{}'", k, oldValue, newValue );
}
multi.setProperty( k , newValue );
}
}
this.props = multi;
} else {
this.init();
}
}
public void init() throws IOException {
this.props = load( this.getMode() , this.getPath(), this.getXml(), this.getUnsafe(), this.getUnsafeMessage() );
}
public boolean isEmpty() {
return props.isEmpty();
}
public boolean containsValue(Object value) {
return props.containsValue(value);
}
public boolean containsKey(Object key) {
return props.containsKey(key);
}
public Set<Object> keySet() {
return props.keySet();
}
public Set<Entry<Object, Object>> entrySet() {
return props.entrySet();
}
public String getProperty(String key) {
return props.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return props.getProperty(key, defaultValue);
}
public Enumeration<Object> keys() {
return props.keys();
}
public Properties getInnerProps() {
return props;
}
public String toString() {
return this.getClass().getSimpleName()+"[id:"+this.getId()+",description:"+this.getDescription()+"]";
}
public String getUnsafe() {
return unsafe;
}
public void setUnsafe(String unsafe) {
this.unsafe = unsafe;
}
public String getUnsafeMessage() {
return unsafeMessage;
}
public void setUnsafeMessage(String unsafeMessage) {
this.unsafeMessage = unsafeMessage;
}
}
|
package com.flipkart.foxtrot.sql;
import com.flipkart.foxtrot.common.ActionRequest;
import com.flipkart.foxtrot.common.Period;
import com.flipkart.foxtrot.common.count.CountRequest;
import com.flipkart.foxtrot.common.distinct.DistinctRequest;
import com.flipkart.foxtrot.common.group.GroupRequest;
import com.flipkart.foxtrot.common.histogram.HistogramRequest;
import com.flipkart.foxtrot.common.query.Filter;
import com.flipkart.foxtrot.common.query.Query;
import com.flipkart.foxtrot.common.query.ResultSort;
import com.flipkart.foxtrot.common.query.datetime.LastFilter;
import com.flipkart.foxtrot.common.query.general.*;
import com.flipkart.foxtrot.common.query.numeric.*;
import com.flipkart.foxtrot.common.query.string.ContainsFilter;
import com.flipkart.foxtrot.common.stats.StatsRequest;
import com.flipkart.foxtrot.common.stats.StatsTrendRequest;
import com.flipkart.foxtrot.common.trend.TrendRequest;
import com.flipkart.foxtrot.sql.extendedsql.ExtendedSqlStatement;
import com.flipkart.foxtrot.sql.extendedsql.desc.Describe;
import com.flipkart.foxtrot.sql.extendedsql.showtables.ShowTables;
import com.flipkart.foxtrot.sql.query.FqlActionQuery;
import com.flipkart.foxtrot.sql.query.FqlDescribeTable;
import com.flipkart.foxtrot.sql.query.FqlShowTablesQuery;
import com.flipkart.foxtrot.sql.util.QueryUtils;
import com.google.common.collect.Lists;
import io.dropwizard.util.Duration;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StringReader;
import java.util.List;
public class QueryTranslator extends SqlElementVisitor {
private static final Logger logger = LoggerFactory.getLogger(QueryTranslator.class.getSimpleName());
private static final MetaStatementMatcher metastatementMatcher = new MetaStatementMatcher();
private FqlQueryType queryType = FqlQueryType.select;
private String tableName;
private List<String> groupBycolumnsList = Lists.newArrayList();
private ResultSort resultSort;
private boolean hasLimit = false;
private long limitFrom;
private long limitCount;
private ActionRequest calledAction;
private List<Filter> filters;
private List<String> selectedColumns = Lists.newArrayList();
private List<ResultSort> columnsWithSort = Lists.newArrayList();
@Override
public void visit(PlainSelect plainSelect) {
List selectItems = plainSelect.getSelectItems();
//selectItems.accept(this);
for(Object selectItem : selectItems) {
SelectItem selectExpressionItem = (SelectItem)selectItem;
//System.out.println(selectExpressionItem.getExpression());
FunctionReader functionReader = new FunctionReader();
selectExpressionItem.accept(functionReader);
final String columnName = functionReader.columnName;
if(null != columnName && !columnName.isEmpty()) {
selectedColumns.add(columnName);
continue;
}
calledAction = functionReader.actionRequest;
queryType = functionReader.queryType;
}
plainSelect.getFromItem().accept(this); //Populate table name
List groupByItems = plainSelect.getGroupByColumnReferences();
if(null != groupByItems) {
queryType = FqlQueryType.group;
for(Object groupByItem : groupByItems) {
if(groupByItem instanceof Column) {
Column column = (Column) groupByItem;
groupBycolumnsList.add(column.getFullyQualifiedName());
}
}
}
if(FqlQueryType.select == queryType) {
List orderByElements = plainSelect.getOrderByElements();
resultSort = generateResultSort(orderByElements);
if (null != plainSelect.getLimit()) {
hasLimit = true;
limitFrom = plainSelect.getLimit().getOffset();
limitCount = plainSelect.getLimit().getRowCount();
}
}
if(null != plainSelect.getWhere()) {
FilterParser filterParser = new FilterParser();
plainSelect.getWhere().accept(filterParser);
filters = (filterParser.filters.isEmpty()) ? null : filterParser.filters;
}
// Handle distinct
List<ResultSort> tempColumnsWithSort = generateColumnSort(plainSelect.getOrderByElements());
if (null != plainSelect.getDistinct()){
for (String selectedColumn : selectedColumns){
boolean alreadyAdded = false;
for (ResultSort columnWithSort : tempColumnsWithSort){
if (selectedColumn.equalsIgnoreCase(columnWithSort.getField())){
columnsWithSort.add(columnWithSort);
alreadyAdded = true;
break;
}
}
if (!alreadyAdded){
ResultSort resultSort = new ResultSort();
resultSort.setField(selectedColumn);
resultSort.setOrder(ResultSort.Order.desc);
columnsWithSort.add(resultSort);
}
}
this.queryType = FqlQueryType.distinct;
}
}
@Override
public void visit(Select select) {
select.getSelectBody().accept(this);
}
@Override
public void visit(Table tableName) {
this.tableName = tableName.getName().replaceAll(Constants.SQL_TABLE_REGEX, "");
}
@Override
public void visit(Function function) {
List params = function.getParameters().getExpressions();
((Expression)params.toArray()[0]).accept(this); //TODO
}
@Override
public void visit(ExpressionList expressionList) {
ExpressionList expressions = (ExpressionList)expressionList.getExpressions();
for(Object expression : expressions.getExpressions()) {
System.out.println(expression.getClass());
}
}
@Override
public void visit(SelectExpressionItem selectExpressionItem) {
selectExpressionItem.getExpression().accept(this);
}
public FqlQuery translate(String sql) throws Exception {
ExtendedSqlStatement extendedSqlStatement = metastatementMatcher.parse(sql);
if(null != extendedSqlStatement) {
ExtendedSqlParser parser = new ExtendedSqlParser();
extendedSqlStatement.receive(parser);
return parser.getQuery();
}
CCJSqlParserManager ccjSqlParserManager = new CCJSqlParserManager();
Statement statement = ccjSqlParserManager.parse(new StringReader(sql));
Select select = (Select) statement;
select.accept(this);
ActionRequest request = null;
switch (queryType) {
case select: {
Query query = new Query();
query.setTable(tableName);
query.setSort(resultSort);
if(hasLimit) {
query.setFrom((int)limitFrom);
query.setLimit((int) limitCount);
}
query.setFilters(filters);
request = query;
break;
}
case group: {
GroupRequest group = new GroupRequest();
group.setTable(tableName);
group.setNesting(groupBycolumnsList);
group.setFilters(filters);
setUniqueCountOn(group);
request = group;
break;
}
case trend: {
TrendRequest trend = (TrendRequest)calledAction;
trend.setTable(tableName);
trend.setFilters(filters);
request = trend;
break;
}
case statstrend: {
StatsTrendRequest statsTrend = (StatsTrendRequest)calledAction;
statsTrend.setTable(tableName);
statsTrend.setFilters(filters);
request = statsTrend;
break;
}
case stats: {
StatsRequest stats = (StatsRequest)calledAction;
stats.setTable(tableName);
stats.setFilters(filters);
request = stats;
break;
}
case histogram: {
HistogramRequest histogram = (HistogramRequest)calledAction;
histogram.setTable(tableName);
histogram.setFilters(filters);
request = histogram;
break;
}
case count: {
CountRequest countRequest = (CountRequest)calledAction;
countRequest.setTable(tableName);
countRequest.setFilters(filters);
request = countRequest;
break;
}
case distinct: {
DistinctRequest distinctRequest = new DistinctRequest();
distinctRequest.setTable(tableName);
distinctRequest.setFilters(filters);
distinctRequest.setNesting(columnsWithSort);
request = distinctRequest;
}
}
if(null == request) {
throw new Exception("Could not parse provided FQL.");
}
return new FqlActionQuery(queryType, request, selectedColumns);
}
private ResultSort generateResultSort(List orderByElements) {
if(null == orderByElements) {
return null;
}
for(Object orderByElementObject : orderByElements) {
OrderByElement orderByElement = (OrderByElement)orderByElementObject;
Column sortColumn = (Column)orderByElement.getExpression();
ResultSort resultSort = new ResultSort();
resultSort.setField(sortColumn.getFullyQualifiedName());
resultSort.setOrder(orderByElement.isAsc()? ResultSort.Order.asc : ResultSort.Order.desc);
logger.info("ResultSort: " + resultSort);
return resultSort;
}
return null;
}
private void setUniqueCountOn(GroupRequest group) {
if(calledAction instanceof CountRequest) {
CountRequest calledAction = (CountRequest)this.calledAction;
boolean distinct = calledAction.isDistinct();
if(distinct) {
group.setUniqueCountOn(calledAction.getField());
}
}
}
private List<ResultSort> generateColumnSort(List<OrderByElement> orderItems) {
List<ResultSort> resultSortList = Lists.newArrayList();
if (orderItems == null || orderItems.isEmpty()){
return resultSortList;
}
for (OrderByElement orderByElement : orderItems){
Column sortColumn = (Column)orderByElement.getExpression();
ResultSort resultSort = new ResultSort();
resultSort.setField(sortColumn.getFullyQualifiedName());
resultSort.setOrder(orderByElement.isAsc()? ResultSort.Order.asc : ResultSort.Order.desc);
resultSortList.add(resultSort);
}
return resultSortList;
}
private static final class FunctionReader extends SqlElementVisitor {
private boolean allColumn = false;
private ActionRequest actionRequest;
public FqlQueryType queryType = FqlQueryType.select;
private String columnName = null;
@Override
public void visit(SelectExpressionItem selectExpressionItem) {
Expression expression = selectExpressionItem.getExpression();
if(expression instanceof Function) {
Function function = (Function)expression;
queryType = getType(function.getName());
switch (queryType) {
case trend:
actionRequest = parseTrendFunction(function.getParameters().getExpressions());
break;
case statstrend:
actionRequest = parseStatsTrendFunction(function.getParameters().getExpressions());
break;
case stats:
actionRequest = parseStatsFunction(function.getParameters().getExpressions());
break;
case histogram:
actionRequest = parseHistogramRequest(function.getParameters());
break;
case count:
actionRequest = parseCountRequest(function.getParameters(), function.isAllColumns(), function.isDistinct());
break;
case desc:
case select:
case group:
break;
}
}
else {
if (expression instanceof Parenthesis){
columnName = ((Column)((Parenthesis)expression).getExpression()).getFullyQualifiedName();
} else if(expression instanceof Column) {
columnName = ((Column)expression).getFullyQualifiedName();
}
}
}
private FqlQueryType getType(String function) {
if(function.equalsIgnoreCase("trend")) {
return FqlQueryType.trend;
}
if(function.equalsIgnoreCase("statstrend")) {
return FqlQueryType.statstrend;
}
if(function.equalsIgnoreCase("stats")) {
return FqlQueryType.stats;
}
if(function.equalsIgnoreCase("histogram")) {
return FqlQueryType.histogram;
}
if(function.equalsIgnoreCase("count")) {
return FqlQueryType.count;
}
return FqlQueryType.select;
}
private TrendRequest parseTrendFunction(List expressions) {
if(expressions == null || expressions.isEmpty() || expressions.size() > 3) {
throw new RuntimeException("trend function has following format: trend(fieldname, [period, [timestamp field]])");
}
TrendRequest trendRequest = new TrendRequest();
trendRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0)));
if(expressions.size() > 1) {
trendRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(1)).toLowerCase()));
}
if(expressions.size() > 2) {
trendRequest.setTimestamp(QueryUtils.expressionToString((Expression) expressions.get(2)));
}
return trendRequest;
}
private StatsTrendRequest parseStatsTrendFunction(List expressions) {
if(expressions == null || expressions.isEmpty() || expressions.size() > 2) {
throw new RuntimeException("statstrend function has following format: statstrend(fieldname, [period])");
}
StatsTrendRequest statsTrendRequest = new StatsTrendRequest();
statsTrendRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0)));
if(expressions.size() > 1) {
statsTrendRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(1)).toLowerCase()));
}
return statsTrendRequest;
}
private StatsRequest parseStatsFunction(List expressions) {
if(expressions == null || expressions.isEmpty() || expressions.size() > 1) {
throw new RuntimeException("stats function has following format: stats(fieldname)");
}
StatsRequest statsRequest = new StatsRequest();
statsRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0)));
return statsRequest;
}
private HistogramRequest parseHistogramRequest(ExpressionList expressionList) {
if(expressionList != null && (expressionList.getExpressions() != null && expressionList.getExpressions().size() > 2)) {
throw new RuntimeException("histogram function has the following format: histogram([period, [timestamp field]])");
}
HistogramRequest histogramRequest = new HistogramRequest();
if(null != expressionList) {
List expressions = expressionList.getExpressions();
histogramRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(0)).toLowerCase()));
if(expressions.size() > 1) {
histogramRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(1)));
}
}
return histogramRequest;
}
private ActionRequest parseCountRequest(ExpressionList expressionList, boolean allColumns, boolean isDistinct) {
CountRequest countRequest = new CountRequest();
if (allColumns){
countRequest.setField(null);
return countRequest;
}
if (expressionList != null && (expressionList.getExpressions() != null && expressionList.getExpressions().size() == 1)) {
List<Expression> expressions = expressionList.getExpressions();
if (allColumns){
countRequest.setField(null);
} else {
countRequest.setField(expressionToString(expressions.get(0)));
countRequest.setDistinct(isDistinct);
}
return countRequest;
}
throw new RuntimeException("count function has the following format: count([distinct] */column_name)");
}
private String expressionToString(Expression expression) {
if(expression instanceof Column) {
return ((Column)expression).getFullyQualifiedName();
}
if(expression instanceof StringValue) {
return ((StringValue)expression).getValue();
}
return null;
}
@Override
public void visit(AllColumns allColumns) {
allColumn = true;
}
public boolean isAllColumn() {
return allColumn;
}
}
private static final class FilterParser extends SqlElementVisitor {
private List<Filter> filters = Lists.newArrayList();
@Override
public void visit(EqualsTo equalsTo) {
EqualsFilter equalsFilter = new EqualsFilter();
String field = ((Column)equalsTo.getLeftExpression()).getFullyQualifiedName();
equalsFilter.setField(field.replaceAll(Constants.SQL_FIELD_REGEX, ""));
equalsFilter.setValue(getValueFromExpression(equalsTo.getRightExpression()));
filters.add(equalsFilter);
}
@Override
public void visit(NotEqualsTo notEqualsTo) {
NotEqualsFilter notEqualsFilter = new NotEqualsFilter();
String field = ((Column)notEqualsTo.getLeftExpression()).getFullyQualifiedName();
notEqualsFilter.setField(field.replaceAll(Constants.SQL_FIELD_REGEX, ""));
notEqualsFilter.setValue(getValueFromExpression(notEqualsTo.getRightExpression()));
filters.add(notEqualsFilter);
}
@Override
public void visit(AndExpression andExpression) {
andExpression.getLeftExpression().accept(this);
andExpression.getRightExpression().accept(this);
}
@Override
public void visit(Between between) {
BetweenFilter betweenFilter = new BetweenFilter();
ColumnData columnData = setupColumn(between.getLeftExpression());
betweenFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
betweenFilter.setTemporal(columnData.isTemporal());
Number from = getNumbericValue(between.getBetweenExpressionStart());
Number to = getNumbericValue(between.getBetweenExpressionEnd());
betweenFilter.setFrom(from);
betweenFilter.setTo(to);
filters.add(betweenFilter);
}
@Override
public void visit(GreaterThan greaterThan) {
GreaterThanFilter greaterThanFilter = new GreaterThanFilter();
ColumnData columnData = setupColumn(greaterThan.getLeftExpression());
greaterThanFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
greaterThanFilter.setTemporal(columnData.isTemporal());
greaterThanFilter.setValue(getNumbericValue(greaterThan.getRightExpression()));
filters.add(greaterThanFilter);
}
@Override
public void visit(GreaterThanEquals greaterThanEquals) {
GreaterEqualFilter greaterEqualFilter = new GreaterEqualFilter();
ColumnData columnData = setupColumn(greaterThanEquals.getLeftExpression());
greaterEqualFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
greaterEqualFilter.setTemporal(columnData.isTemporal());
greaterEqualFilter.setValue(getNumbericValue(greaterThanEquals.getRightExpression()));
filters.add(greaterEqualFilter);
}
@Override
public void visit(InExpression inExpression) {
InFilter inFilter = new InFilter();
inFilter.setField(((Column)inExpression.getLeftExpression()).getFullyQualifiedName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
ItemsList itemsList = inExpression.getRightItemsList();
if(!(itemsList instanceof ExpressionList)) {
throw new RuntimeException("Sub selects not supported");
}
ExpressionList expressionList = (ExpressionList)itemsList;
List<Object> filterValues = Lists.newArrayList();
for(Object expressionObject : expressionList.getExpressions()) {
Expression expression = (Expression) expressionObject;
filterValues.add(getValueFromExpression(expression));
}
inFilter.setValues(filterValues);
filters.add(inFilter);
}
@Override
public void visit(IsNullExpression isNullExpression) {
super.visit(isNullExpression);
ColumnData columnData = setupColumn(isNullExpression.getLeftExpression());
if (isNullExpression.isNot()) {
ExistsFilter existsFilter = new ExistsFilter();
existsFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
filters.add(existsFilter);
} else {
MissingFilter missingFilter = new MissingFilter();
missingFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
filters.add(missingFilter);
}
}
@Override
public void visit(LikeExpression likeExpression) {
super.visit(likeExpression);
ContainsFilter containsFilter = new ContainsFilter();
containsFilter.setValue(getStringValue(likeExpression.getRightExpression()));
containsFilter.setField(((Column)likeExpression.getLeftExpression()).getFullyQualifiedName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
filters.add(containsFilter);
}
@Override
public void visit(MinorThan minorThan) {
LessThanFilter lessThanFilter = new LessThanFilter();
ColumnData columnData = setupColumn(minorThan.getLeftExpression());
lessThanFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
lessThanFilter.setTemporal(columnData.isTemporal());
lessThanFilter.setValue(getNumbericValue(minorThan.getRightExpression()));
filters.add(lessThanFilter);
}
@Override
public void visit(MinorThanEquals minorThanEquals) {
LessEqualFilter lessEqualFilter = new LessEqualFilter();
ColumnData columnData = setupColumn(minorThanEquals.getLeftExpression());
lessEqualFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, ""));
lessEqualFilter.setTemporal(columnData.isTemporal());
lessEqualFilter.setValue(getNumbericValue(minorThanEquals.getRightExpression()));
filters.add(lessEqualFilter);
}
@Override
public void visit(Function function) {
if(function.getName().equalsIgnoreCase("last")) {
LastFilter lastFilter = parseWindowFunction(function.getParameters().getExpressions());
filters.add(lastFilter);
return;
}
throw new RuntimeException("Only last() function is supported");
}
private LastFilter parseWindowFunction(List expressions) {
if(expressions == null || expressions.isEmpty() || expressions.size() > 3) {
throw new RuntimeException("last function has following format: last(duration, [start-time, [timestamp field]])");
}
LastFilter lastFilter = new LastFilter();
lastFilter.setDuration(Duration.parse(QueryUtils.expressionToString((Expression) expressions.get(0))));
if(expressions.size() > 1) {
lastFilter.setCurrentTime(QueryUtils.expressionToNumber((Expression) expressions.get(1)).longValue());
}
if(expressions.size() > 2) {
lastFilter.setField(QueryUtils.expressionToString((Expression) expressions.get(2)).replaceAll(Constants.SQL_FIELD_REGEX, ""));
}
return lastFilter;
}
private Object getValueFromExpression(Expression expression) {
if(expression instanceof StringValue) {
return ((StringValue) expression).getValue();
}
return getNumbericValue(expression);
}
private String getStringValue(Expression expression) {
if(expression instanceof StringValue) {
return ((StringValue) expression).getValue();
}
throw new RuntimeException("Unsupported value type.");
}
private Number getNumbericValue(Expression expression) {
if(expression instanceof DoubleValue) {
return ((DoubleValue)expression).getValue();
}
if(expression instanceof LongValue) {
return ((LongValue)expression).getValue();
}
if(expression instanceof DateValue) {
return ((DateValue)expression).getValue().getTime();
}
if(expression instanceof TimeValue) {
return ((TimeValue)expression).getValue().getTime();
}
throw new RuntimeException("Unsupported value type.");
}
private static final class ColumnData {
private final String columnName;
private boolean temporal = false;
private boolean window = false;
private ColumnData(String columnName) {
this.columnName = columnName;
}
static ColumnData temporal(String columnName) {
ColumnData columnData = new ColumnData(columnName);
columnData.temporal = true;
return columnData;
}
static ColumnData window(String columnName) {
ColumnData columnData = new ColumnData(columnName);
columnData.window = true;
return columnData;
}
public String getColumnName() {
return columnName;
}
public boolean isTemporal() {
return temporal;
}
public boolean isWindow() {
return window;
}
}
private ColumnData setupColumn(Expression expression) {
if(expression instanceof Function) {
Function function = (Function) expression;
if(function.getName().equalsIgnoreCase("temporal")) {
List parameters = function.getParameters().getExpressions();
if(parameters.size() != 1 || ! (parameters.get(0) instanceof Column)) {
throw new RuntimeException("temporal function must have a fieldname as parameter");
}
return ColumnData.temporal(((Column)parameters.get(0)).getFullyQualifiedName());
}
throw new RuntimeException("Only the function 'temporal' is supported in where clause");
}
if(expression instanceof Column) {
return new ColumnData(((Column)expression).getFullyQualifiedName());
}
throw new RuntimeException("Only the function 'temporal([fieldname)' and fieldname is supported in where clause");
}
}
private static final class ExtendedSqlParser extends SqlElementVisitor {
private FqlQuery query;
@Override
public void visit(Describe describe) {
query = new FqlDescribeTable(describe.getTable().getName());
}
@Override
public void visit(ShowTables showTables) {
query = new FqlShowTablesQuery();
}
public FqlQuery getQuery() {
return query;
}
}
}
|
package org.opennms.netmgt.provision.service;
import static org.opennms.core.utils.InetAddressUtils.addr;
import static org.opennms.core.utils.LogUtils.debugf;
import static org.opennms.core.utils.LogUtils.infof;
import static org.opennms.core.utils.LogUtils.warnf;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.opennms.core.tasks.BatchTask;
import org.opennms.core.tasks.ContainerTask;
import org.opennms.core.tasks.DefaultTaskCoordinator;
import org.opennms.core.tasks.NeedsContainer;
import org.opennms.core.tasks.RunInBatch;
import org.opennms.core.tasks.Task;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.SnmpAgentConfigFactory;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.model.events.EventForwarder;
import org.opennms.netmgt.provision.IpInterfacePolicy;
import org.opennms.netmgt.provision.NodePolicy;
import org.opennms.netmgt.provision.SnmpInterfacePolicy;
import org.opennms.netmgt.snmp.SnmpAgentConfig;
import org.opennms.netmgt.snmp.SnmpUtils;
import org.opennms.netmgt.snmp.SnmpWalker;
import org.opennms.netmgt.snmp.TableTracker;
import org.springframework.util.Assert;
/**
* <p>NodeScan class.</p>
*
* @author ranger
* @version $Id: $
*/
public class NodeScan implements RunInBatch {
private Integer m_nodeId;
private String m_foreignSource;
private String m_foreignId;
private Date m_scanStamp;
private ProvisionService m_provisionService;
private EventForwarder m_eventForwarder;
private SnmpAgentConfigFactory m_agentConfigFactory;
private DefaultTaskCoordinator m_taskCoordinator;
//NOTE TO SELF: This is referenced from the AgentScan inner class
private boolean m_aborted = false;
private OnmsNode m_node;
private boolean m_agentFound = false;
/**
* <p>Constructor for NodeScan.</p>
*
* @param nodeId a {@link java.lang.Integer} object.
* @param foreignSource a {@link java.lang.String} object.
* @param foreignId a {@link java.lang.String} object.
* @param provisionService a {@link org.opennms.netmgt.provision.service.ProvisionService} object.
* @param eventForwarder a {@link org.opennms.netmgt.model.events.EventForwarder} object.
* @param agentConfigFactory a {@link org.opennms.netmgt.config.SnmpAgentConfigFactory} object.
* @param taskCoordinator a {@link org.opennms.core.tasks.DefaultTaskCoordinator} object.
*/
public NodeScan(final Integer nodeId, final String foreignSource, final String foreignId, final ProvisionService provisionService, final EventForwarder eventForwarder, final SnmpAgentConfigFactory agentConfigFactory, final DefaultTaskCoordinator taskCoordinator) {
m_nodeId = nodeId;
m_foreignSource = foreignSource;
m_foreignId = foreignId;
m_scanStamp = new Date();
m_provisionService = provisionService;
m_eventForwarder = eventForwarder;
m_agentConfigFactory = agentConfigFactory;
m_taskCoordinator = taskCoordinator;
}
/**
* <p>getForeignSource</p>
*
* @return a {@link java.lang.String} object.
*/
public String getForeignSource() {
return m_foreignSource;
}
/**
* <p>getForeignId</p>
*
* @return a {@link java.lang.String} object.
*/
public String getForeignId() {
return m_foreignId;
}
/**
* <p>getNodeId</p>
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getNodeId() {
return m_nodeId;
}
/**
* <p>getNode</p>
*
* @return a {@link org.opennms.netmgt.model.OnmsNode} object.
*/
public OnmsNode getNode() {
return m_node;
}
/**
* @param agentFound the agentFound to set
*/
private void setAgentFound(final boolean agentFound) {
m_agentFound = agentFound;
}
/**
* @return the agentFound
*/
private boolean isAgentFound() {
return m_agentFound;
}
/**
* <p>getScanStamp</p>
*
* @return a {@link java.util.Date} object.
*/
public Date getScanStamp() {
return m_scanStamp;
}
/**
* <p>getProvisionService</p>
*
* @return the provisionService
*/
public ProvisionService getProvisionService() {
return m_provisionService;
}
/**
* <p>getEventForwarder</p>
*
* @return the eventForwarder
*/
public EventForwarder getEventForwarder() {
return m_eventForwarder;
}
/**
* <p>getTaskCoordinator</p>
*
* @return a {@link org.opennms.core.tasks.DefaultTaskCoordinator} object.
*/
public DefaultTaskCoordinator getTaskCoordinator() {
return m_taskCoordinator;
}
/**
* <p>isAborted</p>
*
* @return a boolean.
*/
public boolean isAborted() {
return m_aborted;
}
/**
* <p>abort</p>
*
* @param reason a {@link java.lang.String} object.
*/
public void abort(final String reason) {
m_aborted = true;
infof(this, "Aborting Scan of node %d for the following reason: %s", m_nodeId, reason);
final EventBuilder bldr = new EventBuilder(EventConstants.PROVISION_SCAN_ABORTED_UEI, "Provisiond");
if (m_nodeId != null) {
bldr.setNodeid(m_nodeId);
}
bldr.addParam(EventConstants.PARM_FOREIGN_SOURCE, m_foreignSource);
bldr.addParam(EventConstants.PARM_FOREIGN_ID, m_foreignId);
bldr.addParam(EventConstants.PARM_REASON, reason);
m_eventForwarder.sendNow(bldr.getEvent());
}
Task createTask() {
return getTaskCoordinator().createBatch().add(NodeScan.this).get();
}
/** {@inheritDoc} */
public void run(final BatchTask parent) {
infof(this, "Scanning node %d/%s/%s", m_nodeId, m_foreignSource, m_foreignId);
parent.getBuilder().addSequence(
new RunInBatch() {
public void run(final BatchTask phase) {
loadNode(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
detectAgents(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
handleAgentUndetected(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
scanCompleted(phase);
}
}
);
}
ScheduledFuture<?> schedule(ScheduledExecutorService executor, NodeScanSchedule schedule) {
final Runnable r = new Runnable() {
public void run() {
try {
final Task t = createTask();
t.schedule();
t.waitFor();
infof(NodeScan.this, "Finished scanning node %d/%s/%s", getNodeId(), getForeignSource(), getForeignId());
} catch (final InterruptedException e) {
warnf(NodeScan.this, e, "The node scan for node %d/%s/%s was interrupted", getNodeId(), getForeignSource(), getForeignId());
Thread.currentThread().interrupt();
} catch (final ExecutionException e) {
warnf(NodeScan.this, e, "An error occurred while scanning node %d/%s/%s", getNodeId(), getForeignSource(), getForeignId());
}
}
};
final ScheduledFuture<?> future = executor.scheduleWithFixedDelay(r, schedule.getInitialDelay().getMillis(), schedule.getScanInterval().getMillis(), TimeUnit.MILLISECONDS);
return future;
}
/**
* <p>loadNode</p>
*
* @param loadNode a {@link org.opennms.core.tasks.BatchTask} object.
*/
public void loadNode(final BatchTask loadNode) {
if (getForeignSource() != null) {
m_node = m_provisionService.getRequisitionedNode(getForeignSource(), getForeignId());
if (m_node == null) {
abort(String.format("Unable to get requisitioned node (%s/%s): aborted", m_foreignSource, m_foreignId));
} else {
for(final OnmsIpInterface iface : m_node.getIpInterfaces()) {
loadNode.add(new IpInterfaceScan(getNodeId(), iface.getIpAddress(), getForeignSource(), getProvisionService()));
}
}
} else {
m_node = m_provisionService.getNode(m_nodeId);
}
}
/**
* <p>createAgentScan</p>
*
* @param agentAddress a {@link java.net.InetAddress} object.
* @param agentType a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.provision.service.NodeScan.AgentScan} object.
*/
public AgentScan createAgentScan(final InetAddress agentAddress, final String agentType) {
return new AgentScan(getNodeId(), getNode(), agentAddress, agentType);
}
NoAgentScan createNoAgentScan() {
return new NoAgentScan(getNodeId(), getNode());
}
/**
* AgentScan
*
* @author brozow
*/
public class AgentScan extends BaseAgentScan implements NeedsContainer, ScanProgress {
private InetAddress m_agentAddress;
private String m_agentType;
public AgentScan(final Integer nodeId, final OnmsNode node, final InetAddress agentAddress, final String agentType) {
super(nodeId, node);
m_agentAddress = agentAddress;
m_agentType = agentType;
}
public InetAddress getAgentAddress() {
return m_agentAddress;
}
public String getAgentType() {
return m_agentType;
}
public void setNode(final OnmsNode node) {
m_node = node;
}
public String toString() {
return new ToStringBuilder(this)
.append("address", m_agentAddress)
.append("type", m_agentType)
.toString();
}
public EventForwarder getEventForwarder() {
return m_eventForwarder;
}
void completed() {
if (!isAborted()) {
final EventBuilder bldr = new EventBuilder(EventConstants.REINITIALIZE_PRIMARY_SNMP_INTERFACE_EVENT_UEI, "Provisiond");
bldr.setNodeid(getNodeId());
bldr.setInterface(getAgentAddress());
getEventForwarder().sendNow(bldr.getEvent());
}
}
void deleteObsoleteResources() {
if (!isAborted()) {
getProvisionService().updateNodeScanStamp(getNodeId(), getScanStamp());
getProvisionService().deleteObsoleteInterfaces(getNodeId(), getScanStamp());
debugf(this, "Finished deleteObsoleteResources for %s", this);
}
}
public SnmpAgentConfigFactory getAgentConfigFactory() {
return m_agentConfigFactory;
}
public void detectIpAddressTable(final BatchTask currentPhase) {
final OnmsNode node = getNode();
debugf(this, "Attempting to scan the IPAddress table for node %s", node);
// mark all provisioned interfaces as 'in need of scanning' so we can mark them
// as scanned during ipAddrTable processing
final Set<InetAddress> provisionedIps = new HashSet<InetAddress>();
if (getForeignSource() != null) {
for(final OnmsIpInterface provisioned : node.getIpInterfaces()) {
provisionedIps.add(provisioned.getIpAddress());
}
}
final IPAddressTableTracker ipAddressTracker = new IPAddressTableTracker() {
@Override
public void processIPAddressRow(final IPAddressRow row) {
final String ipAddress = row.getIpAddress();
infof(this, "Processing IPAddress table row with ipAddr %s", ipAddress);
final InetAddress address = addr(ipAddress);
// skip if it's any number of unusual/local address types
if (address == null) return;
if (address.isAnyLocalAddress()) {
debugf(this, "%s.isAnyLocalAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isLinkLocalAddress()) {
debugf(this, "%s.isLinkLocalAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isLoopbackAddress()) {
debugf(this, "%s.isLoopbackAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isMulticastAddress()) {
debugf(this, "%s.isMulticastAddress() == true, Skipping.", ipAddress);
return;
}
// mark any provisioned interface as scanned
provisionedIps.remove(ipAddress);
OnmsIpInterface iface = row.createInterfaceFromRow();
if (iface != null) {
iface.setIpLastCapsdPoll(getScanStamp());
iface.setIsManaged("M");
final List<IpInterfacePolicy> policies = getProvisionService().getIpInterfacePoliciesForForeignSource(getForeignSource() == null ? "default" : getForeignSource());
for(final IpInterfacePolicy policy : policies) {
if (iface != null) {
iface = policy.apply(iface);
}
}
if (iface != null) {
currentPhase.add(ipUpdater(currentPhase, iface), "write");
}
}
}
};
walkTable(currentPhase, provisionedIps, ipAddressTracker);
}
public void detectIpInterfaceTable(final BatchTask currentPhase) {
final OnmsNode node = getNode();
debugf(this, "Attempting to scan the IPInterface table for node %s", node);
// mark all provisioned interfaces as 'in need of scanning' so we can mark them
// as scanned during ipAddrTable processing
final Set<InetAddress> provisionedIps = new HashSet<InetAddress>();
if (getForeignSource() != null) {
for(final OnmsIpInterface provisioned : node.getIpInterfaces()) {
provisionedIps.add(provisioned.getIpAddress());
}
}
final IPInterfaceTableTracker ipIfTracker = new IPInterfaceTableTracker() {
@Override
public void processIPInterfaceRow(final IPInterfaceRow row) {
final String ipAddress = row.getIpAddress();
infof(this, "Processing IPInterface table row with ipAddr %s for node %d/%s/%s", ipAddress, node.getId(), node.getForeignSource(), node.getForeignId());
final InetAddress address = addr(ipAddress);
// skip if it's any number of unusual/local address types
if (address == null) return;
if (address.isAnyLocalAddress()) {
debugf(this, "%s.isAnyLocalAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isLinkLocalAddress()) {
debugf(this, "%s.isLinkLocalAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isLoopbackAddress()) {
debugf(this, "%s.isLoopbackAddress() == true, Skipping.", ipAddress);
return;
}
if (address.isMulticastAddress()) {
debugf(this, "%s.isMulticastAddress() == true, Skipping.", ipAddress);
return;
}
// mark any provisioned interface as scanned
provisionedIps.remove(ipAddress);
// save the interface
OnmsIpInterface iface = row.createInterfaceFromRow();
if (iface != null) {
iface.setIpLastCapsdPoll(getScanStamp());
// add call to the ip interface is managed policies
iface.setIsManaged("M");
final List<IpInterfacePolicy> policies = getProvisionService().getIpInterfacePoliciesForForeignSource(getForeignSource() == null ? "default" : getForeignSource());
for(final IpInterfacePolicy policy : policies) {
if (iface != null) {
iface = policy.apply(iface);
}
}
if (iface != null) {
currentPhase.add(ipUpdater(currentPhase, iface), "write");
}
}
}
};
walkTable(currentPhase, provisionedIps, ipIfTracker);
}
private void walkTable(final BatchTask currentPhase, final Set<InetAddress> provisionedIps, final TableTracker tracker) {
final OnmsNode node = getNode();
infof(this, "detecting IP interfaces for node %d/%s/%s using table tracker %s", node.getId(), node.getForeignSource(), node.getForeignId(), tracker);
if (isAborted()) {
debugf(this, "'%s' is marked as aborted; skipping scan of table %s", currentPhase, tracker);
} else {
Assert.notNull(getAgentConfigFactory(), "agentConfigFactory was not injected");
final SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(getAgentAddress());
final SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "IP address tables", tracker);
walker.start();
try {
walker.waitFor();
if (walker.timedOut()) {
abort("Aborting node scan : Agent timed out while scanning the IP address tables");
}
else if (walker.failed()) {
abort("Aborting node scan : Agent failed while scanning the IP address tables : " + walker.getErrorMessage());
} else {
// After processing the SNMP provided interfaces then we need to scan any that
// were provisioned but missing from the ip table
for(final InetAddress ipAddr : provisionedIps) {
final OnmsIpInterface iface = node.getIpInterfaceByIpAddress(ipAddr);
if (iface != null) {
iface.setIpLastCapsdPoll(getScanStamp());
iface.setIsManaged("M");
currentPhase.add(ipUpdater(currentPhase, iface), "write");
}
}
debugf(this, "Finished phase %s", currentPhase);
}
} catch (final InterruptedException e) {
abort("Aborting node scan : Scan thread failed while waiting for the IP address tables");
}
}
}
public void detectPhysicalInterfaces(final BatchTask currentPhase) {
if (isAborted()) { return; }
final SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(getAgentAddress());
Assert.notNull(getAgentConfigFactory(), "agentConfigFactory was not injected");
final PhysInterfaceTableTracker physIfTracker = new PhysInterfaceTableTracker() {
@Override
public void processPhysicalInterfaceRow(PhysicalInterfaceRow row) {
infof(this, "Processing ifTable row for ifIndex %d on node %d/%s/%s", row.getIfIndex(), getNodeId(), getForeignSource(), getForeignId());
OnmsSnmpInterface snmpIface = row.createInterfaceFromRow();
snmpIface.setLastCapsdPoll(getScanStamp());
final List<SnmpInterfacePolicy> policies = getProvisionService().getSnmpInterfacePoliciesForForeignSource(getForeignSource() == null ? "default" : getForeignSource());
for(final SnmpInterfacePolicy policy : policies) {
if (snmpIface != null) {
snmpIface = policy.apply(snmpIface);
}
}
if (snmpIface != null) {
final OnmsSnmpInterface snmpIfaceResult = snmpIface;
// add call to the SNMP interface collection enable policies
final Runnable r = new Runnable() {
public void run() {
getProvisionService().updateSnmpInterfaceAttributes(getNodeId(), snmpIfaceResult);
}
};
currentPhase.add(r, "write");
}
}
};
final SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "ifTable/ifXTable", physIfTracker);
walker.start();
try {
walker.waitFor();
if (walker.timedOut()) {
abort("Aborting node scan : Agent timed out while scanning the interfaces table");
}
else if (walker.failed()) {
abort("Aborting node scan : Agent failed while scanning the interfaces table: " + walker.getErrorMessage());
}
else {
debugf(this, "Finished phase %s", currentPhase);
}
} catch (final InterruptedException e) {
abort("Aborting node scan : Scan thread interrupted while waiting for interfaces table");
Thread.currentThread().interrupt();
}
}
public void run(final ContainerTask<?> parent) {
parent.getBuilder().addSequence(
new NodeInfoScan(getNode(),getAgentAddress(), getForeignSource(), this, getAgentConfigFactory(), getProvisionService(), getNodeId()),
new RunInBatch() {
public void run(final BatchTask phase) {
detectPhysicalInterfaces(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
detectIpAddressTable(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
detectIpInterfaceTable(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
deleteObsoleteResources();
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
completed();
}
}
);
}
}
public class NoAgentScan extends BaseAgentScan implements NeedsContainer {
private NoAgentScan(final Integer nodeId, final OnmsNode node) {
super(nodeId, node);
}
private void setNode(final OnmsNode node) {
m_node = node;
}
private void applyNodePolicies(final BatchTask phase) {
final List<NodePolicy> nodePolicies = getProvisionService().getNodePoliciesForForeignSource(getForeignSource() == null ? "default" : getForeignSource());
OnmsNode node = getNode();
for(final NodePolicy policy : nodePolicies) {
if (node != null) {
node = policy.apply(node);
}
}
if (node == null) {
abort("Aborted scan of node due to configured policy");
} else {
setNode(node);
}
}
void stampProvisionedInterfaces(final BatchTask phase) {
if (!isAborted()) {
for(final OnmsIpInterface iface : getNode().getIpInterfaces()) {
iface.setIpLastCapsdPoll(getScanStamp());
phase.add(ipUpdater(phase, iface), "write");
}
}
}
void deleteObsoleteResources(final BatchTask phase) {
getProvisionService().updateNodeScanStamp(getNodeId(), getScanStamp());
getProvisionService().deleteObsoleteInterfaces(getNodeId(), getScanStamp());
}
private void doPersistNodeInfo(final BatchTask phase) {
if (!isAborted()) {
getProvisionService().updateNodeAttributes(getNode());
}
debugf(this, "Finished phase %s", phase);
}
public void run(final ContainerTask<?> parent) {
parent.getBuilder().addSequence(
new RunInBatch() {
public void run(final BatchTask phase) {
applyNodePolicies(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
stampProvisionedInterfaces(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
deleteObsoleteResources(phase);
}
},
new RunInBatch() {
public void run(final BatchTask phase) {
doPersistNodeInfo(phase);
}
}
);
}
}
public class BaseAgentScan {
private OnmsNode m_node;
private Integer m_nodeId;
private BaseAgentScan(final Integer nodeId, final OnmsNode node) {
m_nodeId = nodeId;
m_node = node;
}
public Date getScanStamp() {
return m_scanStamp;
}
public OnmsNode getNode() {
return m_node;
}
public Integer getNodeId() {
return m_nodeId;
}
public boolean isAborted() {
return NodeScan.this.isAborted();
}
public void abort(final String reason) {
NodeScan.this.abort(reason);
}
public String getForeignSource() {
return getNode().getForeignSource();
}
public String getForeignId() {
return getNode().getForeignId();
}
public ProvisionService getProvisionService() {
return m_provisionService;
}
public String toString() {
return new ToStringBuilder(this)
.append("foreign source", getForeignSource())
.append("foreign id", getForeignId())
.append("node id", m_nodeId)
.append("scan stamp", m_scanStamp)
.toString();
}
void updateIpInterface(final BatchTask currentPhase, final OnmsIpInterface iface) {
getProvisionService().updateIpInterfaceAttributes(getNodeId(), iface);
if (iface.isManaged()) {
currentPhase.add(new IpInterfaceScan(getNodeId(), iface.getIpAddress(), getForeignSource(), getProvisionService()));
}
}
protected Runnable ipUpdater(final BatchTask currentPhase, final OnmsIpInterface iface) {
Runnable r = new Runnable() {
public void run() {
updateIpInterface(currentPhase, iface);
}
};
return r;
}
}
/**
* <p>toString</p>
*
* @return a {@link java.lang.String} object.
*/
public String toString() {
return new ToStringBuilder(this)
.append("foreign source", m_foreignSource)
.append("foreign id", m_foreignId)
.append("node id", m_nodeId)
.append("aborted", m_aborted)
.append("provision service", m_provisionService)
.toString();
}
/**
* <p>detectAgents</p>
*
* @param currentPhase a {@link org.opennms.core.tasks.BatchTask} object.
*/
public void detectAgents(final BatchTask currentPhase) {
if (!isAborted()) {
final OnmsNode node = getNode();
final OnmsIpInterface primaryIface = m_provisionService.getPrimaryInterfaceForNode(node);
if (primaryIface != null && primaryIface.getMonitoredServiceByServiceType("SNMP") != null) {
debugf(this, "Found primary interface and SNMP service for node %d/%s/%s", node.getId(), node.getForeignSource(), node.getForeignId());
onAgentFound(currentPhase, primaryIface);
} else {
debugf(this, "Failed to locate primary interface and SNMP service for node %d/%s/%s", node.getId(), node.getForeignSource(), node.getForeignId());
}
}
}
/**
* <p>handleAgentUndetected</p>
*
* @param currentPhase a {@link org.opennms.core.tasks.BatchTask} object.
*/
public void handleAgentUndetected(final BatchTask currentPhase) {
if (!isAgentFound()) {
currentPhase.add(createNoAgentScan());
}
}
private void onAgentFound(final ContainerTask<?> currentPhase, final OnmsIpInterface primaryIface) {
// Make AgentScan a NeedContainer class and have that call run
currentPhase.add(createAgentScan(primaryIface.getIpAddress(), "SNMP"));
setAgentFound(true);
}
/**
* <p>scanCompleted</p>
*
* @param currentPhase a {@link org.opennms.core.tasks.BatchTask} object.
*/
public void scanCompleted(final BatchTask currentPhase) {
if (!isAborted()) {
final EventBuilder bldr = new EventBuilder(EventConstants.PROVISION_SCAN_COMPLETE_UEI, "Provisiond");
bldr.setNodeid(getNodeId());
bldr.addParam(EventConstants.PARM_FOREIGN_SOURCE, getForeignSource());
bldr.addParam(EventConstants.PARM_FOREIGN_ID, getForeignId());
getEventForwarder().sendNow(bldr.getEvent());
}
}
}
|
package org.eclipse.mylyn.internal.tasks.ui.actions;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.RepositoryQuery;
import org.eclipse.mylyn.internal.tasks.core.deprecated.RepositoryTaskData;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskSelection;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskElement;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.BaseSelectionListenerAction;
/**
* @author Mik Kersten
*/
public class CopyTaskDetailsAction extends BaseSelectionListenerAction {
private static final String LABEL = "Copy Details";
public static final String ID = "org.eclipse.mylyn.tasklist.actions.copy";
private final Clipboard clipboard;
public CopyTaskDetailsAction() {
super(LABEL);
setToolTipText(LABEL);
setId(ID);
setImageDescriptor(CommonImages.COPY);
// FIXME the clipboard is not disposed
Display display = PlatformUI.getWorkbench().getDisplay();
clipboard = new Clipboard(display);
}
@Override
public void run() {
ISelection selection = getStructuredSelection();
StringBuilder sb = new StringBuilder();
Object[] seletedElements = ((IStructuredSelection) selection).toArray();
for (int i = 0; i < seletedElements.length; i++) {
if (i > 0) {
sb.append("\n\n");
}
sb.append(getTextForTask(seletedElements[i]));
}
if (sb.length() > 0) {
TextTransfer textTransfer = TextTransfer.getInstance();
clipboard.setContents(new Object[] { sb.toString() }, new Transfer[] { textTransfer });
}
}
// API 3.0: move to TasksUiUtil / into core
public static String getTextForTask(Object object) {
String text = "";
if (object instanceof ITask) {
AbstractTask task = (AbstractTask) object;
if (task.getTaskKey() != null) {
text += task.getTaskKey() + ": ";
}
text += task.getSummary();
if (TasksUiInternal.isValidUrl(task.getUrl())) {
text += "\n" + task.getUrl();
}
} else if (object instanceof RepositoryTaskData) {
RepositoryTaskData taskData = (RepositoryTaskData) object;
if (taskData.getTaskKey() != null) {
text += taskData.getTaskKey() + ": ";
}
text += taskData.getSummary();
AbstractRepositoryConnector connector = TasksUi.getRepositoryManager().getRepositoryConnector(
taskData.getConnectorKind());
if (connector != null) {
text += "\n" + connector.getTaskUrl(taskData.getRepositoryUrl(), taskData.getTaskId());
}
} else if (object instanceof IRepositoryQuery) {
RepositoryQuery query = (RepositoryQuery) object;
text += query.getSummary();
text += "\n" + query.getUrl();
} else if (object instanceof ITaskElement) {
ITaskElement element = (ITaskElement) object;
text = element.getSummary();
} else if (object instanceof RepositoryTaskSelection) {
RepositoryTaskSelection selection = (RepositoryTaskSelection) object;
text += selection.getId() + ": " + selection.getBugSummary();
AbstractRepositoryConnector connector = TasksUi.getRepositoryManager().getRepositoryConnector(
selection.getRepositoryKind());
if (connector != null) {
text += "\n" + connector.getTaskUrl(selection.getRepositoryUrl(), selection.getId());
} else {
text += "\n" + selection.getRepositoryUrl();
}
}
return text;
}
}
|
package org.lamport.tla.toolbox.tool.prover.ui.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Position;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.lamport.tla.toolbox.editor.basic.TLAEditor;
import org.lamport.tla.toolbox.editor.basic.util.EditorUtil;
import org.lamport.tla.toolbox.spec.parser.IParseConstants;
import org.lamport.tla.toolbox.spec.parser.ModuleParserLauncher;
import org.lamport.tla.toolbox.spec.parser.ParseResult;
import org.lamport.tla.toolbox.tool.ToolboxHandle;
import org.lamport.tla.toolbox.tool.prover.job.ProverJob;
import org.lamport.tla.toolbox.tool.prover.job.ProverJobRule;
import org.lamport.tla.toolbox.tool.prover.job.ProverJob.ProverJobMatcher;
import org.lamport.tla.toolbox.tool.prover.ui.ProverUIActivator;
import org.lamport.tla.toolbox.tool.prover.ui.output.data.ObligationStatus;
import org.lamport.tla.toolbox.tool.prover.ui.output.data.ObligationStatusMessage;
import org.lamport.tla.toolbox.tool.prover.ui.output.data.StepStatusMessage;
import org.lamport.tla.toolbox.tool.prover.ui.output.data.StepTuple;
import org.lamport.tla.toolbox.tool.prover.ui.output.data.WarningMessage;
import org.lamport.tla.toolbox.tool.prover.ui.view.ObligationsView;
import org.lamport.tla.toolbox.util.AdapterFactory;
import org.lamport.tla.toolbox.util.ResourceHelper;
import org.lamport.tla.toolbox.util.UIHelper;
import tla2sany.semantic.LeafProofNode;
import tla2sany.semantic.LevelNode;
import tla2sany.semantic.ModuleNode;
import tla2sany.semantic.NonLeafProofNode;
import tla2sany.semantic.ProofNode;
import tla2sany.semantic.TheoremNode;
import tla2sany.semantic.UseOrHideNode;
import tla2sany.st.Location;
import util.UniqueString;
/**
* Helper methods for the launching of the prover.
*
* @author Daniel Ricketts
*
*/
public class ProverHelper
{
/**
* Type of a marker that contains information about an obligation.
*/
public static final String OBLIGATION_MARKER = "org.lamport.tla.toolbox.tool.prover.obligation";
/**
* Attribute on an obligation marker giving the integer id of the obligation.
*/
public static final String OBLIGATION_ID = "org.lamport.tla.toolbox.tool.prover.obId";
/**
* Attribute on an obligation marker giving the String status of the obligation.
*/
public static final String OBLIGATION_STATUS = "org.lamport.tla.toolbox.tool.prover.obStatus";
/**
* Attribute on an obligation marker giving the String method of the obligation.
*/
public static final String OBLIGATION_METHOD = "org.lamport.tla.toolbox.tool.prover.obMethod";
/**
* Attribute on an obligation marker giving the formatted String of the obligation.
*/
public static final String OBLIGATION_STRING = "org.lamport.tla.toolbox.tool.prover.obString";
/**
* Type of marker that contains SANY information about a proof step.
* In particular, it contains the location of the proof step as reported
* by SANY when the prover was last launched for a step status update.
* This location may not be the same as the marker's location
* because the marker is sticky and the module may have been edited since
* the prover was last launch for a status check.
*/
public static final String SANY_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.sanyMarker";
/**
* String attribute on a SANY marker giving the location of the proof
* step the last time the prover was launched for a proof step
* status check. The string value should be set from a {@link Location}
* using {@link #locToString(Location)}.
*/
public static final String SANY_LOC_ATR = "org.lamport.tla.toolbox.tool.prover.ui.sanyLoc";
/**
* Boolean attribute on a SANY marker that should be true iff the step is
* a step with no children or with only a leaf proof.
*/
public static final String SANY_IS_LEAF_ATR = "org.lamport.tla.toolbox.tool.prover.ui.isLeafStep";
/**
* Delimiter used for representing
* locations as strings.
*/
public static final String LOC_DELIM = ":";
/**
* Obligation status that occurs when
* zenon or isabelle "takes time" to prove an obligation.
*/
public static final String BEING_PROVED = "being proved";
/**
* Obligation status indicating that the obligation
* has been proved by the value of the "meth" field.
*/
public static final String PROVED = "proved";
/**
* Obligation status indicating that proving the obligation
* has failed.
*/
public static final String FAILED = "failed";
/**
* Obligation status indicating that the obligation
* is considered trivial.
*/
public static final String TRIVIAL = "trivial";
/**
* Obligation status indicating that the obligation
* has been skipped by the value of the "meth" field.
*/
public static final String SKIPPED = "skipped";
/**
* Obligation status indicating that the obligation
* has been checked.
*/
public static final String CHECKED = "checked";
/**
* Obligation status indicating that the checking
* has failed on the obligation.
*/
public static final String CHECKING_FAILED = "checking failed";
/**
* Obligation status indicating that checking an obligation
* was interrupted.
*/
public static final String CHECKING_INTERUPTED = "checking interrupted";
/**
* Obligation status indicating that the obligation
* has been proved in a prior run of the prover.
*/
public static final String PROVED_ALREADY = "proved (already processed)";
/**
* Obligation status indicating that the obligation
* was determined to be trivial in a prior run of the prover.
*/
public static final String TRIVIAL_ALREADY = "trivial (already processed)";
/**
* Obligation status indicating that proving the obligation
* failed in a prior run of the prover.
*/
public static final String FAILED_ALREADY = "failed (already processed)";
/**
* Obligation status indicating that the obligation
* has been checked in a prior run of the prover.
*/
public static final String CHECKED_ALREADY = "checked (already processed)";
/**
* Obligation status indicating that the obligation
* has not yet been sent anywhere to be proved.
*/
public static final String TO_BE_PROVED = "to be proved";
/**
* Marker type corresponding to the status {@link StepStatusMessage#PROVING_FAILED} for non-leaf
* steps (steps with children).
*/
public static final String STEP_PROVING_FAILED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepProvingFailed";
/**
* Marker type corresponding to the status {@link StepStatusMessage#CHECKING_FAILED}
*/
public static final String STEP_CHECKING_FAILED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepCheckingFailed";
/**
* Marker type corresponding to the status {@link StepStatusMessage#MISSING_PROOFS}
*/
public static final String STEP_MISSING_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepMissing";
/**
* Marker type corresponding to the status {@link StepStatusMessage#OMITTED}
*/
public static final String STEP_OMITTED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepOmitted";
/**
* Marker type corresponding to the status {@link StepStatusMessage#CHECKED}
*/
public static final String STEP_CHECKED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepChecked";
/**
* Marker type corresponding to the status {@link StepStatusMessage#PROVED}
*/
public static final String STEP_PROVED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepProved";
/**
* Marker type corresponding to the status {@link StepStatusMessage#BEING_PROVED}.
*/
public static final String STEP_BEING_PROVED_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.stepBeingProved";
/**
* Marker type corresponding to the status {@link StepStatusMessage#PROVING_FAILED} for leaf
* steps (steps with a leaf proof or with no children.
*/
public static final String STEP_LEAF_FAILED = "org.lamport.tla.toolbox.tool.prover.ui.leafFailed";
/**
* Super type for the following four marker types for step status.
*/
public static final String STEP_STATUS_MARKER = "org.lamport.tla.toolbox.tool.prover.ui.proofStepStatus";
public static final int STEP_CHECKED_INT = 0;
public static final int STEP_PROVED_INT = 1;
public static final int STEP_TO_BE_PROVED_INT = 2;
public static final int STEP_BEING_PROVED_INT = 3;
public static final int STEP_PROOF_OMITTED_INT = 4;
public static final int STEP_PROOF_MISSING_INT = 5;
public static final int STEP_PROVING_FAILED_INT = 6;
public static final int STEP_CHECKING_FAILED_INT = 100;
public static final int STEP_UNKNOWN_INT = -1;
/**
* Removes all markers indicating obligation information on a resource. Does
* nothing if the resource does not exist. It deletes these markers only at one level
* under the resource. That is, if the resource is a directory, it deletes markers
* on its children.
*
* @param resource
* @throws CoreException
*/
public static void clearObligationMarkers(IResource resource) throws CoreException
{
if (resource.exists())
{
/*
* Obligation markers should only be on files directly in the project folder, so we
* only need to delete markers to depth one. Depth infinite would search any
* checkpoint folders, which can be slow if there are many files.
*/
resource.deleteMarkers(OBLIGATION_MARKER, false, IResource.DEPTH_ONE);
}
}
/**
* Returns true iff the marker is of the type
* {@link ProverHelper#OBLIGATION_MARKER} and represents
* an obligation that is in an "interesting" state. Interesting
* currently means one of:
*
* {@link #BEING_PROVED}
* {@link #FAILED}
* {@link #FAILED_ALREADY}
* {@link #CHECKING_FAILED}
* {@link #CHECKING_INTERUPTED}
*
* @param marker
* @return
* @throws CoreException
*/
public static boolean isInterestingObligation(IMarker marker)
{
/*
* Should return true iff that status is one of some collection of strings.
*
* A status is interesting if it contains the string "beingproved",
* e.g. "beingproved(3s)".
*/
String obStatus = marker.getAttribute(OBLIGATION_STATUS, "");
return obStatus.contains(BEING_PROVED) || obStatus.equals(FAILED) || obStatus.equals(FAILED_ALREADY)
|| obStatus.equals(CHECKING_FAILED) || obStatus.equals(CHECKING_INTERUPTED);
}
/**
* Returns true iff the marker represents an obligation that is
* finished being processed in any way (proving or checking).
*
* The proverJob gives information about the parameters used to launch
* the prover.
*
* @param message
* @param proverJob
* @return
* @throws CoreException
*/
public static boolean isObligationFinished(ObligationStatusMessage message, ProverJob proverJob)
{
String status = message.getStatus();
boolean isTrivial = status.equals(TRIVIAL) || status.equals(TRIVIAL_ALREADY);
if (!proverJob.isCheckProofs())
{
return isTrivial || status.equals(PROVED) || status.equals(PROVED_ALREADY);
}
if (proverJob.isCheckProofs())
{
return isTrivial || status.equals(CHECKED) || status.equals(CHECKED_ALREADY);
}
return false;
}
/**
* Returns all {@link IMarker} of type {@link ProverHelper#OBLIGATION_MARKER}
* for the currently opened spec. These markers contain information about obligations.
*
* If there is no spec currently open in the toolbox, this returns null.
*
* @return
* @throws CoreException
*/
public static IMarker[] getObMarkersCurSpec() throws CoreException
{
if (ToolboxHandle.getCurrentSpec() != null)
{
return ToolboxHandle.getCurrentSpec().getProject().findMarkers(OBLIGATION_MARKER, false,
IResource.DEPTH_ONE);
}
return null;
}
/**
* Removes all SANY step markers on the module.
* See {@link ProverHelper#SANY_MARKER} for a description of
* these markers.
*
* @param module
* @throws CoreException
*/
public static void removeSANYStepMarkers(IResource module) throws CoreException
{
module.deleteMarkers(SANY_MARKER, false, IResource.DEPTH_ZERO);
}
/**
* This method prepares the module for the launch of the prover.
* In the following, levelNode is the levelNode in proverJob.
* If levelNode or module, it prints debugging info and returns.
* If not, it takes the following steps:
*
* 1.) Call {@link #removeSANYStepMarkers(IResource)} on the module.
* 2.) If level node is not an instance of {@link ModuleNode},
* call {@link #removeStatusFromTree(IFile, LevelNode)}. Else
* call {@link #removeStatusFromModule(IResource)}.
* 3.) If levelNode is an instance of {@link ModuleNode}, then the following
* is done for the entire module. If it is not an instance, the following is
* only done for the tree rooted at levelNode:
*
* Create SANY markers on all nodes for which there can be
* a prover status. A SANY marker stores the location of the node as returned
* by SANY when the marker is created. Since markers are "sticky", SANY markers
* can be used to map from locations returned by the prover to the current
* location of a node. A location returned by the prover should equal
* the SANY location of a SANY marker.
*
* This currently puts SANY markers on all step or top level
* USE nodes. If levelNode is null and there is no valid parse result for the module,
* this method does nothing.
*
* See {@link ProverHelper#SANY_MARKER} for a description of
* these markers.
*
* This method also creates the tree of {@link StepTuple}s for
* this module or LevelNode.
*
* The proverJob is the instance of {@link ProverJob} used to launch the prover
* and passed to listeners of TLAPM output for that launch. It provides access
* to information about launch parameters and other useful data structures.
*
* @param module
* @throws CoreException
*/
public static void prepareModuleForProverLaunch(final IFile module, final ProverJob proverJob) throws CoreException
{
/*
* This does a lot of stuff creating, deleting, and modifying
* markers. Each of these operations results in a separate resource change
* notification sent to all listeners unless the operations are wrapped
* in an IWorkspaceRunnable(). If they are wrapped in an IWorkspaceRunnable
* and the flag IWorkspace.AVOID_UPDATE is specified when running the runnable,
* the resource change notifications will be delayed until after the runnables run method
* has completed. The notification will then be batched as a single notification. This
* seems to be more efficient.
*/
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException
{
if (module == null)
{
ProverUIActivator.logDebug("Module is null in method prepareModuleForProverLaunch. This is a bug.");
return;
}
if (proverJob.getLevelNode() == null)
{
ProverUIActivator.logDebug("Module is null in method prepareModuleForProverLaunch. This is a bug.");
return;
}
/*
* Remove existing sany markers and step status markers.
*/
removeSANYStepMarkers(module);
if (proverJob.getLevelNode() instanceof ModuleNode)
{
removeStatusFromModule(module);
} else
{
removeStatusFromTree(module, proverJob.getLevelNode());
}
/*
* Clear the maps that hold information about obligations
* and steps.
*/
proverJob.getObsMap().clear();
proverJob.getStepMap().clear();
proverJob.getStepMessageMap().clear();
/*
* Create new SANY markers and prepare the data structures for computing step statuses.
*/
if (proverJob.getLevelNode() instanceof ModuleNode)
{
ParseResult parseResult = ResourceHelper.getValidParseResult(module);
if (parseResult == null)
{
return;
}
String moduleName = ResourceHelper.getModuleName(module);
ModuleNode moduleNode = parseResult.getSpecObj().getExternalModuleTable().getModuleNode(
UniqueString.uniqueStringOf(moduleName));
if (module == null)
{
return;
}
LevelNode[] topLevelNodes = moduleNode.getTopLevel();
for (int i = 0; i < topLevelNodes.length; i++)
{
if (topLevelNodes[i].getLocation().source().equals(moduleName))
{
// found a theorem in the module
prepareTreeForProverLaunch(topLevelNodes[i], module, proverJob);
}
}
} else
{
prepareTreeForProverLaunch(proverJob.getLevelNode(), module, proverJob);
return;
}
}
};
module.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null);
}
/**
* Creates a SANY marker for levelNode if it is a {@link TheoremNode} or a {@link UseOrHideNode}.
* If it has a proof, this method recursively calls it self on all children. The SANY location
* attribute for these markers is a string representation of the location of the node
* if it is a {@link UseOrHideNode} and the string representation of the location of the node
* {@link TheoremNode#getTheorem()} if it is a {@link TheoremNode}.
*
* The methods {@link #locToString(Location)} and {@link #stringToLoc(String)} convert from
* {@link Location} to Strings and back.
*
* See {@link ProverHelper#SANY_MARKER} for a description of
* these markers.
*
* Creates and returns the {@link StepTuple} for levelNode if levelNode is an instance of
* {@link UseOrHideNode} or {@link TheoremNode}. Sets the marker for this tuple.
* Returns null otherwise. If levelNode is a {@link TheoremNode} then it sets levelNode
* as the parent of all non-null {@link StepTuple}s returned by calling this method on its children.
*
* The proverJob is the instance of {@link ProverJob} used to launch the prover
* and passed to listeners of TLAPM output for that launch. It provides access
* to information about launch parameters and other useful data structures.
*
* @param theoremNode
* @throws CoreException
*/
public static StepTuple prepareTreeForProverLaunch(LevelNode levelNode, IResource module, ProverJob proverJob)
throws CoreException
{
if (levelNode == null)
{
return null;
}
if (levelNode instanceof UseOrHideNode || levelNode instanceof TheoremNode)
{
IMarker marker = module.createMarker(SANY_MARKER);
// the location to be used for setting the sany location attribute on the marker
Location locForAttr;
if (levelNode instanceof UseOrHideNode)
{
locForAttr = levelNode.getLocation();
} else
{
TheoremNode theoremNode = (TheoremNode) levelNode;
/*
* The location of a theorem node is the location beginning at the
* step number or keyword THEOREM and ending at the end of the statement
* of the step or theorem.
*/
Location beginLoc = theoremNode.getLocation();
Location statementLoc = theoremNode.getTheorem().getLocation();
locForAttr = new Location(UniqueString.uniqueStringOf(statementLoc.source()), beginLoc.beginLine(),
beginLoc.beginColumn(), statementLoc.endLine(), statementLoc.endColumn());
}
marker.setAttribute(SANY_LOC_ATR, locToString(locForAttr));
IRegion locRegion = AdapterFactory.locationToRegion(locForAttr);
marker.setAttribute(IMarker.CHAR_START, locRegion.getOffset());
/*
* For marking a region that starts at offset o and has length l, the
* start character is o and the end character is o+l.
*/
marker.setAttribute(IMarker.CHAR_END, locRegion.getOffset() + locRegion.getLength());
/*
* Create the tuple. Eventually return this tuple.
*
* Note that for this step tuple, we do not initialize
* the status unless it is a leaf step with a PROOF OMITTED
* or a step with no proof. In that case we set the status
* to omitted or missing. There are some steps with missing
* proofs that still have obligations. When the prover sends
* information about these obligations, the status of the step
* tuple will be updated to reflect the maximum status of the
* obligations. Thus, leaf steps with a missing proof and with obligations
* will only briefly have the status "missing proof".
*
* As is noted in the constructor for step tuple, all other
* step tuples created here will be initialized with status
* STEP_UNKNOWN_INT.
*
* See the method processObligationMessage() for information
* on how information about the status of obligations
* is used to update the status of steps.
*/
StepTuple stepTuple = new StepTuple();
stepTuple.setSanyMarker(marker);
proverJob.getStepMap().put(levelNode, stepTuple);
if (levelNode instanceof TheoremNode)
{
TheoremNode theoremNode = (TheoremNode) levelNode;
ProofNode proof = theoremNode.getProof();
if (proof != null)
{
if (proof instanceof NonLeafProofNode)
{
NonLeafProofNode nonLeafProof = (NonLeafProofNode) proof;
LevelNode[] steps = nonLeafProof.getSteps();
// the step is not a leaf iff it has at least 1 step
marker.setAttribute(SANY_IS_LEAF_ATR, steps.length == 0);
/*
* Recursively put markers on each child node.
*/
for (int i = 0; i < steps.length; i++)
{
StepTuple childTuple = prepareTreeForProverLaunch(steps[i], module, proverJob);
// child tuple will be null if the step
// is not a TheoremNode or UseOrHideNode
if (childTuple != null)
{
childTuple.setParent(stepTuple);
stepTuple.addChild(childTuple);
}
}
} else
{
// leaf proof
LeafProofNode leafProof = (LeafProofNode) proof;
if (leafProof.getOmitted())
{
stepTuple.setStatus(getIntFromStringStatus(StepStatusMessage.OMITTED));
}
marker.setAttribute(SANY_IS_LEAF_ATR, true);
}
} else
{
// missing proof
stepTuple.setStatus(getIntFromStringStatus(StepStatusMessage.MISSING_PROOFS));
marker.setAttribute(SANY_IS_LEAF_ATR, true);
}
} else
{
marker.setAttribute(SANY_IS_LEAF_ATR, true);
}
return stepTuple;
}
return null;
}
/**
* Turns a {@link Location} into a String that can
* be parsed back to a location using {@link ProverHelper#stringToLoc(String)}.
* @param location
* @return
*/
public static String locToString(Location location)
{
/*
* moduleName:bl:bc:el:ec
*/
StringBuilder sb = new StringBuilder();
sb.append(location.source()).append(LOC_DELIM).append(location.beginLine()).append(LOC_DELIM).append(
location.beginColumn()).append(LOC_DELIM).append(location.endLine()).append(LOC_DELIM).append(
location.endColumn());
return sb.toString();
}
/**
* Takes a string produced by {@link #locToString(Location)}
* and produces a {@link Location}. Will throw a number format exception if
* the string was not produced by {@link #locToString(Location)}.
*
* @param locString
* @return
*/
public static Location stringToLoc(String locString)
{
/*
* moduleName:bl:bc:el:ec
*/
String[] segments = locString.split(LOC_DELIM);
return new Location(UniqueString.uniqueStringOf(segments[0]), Integer.parseInt(segments[1]), Integer
.parseInt(segments[2]), Integer.parseInt(segments[3]), Integer.parseInt(segments[4]));
}
/**
* Returns the SANY step marker on the module whose SANY location
* has the same begin and end line as the location passed to this method.
* Returns null if such a marker is not found.
*
* See {@link ProverHelper#SANY_MARKER} for a description of
* these markers.
*
* @param location
* @param module
* @return
*/
public static IMarker findSANYMarker(IResource module, Location location)
{
try
{
IMarker[] sanyMarkers = module.findMarkers(SANY_MARKER, false, IResource.DEPTH_ZERO);
/*
* Iterate through all markers. For each marker, retrieve
* the SANY location. Return the marker if its SANY location
* equals location.
*/
for (int i = 0; i < sanyMarkers.length; i++)
{
String sanyLocString = sanyMarkers[i].getAttribute(SANY_LOC_ATR, "");
if (!sanyLocString.isEmpty())
{
Location sanyLoc = stringToLoc(sanyLocString);
if (sanyLoc.beginLine() == location.beginLine()/* && sanyLoc.endLine() == location.endLine()*/)
{
return sanyMarkers[i];
}
}
}
} catch (CoreException e)
{
ProverUIActivator.logError("Error finding existing SANY marker for location " + location, e);
}
return null;
}
/**
* Converts the status string to the correct marker type.
* The status string should be one of :
*
* {@link StepStatusMessage#CHECKED}
* {@link StepStatusMessage#CHECKING_FAILED}
* {@link StepStatusMessage.MISSING_PROOFS}
* {@link StepStatusMessage.OMITTED}
* {@link StepStatusMessage.PROVED}
* {@link StepStatusMessage.PROVING_FAILED}
* {@link StepStatusMessage.BEING_PROVED}
*
* If status is not one of these, this
* method will return null.
*
* If status is null, this method returns null.
*
* The marker type for proving failed steps is different depending
* on whether it is a leaf step or not.
*
* @param status
* @param isLeafStep true iff the status is for a leaf step (a step with no
* children or with a leaf proof).
* @return
*/
public static String statusStringToMarkerType(String status, boolean isLeafStep)
{
if (status == null)
{
return null;
}
if (status.equals(StepStatusMessage.CHECKED))
{
return STEP_CHECKED_MARKER;
} else if (status.equals(StepStatusMessage.CHECKING_FAILED))
{
return STEP_CHECKING_FAILED_MARKER;
} else if (status.equals(StepStatusMessage.MISSING_PROOFS))
{
return STEP_MISSING_MARKER;
} else if (status.equals(StepStatusMessage.OMITTED))
{
return STEP_OMITTED_MARKER;
} else if (status.equals(StepStatusMessage.PROVED))
{
return STEP_PROVED_MARKER;
} else if (status.equals(StepStatusMessage.PROVING_FAILED))
{
if (isLeafStep)
{
return STEP_LEAF_FAILED;
} else
{
return STEP_PROVING_FAILED_MARKER;
}
} else if (status.equals(StepStatusMessage.BEING_PROVED))
{
return STEP_BEING_PROVED_MARKER;
}
return null;
}
/**
* Converts from an integer status of a step to
* the marker type. The int should be one of
*
* {@link #STEP_CHECKED_INT}
* {@link #STEP_CHECKING_FAILED_INT}
* {@link #STEP_PROOF_MISSING_INT}
* {@link #STEP_PROOF_OMITTED_INT}
* {@link #STEP_PROVED_INT}
* {@link #STEP_PROVING_FAILED_INT}
* {@link #STEP_BEING_PROVED_INT}
*
* Else, this method returns null.
*
* @param status
* @return
*/
public static String statusIntToStatusString(int status)
{
switch (status) {
case STEP_CHECKED_INT:
return StepStatusMessage.CHECKED;
case STEP_CHECKING_FAILED_INT:
return StepStatusMessage.CHECKING_FAILED;
case STEP_PROOF_MISSING_INT:
return StepStatusMessage.MISSING_PROOFS;
case STEP_PROOF_OMITTED_INT:
return StepStatusMessage.OMITTED;
case STEP_PROVED_INT:
return StepStatusMessage.PROVED;
case STEP_PROVING_FAILED_INT:
return StepStatusMessage.PROVING_FAILED;
case STEP_BEING_PROVED_INT:
return StepStatusMessage.BEING_PROVED;
default:
return null;
}
}
/**
* Process the obligation message. If the status of the message is not
* {@link #TO_BE_PROVED} then it creates a marker for that obligation
* by calling {@link #newObligationStatus(ObligationStatusMessage)}. Else, it prepares
* the necessary data structure for computing proof step statuses.
*
* The proverJob is the instance of {@link ProverJob} used to launch the prover
* and passed to listeners of TLAPM output for that launch. It provides access
* to information about launch parameters and other useful data structures.
*
* @param message
* @param nodeToProve the step or module on which the prover was launched
*/
public static void processObligationMessage(ObligationStatusMessage message, ProverJob proverJob)
{
if (message.getStatus().equals(TO_BE_PROVED))
{
/*
* Find the LevelNode in the semantic tree containing
* the obligation.
*/
Location obLoc = message.getLocation();
/*
* If nodeToProver is not null, then the prover was launched on that node, and so we
* can search in the tree rooted at that node for the step containing the obligation.
* If nodeToProve is false, the prover was launched on the entire module, so we have to search
* through the entire module for the step containing the obligation.
*/
LevelNode levelNode = null;
if (proverJob.getLevelNode() != null)
{
if (proverJob.getLevelNode() instanceof ModuleNode)
{
levelNode = ResourceHelper.getPfStepOrUseHideFromModuleNode((ModuleNode) proverJob.getLevelNode(),
obLoc.beginLine());
} else
{
levelNode = ResourceHelper.getLevelNodeFromTree(proverJob.getLevelNode(), obLoc.beginLine());
}
}
if (levelNode == null)
{
ProverUIActivator.logDebug("Cannot find level node containing obligation at " + obLoc
+ ". This is a bug.");
return;
}
/*
* Get the step tuple for the level node containing
* the obligation. This is the parent of the obligation.
* Create a new ObligationStatus with the step tuple as the
* parent and the message status as the initial status, add
* the obligation as a child of the step tuple. Adding
* the obligation as a child will update the status of the parent.
*/
StepTuple stepTuple = (StepTuple) proverJob.getStepMap().get(levelNode);
if (stepTuple != null)
{
ObligationStatus obStatus = new ObligationStatus(stepTuple, getIntFromStringStatus(message.getStatus()));
stepTuple.addChild(obStatus);
proverJob.getObsMap().put(new Integer(message.getID()), obStatus);
} else
{
ProverUIActivator.logDebug("Cannot find a step tuple for level node at " + levelNode.getLocation()
+ ". This is a bug.");
}
} else
{
/*
* Update the status of the obligation. The obligation will
* inform its parents step that its status should be updated.
*
* Don't update the status if the status is checking interrupted.
*/
if (!message.getStatus().equals(CHECKING_INTERUPTED))
{
ObligationStatus obStatus = (ObligationStatus) proverJob.getObsMap().get(new Integer(message.getID()));
obStatus.setStatus(getIntFromStringStatus(message.getStatus()));
}
// create the marker and update the obligations view
final IMarker obMarker = newObligationStatus(message);
UIHelper.runUIAsync(new Runnable() {
public void run()
{
ObligationsView.updateObligationView(obMarker);
}
});
}
}
/**
* Installs a new marker on the obligation in the message or updates the existing
* marker on that obligation (if there is one) with the information contained in
* message.
*
* The message location should be for a module in the currently opened spec. If no
* such module exists, this method returns null.
*
* Returns the marker created or updated.
*
* @param message must not be null
*/
public static IMarker newObligationStatus(ObligationStatusMessage message)
{
Location location = message.getLocation();
IResource module = ResourceHelper.getResourceByModuleName(location.source());
if (module != null && module instanceof IFile && module.exists())
{
/*
* We may need to convert the 4-int location of the message
* to a 2-int region if an existing marker is not found. We use a FileDocumentProvider.
* We create it now so that if it is used, it can be disconnected in
* the finally block of the following try block to avoid a memory leak.
*/
FileEditorInput fileEditorInput = new FileEditorInput((IFile) module);
FileDocumentProvider fileDocumentProvider = new FileDocumentProvider();
try
{
/*
* First try to find an existing marker with the same id
* and update it.
*/
IMarker[] markers = module.findMarkers(OBLIGATION_MARKER, false, IResource.DEPTH_ZERO);
// the marker to be updated or created from the message
IMarker marker = null;
for (int i = 0; i < markers.length; i++)
{
if (markers[i].getAttribute(OBLIGATION_ID, -1) == message.getID())
{
// DEBUG
// System.out.println("Marker updated for obligation from message \n" + message);
marker = markers[i];
break;
}
}
if (marker == null)
{
// marker not found, create new one
marker = module.createMarker(OBLIGATION_MARKER);
marker.setAttribute(OBLIGATION_ID, message.getID());
}
marker.setAttribute(OBLIGATION_METHOD, message.getMethod());
marker.setAttribute(OBLIGATION_STATUS, message.getStatus());
/*
* The obligation string is not sent by the prover for every message.
* It is only sent once when the obligation is first interesting.
* Thus, message.getObString() can be null. Everytime a new message comes
* in for a given id, we set the obligation string. This way, when the obligation
* string is actually sent by the prover, it is set on the marker.
*/
marker.setAttribute(OBLIGATION_STRING, message.getObString());
fileDocumentProvider.connect(fileEditorInput);
IDocument document = fileDocumentProvider.getDocument(fileEditorInput);
IRegion obRegion = AdapterFactory.locationToRegion(document, location);
/*
* For marking a region that starts at offset o and has length l, the
* start character is o and the end character is o+l.
*/
marker.setAttribute(IMarker.CHAR_START, obRegion.getOffset());
marker.setAttribute(IMarker.CHAR_END, obRegion.getOffset() + obRegion.getLength());
// DEBUG
// System.out.println("Marker created for obligation from message \n" + message);
return marker;
} catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
fileDocumentProvider.disconnect(fileEditorInput);
}
}
return null;
}
/**
* Should be called to update the status of a proof
* step using a message from the tlapm. This method always
* stores the message in a map for later use comparing messages
* from the tlapm to step status computed by the toolbox.
*
* If addMarker is true, this searches for an existing SANY marker
* with the same location as the status. If found, replaces
* this marker with the appropriate step status marker. If
* a SANY marker is not found, this is a bug and will be
* printed out on the console.
*
* The proverJob is the instance of {@link ProverJob} used to launch the prover
* and passed to listeners of TLAPM output for that launch. It provides access
* to information about launch parameters and other useful data structures.
*
* @param status
* @param proverJob the description of the launch of the prover
* indicating its status
*/
public static void newStepStatusMessage(StepStatusMessage status, ProverJob proverJob)
{
proverJob.getStepMessageMap().put(new Integer(status.getLocation().beginLine()), status);
if (proverJob.isStatusCheck())
{
if (status == null)
{
return;
}
/*
* Create a marker located at the proof step. The current location
* of the proof step is determined by finding an existing SANY marker
* whose attribute matches the location according to the method
* findSANYMarker().
*/
Location location = status.getLocation();
IResource module = ResourceHelper.getResourceByModuleName(location.source());
if (module != null && module instanceof IFile && module.exists())
{
/*
* Try to find an existing SANY marker.
*
* If a sany marker is found, put a marker at the current location
* of the sany marker (not at the SANY location attribute of the sany marker).
*/
IMarker sanyMarker = findSANYMarker(module, location);
if (sanyMarker == null)
{
ProverUIActivator.logDebug("Existing SANY marker not found for location " + location
+ ". This is a bug.");
}
newStepStatusMarker(sanyMarker, status.getStatus());
// the following code was commented out because it is basically
// done in newStepStatusMarker().
// try
// /*
// * If the status string does not correspond
// * to a marker type, then do not create a marker.
// */
// String markerType = statusStringToMarkerType(status.getStatus());
// if (markerType == null)
// ProverUIActivator
// .logDebug("Status of proof step does not correspond to an existing marker type. The status is "
// + status.getStatus());
// return;
// IMarker newMarker = module.createMarker(markerType);
// Map markerAttributes = new HashMap(2);
// // value based on whether a sany marker is found or not
// int newCharStart;
// int newCharEnd;
// if (sanyMarker != null)
// newCharStart = sanyMarker.getAttribute(IMarker.CHAR_START, 0);
// newCharEnd = sanyMarker.getAttribute(IMarker.CHAR_END, 0);
// } else
// ProverUIActivator.logDebug("Existing SANY marker not found for location " + location
// + ". This is a bug.");
// // the region from the tlapm message
// IRegion messageRegion = AdapterFactory.locationToRegion(location);
// /*
// * For marking a region that starts at offset o and has length l, the
// * start character is o and the end character is o+l.
// */
// newCharStart = messageRegion.getOffset();
// newCharEnd = messageRegion.getOffset() + messageRegion.getLength();
// return;
// /*
// * Remove any existing step status markers that overlap
// * with the new step status marker.
// */
// IMarker[] existingMarkers = module.findMarkers(ProverHelper.STEP_STATUS_MARKER, true,
// IResource.DEPTH_ZERO);
// for (int i = 0; i < existingMarkers.length; i++)
// IMarker existingMarker = existingMarkers[i];
// int existingCharStart = existingMarker.getAttribute(IMarker.CHAR_START, -1);
// int existingCharEnd = existingMarker.getAttribute(IMarker.CHAR_END, -1);
// // conditions for overlapping
// if (existingCharStart < newCharEnd && existingCharEnd > newCharStart)
// existingMarker.delete();
// markerAttributes.put(IMarker.CHAR_START, new Integer(newCharStart));
// markerAttributes.put(IMarker.CHAR_END, new Integer(newCharEnd));
// newMarker.setAttributes(markerAttributes);
// } catch (CoreException e)
// ProverUIActivator.logError("Error creating new status marker.", e);
} else
{
ProverUIActivator.logDebug("A module could not be located for a step status.\n" + "Status : "
+ status.getStatus() + "\nLocation : " + location);
}
}
}
/**
* Compares the step status computations of the TLAPM and the toolbox.
* Any discrepancies are reported. Currently the reporting is to the
* console.
*
* This method does the comparison for the step statuses computed
* for the launch of the prover described by proverJob.
* This is the instance of {@link ProverJob} used to launch the prover
* and passed to listeners of TLAPM output for that launch.
*/
public static void compareStepStatusComputations(ProverJob proverJob)
{
System.out.println("
Collection stepTuples = proverJob.getStepMap().values();
for (Iterator it = stepTuples.iterator(); it.hasNext();)
{
StepTuple stepTuple = (StepTuple) it.next();
Location stepLoc = stringToLoc(stepTuple.getSanyMarker().getAttribute(SANY_LOC_ATR, ""));
StepStatusMessage stepMessage = (StepStatusMessage) proverJob.getStepMessageMap().remove(
new Integer(stepLoc.beginLine()));
if (stepMessage == null)
{
System.out.println("NO STATUS BUG :\n No TLAPM step status message found for the step at " + stepLoc);
} else if (!stepMessage.getStatus().equals(statusIntToStatusString(stepTuple.getStatus())))
{
System.out.println("DIFFERENT STATUS BUG : \n Loc : " + stepLoc + "\n TLAPM : "
+ stepMessage.getStatus() + "\n Toolbox : " + statusIntToStatusString(stepTuple.getStatus()));
}
}
Collection remainingMessages = proverJob.getStepMessageMap().values();
for (Iterator it = remainingMessages.iterator(); it.hasNext();)
{
StepStatusMessage message = (StepStatusMessage) it.next();
System.out.println("NO STATUS BUG :\n No Toolbox step status message found for the step at "
+ message.getLocation());
}
System.out.println("
}
/**
* Creates a new marker at the current location of sanyMarker indicating the
* status given by status. If status is not a known type (the method
* {@link #statusStringToMarkerType(String, boolean)} returns null) then this prints
* some debugging message and returns. If sanyMarker is null, this also
* prints some debugging message and returns. If status is null, this method
* removes any step status markers that overlap with sanyMarker. A null status
* means that no color should be shown on the editor.
*
* @param sanyMarker
* @param status
*/
public static void newStepStatusMarker(final IMarker sanyMarker, String status)
{
if (sanyMarker == null)
{
ProverUIActivator.logDebug("Null sanyMarker passed to newStepStatusMarker. This is a bug.");
return;
}
try
{
final IResource module = sanyMarker.getResource();
/*
* If the status string does not correspond
* to a marker type, then do not create a marker.
*/
final String markerType = statusStringToMarkerType(status, sanyMarker.getAttribute(SANY_IS_LEAF_ATR, false));
// This is commented out because we now will not create a marker if
// marker type is null. A null marker type indicates that all overlapping markers
// should be deleted and a new one not created.
// if (markerType == null)
// ProverUIActivator
// .logDebug("Status of proof step does not correspond to an existing marker type. The status is "
// + status);
// return;
/*
* We wrap the marker creation and deletion operation
* in a runnable that tells the workspace to avoid
* sending resource change notifications while
* the run method is executing.
*/
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException
{
/*
* Its important to note that the location of the marker
* obtained by sanyMarker.getAttribute(IMarker.CHAR_START, 0)
* and sanyMarker.getAttribute(IMarker.CHAR_END, 0) can be different
* than the location of the marker in the editor if the editor is
* currently dirty. It seems that the eclipse text editors update
* the CHAR_START and CHAR_END attributes of markers only on save.
* The current position of the marker in the editor can be obtained
* through the editor's annotation model. The code for doing this
* is in the method EditorUtil.getMarkerPosition(sanyMarker).
*/
// The current position of the sany marker in the editor
// if there is at least one editor open on the module.
Position curPosition = EditorUtil.getMarkerPosition(sanyMarker);
// char start and end of the marker to be created
int newCharStart;
int newCharEnd;
if (curPosition != null)
{
newCharStart = curPosition.getOffset();
newCharEnd = curPosition.getOffset() + curPosition.getLength();
} else
{
/*
* We cannot get the position, which means there may not be
* an editor open on the module, so we just use the marker's location
* attributes.
*/
newCharStart = sanyMarker.getAttribute(IMarker.CHAR_START, 0);
newCharEnd = sanyMarker.getAttribute(IMarker.CHAR_END, 0);
}
/*
* Remove any existing step status markers that overlap
* with the new step status marker.
*/
IMarker[] existingMarkers = module.findMarkers(ProverHelper.STEP_STATUS_MARKER, true,
IResource.DEPTH_ZERO);
for (int i = 0; i < existingMarkers.length; i++)
{
IMarker existingMarker = existingMarkers[i];
int existingCharStart = existingMarker.getAttribute(IMarker.CHAR_START, -1);
int existingCharEnd = existingMarker.getAttribute(IMarker.CHAR_END, -1);
// conditions for overlapping
if (existingCharStart < newCharEnd && existingCharEnd > newCharStart)
{
existingMarker.delete();
}
}
if (markerType != null)
{
// the attributes for the new marker to be created
Map markerAttributes = new HashMap(2);
markerAttributes.put(IMarker.CHAR_START, new Integer(newCharStart));
markerAttributes.put(IMarker.CHAR_END, new Integer(newCharEnd));
markerAttributes.put(IMarker.LINE_NUMBER, new Integer(stringToLoc(
sanyMarker.getAttribute(SANY_LOC_ATR, "")).beginLine()));
// create the new marker and set its attributes
IMarker newMarker = module.createMarker(markerType);
newMarker.setAttributes(markerAttributes);
}
}
};
module.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null);
} catch (CoreException e)
{
ProverUIActivator.logError("Error creating new status marker.", e);
}
}
/**
* Removes all status markers from the module.
*/
public static void removeStatusFromModule(IResource module)
{
try
{
module.deleteMarkers(STEP_STATUS_MARKER, true, IResource.DEPTH_ZERO);
} catch (CoreException e)
{
ProverUIActivator.logError("Error removing status markers from module " + module, e);
}
}
/**
* Removes or modifies status markers so that no markers appear on any
* of the lines from the begin line to the end line of the root.
* Any markers that are only on those lines are deleted. Any markers that overlap
* with those lines are shortened so that they do not overlap.
*
* If root is a TheoremNode with a proof, then the begin line is
* root.getLocation().beginLine() and the end line is
* root.getProof().getLocation().endLine().
*
* For all other cases, the begin line is root.getLocation().beginLine()
* and the end line is root.getLocation().endLine().
*
* @param module
* @param root
*/
public static void removeStatusFromTree(IFile module, LevelNode root)
{
try
{
/*
* We need a document to convert
* from the 4-int location provided by SANY
* to the 2-int location of markers.
*/
IDocument document = ResourceHelper.getDocFromFile(module);
/*
* SANY lines are 1-based and document lines
* are 0-based. We use document lines from now
* on.
*/
int beginLine = root.getLocation().beginLine() - 1;
int endLine = root.getLocation().endLine() - 1;
if (root instanceof TheoremNode && ((TheoremNode) root).getProof() != null)
{
endLine = ((TheoremNode) root).getProof().getLocation().endLine() - 1;
}
// get the start and end characters of the tree
int treeBeginChar = document.getLineOffset(beginLine);
/*
* In the following, we subtract 1 to get the end char.
*
* For a marker representing a region that starts at offset o and has length l, the
* start character is o and the end character is o+l.
*/
int treeEndChar = document.getLineOffset(endLine) + document.getLineLength(endLine);
// get all existing step status markers on the module
IMarker[] markers = module.findMarkers(STEP_STATUS_MARKER, true, IResource.DEPTH_ZERO);
for (int i = 0; i < markers.length; i++)
{
IMarker oldMarker = markers[i];
// get the start and end characters of the marker
int markerStartChar = oldMarker.getAttribute(IMarker.CHAR_START, -1);
int markerEndChar = oldMarker.getAttribute(IMarker.CHAR_END, -1);
/*
* It appears that simply altering the char start and char end
* attributes of a marker will not cause that change to be reflected in the
* open editor. To solve this, markers that should be altered will instead
* be deleted and one or two markers will be created at the correct locations.
*
* If the marker is completely contained by the tree, delete it.
*
* If the marker starts before the tree and ends inside the tree, delete
* the marker and create one new marker that begins at the same point
* as the deleted marker but ends one character before the start of the tree.
*
* If the marker completely contains the tree, delete that marker. Create two
* new markers. One marker will start at the old marker's start point and end
* one character before the tree. The second marker will begin one character after
* the end of the tree and end at the old marker's end point.
*
* If the marker starts inside the tree and ends after the tree, delete that marker.
* Create a new marker that begins one character after the end of the tree and
* ends at the old marker's end point.
*/
if (markerStartChar >= treeBeginChar && markerEndChar <= treeEndChar)
{
oldMarker.delete();
} else if (markerStartChar < treeBeginChar && markerEndChar >= treeBeginChar
&& markerEndChar <= treeEndChar)
{
IMarker newMarker = module.createMarker(oldMarker.getType());
newMarker.setAttribute(IMarker.CHAR_START, markerStartChar);
newMarker.setAttribute(IMarker.CHAR_END, treeBeginChar - 1);
oldMarker.delete();
} else if (markerStartChar < treeBeginChar && markerEndChar > treeEndChar)
{
// marker before the tree
IMarker beforeMarker = module.createMarker(oldMarker.getType());
beforeMarker.setAttribute(IMarker.CHAR_START, markerStartChar);
beforeMarker.setAttribute(IMarker.CHAR_END, treeBeginChar - 1);
// marker after the tree
IMarker afterMarker = module.createMarker(oldMarker.getType());
afterMarker.setAttribute(IMarker.CHAR_START, treeEndChar + 1);
afterMarker.setAttribute(IMarker.CHAR_END, markerEndChar);
oldMarker.delete();
} else if (markerStartChar >= treeBeginChar && markerStartChar <= treeEndChar
&& markerEndChar > treeEndChar)
{
IMarker newMarker = module.createMarker(oldMarker.getType());
newMarker.setAttribute(IMarker.CHAR_START, treeEndChar + 1);
newMarker.setAttribute(IMarker.CHAR_END, markerEndChar);
oldMarker.delete();
}
}
} catch (CoreException e)
{
ProverUIActivator.logError("Error removing status markers from tree rooted at " + root, e);
} catch (BadLocationException e)
{
ProverUIActivator.logError("Error removing status markers from tree rooted at " + root, e);
}
}
/**
* Requests cancellation of all running prover jobs. If wait
* is true, sleeps the current thread until all prover jobs are done
* that they are done.
*/
public static void cancelProverJobs(boolean wait)
{
ProverJobMatcher jobMatcher = new ProverJob.ProverJobMatcher();
Job.getJobManager().cancel(jobMatcher);
if (wait)
{
while (Job.getJobManager().find(jobMatcher).length > 0)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
ProverUIActivator.logError("Error sleeping thread.", e);
}
}
}
}
/**
* Runs the prover on the active selection in the {@link TLAEditor} with
* focus. The active selection is the position of the caret. This method
* runs the prover on the step at the caret, where step is either a proof
* step or a top level USE node. A step is at the caret if the method
* {@link ResourceHelper#getPfStepOrUseHideFromMod(ParseResult, String, ITextSelection, IDocument)}
* returns that node for the text selection representing the caret position.
*
* If there is not a step at the caret, this method will launch the prover
* on the entire module.
*
* If there are dirty editors open, this method will prompt the user
* to save them before continuing. If there is not a valid parse result
* available, this method will parse the module in the editor with focus.
* If there are parse errors, the prover will not be launched, but the parse
* error window will show the errors.
*
* If statusCheck is true, this tells prover job to launch the prover
* for status checking, not proving. If checkProofs is true, the prover
* will check proofs.
*
* Note that checkProofs and checkStatus should not both be true.
*
* @param checkProofs true iff proofs should be checked
* @param checkStatus true iff the prover should only be run for status checking
*
* @return
*/
public static void runProverForActiveSelection(boolean checkStatus, boolean checkProofs)
{
/*
* This method works by scheduling a ProverJob. The ProverJob
* requires a full file system path to the module for which it is launched
* and the node on which the prover will be launched. In order
* to do this, this method will take the following steps:
*
* 1.) Prompt the user to save any modules that are currently open
* and unsaved.
* 2.) Get the active module editor.
* 3.) Try to obtain a valid parse result for the module in the active editor.
* A valid parse result is one that was created since the module was last
* written. If there is no valid parse result available, then prompt the user
* to parse the module (or maybe just always parse the module). This creates
* a valid parse result because the parsing is run in the UI thread.
* 4.) Check if there are errors in the valid parse result obtained in step 3. If
* there are errors, return on this method. There is no need to show a message
* to the user in this case because the parse errors view will pop open anyway.
* 5.) Get the LevelNode representing a step or top level use/hide containing the caret,
* if the caret is at such a node.
* 6.) If a LevelNode is not found in step 5, launch the prover on the entire module.
* 7.) Create and schedule a prover job if a level node is found in step 5.
*
* Note that at step 6 ,there are some other possibilities:
* -If the caret is not at any proof step, check the whole module.
* -If the caret is at a step without a proof, check the whole module.
* -If the caret is at a step without a proof, show a message to the user.
* -If the caret is at a step without a proof, disable this handler.
* -If the caret is not at any proof step, disable this handler.
* -If the caret is not at a step with a proof, ask the user if he wants
* to check the entire module.
*/
boolean proceed = UIHelper.promptUserForDirtyModules();
if (!proceed)
{
// the user cancelled
return;
}
TLAEditor editor = EditorUtil.getTLAEditorWithFocus();
Assert.isNotNull(editor, "User attempted to run prover without a tla editor in focus. This is a bug.");
IFile moduleFile = ((FileEditorInput) editor.getEditorInput()).getFile();
ParseResult parseResult = ResourceHelper.getValidParseResult(moduleFile);
if (parseResult == null)
{
parseResult = new ModuleParserLauncher().parseModule(moduleFile, new NullProgressMonitor());
}
if (parseResult.getStatus() != IParseConstants.PARSED)
{
return;
}
String moduleName = ResourceHelper.getModuleName(moduleFile);
IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
LevelNode nodeToProve = ResourceHelper.getPfStepOrUseHideFromMod(parseResult, moduleName,
(ITextSelection) editor.getSelectionProvider().getSelection(), document);
if (nodeToProve == null)
{
// launch the prover on the entire module
ProverJob proverJob = new ProverJob(moduleFile, checkStatus, parseResult.getSpecObj()
.getExternalModuleTable().getModuleNode(UniqueString.uniqueStringOf(moduleName)), checkProofs);
proverJob.setUser(true);
proverJob.setRule(new ProverJobRule());
proverJob.schedule();
// ask user if he wants to check the entire module
// MessageDialog.openWarning(UIHelper.getShellProvider().getShell(), "Cannot launch prover",
// "The caret is not at a theorem, proof step, or USE statement. It must be to launch this command.");
return;
}
ProverJob proverJob = new ProverJob(moduleFile, checkStatus, nodeToProve, checkProofs);
proverJob.setUser(true);
proverJob.setRule(new ProverJobRule());
proverJob.schedule();
}
/**
* Runs the prover on the entire module in the active editor. If checkStatus is true,
* the prover is launched only for status checking. If it is false,
* the prover is launched for proving. If checkProofs is true, the prover
* also checks the proofs.
*
* Note that checkProofs and checkStatus should not both be true.
*
* If there are dirty editors, this method first prompts the user to save them.
*
* @param checkStatus true iff the prover should only be run for status checking
* @param checkProofs true iff proofs should be checked
*/
public static void runProverForEntireModule(boolean checkStatus, boolean checkProofs)
{
boolean proceed = UIHelper.promptUserForDirtyModules();
if (!proceed)
{
// the user cancelled
return;
}
TLAEditor editor = EditorUtil.getTLAEditorWithFocus();
Assert.isNotNull(editor, "User attempted to run prover without a tla editor in focus. This is a bug.");
IFile moduleFile = ((FileEditorInput) editor.getEditorInput()).getFile();
ProverJob proverJob = new ProverJob(moduleFile, checkStatus, null, checkProofs);
proverJob.setUser(true);
proverJob.setRule(new ProverJobRule());
proverJob.schedule();
}
/**
* Takes the String representation of the status of a step
* or obligation and translates to the integer representation
* of the status of a proof step.
*
* This can be used to translate the String status of an obligation
* to the integer status that can be used to compute the status of
* the proof step containing that obligation.
*
* Returns -1 if no known status is passed in. Returns 100 if
* {@link #CHECKING_FAILED} is the status.
*
* @param status
* @return
*/
public static int getIntFromStringStatus(String status)
{
if (status.equals(CHECKED) || status.equals(CHECKED_ALREADY))
{
return STEP_CHECKED_INT;
} else if (status.equals(PROVED) || status.equals(PROVED_ALREADY) || status.equals(SKIPPED)
|| status.equals(TRIVIAL) || status.equals(TRIVIAL_ALREADY))
{
return STEP_PROVED_INT;
} else if (status.equals(TO_BE_PROVED))
{
return STEP_TO_BE_PROVED_INT;
} else if (status.equals(BEING_PROVED))
{
return STEP_BEING_PROVED_INT;
} else if (status.equals(StepStatusMessage.OMITTED))
{
return STEP_PROOF_OMITTED_INT;
} else if (status.equals(StepStatusMessage.MISSING_PROOFS))
{
return STEP_PROOF_MISSING_INT;
} else if (status.equals(FAILED) || status.equals(FAILED_ALREADY))
{
return STEP_PROVING_FAILED_INT;
} else if (status.equals(CHECKING_FAILED))
{
return STEP_CHECKING_FAILED_INT;
}
System.out.println("Unknown status : " + status);
return STEP_UNKNOWN_INT;
}
/**
* Processes a warning message from the tlapm. This simply displays
* a warning to the user.
*
* @param message
*/
public static void processWarningMessage(WarningMessage message)
{
MessageDialog.openWarning(UIHelper.getShellProvider().getShell(), "TLAPM Warning", message.getMessage());
}
}
|
package hu.eltesoft.modelexecution.ide.ui;
import hu.eltesoft.modelexecution.ide.IdePlugin;
import hu.eltesoft.modelexecution.ide.Messages;
import hu.eltesoft.modelexecution.ide.launch.ModelExecutionLaunchConfig;
import hu.eltesoft.modelexecution.ide.project.ExecutableModelNature;
import hu.eltesoft.modelexecution.uml.incquery.ClsMatcher;
import hu.eltesoft.modelexecution.uml.incquery.MethodMatcher;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.incquery.runtime.api.IncQueryEngine;
import org.eclipse.incquery.runtime.exception.IncQueryException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.papyrus.infra.emf.providers.EMFLabelProvider;
import org.eclipse.papyrus.infra.widgets.editors.TreeSelectorDialog;
import org.eclipse.papyrus.infra.widgets.providers.WorkspaceContentProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ListDialog;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.resource.UMLResource;
/**
* Allows the user to configure the model that is loaded, the main class and the
* feed function that starts the execution.
*/
public class LaunchConfigMainTab extends AbstractLaunchConfigurationTab
implements ILaunchConfigurationTab {
public static final String TAB_ID = "hu.eltesoft.modelexecution.ide.tabs.executableModel.mainTab"; //$NON-NLS-1$
private static final String EMPTY_STR = ""; //$NON-NLS-1$
private IFile selectedModelResource;
private Text selectedModelField;
private Text selectedClassField;
private Class selectedClass;
private Operation selectedFeedFunction;
private ResourceSet resourceSet = new ResourceSetImpl();
private Resource resource;
private ClsMatcher classMatcher;
private MethodMatcher methodMatcher;
private Text selectedFeedFunctionField;
@Override
public String getId() {
return TAB_ID;
}
@Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
comp.setLayout(new GridLayout(1, false));
setControl(comp);
createModelSelector(comp);
createClassSelector(comp);
createFeedFunctionSelector(comp);
comp.pack();
}
private void createModelSelector(Composite parent) {
Group group = new Group(parent, SWT.NONE);
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
group.setText(Messages.LaunchConfigurationMainTab_select_model_group_caption);
group.setLayout(new GridLayout(2, false));
group.setToolTipText(Messages.LaunchConfigurationMainTab_select_model_tooltip);
selectedModelField = new Text(group, SWT.BORDER);
selectedModelField.setEditable(false);
selectedModelField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
true, false));
selectedModelField.pack();
Button browseButton = new Button(group, SWT.NONE);
browseButton.setFont(group.getFont());
browseButton
.setText(Messages.LaunchConfigurationMainTab_select_model_button_text);
browseButton.addSelectionListener(new ModelSelector());
browseButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
false));
browseButton.pack();
group.pack();
}
/**
* Selects a model resource.
*/
private final class ModelSelector extends SelectionAdapter {
@Override
public void widgetSelected(SelectionEvent event) {
TreeSelectorDialog dialog = new TreeSelectorDialog(getShell());
dialog.setTitle(Messages.LaunchConfigurationMainTab_select_model_dialog_title);
WorkspaceContentProvider content = new WorkspaceContentProvider();
HashMap<String, String> extensions = new HashMap<String, String>();
extensions.put(
".uml", Messages.LaunchConfigMainTab_uml_extension_filter); //$NON-NLS-1$
extensions.put(
"*", Messages.LaunchConfigMainTab_all_extensions_filter); //$NON-NLS-1$
content.setExtensionFilters(extensions);
dialog.setContentProvider(content);
dialog.setLabelProvider(WorkbenchLabelProvider
.getDecoratingWorkbenchLabelProvider());
if (selectedModelResource != null && selectedModelResource.exists()) {
dialog.setInitialSelections(new IFile[] { selectedModelResource });
}
dialog.open();
Object[] selection = dialog.getResult();
if (selectionIsOk(dialog, selection)) {
selectedModelResource = (IFile) selection[0];
try {
if (selectedModelResource.getProject().hasNature(
ExecutableModelNature.NATURE_ID)) {
selectedModelField.setText(selectedModelResource
.getFullPath().toString());
registerUMLPackageAndExtension();
URI uri = URI.createFileURI(selectedModelResource
.getLocation().toString());
resource = resourceSet.getResource(uri, true);
initMatchers();
selectedClass = null;
selectedClassField.setText("");
selectedFeedFunction = null;
selectedFeedFunctionField.setText("");
updateDialog();
} else {
MessageDialog
.openError(
getShell(),
Messages.LaunchConfigMainTab_model_not_in_execution_project_caption,
Messages.LaunchConfigMainTab_model_not_in_execution_project_text);
}
} catch (CoreException e) {
IdePlugin.logError(
"Error while checking model for execution", e); //$NON-NLS-1$
}
}
}
private boolean selectionIsOk(TreeSelectorDialog dialog,
Object[] selection) {
return selection != null
&& dialog.getReturnCode() == TreeSelectorDialog.OK
&& selection.length > 0 && (selection[0] instanceof IFile);
}
private void registerUMLPackageAndExtension() {
resourceSet.getPackageRegistry().put(UMLPackage.eNS_URI,
UMLPackage.eINSTANCE);
resourceSet
.getResourceFactoryRegistry()
.getExtensionToFactoryMap()
.put(UMLResource.FILE_EXTENSION,
UMLResource.Factory.INSTANCE);
}
}
private void updateDialog() {
setDirty(true);
updateLaunchConfigurationDialog();
}
private void createClassSelector(Composite parent) {
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.LaunchConfigurationMainTab_select_class_group_caption);
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
group.setToolTipText(Messages.LaunchConfigurationMainTab_select_class_tooltip);
selectedClassField = new Text(group, SWT.BORDER);
selectedClassField.setEditable(false);
selectedClassField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
true, false));
Button browseClass = new Button(group, SWT.NONE);
browseClass
.setText(Messages.LaunchConfigurationMainTab_select_class_button_text);
browseClass.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
false));
browseClass.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (selectedClassField == null
|| selectedClassField.isDisposed()) {
return;
}
ListDialog dialog = new ListDialog(getShell());
dialog.setInput(getAllClasses());
dialog.setLabelProvider(new EMFLabelProvider());
dialog.setContentProvider(new ArrayContentProvider());
dialog.setTitle(Messages.LaunchConfigurationMainTab_select_class_dialog_title);
dialog.open();
Object[] selection = dialog.getResult();
if (selection != null
&& dialog.getReturnCode() == TreeSelectorDialog.OK
&& selection.length > 0
&& (selection[0] instanceof Class)) {
selectedClass = (Class) selection[0];
selectedClassField.setText(selectedClass.getName());
selectedFeedFunction = null;
selectedFeedFunctionField.setText("");
updateDialog();
}
}
});
group.pack();
}
private Object[] getAllClasses() {
List<Class> classes = new LinkedList<>();
classMatcher.getAllMatches().forEach(m -> classes.add(m.getCls()));
Object[] classesArray = classes.toArray(new Object[classes.size()]);
return classesArray;
}
private void createFeedFunctionSelector(Composite parent) {
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.LaunchConfigurationMainTab_select_feed_group_caption);
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
group.setToolTipText(Messages.LaunchConfigurationMainTab_select_feed_tooltip);
selectedFeedFunctionField = new Text(group, SWT.BORDER);
selectedFeedFunctionField.setEditable(false);
selectedFeedFunctionField.setLayoutData(new GridData(SWT.FILL,
SWT.CENTER, true, false));
Button browseEObjectButton = new Button(group, SWT.NONE);
browseEObjectButton
.setText(Messages.LaunchConfigurationMainTab_select_feed_button_text);
browseEObjectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
false, false));
browseEObjectButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (selectedFeedFunctionField == null
|| selectedFeedFunctionField.isDisposed()) {
return;
}
ListDialog dialog = new ListDialog(getShell());
dialog.setInput(getAllFunctions());
dialog.setLabelProvider(new EMFLabelProvider());
dialog.setContentProvider(new ArrayContentProvider());
dialog.setTitle(Messages.LaunchConfigurationMainTab_select_feed_dialog_title);
dialog.open();
Object[] selection = dialog.getResult();
if (selection != null
&& dialog.getReturnCode() == TreeSelectorDialog.OK
&& selection.length > 0
&& (selection[0] instanceof Operation)) {
selectedFeedFunction = (Operation) selection[0];
selectedFeedFunctionField.setText(selectedFeedFunction
.getName());
updateDialog();
}
}
});
group.pack();
}
@Override
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
}
@Override
public void initializeFrom(ILaunchConfiguration configuration) {
String uri;
try {
uri = configuration.getAttribute(
ModelExecutionLaunchConfig.ATTR_UML_RESOURCE, EMPTY_STR);
if (!uri.equals(EMPTY_STR)) {
resource = resourceSet.getResource(URI.createURI(uri), true);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResource member = workspace.getRoot().findMember(uri);
if (member instanceof IFile) {
selectedModelResource = (IFile) member;
selectedModelField.setText(member.getFullPath().toString());
}
initMatchers();
selectedClass = (Class) resource
.getEObject(configuration
.getAttribute(
ModelExecutionLaunchConfig.ATTR_EXECUTED_CLASS_URI,
EMPTY_STR));
selectedClassField.setText(selectedClass.getName());
selectedFeedFunction = (Operation) resource
.getEObject(configuration
.getAttribute(
ModelExecutionLaunchConfig.ATTR_EXECUTED_FEED_URI,
EMPTY_STR));
selectedFeedFunctionField.setText(selectedFeedFunction
.getName());
}
} catch (Exception e) {
IdePlugin.logError("Cannot initialize from configuration", e); //$NON-NLS-1$
}
}
@SuppressWarnings("restriction")
// Restriction warning is suppressed for
// org.eclipse.debug.internal.core.LaunchConfiguration
// because the Common tab uses its ATTR_MAPPED_RESOURCE_PATHS and
// ATTR_MAPPED_RESOURCE_TYPES attributes to find the
// project that owns the configuration.
@Override
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
if (selectedModelResource == null || selectedClass == null
|| selectedFeedFunction == null) {
return;
}
String projectName = selectedModelResource.getProject().getName();
configuration.setAttribute(
ModelExecutionLaunchConfig.ATTR_PROJECT_NAME, projectName);
configuration.setAttribute(
ModelExecutionLaunchConfig.ATTR_EXEC_CLASS_NAME,
selectedClass.getName());
configuration.setAttribute(
ModelExecutionLaunchConfig.ATTR_FEED_FUN_NAME,
selectedFeedFunction.getName());
String modelResourcePath = selectedModelResource.getFullPath()
.toString();
configuration
.setAttribute(ModelExecutionLaunchConfig.ATTR_UML_RESOURCE,
modelResourcePath);
configuration.setAttribute(
ModelExecutionLaunchConfig.ATTR_EXECUTED_CLASS_URI,
resource.getURIFragment(selectedClass));
configuration.setAttribute(
ModelExecutionLaunchConfig.ATTR_EXECUTED_FEED_URI,
resource.getURIFragment(selectedFeedFunction));
// adds the model resource as a mapped resource path
configuration
.setAttribute(
org.eclipse.debug.internal.core.LaunchConfiguration.ATTR_MAPPED_RESOURCE_PATHS,
Arrays.asList(modelResourcePath));
configuration
.setAttribute(
org.eclipse.debug.internal.core.LaunchConfiguration.ATTR_MAPPED_RESOURCE_TYPES,
Arrays.asList(Integer.toString(IResource.FILE)));
}
@Override
public String getName() {
return Messages.LaunchConfigurationMainTab_launch_config_main_tab_caption;
}
private void initMatchers() {
try {
IncQueryEngine engine = IncQueryEngine.on(resource);
classMatcher = ClsMatcher.on(engine);
methodMatcher = MethodMatcher.on(engine);
} catch (IncQueryException e) {
IdePlugin.logError("Problem while creating IncQuery engine", e); //$NON-NLS-1$
}
}
private Object[] getAllFunctions() {
List<Operation> functions = new LinkedList<>();
methodMatcher.getAllMatches(selectedClass, null, null).forEach(
m -> functions.add(m.getOperation()));
Object[] functionArray = functions
.toArray(new Object[functions.size()]);
return functionArray;
}
@Override
public boolean isValid(ILaunchConfiguration launchConfig) {
return super.isValid(launchConfig) && selectedModelResource != null
&& selectedClass != null && selectedFeedFunction != null;
}
}
|
package org.jkiss.dbeaver.ui.editors.content;
import org.jkiss.dbeaver.core.Log;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.*;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.*;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.texteditor.BasicTextEditorActionContributor;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.utils.ContentUtils;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
/**
* Content Editor contributor.
* Uses text editor contributor to fill status bar and menu for possible integrated text editors.
*/
public class ContentEditorContributor extends MultiPageEditorActionBarContributor
{
static final Log log = Log.getLog(ContentEditorContributor.class);
private final BasicTextEditorActionContributor textContributor;
private ContentEditor activeEditor;
//private IEditorPart activePage;
private final IAction saveAction = new FileExportAction();
private final IAction loadAction = new FileImportAction();
private final IAction infoAction = new InfoAction();
private final IAction applyAction = new ApplyAction();
private final IAction closeAction = new CloseAction();
private Combo encodingCombo;
private IPropertyListener dirtyListener = new IPropertyListener() {
@Override
public void propertyChanged(Object source, int propId)
{
if (propId == ContentEditor.PROP_DIRTY) {
if (activeEditor != null) {
applyAction.setEnabled(activeEditor.isDirty());
}
}
}
};
public ContentEditorContributor()
{
textContributor = new BasicTextEditorActionContributor();
}
ContentEditor getEditor()
{
return activeEditor;
}
@Override
public void init(IActionBars bars, IWorkbenchPage page)
{
super.init(bars, page);
textContributor.init(bars, page);
}
@Override
public void init(IActionBars bars)
{
super.init(bars);
textContributor.init(bars);
}
@Override
public void dispose()
{
textContributor.dispose();
if (activeEditor != null) {
activeEditor.removePropertyListener(dirtyListener);
}
super.dispose();
}
@Override
public void setActiveEditor(IEditorPart part)
{
super.setActiveEditor(part);
//textContributor.setActiveEditor(part);
if (activeEditor != null) {
activeEditor.removePropertyListener(dirtyListener);
}
this.activeEditor = (ContentEditor) part;
this.activeEditor.addPropertyListener(dirtyListener);
if (this.activeEditor != null) {
if (encodingCombo != null && !encodingCombo.isDisposed()) {
try {
String curCharset = this.activeEditor.getEditorInput().getFile().getCharset();
int charsetCount = encodingCombo.getItemCount();
for (int i = 0; i < charsetCount; i++) {
if (encodingCombo.getItem(i).equals(curCharset)) {
encodingCombo.select(i);
break;
}
}
} catch (CoreException e) {
log.error(e);
}
}
applyAction.setEnabled(activeEditor.isDirty());
loadAction.setEnabled(!activeEditor.getEditorInput().isReadOnly());
}
}
@Override
public void setActivePage(IEditorPart activeEditor)
{
//this.activePage = activeEditor;
this.textContributor.setActiveEditor(activeEditor);
}
@Override
public void contributeToMenu(IMenuManager manager)
{
super.contributeToMenu(manager);
textContributor.contributeToMenu(manager);
IMenuManager menu = new MenuManager("L&OB Editor");
manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu);
menu.add(loadAction);
menu.add(saveAction);
menu.add(new Separator());
menu.add(infoAction);
menu.add(new Separator());
menu.add(applyAction);
menu.add(closeAction);
}
@Override
public void contributeToStatusLine(IStatusLineManager statusLineManager)
{
super.contributeToStatusLine(statusLineManager);
textContributor.contributeToStatusLine(statusLineManager);
}
@Override
public void contributeToToolBar(IToolBarManager manager)
{
super.contributeToToolBar(manager);
textContributor.contributeToToolBar(manager);
// Execution
manager.add(loadAction);
manager.add(saveAction);
manager.add(new Separator());
manager.add(infoAction);
manager.add(new Separator());
manager.add(applyAction);
manager.add(closeAction);
manager.add(new Separator());
manager.add(new ControlContribution("Encoding")
{
@Override
protected Control createControl(Composite parent)
{
String curCharset = null;
if (getEditor() != null) {
try {
curCharset = getEditor().getEditorInput().getFile().getCharset();
} catch (CoreException e) {
log.error(e);
}
}
encodingCombo = UIUtils.createEncodingCombo(parent, curCharset);
encodingCombo.setToolTipText("Content Encoding");
encodingCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final ContentEditor contentEditor = getEditor();
if (contentEditor != null) {
final ContentEditorInput contentEditorInput = contentEditor.getEditorInput();
Combo combo = (Combo) e.widget;
final String charset = combo.getItem(combo.getSelectionIndex());
try {
contentEditor.getSite().getWorkbenchWindow().run(false, false, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
contentEditorInput.getFile().setCharset(charset, monitor);
} catch (CoreException e1) {
throw new InvocationTargetException(e1);
}
}
});
} catch (InvocationTargetException e1) {
log.error(e1.getTargetException());
} catch (InterruptedException e1) {
// do nothing
}
}
}
});
return encodingCombo;
}
@Override
public void dispose() {
encodingCombo = null;
super.dispose();
}
});
}
// Actions
public abstract class SimpleAction extends Action {
public SimpleAction(String id, String text, String toolTip, DBIcon icon)
{
super(text, icon.getImageDescriptor());
setId(id);
//setActionDefinitionId(id);
setToolTipText(toolTip);
}
@Override
public abstract void run();
}
private class FileExportAction extends SimpleAction
{
public FileExportAction()
{
super(IWorkbenchCommandConstants.FILE_EXPORT, "Export", "Save to File", DBIcon.EXPORT);
}
@Override
public void run()
{
Shell shell = getEditor().getSite().getShell();
final File saveFile = ContentUtils.selectFileForSave(shell);
if (saveFile == null) {
return;
}
try {
getEditor().getSite().getWorkbenchWindow().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException
{
try {
getEditor().getEditorInput().saveToExternalFile(saveFile, monitor);
}
catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
}
catch (InvocationTargetException e) {
UIUtils.showErrorDialog(
shell,
"Could not save content",
"Could not save content to file '" + saveFile.getAbsolutePath() + "'",
e.getTargetException());
}
catch (InterruptedException e) {
// do nothing
}
}
}
private class FileImportAction extends SimpleAction
{
public FileImportAction()
{
super(IWorkbenchCommandConstants.FILE_IMPORT, "Import", "Load from File", DBIcon.IMPORT);
}
@Override
public void run()
{
Shell shell = getEditor().getSite().getShell();
final File loadFile = ContentUtils.openFile(shell);
if (loadFile == null) {
return;
}
try {
getEditor().getSite().getWorkbenchWindow().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException
{
try {
getEditor().getEditorInput().loadFromExternalFile(loadFile, monitor);
}
catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
}
catch (InvocationTargetException e) {
UIUtils.showErrorDialog(
shell,
"Could not load content",
"Could not load content from file '" + loadFile.getAbsolutePath() + "'",
e.getTargetException());
}
catch (InterruptedException e) {
// do nothing
}
}
}
private class InfoAction extends SimpleAction
{
public InfoAction()
{
super("org.jkiss.dbeaver.lob.actions.info", "Info", "Show column information", DBIcon.TREE_INFO);
}
@Override
public void run()
{
getEditor().toggleInfoBar();
}
}
private class ApplyAction extends SimpleAction
{
public ApplyAction()
{
super("org.jkiss.dbeaver.lob.actions.apply", "Apply Changes", "Apply Changes", DBIcon.SAVE);
}
@Override
public void run()
{
try {
getEditor().getSite().getWorkbenchWindow().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException
{
getEditor().doSave(monitor);
}
});
}
catch (InvocationTargetException e) {
UIUtils.showErrorDialog(
getEditor().getSite().getShell(),
"Could not apply content changes",
"Could not apply content changes",
e.getTargetException());
}
catch (InterruptedException e) {
// do nothing
}
}
}
private class CloseAction extends SimpleAction
{
public CloseAction()
{
super("org.jkiss.dbeaver.lob.actions.close", "Close", "Reject changes", DBIcon.REJECT);
}
@Override
public void run()
{
ContentEditor contentEditor = getEditor();
if (contentEditor != null) {
contentEditor.closeValueEditor();
}
}
}
}
|
import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
@SuppressWarnings("serial")
public class AwesomeButton {
public final static String SOUNDFOLDER = "sounds/";
public final static String SOUNDFILE = SOUNDFOLDER+"sounds.txt";
private final static int PORT = 1990;
private DatagramSocket socket;
private boolean running = true;
private Set<InetAddress> blocked;
private boolean currentlyPlaying = true;
private Object mutex = new Object();
public Settings settings = Settings.loadSettings();
private AwesomeButtonGUI GUI;
public AwesomeButton() throws Exception {
this.GUI = new AwesomeButtonGUI(this);
if (!Lib.init(new FileInputStream(new File(SOUNDFILE))))
GUI.println("Failed to initialize sounds.");
this.blocked = Collections.synchronizedSet(new HashSet<InetAddress>());
(new FileRequestServer()).start();
start();
}
private void start() throws Exception {
byte[] in = new byte[1024];
GUI.println("Listening on "+InetAddress.getLocalHost()+":"+PORT);
DatagramPacket p = new DatagramPacket(in, in.length);
while (running && socket != null) {
try {
socket.receive(p);
} catch (Exception e) { continue; }
handleInput(p);
}
socket.close();
}
private void handleInput(DatagramPacket p) throws Exception {
String m = new String(p.getData(), 0, p.getLength());
if (m.startsWith("delay ")) { // Change delay
String[] parts = m.split(" ");
if (parts.length > 0) {
int delay = Integer.parseInt(parts[1]);
if (delay >= 0) {
GUI.println("Set blocking time to "+delay);
settings.setBlockDelay(delay);
}
}
} else if (m.startsWith("min ")) { // Change delay
String[] parts = m.split(" ");
if (parts.length > 0) {
int minVol = Integer.parseInt(parts[1]);
if (minVol >= 0 && minVol <= 255) {
GUI.println("Set min volume to "+minVol);
settings.setMinVol(minVol);
}
}
} else if (m.startsWith("max ")) { // Change delay
String[] parts = m.split(" ");
if (parts.length > 0) {
int maxVol = Integer.parseInt(parts[1]);
if (maxVol >= 0 && maxVol <= 255) {
GUI.println("Set max volume to "+maxVol);
settings.setMaxVol(maxVol);
}
}
} else if (m.equals("abort")) { // Stop the program
running = false;
} else {
GUI.println("Received \""+m+"\" from "+p.getAddress().toString());
if (Lib.SOUNDS.containsKey(m)) { // Play a sound
requestSound(p.getAddress(), Lib.SOUNDS.get(m));
}
}
}
private void requestSound(InetAddress ip, Sound sound) throws Exception {
if (!blocked.contains(ip) && playSound(sound)) {
block(ip);
}
}
private boolean playSound(Sound sound) throws Exception {
// Check if the audio file exists
File audioFile = getAudioFile(sound);
if (!audioFile.exists()) {
GUI.println("Sound not found: "+sound.filename);
return false;
}
// Prepare and play the sound
prepareSound();
AudioInputStream as = AudioSystem.getAudioInputStream(audioFile);
final Clip clip = AudioSystem.getClip();
clip.open(as);
clip.start();
// Set up listener for when song ends
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent myLineEvent) {
if (myLineEvent.getType() == LineEvent.Type.STOP) {
clip.close();
endSound();
}
}
});
return true;
}
public synchronized void block(InetAddress ip) {
this.blocked.add(ip);
(new Blocker(this, ip, settings.getBlockDelay())).start();
}
public synchronized void unblock(InetAddress ip) {
this.blocked.remove(ip);
}
private void prepareSound() {
synchronized (mutex) {
currentlyPlaying = true;
if (settings.hasSj() && currentlyPlaying) {
setSjVol(settings.getMinVol());
}
}
}
private void endSound() {
synchronized (mutex) {
currentlyPlaying = false;
if (settings.hasSj() && !currentlyPlaying) {
try {
setSjVol(settings.getMaxVol());
} catch (Exception e) { }
}
}
}
private void setSjVol(int vol) {
if (vol < 0 || vol > 255) return;
String command = String.format(
"--execute=\"player.volume=%d\"",
vol);
String[] args = { settings.getSjPath(), command };
try {
Runtime.getRuntime().exec(args);
} catch (Exception e) { }
}
private File getAudioFile(Sound sound) {
return new File(SOUNDFOLDER+sound.filename);
}
public void shutdown() {
running = false;
this.socket.close();
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
System.exit(0);
}
public void removeSj() {
settings.setSjPath(null);
}
public void setSjPath(String path) {
settings.setSjPath(path);
}
public static void main(String[] args) throws Exception {
new AwesomeButton();
}
}
|
package com.intellij.debugger.streams.trace.smart.handler;
import com.intellij.debugger.streams.trace.smart.handler.type.GenericType;
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall;
import com.intellij.debugger.streams.wrapper.StreamCallType;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PeekCall implements IntermediateStreamCall {
private final String myLambda;
private final GenericType myElementType;
public PeekCall(@NotNull String lambda, @NotNull GenericType elementType) {
myLambda = lambda;
myElementType = elementType;
}
@NotNull
@Override
public String getName() {
return "peek";
}
@NotNull
@Override
public String getArguments() {
return String.format("(%s)", myLambda);
}
@NotNull
@Override
public StreamCallType getType() {
return StreamCallType.INTERMEDIATE;
}
@NotNull
@Override
public GenericType getTypeAfter() {
return myElementType;
}
@NotNull
@Override
public GenericType getTypeBefore() {
return myElementType;
}
}
|
package uk.ac.ebi.quickgo.rest.search.request.converter;
import uk.ac.ebi.quickgo.rest.controller.FilterRequestConfig;
import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.config.FilterConfig;
import uk.ac.ebi.quickgo.rest.search.request.config.FilterConfigRetrieval;
import com.google.common.base.Preconditions;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;
@Component
@Import(FilterRequestConfig.class)
public class FilterConverterFactory {
private final FilterConfigRetrieval filterConfigRetrieval;
private final RestOperations restOperations;
@Autowired
public FilterConverterFactory(FilterConfigRetrieval globalFilterConfigRetrieval, RestOperations restOperations) {
Preconditions.checkArgument(globalFilterConfigRetrieval != null, "RequestConfigRetrieval cannot be null");
Preconditions.checkArgument(restOperations != null, "RestOperations cannot be null");
this.filterConfigRetrieval = globalFilterConfigRetrieval;
this.restOperations = restOperations;
}
public ConvertedFilter<QuickGOQuery> convert(FilterRequest request) {
Optional<FilterConfig> configOpt = filterConfigRetrieval.getBySignature(request.getSignature());
if (configOpt.isPresent()) {
FilterConfig filterConfig = configOpt.get();
switch (filterConfig.getExecution()) {
case REST_COMM:
return new RESTFilterConverter<QuickGOQuery>(filterConfig, restOperations).transform(request);
case SIMPLE:
return new SimpleFilterConverter(filterConfig).transform(request);
case JOIN:
return new JoinFilterConverter(filterConfig).transform(request);
default:
throw new IllegalStateException(
"RequestConfig execution has not been handled " +
"for signature (" + request.getSignature() + ") in " + filterConfigRetrieval);
}
} else {
throw new IllegalStateException(
"Could not find signature (" + request.getSignature() + ") in " + filterConfigRetrieval);
}
}
}
|
package de.dakror.vloxlands.layer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.utils.Array;
import de.dakror.vloxlands.Vloxlands;
import de.dakror.vloxlands.ai.AStar;
import de.dakror.vloxlands.ai.BFS;
import de.dakror.vloxlands.ai.node.AStarNode;
import de.dakror.vloxlands.ai.node.BFSNode;
import de.dakror.vloxlands.game.entity.Entity;
import de.dakror.vloxlands.game.entity.creature.Creature;
import de.dakror.vloxlands.game.entity.creature.Human;
import de.dakror.vloxlands.game.entity.structure.Structure;
import de.dakror.vloxlands.game.entity.structure.Warehouse;
import de.dakror.vloxlands.game.item.Item;
import de.dakror.vloxlands.game.voxel.Voxel;
import de.dakror.vloxlands.game.world.Chunk;
import de.dakror.vloxlands.game.world.Island;
import de.dakror.vloxlands.game.world.World;
import de.dakror.vloxlands.render.MeshingThread;
import de.dakror.vloxlands.util.Direction;
import de.dakror.vloxlands.util.event.SelectionListener;
import de.dakror.vloxlands.util.event.VoxelSelection;
import de.dakror.vloxlands.util.math.CustomizableFrustum;
/**
* @author Dakror
*/
public class GameLayer extends Layer
{
public static final long seed = (long) (Math.random() * Long.MAX_VALUE);
public static final float velocity = 10;
public static final float rotateSpeed = 0.2f;
public static final float pickRayMaxDistance = 150f;
public static GameLayer instance;
public static World world;
public static Camera camera;
public static ShapeRenderer shapeRenderer;
public Environment env;
public Array<SelectionListener> listeners = new Array<SelectionListener>();
public Environment minimapEnv;
public Camera minimapCamera;
public ModelBatch minimapBatch;
ModelBatch modelBatch;
CameraInputController controller;
boolean middleDown;
boolean doneLoading;
ModelInstance sky;
int tick;
int ticksForTravel;
int startTick;
Vector3 target = new Vector3();
Vector3 targetDirection = new Vector3();
Vector3 targetUp = new Vector3();
Island targetIsland;
// -- temp -- //
public final Vector3 tmp = new Vector3();
public final Vector3 tmp1 = new Vector3();
public final Vector3 tmp2 = new Vector3();
public final Vector3 tmp3 = new Vector3();
public final Vector3 tmp4 = new Vector3();
public final Vector3 tmp5 = new Vector3();
public final Vector3 tmp6 = new Vector3();
public final Vector3 tmp7 = new Vector3();
public final Vector3 tmp8 = new Vector3();
public final Matrix4 m4 = new Matrix4();
public final BoundingBox bb = new BoundingBox();
public final BoundingBox bb2 = new BoundingBox();
public final BoundingBox bb3 = new BoundingBox();
@Override
public void show()
{
modal = true;
instance = this;
Gdx.app.log("GameLayer.show", "Seed: " + seed + "");
MathUtils.random.setSeed(seed);
minimapBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs"));
minimapCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
minimapCamera.near = 0.1f;
minimapCamera.far = pickRayMaxDistance;
minimapEnv = new Environment();
minimapEnv.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f));
minimapEnv.add(new DirectionalLight().set(255, 255, 255, 0, -1, 1));
modelBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs"));
camera = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.near = 0.1f;
camera.far = pickRayMaxDistance;
controller = new CameraInputController(camera)
{
private final Vector3 tmpV1 = new Vector3();
@Override
public boolean zoom(float amount)
{
if (!alwaysScroll && activateKey != 0 && !activatePressed) return false;
if (camera.position.dst(target) > 10)
{
camera.translate(tmpV1.set(camera.direction).scl(amount));
if (scrollTarget) target.add(tmpV1);
if (autoUpdate) camera.update();
return true;
}
return false;
}
};
controller.translateUnits = 20;
controller.rotateLeftKey = -1;
controller.rotateRightKey = -1;
controller.forwardKey = -1;
controller.backwardKey = -1;
controller.translateButton = -1;
controller.rotateButton = Buttons.MIDDLE;
Vloxlands.currentGame.getMultiplexer().addProcessor(controller);
shapeRenderer = new ShapeRenderer();
new MeshingThread();
env = new Environment();
env.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f), new ColorAttribute(ColorAttribute.Fog, 0.5f, 0.8f, 0.85f, 1.f));
env.add(new DirectionalLight().set(255, 255, 255, 0, -1, 1));
int w = MathUtils.random(1, 5);
int d = MathUtils.random(1, 5);
world = new World(w, d);
Gdx.app.log("GameLayer.show", "World size: " + w + "x" + d);
}
public void doneLoading()
{
for (Item item : Item.getAll())
item.onLoaded();
Vector3 p = world.getIslands()[0].pos;
Human human = new Human(Island.SIZE / 2 - 5, Island.SIZE / 4 * 3 + p.y, Island.SIZE / 2);
human.setTool(Item.get("PICKAXE"));
world.addEntity(human);
world.getIslands()[0].addStructure(new Warehouse(Island.SIZE / 2 - 2, Island.SIZE / 4 * 3, Island.SIZE / 2 - 2), false, true);
world.getIslands()[0].calculateInitBalance();
focusIsland(world.getIslands()[0], true);
doneLoading = true;
// sky = new ModelInstance(assets.get("models/sky/sky.g3db", Model.class));
}
public void focusIsland(Island island, boolean initial)
{
Vector3 islandCenter = new Vector3(island.pos.x + Island.SIZE / 2, island.pos.y + Island.SIZE / 4 * 3, island.pos.z + Island.SIZE / 2);
if (!initial)
{
target.set(islandCenter).add(-Island.SIZE / 2, Island.SIZE / 2, -Island.SIZE / 2);
if (target.equals(camera.position))
{
camera.position.set(islandCenter).add(-Island.SIZE / 2, Island.SIZE / 2, -Island.SIZE / 2);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
controller.update();
camera.update();
return;
}
ticksForTravel = (int) camera.position.dst(target);
targetIsland = island;
Vector3 pos = camera.position.cpy();
Vector3 dir = camera.direction.cpy();
Vector3 up = camera.up.cpy();
camera.position.set(islandCenter).add(-Island.SIZE / 2, Island.SIZE / 2, -Island.SIZE / 2);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
targetDirection.set(camera.direction);
targetUp.set(camera.up);
camera.position.set(pos);
camera.direction.set(dir);
camera.up.set(up);
startTick = tick;
}
else
{
camera.position.set(islandCenter).add(-Island.SIZE / 2, Island.SIZE / 2, -Island.SIZE / 2);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
controller.update();
camera.update();
}
}
@Override
public void render(float delta)
{
if (!doneLoading) return;
Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 1);
controller.update();
world.update();
modelBatch.begin(camera);
world.render(modelBatch, env);
// modelBatch.render(sky, lights);
modelBatch.end();
if (Vloxlands.showPathDebug)
{
renderBFS();
renderAStar();
}
if (BFS.lastTarget != null)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + BFS.lastTarget.x, world.getIslands()[0].pos.y + BFS.lastTarget.y + 1.01f, world.getIslands()[0].pos.z + BFS.lastTarget.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.GREEN);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
}
public void renderAStar()
{
for (AStarNode node : AStar.openList)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.WHITE);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
for (AStarNode node : AStar.closedList)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
}
if (AStar.lastPath != null)
{
for (Vector3 v : AStar.lastPath)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + v.x, world.getIslands()[0].pos.y + v.y + 1.01f, world.getIslands()[0].pos.z + v.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.RED);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
}
}
}
public void renderBFS()
{
for (BFSNode node : BFS.queue)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
if (BFS.lastTarget != null)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + BFS.lastTarget.x, world.getIslands()[0].pos.y + BFS.lastTarget.y + 1.01f, world.getIslands()[0].pos.z + BFS.lastTarget.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.MAGENTA);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
}
@Override
public void tick(int tick)
{
this.tick = tick;
world.tick(tick);
if (targetIsland != null)
{
camera.position.interpolate(target, (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
camera.direction.interpolate(targetDirection, (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
camera.up.interpolate(new Vector3(0, 1, 0), (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
if (tick >= startTick + ticksForTravel || camera.position.dst(target) < 0.1f)
{
Vector3 islandCenter = new Vector3(targetIsland.pos.x + Island.SIZE / 2, targetIsland.pos.y + Island.SIZE / 4 * 3, targetIsland.pos.z + Island.SIZE / 2);
controller.target.set(islandCenter);
camera.position.set(islandCenter).add(-Island.SIZE / 2, Island.SIZE / 2, -Island.SIZE / 2);
camera.lookAt(islandCenter);
targetIsland = null;
startTick = 0;
}
controller.update();
camera.update();
}
}
@Override
public void resize(int width, int height)
{
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
minimapCamera.viewportWidth = width;
minimapCamera.viewportHeight = height;
minimapCamera.update();
}
public void pickRay(boolean hover, boolean lmb, int x, int y)
{
Ray ray = camera.getPickRay(x, y);
if (hover)
{
Entity hovered = null;
float distance = 0;
for (Entity entity : world.getEntities())
{
entity.hovered = false;
if (!entity.inFrustum) continue;
entity.getWorldBoundingBox(bb);
if (Intersector.intersectRayBounds(ray, bb, tmp))
{
float dst = ray.origin.dst(tmp);
if (hovered == null || dst < distance)
{
hovered = entity;
distance = dst;
}
}
}
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.hovered = false;
if (!structure.inFrustum) continue;
structure.getWorldBoundingBox(bb);
if (Intersector.intersectRayBounds(ray, bb, tmp))
{
float dst = ray.origin.dst(tmp);
if (hovered == null || dst < distance)
{
hovered = structure;
distance = dst;
}
}
}
}
if (hovered != null) hovered.hovered = true;
}
else
{
Entity selectedEntity = null;
Structure selectedStructure = null;
Island selectedIsland = null;
Chunk selectedChunk = null;
Vector3 selectedVoxel = new Vector3();
float distance = 0;
for (Entity entity : world.getEntities())
{
entity.wasSelected = entity.selected;
if (lmb) entity.selected = false;
float dst = ray.origin.dst(entity.posCache);
if (entity.inFrustum && entity.hovered && (distance == 0 || dst < distance) && dst < pickRayMaxDistance)
{
distance = dst;
selectedEntity = entity;
break;
}
}
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.wasSelected = structure.selected;
if (lmb) structure.selected = false;
float dst = ray.origin.dst(structure.posCache);
if (structure.inFrustum && structure.hovered && (distance == 0 || dst < distance) && dst < pickRayMaxDistance)
{
distance = dst;
selectedStructure = structure;
}
}
for (Chunk c : i.getChunks())
{
if (c.inFrustum && !c.isEmpty())
{
tmp1.set(i.pos.x + c.pos.x, i.pos.y + c.pos.y, i.pos.z + c.pos.z);
tmp2.set(tmp1.cpy().add(Chunk.SIZE, Chunk.SIZE, Chunk.SIZE));
bb.set(tmp1, tmp2);
c.selectedVoxel.set(-1, 0, 0);
if (Intersector.intersectRayBounds(ray, bb, null) && c.pickVoxel(ray, tmp5, tmp6))
{
float dst = ray.origin.dst(tmp5);
if ((distance == 0 || dst < distance) && dst <= pickRayMaxDistance)
{
distance = dst;
selectedVoxel.set(tmp6);
selectedChunk = c;
selectedIsland = i;
}
}
}
}
}
if (selectedChunk != null)
{
// -- determine selectedVoxelFace -- //
Direction dir = null;
float distanc = 0;
Vector3 is2 = new Vector3();
byte air = Voxel.get("AIR").getId();
for (Direction d : Direction.values())
{
tmp7.set(selectedIsland.pos.x + selectedChunk.pos.x + selectedVoxel.x + d.dir.x, selectedIsland.pos.y + selectedChunk.pos.y + selectedVoxel.y + d.dir.y, selectedIsland.pos.z + selectedChunk.pos.z + selectedVoxel.z + d.dir.z);
tmp8.set(tmp7.cpy().add(1, 1, 1));
bb3.set(tmp7, tmp8);
if (selectedIsland.get(selectedChunk.pos.x + selectedVoxel.x + d.dir.x, selectedChunk.pos.y + selectedVoxel.y + d.dir.y, selectedChunk.pos.z + selectedVoxel.z + d.dir.z) != air) continue;
if (Intersector.intersectRayBounds(ray, bb3, is2))
{
float dist = ray.origin.dst(is2);
if (dir == null || dist < distanc)
{
distanc = dist;
dir = d;
}
}
}
selectedChunk.selectedVoxel.set(selectedVoxel);
for (SelectionListener sl : listeners)
sl.onVoxelSelection(new VoxelSelection(selectedIsland, Voxel.getForId(selectedChunk.get((int) selectedVoxel.x, (int) selectedVoxel.y, (int) selectedVoxel.z)), selectedVoxel.cpy().add(selectedChunk.pos), dir), lmb);
}
else if (selectedStructure != null)
{
selectedStructure.selected = true;
for (SelectionListener sl : listeners)
sl.onStructureSelection(selectedStructure, lmb);
}
else if (selectedEntity != null && selectedEntity instanceof Creature)
{
selectedEntity.selected = true;
for (SelectionListener sl : listeners)
sl.onCreatureSelection((Creature) selectedEntity, lmb);
}
}
}
public void selectionBox(Rectangle rectangle)
{
CustomizableFrustum frustum = new CustomizableFrustum(rectangle);
camera.update();
frustum.update(camera.invProjectionView);
Vector3 origin = camera.unproject(new Vector3(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
boolean anyEntitySelected = false;
for (Entity entity : world.getEntities())
{
entity.wasSelected = entity.selected;
entity.selected = false;
entity.getWorldBoundingBox(bb);
float dst = origin.dst(entity.posCache);
if (entity.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance)
{
entity.selected = true;
anyEntitySelected = true;
break;
}
}
if (!anyEntitySelected)
{
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.wasSelected = structure.selected;
structure.selected = false;
structure.getWorldBoundingBox(bb);
float dst = origin.dst(structure.posCache);
if (structure.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance) structure.selected = true;
}
}
}
}
@Override
public boolean mouseMoved(int screenX, int screenY)
{
pickRay(true, false, screenX, screenY);
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
if (button == Buttons.MIDDLE)
{
middleDown = true;
Gdx.input.setCursorCatched(true);
}
return false;
}
@Override
public boolean tap(float x, float y, int count, int button)
{
if (button != Buttons.MIDDLE) pickRay(false, button == Buttons.LEFT, (int) x, (int) y);
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
if (button == Buttons.MIDDLE)
{
middleDown = false;
Gdx.input.setCursorCatched(false);
}
return false;
}
public void addListener(SelectionListener value)
{
listeners.insert(0, value);
}
public boolean removeListener(SelectionListener value)
{
return listeners.removeValue(value, true);
}
}
|
package com.arun.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.arun.parallel.ParallelProcessor;
import com.arun.parallel.Signature;
import com.arun.student.SchoolService;
import com.arun.student.SchoolService_;
import com.arun.student.Student;
import com.arun.student.StudentService;
import com.arun.student.StudentService_;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Client {
public static final Logger LOGGER = LoggerFactory.getLogger(ParallelProcessor.class);
public static void serialExecution() {
long startTime = System.nanoTime();
StudentService service = new StudentService();
SchoolService schoolService = new SchoolService();
Map<String, Integer> bookSeries = new HashMap<>();
bookSeries.put("A Song of Ice and Fire", 7);
bookSeries.put("Wheel of Time", 14);
bookSeries.put("Harry Potter", 7);
Student student = service.findStudent("[email protected]", 11, false);
List<Integer> marks = service.getStudentMarks(1L);
List<Student> students = service.getStudentsByFirstNames(Arrays.asList("John","Alice"));
String randomName = service.getRandomLastName();
Long studentId = service.findStudentIdByName("Kate", "Williams");
service.printMapValues(bookSeries);
List<String> schoolNames = schoolService.getSchoolNames();
LOGGER.info(student.toString());
LOGGER.info(marks.toString());
LOGGER.info(students.toString());
LOGGER.info(randomName);
LOGGER.info(studentId.toString());
LOGGER.info(schoolNames.toString());
long executionTime = (System.nanoTime() - startTime) / 1000000;
LOGGER.info(String.format("Total elapsed time is [{}]", executionTime));
}
public static <T> void parallelExecution() {
long startTime = System.nanoTime();
StudentService studentService = new StudentService();
SchoolService schoolService = new SchoolService();
Map<Object, List<Signature>> executionMap = new HashMap<>();
List<Signature> studentServiceSignatures = new ArrayList<>();
List<Signature> schoolServiceSignatures = new ArrayList<>();
Map<String, Integer> bookSeries = new HashMap<>();
bookSeries.put("A Song of Ice and Fire", 7);
bookSeries.put("Wheel of Time", 14);
bookSeries.put("Middle Earth Legendarium", 5);
studentServiceSignatures.add(Signature.build(StudentService_.getStudentMarks(1L)));
studentServiceSignatures.add(Signature.build(StudentService_.getStudentsByFirstNames(Arrays.asList("John","Alice"))));
studentServiceSignatures.add(Signature.build(StudentService_.getRandomLastName()));
studentServiceSignatures.add(Signature.build(StudentService_.findStudentIdByName("Kate", "Williams")));
studentServiceSignatures.add(Signature.build(StudentService_.findStudent("[email protected]", 14, false)));
studentServiceSignatures.add(Signature.build(StudentService_.printMapValues(bookSeries)));
schoolServiceSignatures.add(Signature.build(SchoolService_.getSchoolNames()));
executionMap.put(studentService, studentServiceSignatures);
executionMap.put(schoolService, schoolServiceSignatures);
List<T> result = ParallelProcessor.genericParallelExecutor(executionMap);
result.forEach(s -> System.out.println(s));
long executionTime = (System.nanoTime() - startTime) / 1000000;
LOGGER.info("Total elapsed time is [{}]", executionTime);
}
public static void main(String[] args) {
serialExecution();
parallelExecution();
}
}
|
package de.dakror.vloxlands.layer;
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.utils.Array;
import de.dakror.vloxlands.Config;
import de.dakror.vloxlands.Vloxlands;
import de.dakror.vloxlands.ai.AStar;
import de.dakror.vloxlands.ai.BFS;
import de.dakror.vloxlands.ai.node.AStarNode;
import de.dakror.vloxlands.ai.node.BFSNode;
import de.dakror.vloxlands.game.entity.Entity;
import de.dakror.vloxlands.game.entity.creature.Creature;
import de.dakror.vloxlands.game.entity.creature.Human;
import de.dakror.vloxlands.game.entity.structure.Structure;
import de.dakror.vloxlands.game.entity.structure.Towncenter;
import de.dakror.vloxlands.game.item.Item;
import de.dakror.vloxlands.game.item.ItemStack;
import de.dakror.vloxlands.game.voxel.Voxel;
import de.dakror.vloxlands.game.world.Chunk;
import de.dakror.vloxlands.game.world.Island;
import de.dakror.vloxlands.game.world.World;
import de.dakror.vloxlands.render.MeshingThread;
import de.dakror.vloxlands.util.Direction;
import de.dakror.vloxlands.util.event.SelectionListener;
import de.dakror.vloxlands.util.event.VoxelSelection;
import de.dakror.vloxlands.util.math.CustomizableFrustum;
/**
* @author Dakror
*/
@SuppressWarnings("deprecation")
public class GameLayer extends Layer
{
public static long seed = (long) (Math.random() * Long.MAX_VALUE);
public static final float velocity = 10;
public static final float rotateSpeed = 0.2f;
public static final float pickRayMaxDistance = 150f;
public static GameLayer instance;
public static World world;
public static Camera camera;
public static ShapeRenderer shapeRenderer;
public Environment env;
public Array<SelectionListener> listeners = new Array<SelectionListener>();
public Environment minimapEnv;
public Camera minimapCamera;
public ModelBatch minimapBatch;
public String[] activeAction;
public Island activeIsland;
public DirectionalShadowLight shadowLight;
public CameraInputController controller;
ModelBatch modelBatch;
ModelBatch shadowBatch;
boolean middleDown;
boolean doneLoading;
ModelInstance sky;
int tick;
int ticksForTravel;
int startTick;
public Vector3 selectedVoxel = new Vector3();
Vector3 controllerTarget = new Vector3();
Vector3 cameraPos = new Vector3();
Vector3 target = new Vector3();
Vector3 targetDirection = new Vector3();
Vector3 targetUp = new Vector3();
Vector2 mouseDown = new Vector2();
// -- temp -- //
public final Vector3 tmp = new Vector3();
public final Vector3 tmp1 = new Vector3();
public final Vector3 tmp2 = new Vector3();
public final Vector3 tmp3 = new Vector3();
public final Vector3 tmp4 = new Vector3();
public final Vector3 tmp5 = new Vector3();
public final Vector3 tmp6 = new Vector3();
public final Vector3 tmp7 = new Vector3();
public final Vector3 tmp8 = new Vector3();
public final Matrix4 m4 = new Matrix4();
public final BoundingBox bb = new BoundingBox();
public final BoundingBox bb2 = new BoundingBox();
public final BoundingBox bb3 = new BoundingBox();
@Override
public void show()
{
modal = true;
instance = this;
Gdx.app.log("GameLayer.show", "Seed: " + seed + "");
MathUtils.random = new Random(seed);
modelBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs"));
minimapBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs"));
camera = new PerspectiveCamera(Config.pref.getInteger("fov"), Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.near = 0.1f;
camera.far = pickRayMaxDistance;
controller = new CameraInputController(camera)
{
private final Vector3 tmpV1 = new Vector3();
private final Vector3 tmpV2 = new Vector3();
@Override
protected boolean process(float deltaX, float deltaY, int button)
{
if (button == rotateButton && Gdx.input.isKeyPressed(Keys.CONTROL_LEFT)) return false;
return super.process(deltaX, deltaY, button);
}
@Override
public boolean zoom(float amount)
{
if (!alwaysScroll && activateKey != 0 && !activatePressed) return false;
tmpV1.set(camera.direction).scl(amount);
tmpV2.set(camera.position).add(tmpV1);
if (tmpV2.dst(target) > 5)
{
camera.translate(tmpV1);
if (scrollTarget) target.add(tmpV1);
if (autoUpdate) camera.update();
return true;
}
return false;
}
};
controller.translateUnits = 20;
controller.rotateLeftKey = -1;
controller.rotateRightKey = -1;
controller.forwardKey = -1;
controller.backwardKey = -1;
controller.translateButton = -1;
controller.rotateButton = Buttons.MIDDLE;
Vloxlands.currentGame.getMultiplexer().addProcessor(controller);
minimapCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
minimapCamera.near = 0.1f;
minimapCamera.far = pickRayMaxDistance;
minimapEnv = new Environment();
minimapEnv.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f));
minimapEnv.add(new DirectionalLight().set(1f, 1f, 1f, -0.5f, -0.5f, -0.5f));
minimapEnv.add(new DirectionalLight().set(0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f));
shadowBatch = new ModelBatch(new DepthShaderProvider());
shapeRenderer = new ShapeRenderer();
new MeshingThread();
env = new Environment();
env.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f), new ColorAttribute(ColorAttribute.Fog, 0.5f, 0.8f, 0.85f, 1.f));
env.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -0.5f, -0.5f, -0.5f));
int AA = 4;
env.add((shadowLight = new DirectionalShadowLight(Gdx.graphics.getWidth() * AA, Gdx.graphics.getHeight() * AA, 128, 128, camera.near, camera.far)).set(0.6f, 0.6f, 0.6f, 0.5f, -0.5f, 0.5f));
env.shadowMap = shadowLight;
int w = MathUtils.random(1, 5);
int d = MathUtils.random(1, 5);
world = new World(1, 1); // TODO: multi island support
// world = new World(w, d);
Gdx.app.log("GameLayer.show", "World size: " + w + "x" + d);
}
public void doneLoading()
{
for (Item item : Item.getAll())
item.onLoaded();
Vector3 p = world.getIslands()[0].pos;
Human human = new Human(Island.SIZE / 2 - 5, Island.SIZE / 4 * 3 + p.y, Island.SIZE / 2);
world.addEntity(human);
Towncenter tc = new Towncenter(Island.SIZE / 2 - 2, Island.SIZE / 4 * 3, Island.SIZE / 2 - 2);
tc.getInventory().add(new ItemStack(Item.get("AXE"), 5));
tc.getInventory().add(new ItemStack(Item.get("PICKAXE"), 5));
world.getIslands()[0].addStructure(tc, false, true);
world.getIslands()[0].calculateInitBalance();
focusIsland(world.getIslands()[0], true);
doneLoading = true;
}
public void focusIsland(Island island, boolean initial)
{
Vector3 islandCenter = new Vector3(island.pos.x + Island.SIZE / 2, island.pos.y + Island.SIZE / 4 * 3, island.pos.z + Island.SIZE / 2);
activeIsland = island;
selectedVoxel.set(-1, 0, 0);
if (!initial)
{
target.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3);
if (target.equals(camera.position))
{
camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
controller.update();
camera.update();
return;
}
ticksForTravel = (int) camera.position.dst(target);
Vector3 pos = camera.position.cpy();
Vector3 dir = camera.direction.cpy();
Vector3 up = camera.up.cpy();
camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
targetDirection.set(camera.direction);
targetUp.set(camera.up);
camera.position.set(pos);
camera.direction.set(dir);
camera.up.set(up);
startTick = tick;
}
else
{
camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3);
controller.target.set(islandCenter);
camera.lookAt(islandCenter);
controller.update();
camera.update();
}
}
@Override
public void render(float delta)
{
if (!doneLoading) return;
controller.update();
world.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
shadowLight.begin(controller.target, camera.direction);
shadowBatch.begin(shadowLight.getCamera());
world.render(shadowBatch, null);
shadowBatch.end();
shadowLight.end();
Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 1);
modelBatch.begin(camera);
world.render(modelBatch, env);
// modelBatch.render(sky, lights);
modelBatch.end();
if (Vloxlands.showPathDebug)
{
renderBFS();
renderAStar();
}
if (BFS.lastTarget != null && Vloxlands.showPathDebug)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + BFS.lastTarget.x, world.getIslands()[0].pos.y + BFS.lastTarget.y + 1.01f, world.getIslands()[0].pos.z + BFS.lastTarget.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.GREEN);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
}
public void renderAStar()
{
for (AStarNode node : AStar.openList)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.WHITE);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
for (AStarNode node : AStar.closedList)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
}
if (AStar.lastPath != null)
{
for (Vector3 v : AStar.lastPath)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + v.x, world.getIslands()[0].pos.y + v.y + 1.01f, world.getIslands()[0].pos.z + v.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.RED);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
}
}
}
public void renderBFS()
{
for (BFSNode node : BFS.queue)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + node.x, world.getIslands()[0].pos.y + node.y + 1.01f, world.getIslands()[0].pos.z + node.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
if (BFS.lastTarget != null)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(2);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.identity();
shapeRenderer.translate(world.getIslands()[0].pos.x + BFS.lastTarget.x, world.getIslands()[0].pos.y + BFS.lastTarget.y + 1.01f, world.getIslands()[0].pos.z + BFS.lastTarget.z);
shapeRenderer.rotate(1, 0, 0, 90);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.MAGENTA);
shapeRenderer.x(0.5f, 0.5f, 0.49f);
shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
}
@Override
public void tick(int tick)
{
this.tick = tick;
world.tick(tick);
if (activeIsland != null && startTick > 0)
{
camera.position.interpolate(target, (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
camera.direction.interpolate(targetDirection, (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
camera.up.interpolate(new Vector3(0, 1, 0), (tick - startTick) / (float) ticksForTravel, Interpolation.linear);
if (tick >= startTick + ticksForTravel || camera.position.dst(target) < 0.1f)
{
Vector3 islandCenter = new Vector3(activeIsland.pos.x + Island.SIZE / 2, activeIsland.pos.y + Island.SIZE / 4 * 3, activeIsland.pos.z + Island.SIZE / 2);
controller.target.set(islandCenter);
camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3);
camera.lookAt(islandCenter);
startTick = 0;
}
controller.update();
camera.update();
}
}
@Override
public void resize(int width, int height)
{
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
minimapCamera.viewportWidth = width;
minimapCamera.viewportHeight = height;
minimapCamera.update();
}
public void pickRay(boolean hover, boolean lmb, int x, int y)
{
Ray ray = camera.getPickRay(x, y);
if (hover)
{
Entity hovered = null;
float distance = 0;
for (Entity entity : world.getEntities())
{
entity.hovered = false;
if (!entity.inFrustum) continue;
entity.getWorldBoundingBox(bb);
if (Intersector.intersectRayBounds(ray, bb, tmp))
{
float dst = ray.origin.dst(tmp);
if (hovered == null || dst < distance)
{
hovered = entity;
distance = dst;
}
}
}
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.hovered = false;
if (!structure.inFrustum) continue;
structure.getWorldBoundingBox(bb);
if (Intersector.intersectRayBounds(ray, bb, tmp))
{
float dst = ray.origin.dst(tmp);
if (hovered == null || dst < distance)
{
hovered = structure;
distance = dst;
}
}
}
}
if (hovered != null) hovered.hovered = true;
}
else
{
Entity selectedEntity = null;
Structure selectedStructure = null;
Island selectedIsland = null;
Chunk selectedChunk = null;
Vector3 selectedVoxel = new Vector3();
float distance = 0;
for (Entity entity : world.getEntities())
{
entity.wasSelected = entity.selected;
if (lmb) entity.selected = false;
float dst = ray.origin.dst(entity.posCache);
if (entity.inFrustum && entity.hovered && (distance == 0 || dst < distance) && dst < pickRayMaxDistance)
{
distance = dst;
selectedEntity = entity;
break;
}
}
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.wasSelected = structure.selected;
if (lmb) structure.selected = false;
float dst = ray.origin.dst(structure.posCache);
if (structure.inFrustum && structure.hovered && (distance == 0 || dst < distance) && dst < pickRayMaxDistance)
{
distance = dst;
selectedStructure = structure;
}
}
for (Chunk c : i.getChunks())
{
if (c.inFrustum && !c.isEmpty())
{
tmp1.set(i.pos.x + c.pos.x, i.pos.y + c.pos.y, i.pos.z + c.pos.z);
tmp2.set(tmp1.cpy().add(Chunk.SIZE, Chunk.SIZE, Chunk.SIZE));
bb.set(tmp1, tmp2);
if (Intersector.intersectRayBounds(ray, bb, null) && c.pickVoxel(ray, tmp5, tmp6))
{
float dst = ray.origin.dst(tmp5);
if ((distance == 0 || dst < distance) && dst <= pickRayMaxDistance)
{
distance = dst;
selectedVoxel.set(tmp6);
selectedChunk = c;
selectedIsland = i;
}
}
}
}
}
if (selectedChunk != null)
{
// -- determine selectedVoxelFace -- //
Direction dir = null;
float distanc = 0;
Vector3 is2 = new Vector3();
byte air = Voxel.get("AIR").getId();
for (Direction d : Direction.values())
{
tmp7.set(selectedIsland.pos.x + selectedChunk.pos.x + selectedVoxel.x + d.dir.x, selectedIsland.pos.y + selectedChunk.pos.y + selectedVoxel.y + d.dir.y, selectedIsland.pos.z + selectedChunk.pos.z + selectedVoxel.z + d.dir.z);
tmp8.set(tmp7.cpy().add(1, 1, 1));
bb3.set(tmp7, tmp8);
if (selectedIsland.get(selectedChunk.pos.x + selectedVoxel.x + d.dir.x, selectedChunk.pos.y + selectedVoxel.y + d.dir.y, selectedChunk.pos.z + selectedVoxel.z + d.dir.z) != air) continue;
if (Intersector.intersectRayBounds(ray, bb3, is2))
{
float dist = ray.origin.dst(is2);
if (dir == null || dist < distanc)
{
distanc = dist;
dir = d;
}
}
}
this.selectedVoxel.set(selectedVoxel).add(selectedChunk.pos);
for (SelectionListener sl : listeners)
sl.onVoxelSelection(new VoxelSelection(selectedIsland, Voxel.getForId(selectedChunk.get((int) selectedVoxel.x, (int) selectedVoxel.y, (int) selectedVoxel.z)), selectedVoxel.cpy().add(selectedChunk.pos), dir), lmb, activeAction);
}
else if (selectedStructure != null)
{
selectedVoxel.set(-1, 0, 0);
selectedStructure.selected = true;
for (SelectionListener sl : listeners)
sl.onStructureSelection(selectedStructure, lmb, activeAction);
}
else if (selectedEntity != null && selectedEntity instanceof Creature)
{
selectedVoxel.set(-1, 0, 0);
selectedEntity.selected = true;
for (SelectionListener sl : listeners)
sl.onCreatureSelection((Creature) selectedEntity, lmb, activeAction);
}
}
}
public void selectionBox(Rectangle rectangle)
{
CustomizableFrustum frustum = new CustomizableFrustum(rectangle);
camera.update();
frustum.update(camera.invProjectionView);
Vector3 origin = camera.unproject(new Vector3(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
boolean anyEntitySelected = false;
boolean dispatched = false;
for (Entity entity : world.getEntities())
{
entity.wasSelected = entity.selected;
entity.selected = false;
entity.getWorldBoundingBox(bb);
float dst = origin.dst(entity.posCache);
if (entity.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance)
{
entity.selected = true;
anyEntitySelected = true;
if (!dispatched && entity instanceof Creature)
{
for (SelectionListener sl : listeners)
sl.onCreatureSelection((Creature) entity, true, activeAction);
dispatched = true;
}
}
}
if (!anyEntitySelected)
{
for (Island i : world.getIslands())
{
if (i == null) continue;
for (Structure structure : i.getStructures())
{
structure.wasSelected = structure.selected;
structure.selected = false;
structure.getWorldBoundingBox(bb);
float dst = origin.dst(structure.posCache);
if (structure.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance) structure.selected = true;
}
}
}
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer)
{
if (middleDown && Gdx.input.isKeyPressed(Keys.CONTROL_LEFT))
{
float f = 0.1f;
controller.target.y = controllerTarget.y + (screenY - mouseDown.y) * f;
camera.position.y = cameraPos.y + (screenY - mouseDown.y) * f;
camera.update();
controller.update();
}
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY)
{
pickRay(true, false, screenX, screenY);
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
mouseDown.set(screenX, screenY);
if (button == Buttons.MIDDLE)
{
controllerTarget.set(controller.target);
cameraPos.set(camera.position);
middleDown = true;
Gdx.input.setCursorCatched(true);
}
return false;
}
@Override
public boolean tap(float x, float y, int count, int button)
{
if (button != Buttons.MIDDLE) pickRay(false, button == Buttons.LEFT, (int) x, (int) y);
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
if (button == Buttons.MIDDLE)
{
middleDown = false;
Gdx.input.setCursorCatched(false);
}
return false;
}
public void addListener(SelectionListener value)
{
listeners.insert(0, value);
}
public boolean removeListener(SelectionListener value)
{
return listeners.removeValue(value, true);
}
}
|
package org.ow2.proactive_grid_cloud_portal.scheduler.client;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.ow2.proactive_grid_cloud_portal.common.client.Images;
import org.ow2.proactive_grid_cloud_portal.common.client.model.LoginModel;
import org.ow2.proactive_grid_cloud_portal.scheduler.server.SubmitEditServlet;
import org.ow2.proactive_grid_cloud_portal.scheduler.shared.SchedulerConfig;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptException;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.NamedNodeMap;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.util.DateUtil;
import com.smartgwt.client.widgets.DateChooser;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.BlurbItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.TimeItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.Layout;
import com.smartgwt.client.widgets.layout.VLayout;
/**
* Popup Window for job submission
*
* @author mschnoor
*/
public class SubmitWindow {
private static final String CATALOG_SELECT_BUCKET = "Select a Bucket";
private static final String CATALOG_SELECT_WF = "Select a Workflow";
private static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZZ";
private static final String URL_SUBMIT_XML = GWT.getModuleBaseURL() + "submitedit";
private static final String URL_UPLOAD_FILE = GWT.getModuleBaseURL() + "uploader";
private static final String METHOD_INSTRUCTION = "Select a method";
private static final String METHOD_FROM_FILE = "import from file";
private static final String METHOD_FROM_CATALOG = "import from Catalog";
private static final String SESSION_ID_PARAMETER_NAME = "sessionId";
private static final String ERROR_MESSAGE_REGEX = "\"errorMessage\":\"(.*)\",\"stackTrace\"";
private static final int width = 600;
private static final int height = 520;
private Window window;
private SchedulerController controller;
private HandlerRegistration todayClickHR = null;
private HandlerRegistration changedHourHR = null;
private HandlerRegistration changedMinuteHR = null;
private HandlerRegistration gridClickHR = null;
private VLayout rootPage;
// window
private VLayout selectWfLayout;
private ListBox wfMethodsListBox;
// workflow
private VLayout fromFilePanel;
// from disk
private FileUpload fileUpload;
private VerticalPanel selectWorkflowButtonsPanel; // Panel that holds the
// strategic items to
// get a wf
private Button sendFromFileButton;
// servlet from disk
private HorizontalPanel fromCatalogPanel;
// from catalog
private ListBox bucketsListBox;
private ListBox workflowsListBox;
// list
private Button sendFromCatalogButton;
// servlet from catalog
private VLayout varsLayout;
private VerticalPanel hiddenPane;
// to submit along with the job
private Hidden validate = new Hidden("validate", "true");
private FormItem[] fields;
// submit along with the job
private Hidden[] _fields;
// submit along with the job
private Hidden startAtParameter;
// along with the job
private Hidden planParameter;
// along with the job
private FormPanel variablesActualForm;
private VLayout startAtLayout;
private VerticalPanel startAtRadioGroupPanel;
private RadioButton startAccordingPlanningRadioButton;
private RadioButton startNowRadioButton;
// radio button
private RadioButton startAtRadioButton;
// radio button
private DateChooser dateChooser;
private HLayout submitCancelButtons;
// buttons
private IButton submitButton;
private IButton checkButton;
private VLayout messagePanel;
// uploading
private Label waitLabel;
private Label errorLabel;
private String CATALOG_URL = null;
private Map<String, JobVariable> variables;
private String job;
private Boolean isExecCalendarValueNull = true; // capture if EXECUTION_CALENDAR value is null
/**
* Default constructor
*
* @param controller
*/
public SubmitWindow(SchedulerController controller) {
this.controller = controller;
this.build();
}
public void show() {
this.window.show();
}
/**
* Destroy the window, you may null the reference after this as it will not
* be usable again
*/
public void destroy() {
this.window.destroy();
}
/**
* Builds the catalog URL. If none is configured in the settings file, sets
* the URL to the bundled Catalog
*
*/
private void buildCatalogUrl() {
String catalogUrlFromConfig = SchedulerConfig.get().getCatalogUrl();
String defaultCatalogUrl = GWT.getHostPageBaseURL().replace("/scheduler/", "/") + "catalog";
if (catalogUrlFromConfig == null || catalogUrlFromConfig.isEmpty()) {
CATALOG_URL = defaultCatalogUrl;
} else {
CATALOG_URL = catalogUrlFromConfig;
}
}
private void initRootPage() {
rootPage = new VLayout();
rootPage.setMargin(5);
rootPage.setWidth100();
rootPage.setHeight100();
}
private void initSelectWfPart() {
selectWfLayout = new VLayout();
selectWfLayout.setGroupTitle("1. Select workflow");
selectWfLayout.setIsGroup(true);
selectWfLayout.setHeight("130px");
// This panel changes depending on the selected method of getting a
// workflow
selectWorkflowButtonsPanel = new VerticalPanel();
selectWorkflowButtonsPanel.setSpacing(5);
selectWorkflowButtonsPanel.setHeight("50px");
final VerticalPanel getWfMethodsPanel = new VerticalPanel();
getWfMethodsPanel.setSpacing(10);
getWfMethodsPanel.setHeight("30px");
wfMethodsListBox = new ListBox();
wfMethodsListBox.addItem(METHOD_INSTRUCTION);
wfMethodsListBox.addItem(METHOD_FROM_FILE);
wfMethodsListBox.addItem(METHOD_FROM_CATALOG);
getWfMethodsPanel.add(wfMethodsListBox);
wfMethodsListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String selectedMethod = wfMethodsListBox.getSelectedValue();
if (METHOD_FROM_FILE.compareTo(selectedMethod) == 0) {
clearPanel();
initSelectWorkflowFromFilePanel();
selectWorkflowButtonsPanel.add(fromFilePanel);
selectWorkflowButtonsPanel.add(sendFromFileButton);
initFooter();
} else if (METHOD_FROM_CATALOG.compareTo(selectedMethod) == 0) {
clearPanel();
initSelectWorkflowFromCatalogPanel();
selectWorkflowButtonsPanel.add(fromCatalogPanel);
selectWorkflowButtonsPanel.add(sendFromCatalogButton);
initFooter();
} else {
// default case: METHOD_INSTRUCTION
varsLayout.removeMembers(varsLayout.getMembers());
selectWorkflowButtonsPanel.clear();
initFooter();
}
}
private void clearPanel() {
varsLayout.removeMembers(varsLayout.getMembers());
selectWorkflowButtonsPanel.clear();
initSelectWorkflowFromFilePanel();
}
private void initFooter() {
rootPage.removeMember(startAtLayout);
rootPage.removeMember(messagePanel);
rootPage.removeMember(submitCancelButtons);
initSubmitAtPart();
rootPage.addMember(messagePanel);
rootPage.addMember(submitCancelButtons);
startAccordingPlanningRadioButton.setValue(false);
startNowRadioButton.setValue(false);
startAtRadioButton.setValue(false);
setEnabledStartAtPart(false);
}
});
// init both panels (select from disk or from catalog)
initSelectWorkflowFromFilePanel();
initSelectWorkflowFromCatalogPanel();
selectWfLayout.addMember(getWfMethodsPanel);
selectWfLayout.addMember(selectWorkflowButtonsPanel);
rootPage.addMember(selectWfLayout);
}
private void fillVarsPart(String jobDescriptor) {
DynamicForm variablesVisualForm = initVariablesVisualForm();
Layout hiddenVarsLayout = initVariablesActualForm();
initVarsLayout();
Widget worfklowMetaDataWidget = prepareWorlflowInformation(jobDescriptor);
varsLayout.addMember(worfklowMetaDataWidget);
varsLayout.addMember(variablesVisualForm);
varsLayout.addMember(hiddenVarsLayout);
rootPage.addMember(varsLayout);
rootPage.reflow();
}
private Widget prepareWorlflowInformation(String jobDescriptor) {
Document dom = XMLParser.parse(jobDescriptor);
String documentation = null;
String icon = null;
String bucketName = null;
Boolean existBucketName = false;
Boolean existDocumentation = false;
Boolean existIcon = false;
NodeList genericInfo = dom.getElementsByTagName("genericInformation");
// check if the job has genericInformation or not
if (genericInfo != null && genericInfo.getLength() > 0) {
// get the first item
Node root = genericInfo.item(0);
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeName().equals("info") && node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") &&
attribute.getNodeValue().equalsIgnoreCase("bucketName")) {
existBucketName = true;
}
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") &&
attribute.getNodeValue().equalsIgnoreCase("documentation")) {
existDocumentation = true;
}
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") &&
attribute.getNodeValue().equalsIgnoreCase("workflow.icon")) {
existIcon = true;
}
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("value") &&
existBucketName) {
bucketName = attribute.getNodeValue();
existBucketName = false;
}
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("value") &&
existDocumentation) {
documentation = attribute.getNodeValue();
existDocumentation = false;
}
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("value") &&
existIcon) {
icon = attribute.getNodeValue();
existIcon = false;
}
}
}
}
}
Widget worfklowMetaDataWidget = new HTML("<center> <img src=" + icon +
" height=40px width=40px> <br> <b>Documentation :</b> <a href=" +
documentation + " target=_blank>" + documentation +
" </a><br> <b> Bucket name :</b> " + bucketName + " </center>");
return worfklowMetaDataWidget;
}
private DynamicForm initVariablesVisualForm() {
// presentation form
DynamicForm variablesVisualForm;
variablesVisualForm = new DynamicForm();
variablesVisualForm.setNumCols(3);
variablesVisualForm.setColWidths("25%", "50%", "25%");
fields = new FormItem[variables.size() * 2];
int i = 0;
for (Entry<String, JobVariable> var : variables.entrySet()) {
TextItem variableItem = createVariableItem(var);
fields[i++] = variableItem;
String model = var.getValue().getModel();
BlurbItem modelItem = createModelItem(model);
fields[i++] = modelItem;
}
variablesVisualForm.setFields(fields);
return variablesVisualForm;
}
private Layout initVariablesActualForm() {
// actual form used to POST
variablesActualForm = new FormPanel();
variablesActualForm.setMethod(FormPanel.METHOD_POST);
variablesActualForm.setAction(URL_SUBMIT_XML);
hiddenPane = new VerticalPanel();
_fields = new Hidden[variables.size()];
int i = 0;
for (Entry<String, JobVariable> var : variables.entrySet()) {
_fields[i] = new Hidden("var_" + var.getKey());
hiddenPane.add(_fields[i]);
i++;
}
hiddenPane.add(new Hidden("job", job));
hiddenPane.add(new Hidden(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId()));
hiddenPane.add(validate);
variablesActualForm.setWidget(hiddenPane);
Layout fpanelWra = new Layout();
fpanelWra.addMember(variablesActualForm);
return fpanelWra;
}
private void initVarsLayout() {
varsLayout = new VLayout();
varsLayout.setIsGroup(true);
varsLayout.setGroupTitle("2. Fill workflow variables");
varsLayout.setHeight100();
;
varsLayout.setHeight("100px");
varsLayout.setMaxHeight(100);
varsLayout.setPadding(5);
varsLayout.setOverflow(Overflow.AUTO);
}
private BlurbItem createModelItem(String model) {
BlurbItem modelLabel = null;
if (model != null) {
modelLabel = new BlurbItem();
modelLabel.setDefaultValue(model);
} else {
modelLabel = new BlurbItem();
}
modelLabel.setStartRow(false);
modelLabel.setEndRow(true);
return modelLabel;
}
private TextItem createVariableItem(Entry<String, JobVariable> var) {
TextItem t = new TextItem(var.getKey(), var.getKey());
t.setValue(var.getValue().getValue());
t.setWidth("100%");
t.setStartRow(true);
t.setEndRow(false);
return t;
}
private void initVarsPart() {
initVarsLayout();
rootPage.addMember(varsLayout);
rootPage.reflow();
}
private void setStartAccordingPlanningRadioButtonState(String job) {
if (job != null && isExecutionCalendarGIDefined(job)) {
startAccordingPlanningRadioButton.setVisible(true);
startAccordingPlanningRadioButton.setValue(true);
} else {
startAccordingPlanningRadioButton.setVisible(false);
}
}
private void initSubmitAtPart() {
startAtLayout = new VLayout();
startAtLayout.setIsGroup(true);
startAtLayout.setGroupTitle("3. Scheduled time");
startAtParameter = new Hidden("START_AT");
planParameter = new Hidden("PLAN");
startAccordingPlanningRadioButton = new RadioButton("startAtRadioGroup",
"Planned according to embedded Execution Calendar defintion");
startNowRadioButton = new RadioButton("startAtRadioGroup", "As soon as possible");
startAtRadioButton = new RadioButton("startAtRadioGroup", "At");
startAccordingPlanningRadioButton.setVisible(true);
startNowRadioButton.setValue(true);
startAtRadioButton.setValue(false);
startAccordingPlanningRadioButton.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
@Override
public void onClick(com.google.gwt.event.dom.client.ClickEvent event) {
if (isExecCalendarValueNull) {
displayErrorMessage("EXECUTION_CALENDAR value is empty.");
}
startAtLayout.removeMember(dateChooser);
}
});
startNowRadioButton.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
@Override
public void onClick(com.google.gwt.event.dom.client.ClickEvent event) {
startAtRadioButton.setText("At");
startAtLayout.removeMember(dateChooser);
}
});
startAtRadioButton.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
@Override
public void onClick(com.google.gwt.event.dom.client.ClickEvent event) {
startAtLayout.addMember(dateChooser);
DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat(ISO_8601_FORMAT);
String iso8601DateStr = dateTimeFormat.format(dateChooser.getData());
startAtParameter.setValue(iso8601DateStr);
updateScheduledTimeForToday();
resetAllHandlers();
}
});
dateChooser = new DateChooser();
dateChooser.setShowTimeItem(true);
dateChooser.setUse24HourTime(true);
dateChooser.setShowTodayButton(true);
dateChooser.setShowApplyButton(false);
dateChooser.setWidth(width / 2);
dateChooser.setLayoutAlign(Alignment.CENTER);
dateChooser.setMargin(10);
startAtRadioGroupPanel = new VerticalPanel();
startAtRadioGroupPanel.setSpacing(10);
startAtRadioGroupPanel.add(startAccordingPlanningRadioButton);
startAtRadioGroupPanel.add(startNowRadioButton);
startAtRadioGroupPanel.add(startAtRadioButton);
startAtRadioGroupPanel.setHeight("30px");
startAtLayout.addMember(startAtRadioGroupPanel);
FlowPanel planJobPanel = new FlowPanel();
InlineLabel firstPart = new InlineLabel("Or use the ");
firstPart.getElement().getStyle().setProperty("margin-left", "15px");
planJobPanel.add(firstPart);
Anchor jobPlannerPortalLink = new Anchor("Job Planner Portal",
"/automation-dashboard/#/portal/job-planner-calendar-def-workflows",
"_blank");
planJobPanel.add(jobPlannerPortalLink);
planJobPanel.add(new InlineLabel(" to schedule the workflow execution periodically"));
planJobPanel.setHeight("20px");
startAtLayout.addMember(planJobPanel);
rootPage.addMember(startAtLayout);
}
private void updateScheduledTimeAt() {
TimeItem dateTimeItem = dateChooser.getTimeItem();
int selectedHour = Integer.parseInt(dateTimeItem.getHourItem().getValueAsString());
int selectedMinute = Integer.parseInt(dateTimeItem.getMinuteItem().getValueAsString());
Date newDateTime = DateUtil.createLogicalTime(selectedHour, selectedMinute, 0, 0);
Date updatedDate = DateUtil.combineLogicalDateAndTime(dateChooser.getData(), newDateTime);
dateChooser.setData(updatedDate);
startAtRadioButton.setText("At " + updatedDate.toString());
}
private void updateScheduledTimeForToday() {
Date newDate = new Date();
dateChooser.setData(newDate);
dateChooser.getTimeItem().setHours(Integer.parseInt(DateTimeFormat.getFormat("HH").format(newDate)));
dateChooser.getTimeItem().setMinutes(Integer.parseInt(DateTimeFormat.getFormat("mm").format(newDate)));
startAtRadioButton.setText("At " + newDate.toString());
}
private void initMessagesPart() {
messagePanel = new VLayout();
messagePanel.setIsGroup(true);
messagePanel.setGroupTitle("Messages");
rootPage.addMember(messagePanel);
}
private void initButtonsPart() {
submitCancelButtons = new HLayout();
submitCancelButtons.setMargin(10);
submitCancelButtons.setMembersMargin(5);
submitCancelButtons.setHeight(30);
submitCancelButtons.setWidth100();
submitCancelButtons.setAlign(Alignment.RIGHT);
submitButton = new IButton("Submit");
submitButton.setIcon(Images.instance.ok_16().getSafeUri().asString());
submitButton.setShowDisabledIcon(false);
submitButton.setTooltip("A workflow must be selected first");
submitButton.addClickHandler(clickHandlerForSubmitButton());
checkButton = new IButton("Check");
checkButton.setIcon(Images.instance.ok_16().getSafeUri().asString());
checkButton.setShowDisabledIcon(false);
checkButton.setTooltip("Validate current workflow and variables");
checkButton.addClickHandler(clickHandlerForCheckButton());
final IButton cancelButton = new IButton("Cancel");
cancelButton.setShowDisabledIcon(false);
cancelButton.setIcon(Images.instance.cancel_16().getSafeUri().asString());
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SubmitWindow.this.window.hide();
SubmitWindow.this.destroy();
}
});
submitCancelButtons.setMembers(cancelButton, checkButton, submitButton);
rootPage.addMember(submitCancelButtons);
}
private void clearMessagePanel() {
if (messagePanel.contains(waitLabel)) {
messagePanel.removeMember(waitLabel);
}
if (messagePanel.contains(errorLabel)) {
messagePanel.removeMember(errorLabel);
}
}
private void displayLoadingMessage() {
clearMessagePanel();
waitLabel = new Label("Please wait...");
waitLabel.setHeight(30);
waitLabel.setIcon("loading.gif");
waitLabel.setWidth100();
waitLabel.setMargin(10);
waitLabel.setAlign(Alignment.CENTER);
messagePanel.addMember(waitLabel);
rootPage.reflow();
}
private void displayInfoMessage(String message) {
clearMessagePanel();
errorLabel = new Label(message);
errorLabel.setHeight(30);
errorLabel.setWidth100();
errorLabel.setMargin(10);
errorLabel.setAlign(Alignment.CENTER);
errorLabel.setStyleName("infoMessage");
messagePanel.addMember(errorLabel);
rootPage.reflow();
}
private void displayErrorMessage(String message) {
clearMessagePanel();
errorLabel = new Label(message);
errorLabel.setHeight(30);
errorLabel.setWidth100();
errorLabel.setMargin(10);
errorLabel.setAlign(Alignment.CENTER);
errorLabel.setStyleName("errorMessage");
messagePanel.addMember(errorLabel);
rootPage.reflow();
}
private void initSelectWorkflowFromFilePanel() {
fromFilePanel = new VLayout();
fromFilePanel.setHeight("30px");
fileUpload = new FileUpload();
fileUpload.setName("job");
VerticalPanel formContent = new VerticalPanel();
formContent.setHeight("30px");
Hidden hiddenField = new Hidden();
hiddenField.setName(SESSION_ID_PARAMETER_NAME);
hiddenField.setValue(LoginModel.getInstance().getSessionId());
formContent.add(hiddenField);
formContent.add(fileUpload);
final FormPanel importFromFileformPanel = new FormPanel();
importFromFileformPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
importFromFileformPanel.setMethod(FormPanel.METHOD_POST);
importFromFileformPanel.setAction(URL_UPLOAD_FILE);
importFromFileformPanel.add(formContent);
importFromFileformPanel.addSubmitCompleteHandler(fileUploadCompleteHandler());
importFromFileformPanel.setHeight("30px");
fromFilePanel.addMember(importFromFileformPanel);
sendFromFileButton = new Button("Upload file");
sendFromFileButton.addClickHandler(clickHandlerForUploadFromFileButton(importFromFileformPanel));
}
private void initSelectWorkflowFromCatalogPanel() {
fromCatalogPanel = new HorizontalPanel();
fromCatalogPanel.setHeight("30px");
fromCatalogPanel.setWidth("100%");
fromCatalogPanel.setSpacing(2);
bucketsListBox = new ListBox();
workflowsListBox = new ListBox();
bucketsListBox.setEnabled(false);
bucketsListBox.addItem(CATALOG_SELECT_BUCKET);
workflowsListBox.setEnabled(false);
workflowsListBox.addItem(CATALOG_SELECT_WF);
bucketsListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String selectedBucket = bucketsListBox.getSelectedValue();
if (!CATALOG_SELECT_BUCKET.equals(selectedBucket)) {
String workflowUrl = CATALOG_URL + "/buckets/" + selectedBucket + "/resources?kind=workflow";
RequestBuilder req = new RequestBuilder(RequestBuilder.GET, workflowUrl);
req.setHeader(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId());
req.setCallback(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONArray workflows = JSONParser.parseStrict(response.getText()).isArray();
int workflowsSize = workflows.size();
workflowsListBox.setEnabled(false);
workflowsListBox.clear();
workflowsListBox.addItem(CATALOG_SELECT_WF);
for (int i = 0; i < workflowsSize; i++) {
JSONObject workflow = workflows.get(i).isObject();
String workflowName = workflow.get("name").isString().stringValue();
workflowsListBox.addItem(workflowName);
}
workflowsListBox.setEnabled(true);
}
@Override
public void onError(Request request, Throwable exception) {
GWT.log("OOPS:" + request.toString());
}
});
try {
req.send();
} catch (RequestException e) {
GWT.log("Error occured when fetching workflows from Catalog");
e.printStackTrace();
}
}
}
});
RequestBuilder req = new RequestBuilder(RequestBuilder.GET, CATALOG_URL + "/buckets?kind=workflow");
req.setHeader(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId());
req.setCallback(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONArray buckets = JSONParser.parseStrict(response.getText()).isArray();
int bucketSize = buckets.size();
for (int i = 0; i < bucketSize; i++) {
JSONObject bucket = buckets.get(i).isObject();
String bucketName = bucket.get("name").isString().stringValue();
bucketsListBox.addItem(bucketName);
}
bucketsListBox.setEnabled(true);
}
@Override
public void onError(Request request, Throwable exception) {
GWT.log("Error occured when fetching buckets from Catalog");
}
});
try {
req.send();
} catch (RequestException e) {
GWT.log("Error occured when fetching buckets from Catalog");
e.printStackTrace();
}
fromCatalogPanel.add(bucketsListBox);
fromCatalogPanel.add(workflowsListBox);
bucketsListBox.setWidth("130px");
workflowsListBox.setWidth("230px");
final VerticalPanel formContent = new VerticalPanel();
formContent.setHeight("30px");
formContent.add(new Hidden(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId()));
final FormPanel importFromCatalogformPanel = new FormPanel();
importFromCatalogformPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
importFromCatalogformPanel.setMethod(FormPanel.METHOD_POST);
importFromCatalogformPanel.setAction(URL_UPLOAD_FILE);
importFromCatalogformPanel.add(formContent);
importFromCatalogformPanel.addSubmitCompleteHandler(fileUploadCompleteHandler());
importFromCatalogformPanel.setHeight("30px");
fromCatalogPanel.add(importFromCatalogformPanel);
sendFromCatalogButton = new Button("Import workflow");
sendFromCatalogButton.addClickHandler(clickHandlerForUploadFromCatalogButton(formContent,
importFromCatalogformPanel));
}
private ClickHandler clickHandlerForCheckButton() {
return new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for (int i = 0; i < _fields.length; i++) {
String val = "";
if (fields[2 * i].getValue() != null) {
val = fields[2 * i].getValue().toString();
}
_fields[i].setValue(val);
}
if (startAtRadioButton.getValue()) {
DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat(ISO_8601_FORMAT);
String iso8601DateStr = dateTimeFormat.format(dateChooser.getData());
startAtParameter.setValue(iso8601DateStr);
hiddenPane.add(startAtParameter);
}
enableValidation(true);
variablesActualForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String result = event.getResults();
if (result == null) {
GWT.log("Unexpected empty result");
displayErrorMessage("Unexpected empty result");
return;
}
if (result.startsWith(SubmitEditServlet.ERROR)) {
displayErrorMessage(result.substring(SubmitEditServlet.ERROR.length()));
return;
}
try {
JSONValue json = JSONParser.parseStrict(result);
JSONObject obj = json.isObject();
if (obj != null) {
if (obj.containsKey("valid")) {
if (((JSONBoolean) obj.get("valid")).booleanValue()) {
if (obj.containsKey("updatedVariables")) {
updateVariables(obj.get("updatedVariables"));
redrawVariables(job);
}
GWT.log("Job validated");
displayInfoMessage("Job is valid");
} else if (obj.containsKey("errorMessage")) {
String errorMessage = obj.get("errorMessage").toString();
if (errorMessage.contains("JobValidationException")) {
errorMessage = errorMessage.substring(errorMessage.indexOf(":") + 2);
}
displayErrorMessage(errorMessage);
}
}
}
} catch (Throwable t) {
// JSON parsing error workaround to force extract error message
MatchResult errorMessageMatcher = RegExp.compile(ERROR_MESSAGE_REGEX).exec(result);
if (errorMessageMatcher != null) {
GWT.log(errorMessageMatcher.getGroup(1));
displayErrorMessage(errorMessageMatcher.getGroup(1));
} else {
GWT.log("JSON parse ERROR");
displayErrorMessage("JSON parse ERROR");
}
}
}
});
variablesActualForm.submit();
displayLoadingMessage();
}
};
}
private void updateVariables(JSONValue updatedVariablesJsonValue) {
JSONObject obj = updatedVariablesJsonValue.isObject();
if (obj != null) {
for (String varName : obj.keySet()) {
JobVariable variable = variables.get(varName);
if (variable != null) {
JSONValue variableJsonValue = obj.get(varName);
JSONString variableJsonString = variableJsonValue.isString();
if (variableJsonString != null) {
variable.setValue(variableJsonString.stringValue());
}
}
}
}
}
private ClickHandler clickHandlerForSubmitButton() {
return new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for (int i = 0; i < _fields.length; i++) {
String val = "";
if (fields[2 * i].getValue() != null) {
val = fields[2 * i].getValue().toString();
}
_fields[i].setValue(val);
}
enableValidation(false);
if (startAtRadioButton.getValue()) {
DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat(ISO_8601_FORMAT);
String iso8601DateStr = dateTimeFormat.format(dateChooser.getData());
startAtParameter.setValue(iso8601DateStr);
hiddenPane.add(startAtParameter);
} else if (startAccordingPlanningRadioButton.getValue() && !isExecCalendarValueNull) {
planParameter.setValue("true");
hiddenPane.add(planParameter);
}
variablesActualForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
if (event.getResults() == null || !event.getResults().startsWith(SubmitEditServlet.ERROR)) {
GWT.log("Job submitted to the scheduler");
SubmitWindow.this.window.removeMember(rootPage);
SubmitWindow.this.window.hide();
SubmitWindow.this.destroy();
} else {
String jsonError = event.getResults().substring(SubmitEditServlet.ERROR.length());
JSONValue json = controller.parseJSON(jsonError);
JSONObject obj = json.isObject();
if (obj != null && obj.containsKey("errorMessage")) {
String errorMessage = obj.get("errorMessage").toString();
if (errorMessage.contains("JobValidationException")) {
errorMessage = errorMessage.substring(errorMessage.indexOf(":") + 2);
}
displayErrorMessage(errorMessage);
} else {
displayErrorMessage(jsonError);
}
}
}
});
variablesActualForm.submit();
displayLoadingMessage();
}
};
}
private com.google.gwt.event.dom.client.ClickHandler clickHandlerForUploadFromFileButton(final FormPanel toSubmit) {
return new com.google.gwt.event.dom.client.ClickHandler() {
@Override
public void onClick(com.google.gwt.event.dom.client.ClickEvent event) {
String fileName = fileUpload.getFilename();
if ("".compareTo(fileName) != 0) {
displayLoadingMessage();
toSubmit.submit();
} else {
displayErrorMessage("Nothing to upload. Please select a file.");
}
}
};
}
private com.google.gwt.event.dom.client.ClickHandler clickHandlerForUploadFromCatalogButton(
final VerticalPanel formContent, final FormPanel importFromCatalogformPanel) {
return new com.google.gwt.event.dom.client.ClickHandler() {
@Override
public void onClick(com.google.gwt.event.dom.client.ClickEvent event) {
// filter only valid items
if (bucketsListBox.getSelectedIndex() > 0 && workflowsListBox.getSelectedIndex() > 0) {
String selectedWorkflowLabel = workflowsListBox.getSelectedValue();
String selectedBucketName = bucketsListBox.getSelectedValue();
formContent.add(new Hidden("bucketName", selectedBucketName));
formContent.add(new Hidden("workflowName", selectedWorkflowLabel));
displayLoadingMessage();
importFromCatalogformPanel.submit();
}
}
};
}
private SubmitCompleteHandler fileUploadCompleteHandler() {
return new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String fn = fileUpload.getFilename();
// chrome workaround
final String fileName = fn.replace("C:\\fakepath\\", "");
String res = event.getResults();
try {
JSONValue js = JSONParser.parseStrict(res);
JSONObject obj = js.isObject();
if (obj.get("jobEdit") != null && obj.get("jobEdit").isString() != null) {
String val = obj.get("jobEdit").isString().stringValue();
job = new String(org.ow2.proactive_grid_cloud_portal.common.shared.Base64Utils.fromBase64(val));
// if the job has an EXECUTION_CALENDAR Generic Information defined, the startAccordingToPlanningRadioButton becomes visible, and invisible otherwise
setStartAccordingPlanningRadioButtonState(job);
variables = readVars(job);
} else {
GWT.log("JSON parse ERROR");
displayErrorMessage(res);
//Force disable check&submit buttons to prevent confusion if a valid job was uploaded first but not submitted
setEnabledStartAtPart(false);
startAccordingPlanningRadioButton.setVisible(false);
return;
}
} catch (JSONException t) {
GWT.log("JSON parse ERROR");
displayErrorMessage(res);
//Force disable check&submit buttons to prevent confusion if a valid job was uploaded first but not submitted
setEnabledStartAtPart(false);
startAccordingPlanningRadioButton.setVisible(false);
return;
}
redrawVariables(job);
}
};
}
private void redrawVariables(String job) {
removeBottomMembers();
setEnabledStartAtPart(true);
fillVarsPart(job);
rootPage.addMember(startAtLayout);
clearMessagePanel();
rootPage.addMember(messagePanel);
rootPage.addMember(submitCancelButtons);
rootPage.reflow();
}
private void removeBottomMembers() {
rootPage.removeMember(varsLayout);
rootPage.removeMember(startAtLayout);
rootPage.removeMember(messagePanel);
rootPage.removeMember(submitCancelButtons);
}
private void enableValidation(boolean enable) {
validate.setValue(Boolean.toString(enable));
}
private void resetAllHandlers() {
if (changedMinuteHR != null) {
changedMinuteHR.removeHandler();
}
changedMinuteHR = dateChooser.getTimeItem().getMinuteItem().addChangedHandler(newCHForMinuteField());
if (changedHourHR != null) {
changedHourHR.removeHandler();
}
changedHourHR = dateChooser.getTimeItem().getHourItem().addChangedHandler(newCHForHourField());
if (todayClickHR != null) {
todayClickHR.removeHandler();
}
todayClickHR = dateChooser.getTodayButton().addClickHandler(newCHForTodayButton());
if (gridClickHR != null) {
gridClickHR.removeHandler();
}
gridClickHR = dateChooser.addClickHandler(newCHDateGrid());
}
private ClickHandler newCHForTodayButton() {
return new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
updateScheduledTimeForToday();
resetAllHandlers();
}
};
}
private ChangedHandler newCHForMinuteField() {
return new ChangedHandler() {
@Override
public void onChanged(ChangedEvent changedEvent) {
updateScheduledTimeAt();
resetAllHandlers();
}
};
}
private ChangedHandler newCHForHourField() {
return new ChangedHandler() {
@Override
public void onChanged(ChangedEvent changedEvent) {
updateScheduledTimeAt();
resetAllHandlers();
}
};
}
private ClickHandler newCHDateGrid() {
return new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
startAtRadioButton.setText("At " + dateChooser.getData().toString());
resetAllHandlers();
}
};
}
private void setEnabledStartAtPart(boolean state) {
setStartAccordingPlanningRadioButtonState(job);
startNowRadioButton.setEnabled(state);
startAtRadioButton.setEnabled(state);
submitButton.setDisabled(!state);
checkButton.setDisabled(!state);
if (!state) {
submitButton.setTooltip("A workflow must be selected first");
} else {
submitButton.setTooltip("");
}
}
private void build() {
buildCatalogUrl();
initRootPage();
initSelectWfPart();
initVarsPart();
initSubmitAtPart();
initMessagesPart();
initButtonsPart();
setEnabledStartAtPart(false);
this.window = new Window();
this.window.setTitle("Submit a new job");
this.window.setShowMinimizeButton(false);
this.window.setIsModal(true);
this.window.setShowModalMask(true);
this.window.addItem(rootPage);
this.window.setWidth(this.width);
this.window.setHeight(this.height);
this.window.centerInPage();
this.window.setCanDragResize(true);
}
/**
* @param jobDescriptor an XML job descriptor as a string
* @return the name/value of all <variables><variable name value> elements
*/
private Map<String, JobVariable> readVars(String jobDescriptor) {
/*
* this will fail if someday the XML schema gets another <variable> tag
* elsewhere
*/
Document dom = XMLParser.parse(jobDescriptor);
NodeList variables = dom.getElementsByTagName("variable");
Map<String, JobVariable> ret = new LinkedHashMap<>();
if (variables.getLength() > 0) {
for (int i = 0; i < variables.getLength(); i++) {
Node variableNode = variables.item(i);
if (variableNode != null && !isTaskVariableElement(variableNode)) {
NamedNodeMap attrs = variableNode.getAttributes();
try {
if (attrs != null && variableNode.hasAttributes()) {
String name = null;
String value = null;
String model = null;
for (int j = 0; j < attrs.getLength(); j++) {
Node attr = attrs.item(j);
if (attr.getNodeName().equals("name")) {
name = attr.getNodeValue();
}
if (attr.getNodeName().equals("value")) {
value = attr.getNodeValue();
}
if (attr.getNodeName().equals("model")) {
model = attr.getNodeValue();
}
}
if (name != null && value != null) {
if (!name.matches("[A-Za-z0-9._]+")) {
// this won't necessarily be a problem at
// job submission,
// but it definitely will be here in the
// client; don't bother
continue;
}
ret.put(name, new JobVariable(name, value, model));
}
}
} catch (JavaScriptException t) {
// Node.hasAttributes() throws if there are no
// attributes... (GWT 2.1.0)
}
}
}
}
return ret;
}
private Boolean isExecutionCalendarGIDefined(String jobDescriptor) {
Document dom = XMLParser.parse(jobDescriptor);
Boolean exists = false;
Boolean executionCalendarDefined = false;
NodeList genericInfo = dom.getElementsByTagName("genericInformation");
// check if the job has genericInformation or not
if (genericInfo != null && genericInfo.getLength() > 0) {
// get the first item
Node root = genericInfo.item(0);
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeName().equals("info") && node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") &&
attribute.getNodeValue().equalsIgnoreCase("execution_calendars")) {
exists = true;
}
if (isAttributeExecCalendarValueDefined(attribute, "value") && exists) {
executionCalendarDefined = true;
if (!attribute.getNodeValue().isEmpty())
isExecCalendarValueNull = false;
}
}
}
}
}
return executionCalendarDefined;
}
private Boolean isAttributeExecCalendarValueDefined(Node attribute, String name) {
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals(name)) {
return true;
} else
return false;
}
private boolean isTaskVariableElement(Node node) {
if (node.getParentNode() != null && node.getParentNode().getParentNode() != null) {
Node grandparentNode = node.getParentNode().getParentNode();
if (grandparentNode.getNodeName().equals("task")) {
return true;
}
}
return false;
}
class JobVariable {
private String name;
private String value;
private String model;
public JobVariable(String name, String value, String model) {
this.name = name;
this.value = value;
this.model = model;
}
public String getName() {
return name;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public String getModel() {
return model;
}
}
}
|
package hudson.matrix;
import hudson.Util;
import hudson.matrix.listeners.MatrixBuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Executor;
import hudson.model.Fingerprint;
import hudson.model.Hudson;
import hudson.model.JobProperty;
import hudson.model.Node;
import hudson.model.ParametersAction;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.model.Cause.UpstreamCause;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
import hudson.tasks.Publisher;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
/**
* Build of {@link MatrixProject}.
*
* @author Kohsuke Kawaguchi
*/
public class MatrixBuild extends AbstractBuild<MatrixProject,MatrixBuild> {
private AxisList axes;
public MatrixBuild(MatrixProject job) throws IOException {
super(job);
}
public MatrixBuild(MatrixProject job, Calendar timestamp) {
super(job, timestamp);
}
public MatrixBuild(MatrixProject project, File buildDir) throws IOException {
super(project, buildDir);
}
public Object readResolve() {
// MatrixBuild.axes added in 1.285; default to parent axes for old data
if (axes==null)
axes = getParent().getAxes();
return this;
}
/**
* Used by view to render a ball for {@link MatrixRun}.
*/
public final class RunPtr {
public final Combination combination;
private RunPtr(Combination c) { this.combination=c; }
public MatrixRun getRun() {
return MatrixBuild.this.getRun(combination);
}
public String getShortUrl() {
return Util.rawEncode(combination.toString());
}
public String getTooltip() {
MatrixRun r = getRun();
if(r!=null) return r.getIconColor().getDescription();
Queue.Item item = Hudson.getInstance().getQueue().getItem(getParent().getItem(combination));
if(item!=null)
return item.getWhy();
return null; // fall back
}
}
public Layouter<RunPtr> getLayouter() {
// axes can be null if build page is access right when build starts
return axes == null ? null : new Layouter<RunPtr>(axes) {
protected RunPtr getT(Combination c) {
return new RunPtr(c);
}
};
}
/**
* If greater than zero, the {@link MatrixBuild} originates from the given build number.
*/
public int linkedNumber = 0;
/**
* Sets the linked number
* @param linkedNumber A given number indicating the origin
*/
public void setLinkedNumber( int linkedNumber ) {
this.linkedNumber = linkedNumber;
}
/**
* Gets the {@link MatrixRun} in this build that corresponds
* to the given combination.
*/
public MatrixRun getRun(Combination c) {
MatrixConfiguration config = getParent().getItem(c);
if(config==null) return null;
return getRunForConfiguration( config, getNumber() );
}
/**
* Returns all {@link MatrixRun}s for this {@link MatrixBuild}.
*/
@Exported
public List<MatrixRun> getRuns() {
List<MatrixRun> r = new ArrayList<MatrixRun>();
for(MatrixConfiguration c : getParent().getItems()) {
MatrixRun b = getRunForConfiguration( c, getNumber() );
if (b != null) r.add(b);
}
return r;
}
private MatrixRun getRunForConfiguration( MatrixConfiguration c, int number )
{
MatrixRun b = c.getNearestOldBuild(getNumber());
if(b.getNumber()!=getNumber() && linkedNumber > 0) {
b = c.getNearestOldBuild(linkedNumber);
}
return b;
}
/**
* Returns all {@link MatrixRun}s for this {@link MatrixBuild}.
* <p>
* Unlike {@link #getExactRuns()}, this method excludes those runs
* that didn't run and got inherited.
*/
public List<MatrixRun> getExactRuns() {
List<MatrixRun> r = new ArrayList<MatrixRun>();
for(MatrixConfiguration c : getParent().getItems()) {
MatrixRun b = c.getBuildByNumber(getNumber());
if (b != null) r.add(b);
}
return r;
}
@Override
public String getWhyKeepLog() {
MatrixBuild b = getNextBuild();
if (b!=null && b.isPartial())
return b.getDisplayName()+" depends on this";
return super.getWhyKeepLog();
}
/**
* True if this build didn't do a full build and it is depending on the result of the previous build.
*/
public boolean isPartial() {
for(MatrixConfiguration c : getParent().getItems()) {
MatrixRun b = c.getNearestOldBuild(getNumber());
if (b != null && b.getNumber()!=getNumber())
return true;
}
return false;
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
try {
MatrixRun item = getRun(Combination.fromString(token));
if(item!=null)
return item;
} catch (IllegalArgumentException _) {
// failed to parse the token as Combination. Must be something else
}
return super.getDynamic(token,req,rsp);
}
@Override
public void run() {
run(new RunnerImpl());
}
@Override
public Fingerprint.RangeSet getDownstreamRelationship(AbstractProject that) {
Fingerprint.RangeSet rs = super.getDownstreamRelationship(that);
for(MatrixRun run : getRuns())
rs.add(run.getDownstreamRelationship(that));
return rs;
}
private class RunnerImpl extends AbstractRunner {
private final List<MatrixAggregator> aggregators = new ArrayList<MatrixAggregator>();
protected Result doRun(BuildListener listener) throws Exception {
MatrixProject p = getProject();
PrintStream logger = listener.getLogger();
// list up aggregators
for (Publisher pub : p.getPublishers().values()) {
if (pub instanceof MatrixAggregatable) {
MatrixAggregatable ma = (MatrixAggregatable) pub;
MatrixAggregator a = ma.createAggregator(MatrixBuild.this, launcher, listener);
if(a!=null)
aggregators.add(a);
}
}
//let properties do their job
for (JobProperty prop : p.getProperties().values()) {
if (prop instanceof MatrixAggregatable) {
MatrixAggregatable ma = (MatrixAggregatable) prop;
MatrixAggregator a = ma.createAggregator(MatrixBuild.this, launcher, listener);
if(a!=null)
aggregators.add(a);
}
}
axes = p.getAxes();
Collection<MatrixConfiguration> activeConfigurations = p.getActiveConfigurations();
final int n = getNumber();
String touchStoneFilter = p.getTouchStoneCombinationFilter();
Collection<MatrixConfiguration> touchStoneConfigurations = new HashSet<MatrixConfiguration>();
Collection<MatrixConfiguration> delayedConfigurations = new HashSet<MatrixConfiguration>();
for (MatrixConfiguration c: activeConfigurations) {
if (!MatrixBuildListener.buildConfiguration(MatrixBuild.this, c))
continue; // skip rebuild
if (touchStoneFilter != null && c.getCombination().evalGroovyExpression(p.getAxes(), p.getTouchStoneCombinationFilter())) {
touchStoneConfigurations.add(c);
} else {
delayedConfigurations.add(c);
}
}
for (MatrixAggregator a : aggregators)
if(!a.startBuild())
return Result.FAILURE;
try {
if(!p.isRunSequentially())
for(MatrixConfiguration c : touchStoneConfigurations)
scheduleConfigurationBuild(logger, c);
Result r = Result.SUCCESS;
for (MatrixConfiguration c : touchStoneConfigurations) {
if(p.isRunSequentially())
scheduleConfigurationBuild(logger, c);
Result buildResult = waitForCompletion(listener, c);
r = r.combine(buildResult);
}
if (p.getTouchStoneResultCondition() != null && r.isWorseThan(p.getTouchStoneResultCondition())) {
logger.printf("Touchstone configurations resulted in %s, so aborting...%n", r);
return r;
}
if(!p.isRunSequentially())
for(MatrixConfiguration c : delayedConfigurations)
scheduleConfigurationBuild(logger, c);
for (MatrixConfiguration c : delayedConfigurations) {
if(p.isRunSequentially())
scheduleConfigurationBuild(logger, c);
Result buildResult = waitForCompletion(listener, c);
r = r.combine(buildResult);
}
return r;
} catch( InterruptedException e ) {
logger.println("Aborted");
return Result.ABORTED;
} catch (AggregatorFailureException e) {
return Result.FAILURE;
}
finally {
// if the build was aborted in the middle. Cancel all the configuration builds.
Queue q = Hudson.getInstance().getQueue();
synchronized(q) {// avoid micro-locking in q.cancel.
for (MatrixConfiguration c : activeConfigurations) {
if(q.cancel(c))
logger.println(Messages.MatrixBuild_Cancelled(c.getDisplayName()));
MatrixRun b = c.getBuildByNumber(n);
if(b!=null) {
Executor exe = b.getExecutor();
if(exe!=null) {
logger.println(Messages.MatrixBuild_Interrupting(b.getDisplayName()));
exe.interrupt();
}
}
}
}
}
}
private Result waitForCompletion(BuildListener listener, MatrixConfiguration c) throws InterruptedException, IOException, AggregatorFailureException {
String whyInQueue = "";
long startTime = System.currentTimeMillis();
// wait for the completion
int appearsCancelledCount = 0;
while(true) {
MatrixRun b = c.getBuildByNumber(getNumber());
// two ways to get beyond this. one is that the build starts and gets done,
// or the build gets cancelled before it even started.
Result buildResult = null;
if(b!=null && !b.isBuilding())
buildResult = b.getResult();
Queue.Item qi = c.getQueueItem();
if(b==null && qi==null)
appearsCancelledCount++;
else
appearsCancelledCount = 0;
if(appearsCancelledCount>=5) {
// there's conceivably a race condition in computating b and qi, as their computation
// are not synchronized. There are indeed several reports of Hudson incorrectly assuming
// builds being cancelled. See
// http://www.nabble.com/Anyone-using-AccuRev-plugin--tt21634577.html#a21671389
// because of this, we really make sure that the build is cancelled by doing this 5
// times over 5 seconds
listener.getLogger().println(Messages.MatrixBuild_AppearsCancelled(c.getDisplayName()));
buildResult = Result.ABORTED;
}
if(buildResult!=null) {
for (MatrixAggregator a : aggregators)
if(!a.endRun(b))
throw new AggregatorFailureException();
return buildResult;
}
if(qi!=null) {
// if the build seems to be stuck in the queue, display why
String why = qi.getWhy();
if(!why.equals(whyInQueue) && System.currentTimeMillis()-startTime>5000) {
listener.getLogger().println(c.getDisplayName()+" is still in the queue: "+why);
whyInQueue = why;
}
}
Thread.sleep(1000);
}
}
private void scheduleConfigurationBuild(PrintStream logger, MatrixConfiguration c) {
logger.println(Messages.MatrixBuild_Triggering(c.getDisplayName()));
c.scheduleBuild(getAction(ParametersAction.class), new UpstreamCause(MatrixBuild.this));
}
public void post2(BuildListener listener) throws Exception {
for (MatrixAggregator a : aggregators)
a.endBuild();
}
}
/**
* A private exception to help maintain the correct control flow after extracting the 'waitForCompletion' method
*/
private static class AggregatorFailureException extends Exception {}
}
|
package org.realityforge.replicant.server.transport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReadWriteLock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import org.realityforge.guiceyloops.server.AssertUtil;
import org.realityforge.guiceyloops.server.TestInitialContextFactory;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.realityforge.replicant.server.Change;
import org.realityforge.replicant.server.ChangeSet;
import org.realityforge.replicant.server.ChannelAction;
import org.realityforge.replicant.server.ChannelAddress;
import org.realityforge.replicant.server.ChannelLink;
import org.realityforge.replicant.server.EntityMessage;
import org.realityforge.replicant.server.ServerConstants;
import org.realityforge.replicant.server.ee.EntityMessageCacheUtil;
import org.realityforge.replicant.server.ee.RegistryUtil;
import org.realityforge.replicant.server.ee.TransactionSynchronizationRegistryUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
/**
* TODO: Add tests for saveEntityMessages
*/
public class ReplicantSessionManagerImplTest
{
@BeforeMethod
public void setupTransactionContext()
{
RegistryUtil.bind();
}
@AfterMethod
public void clearContext()
{
TestInitialContextFactory.reset();
}
@Test
public void basicWorkflow()
{
final TestReplicantSessionManager sm = new TestReplicantSessionManager();
assertEquals( sm.getSessionIDs().size(), 0 );
assertNull( sm.getSession( "MySessionID" ) );
final ReplicantSession session = createSession( sm );
assertNotNull( session );
assertNotNull( session.getId() );
assertEquals( sm.getSessionIDs().size(), 1 );
// Make sure we can also get it thorugh the map interface
assertEquals( sm.getSessions().get( session.getId() ), session );
// The next line should update the last accessed time too!
assertEquals( sm.getSession( session.getId() ), session );
assertTrue( sm.invalidateSession( session ) );
assertEquals( sm.getSessionIDs().size(), 0 );
assertFalse( sm.invalidateSession( session ) );
assertNull( sm.getSession( session.getId() ) );
}
@Test
public void removeClosedSessions_openWebSocketSession()
{
final Session webSocketSession = mock( Session.class );
final String id = ValueUtil.randomString();
when( webSocketSession.getId() ).thenReturn( id );
when( webSocketSession.isOpen() ).thenReturn( true );
final ReplicantSessionManagerImpl sm = new TestReplicantSessionManager();
final ReplicantSession session = sm.createSession( webSocketSession );
assertEquals( sm.getSessions().get( session.getId() ), session );
sm.removeClosedSessions();
assertEquals( sm.getSessions().get( session.getId() ), session );
}
@Test
public void removeClosedSessions_closedWebSocketSession()
{
final Session webSocketSession = mock( Session.class );
final String id = ValueUtil.randomString();
when( webSocketSession.getId() ).thenReturn( id );
when( webSocketSession.isOpen() ).thenReturn( false );
final ReplicantSessionManagerImpl sm = new TestReplicantSessionManager();
final ReplicantSession session = sm.createSession( webSocketSession );
assertEquals( sm.getSessions().get( session.getId() ), session );
sm.removeClosedSessions();
assertNull( sm.getSessions().get( session.getId() ) );
}
@Test
public void locking()
throws Exception
{
final TestReplicantSessionManager sm = new TestReplicantSessionManager();
final ReadWriteLock lock = sm.getLock();
// Variable used to pass data back from threads
final ReplicantSession[] sessions = new ReplicantSession[ 2 ];
lock.readLock().lock();
// Make sure createSession can not complete if something has a read lock
final CyclicBarrier end = go( () -> sessions[ 0 ] = createSession( sm ) );
assertNull( sessions[ 0 ] );
lock.readLock().unlock();
end.await();
assertNotNull( sessions[ 0 ] );
lock.writeLock().lock();
// Make sure getSession can acquire a read lock
final CyclicBarrier end2 = go( () -> sessions[ 1 ] = sm.getSession( sessions[ 0 ].getId() ) );
assertNull( sessions[ 1 ] );
lock.writeLock().unlock();
end2.await();
assertNotNull( sessions[ 1 ] );
lock.readLock().lock();
final Boolean[] invalidated = new Boolean[ 1 ];
// Make sure createSession can not complete if something has a read lock
final CyclicBarrier end3 = go( () -> invalidated[ 0 ] = sm.invalidateSession( sessions[ 0 ] ) );
assertNull( invalidated[ 0 ] );
lock.readLock().unlock();
end3.await();
assertEquals( invalidated[ 0 ], Boolean.TRUE );
}
private CyclicBarrier go( final Runnable target )
throws Exception
{
final CyclicBarrier start = new CyclicBarrier( 2 );
final CyclicBarrier stop = new CyclicBarrier( 2 );
new Thread( () -> {
try
{
start.await();
target.run();
stop.await();
}
catch ( Exception e )
{
// Ignored
}
} ).start();
start.await();
Thread.sleep( 1 );
return stop;
}
@Test
public void deleteCacheEntry()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
assertFalse( sm.deleteCacheEntry( address1 ) );
sm.setCacheKey( "X" );
sm.tryGetCacheEntry( address1 );
assertTrue( sm.deleteCacheEntry( address1 ) );
}
@Test
public void ensureCdiType()
{
AssertUtil.assertNoFinalMethodsForCDI( ReplicantSessionManagerImpl.class );
}
@Test
public void subscribe()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch3 =
new ChannelMetaData( 2,
"C3",
null,
ChannelMetaData.FilterType.STATIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2, ch3 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final ChannelAddress address2 = new ChannelAddress( ch2.getChannelId(), null );
final ChannelAddress address3 = new ChannelAddress( ch3.getChannelId(), null );
final TestFilter originalFilter = new TestFilter( 41 );
final TestFilter filter = new TestFilter( 42 );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
final Session webSocketSession = session.getWebSocketSession();
when( webSocketSession.isOpen() ).thenReturn( true );
assertNull( session.findSubscriptionEntry( address1 ) );
// subscribe
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, false, 0, 0, null );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
}
// re-subscribe- should be noop
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( session.getSubscriptionEntry( address1 ), false, 0, 0, null );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
}
// re-subscribe explicitly - should only set explicit flag
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
assertEntry( session.getSubscriptionEntry( address1 ), true, 0, 0, null );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
}
// subscribe when existing subscription present
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address2, originalFilter );
assertEntry( session.getSubscriptionEntry( address2 ), true, 0, 0, originalFilter );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
EntityMessageCacheUtil.removeSessionChanges();
TransactionSynchronizationRegistryUtil.lookup()
.putResource( ServerConstants.REQUEST_ID_KEY, ValueUtil.randomInt() );
//Should be a noop as same filter
sm.subscribe( session, address2, originalFilter );
assertEntry( session.getSubscriptionEntry( address2 ), true, 0, 0, originalFilter );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
EntityMessageCacheUtil.removeSessionChanges();
//Should be a filter update
sm.subscribe( session, address2, filter );
assertEntry( session.getSubscriptionEntry( address2 ), true, 0, 0, filter );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
}
//Subscribe and attempt to update static filter
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address3, originalFilter );
assertEntry( session.getSubscriptionEntry( address3 ), true, 0, 0, originalFilter );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
EntityMessageCacheUtil.removeSessionChanges();
//Should be a noop as same filter
sm.subscribe( session, address3, originalFilter );
assertEntry( session.getSubscriptionEntry( address3 ), true, 0, 0, originalFilter );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
try
{
sm.subscribe( session, address3, filter );
fail( "Successfully updated a static filter" );
}
catch ( final AttemptedToUpdateStaticFilterException ignore )
{
//Ignore. Fine
}
}
}
@Test
public void subscribe_withCache()
throws Exception
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
sm.setCacheKey( "X" );
// subscribe - matching cacheKey
{
final ReplicantSession session = createSession( sm );
final Session webSocketSession = session.getWebSocketSession();
when( webSocketSession.isOpen() ).thenReturn( true );
assertNull( session.findSubscriptionEntry( address1 ) );
EntityMessageCacheUtil.removeSessionChanges();
session.setETag( address1, "X" );
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, false, 0, 0, null );
verify( webSocketSession.getBasicRemote() ).sendText( "{\"type\":\"use-cache\",\"channel\":\"0\",\"etag\":\"X\"}" );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
}
// subscribe - cacheKey differs
{
final ReplicantSession session = createSession( sm );
assertNull( session.findSubscriptionEntry( address1 ) );
EntityMessageCacheUtil.removeSessionChanges();
session.setETag( address1, "Y" );
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, false, 0, 0, null );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText(
"{\"type\":\"update\",\"etag\":\"X\",\"channels\":[\"+0\"],\"changes\":[{\"id\":\"1.79\",\"channels\":[\"0\"],\"data\":{\"ID\":79}}]}" );
}
}
@Test
public void subscribe_withSessionID()
throws Exception
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
assertNull( session.findSubscriptionEntry( address1 ) );
sm.subscribe( session, address1, null );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, true, 0, 0, null );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote, never() ).sendText( anyString() );
}
@Test
public void subscribe_withSessionID_andCaching()
throws Exception
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
sm.setCacheKey( "X" );
assertNull( session.getETag( address1 ) );
assertNull( session.findSubscriptionEntry( address1 ) );
session.setETag( address1, "X" );
sm.subscribe( session, address1, null );
assertEquals( session.getETag( address1 ), "X" );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, true, 0, 0, null );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText( "{\"type\":\"use-cache\",\"channel\":\"0\",\"etag\":\"X\"}" );
}
@Test
public void subscribe_withSessionID_andCachingThatNoMatch()
throws Exception
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
sm.setCacheKey( "X" );
assertNull( session.getETag( address1 ) );
assertNull( session.findSubscriptionEntry( address1 ) );
session.setETag( address1, "Y" );
sm.subscribe( session, address1, null );
assertNull( session.getETag( address1 ) );
final SubscriptionEntry entry1 = session.findSubscriptionEntry( address1 );
assertNotNull( entry1 );
assertEntry( entry1, true, 0, 0, null );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText(
"{\"type\":\"update\",\"etag\":\"X\",\"channels\":[\"+0\"],\"changes\":[{\"id\":\"1.79\",\"channels\":[\"0\"],\"data\":{\"ID\":79}}]}" );
}
@Test
public void performSubscribe()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch3 =
new ChannelMetaData( 2,
"C3",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2, ch3 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId() );
final ChannelAddress address2 = new ChannelAddress( ch2.getChannelId() );
final ChannelAddress address3 = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
// Test with no filter
{
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, true, 0, 0, null );
final LinkedList<ChannelAction> actions = getChannelActions();
assertEquals( actions.size(), 1 );
assertChannelAction( actions.get( 0 ), address1, ChannelAction.Action.ADD, null );
// 1 Change comes from collectDataForSubscribe
final Collection<Change> changes = getChanges();
assertEquals( changes.size(), 1 );
assertEquals( changes.iterator().next().getEntityMessage().getId(), 79 );
assertEntry( e1, true, 0, 0, null );
}
{
final TestFilter filter = new TestFilter( 42 );
EntityMessageCacheUtil.removeSessionChanges();
final SubscriptionEntry e1 = session.createSubscriptionEntry( address2 );
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.performSubscribe( session, e1, true, filter, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, true, 0, 0, filter );
final LinkedList<ChannelAction> actions = getChannelActions();
assertEquals( actions.size(), 1 );
assertChannelAction( actions.get( 0 ), address2, ChannelAction.Action.ADD, "{\"myField\":42}" );
// 1 Change comes from collectDataForSubscribe
final Collection<Change> changes = getChanges();
assertEquals( changes.size(), 1 );
assertEquals( changes.iterator().next().getEntityMessage().getId(), 79 );
assertEntry( e1, true, 0, 0, filter );
session.deleteSubscriptionEntry( e1 );
}
// Root instance is deleted
{
final SubscriptionEntry e1 = session.createSubscriptionEntry( address3 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.markChannelRootAsDeleted();
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, false, 0, 0, null );
final LinkedList<ChannelAction> actions = getChannelActions();
assertEquals( actions.size(), 1 );
assertChannelAction( actions.get( 0 ), address3, ChannelAction.Action.DELETE, null );
assertEquals( getChanges().size(), 0 );
}
}
@Test
public void performSubscribe_withCaching()
throws Exception
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId() );
final ChannelAddress address2 = new ChannelAddress( ch2.getChannelId(), 1 );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
sm.setCacheKey( "X" );
//Locally cached
{
sm.deleteAllCacheEntries();
final ReplicantSession session = createSession( sm );
session.setETag( address1, "X" );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, true, 0, 0, null );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
verify( session.getWebSocketSession().getBasicRemote() ).sendText(
"{\"type\":\"use-cache\",\"channel\":\"0\",\"etag\":\"X\"}" );
}
//Locally cached but an old version
{
sm.deleteAllCacheEntries();
final ReplicantSession session = createSession( sm );
session.setETag( address1, "NOT" + sm._cacheKey );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, true, 0, 0, null );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText(
"{\"type\":\"update\",\"etag\":\"X\",\"channels\":[\"+0\"],\"changes\":[{\"id\":\"1.79\",\"channels\":[\"0\"],\"data\":{\"ID\":79}}]}" );
}
//Not cached locally
{
sm.deleteAllCacheEntries();
final ReplicantSession session = createSession( sm );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, true, 0, 0, null );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText(
"{\"type\":\"update\",\"etag\":\"X\",\"channels\":[\"+0\"],\"changes\":[{\"id\":\"1.79\",\"channels\":[\"0\"],\"data\":{\"ID\":79}}]}" );
}
//Locally cached but deleted
{
sm.deleteAllCacheEntries();
final ReplicantSession session = createSession( sm );
session.setETag( address1, "X" );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address2 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, null );
sm.markChannelRootAsDeleted();
sm.performSubscribe( session, e1, true, null, EntityMessageCacheUtil.getSessionChanges() );
assertEntry( e1, false, 0, 0, null );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
}
}
@Test
public void performUnsubscribe()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address3 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address4 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address5 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
// Unsubscribe from channel that was explicitly subscribed
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.performUnsubscribe( session, entry, true, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
}
// implicit unsubscribe from channel that was implicitly subscribed should leave explicit subscription
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.performUnsubscribe( session, entry, false, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 0 );
assertNotNull( session.findSubscriptionEntry( address1 ) );
sm.performUnsubscribe( session, entry, true, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertNull( session.findSubscriptionEntry( address1 ) );
}
// implicit unsubscribe from channel that was implicitly subscribed should delete subscription
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.performUnsubscribe( session, entry, false, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
}
// implicit unsubscribe from channel that was implicitly subscribed should leave subscription that
// implicitly linked from elsewhere
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
sm.subscribe( session, address2, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry2 = session.getSubscriptionEntry( address2 );
sm.linkSubscriptionEntries( entry2, entry );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.performUnsubscribe( session, entry, false, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 0 );
assertNotNull( session.findSubscriptionEntry( address1 ) );
sm.delinkSubscriptionEntries( entry2, entry );
sm.performUnsubscribe( session, entry, false, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
}
// Unsubscribe also results in unsubscribe for all downstream channels
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
sm.subscribe( session, address2, false, null, EntityMessageCacheUtil.getSessionChanges() );
sm.subscribe( session, address3, false, null, EntityMessageCacheUtil.getSessionChanges() );
sm.subscribe( session, address4, false, null, EntityMessageCacheUtil.getSessionChanges() );
sm.subscribe( session, address5, false, null, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
final SubscriptionEntry entry2 = session.getSubscriptionEntry( address2 );
final SubscriptionEntry entry3 = session.getSubscriptionEntry( address3 );
final SubscriptionEntry entry4 = session.getSubscriptionEntry( address4 );
final SubscriptionEntry entry5 = session.getSubscriptionEntry( address5 );
sm.linkSubscriptionEntries( entry, entry2 );
sm.linkSubscriptionEntries( entry, entry3 );
sm.linkSubscriptionEntries( entry3, entry4 );
sm.linkSubscriptionEntries( entry4, entry5 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.performUnsubscribe( session, entry, true, false, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 5 );
for ( final ChannelAction action : getChannelActions() )
{
assertEquals( action.getAction(), ChannelAction.Action.REMOVE );
}
assertNull( session.findSubscriptionEntry( address1 ) );
assertNull( session.findSubscriptionEntry( address2 ) );
assertNull( session.findSubscriptionEntry( address3 ) );
assertNull( session.findSubscriptionEntry( address4 ) );
assertNull( session.findSubscriptionEntry( address5 ) );
}
}
@Test
public void unsubscribe()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
// Unsubscribe from channel that was explicitly subscribed
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
final SubscriptionEntry entry = session.getSubscriptionEntry( address1 );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.unsubscribe( session, entry.getAddress(), EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
}
// unsubscribe from unsubscribed
{
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.unsubscribe( session, address1, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 0 );
}
}
@Test
public void unsubscribe_usingSessionID()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
sm.unsubscribe( session, address1, EntityMessageCacheUtil.getSessionChanges() );
assertChannelActionCount( 1 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
}
@Test
public void bulkUnsubscribe()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address3 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address4 = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
// Unsubscribe from channel that was explicitly subscribed
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
sm.subscribe( session, address2, null );
sm.subscribe( session, address4, null );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
final ArrayList<Integer> subChannelIds = new ArrayList<>();
subChannelIds.add( address1.getSubChannelId() );
subChannelIds.add( address2.getSubChannelId() );
//This next one is not subscribed
subChannelIds.add( address3.getSubChannelId() );
// This next one is for wrong channel so should be no-op
subChannelIds.add( address4.getSubChannelId() );
sm.bulkUnsubscribe( session, ch1.getChannelId(), subChannelIds );
assertChannelActionCount( 2 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertChannelAction( getChannelActions().get( 1 ), address2, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
assertNull( session.findSubscriptionEntry( address2 ) );
}
}
@Test
public void bulkUnsubscribe_withSessionID()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address3 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address4 = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
// Unsubscribe from channel that was explicitly subscribed
{
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, address1, null );
sm.subscribe( session, address2, null );
sm.subscribe( session, address4, null );
//Rebind clears the state
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
final ArrayList<Integer> subChannelIds = new ArrayList<>();
subChannelIds.add( address1.getSubChannelId() );
subChannelIds.add( address2.getSubChannelId() );
//This next one is not subscribed
subChannelIds.add( address3.getSubChannelId() );
// This next one is for wrong channel so should be no-op
subChannelIds.add( address4.getSubChannelId() );
//sm.setupRegistryContext( sessionId );
sm.bulkUnsubscribe( session, ch1.getChannelId(), subChannelIds );
assertChannelActionCount( 2 );
assertChannelAction( getChannelActions().get( 0 ), address1, ChannelAction.Action.REMOVE, null );
assertChannelAction( getChannelActions().get( 1 ), address2, ChannelAction.Action.REMOVE, null );
assertNull( session.findSubscriptionEntry( address1 ) );
assertNull( session.findSubscriptionEntry( address2 ) );
}
}
@Test
public void updateSubscription()
{
final ChannelMetaData ch =
new ChannelMetaData( 0,
"C2",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch };
final ChannelAddress cd = new ChannelAddress( ch.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
final TestFilter originalFilter = new TestFilter( 41 );
final TestFilter filter = new TestFilter( 42 );
EntityMessageCacheUtil.removeSessionChanges();
sm.subscribe( session, cd, originalFilter );
EntityMessageCacheUtil.removeSessionChanges();
TransactionSynchronizationRegistryUtil.lookup()
.putResource( ServerConstants.REQUEST_ID_KEY, ValueUtil.randomInt() );
// Attempt to update to same filter - should be a noop
sm.subscribe( session, cd, originalFilter );
final SubscriptionEntry e1 = session.getSubscriptionEntry( cd );
assertEntry( e1, true, 0, 0, originalFilter );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
sm.subscribe( session, cd, filter );
assertEntry( e1, true, 0, 0, filter );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
}
@Test
public void bulkSubscribe_forUpdate()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
final TestFilter originalFilter = new TestFilter( 41 );
final TestFilter filter = new TestFilter( 42 );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
e1.setFilter( originalFilter );
final SubscriptionEntry e2 = session.createSubscriptionEntry( address2 );
e2.setFilter( originalFilter );
final ArrayList<Integer> subChannelIds = new ArrayList<>();
subChannelIds.add( address1.getSubChannelId() );
subChannelIds.add( address2.getSubChannelId() );
TransactionSynchronizationRegistryUtil.lookup()
.putResource( ServerConstants.REQUEST_ID_KEY, ValueUtil.randomInt() );
sm.bulkSubscribe( session, ch1.getChannelId(), subChannelIds, originalFilter );
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, true, 0, 0, originalFilter );
assertEntry( e2, true, 0, 0, originalFilter );
// Attempt to update to same filter - should be a noop
sm.bulkSubscribe( session, ch1.getChannelId(), subChannelIds, originalFilter );
assertEntry( e1, true, 0, 0, originalFilter );
assertEntry( e2, true, 0, 0, originalFilter );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
// Attempt to update no channels - should be noop
sm.bulkSubscribe( session, ch1.getChannelId(), new ArrayList<>(), filter );
assertEntry( e1, true, 0, 0, originalFilter );
assertEntry( e2, true, 0, 0, originalFilter );
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
// Attempt to update both channels
sm.bulkSubscribe( session, ch1.getChannelId(), subChannelIds, filter );
assertEntry( e1, true, 0, 0, filter );
assertEntry( e2, true, 0, 0, filter );
assertChannelActionCount( 2 );
assertSessionChangesCount( 1 );
//Clear counts
EntityMessageCacheUtil.removeSessionChanges();
//Set original filter so next action updates this one again
e2.setFilter( originalFilter );
// Attempt to update one channels
sm.bulkSubscribe( session, ch1.getChannelId(), subChannelIds, filter );
assertEntry( e1, true, 0, 0, filter );
assertEntry( e2, true, 0, 0, filter );
assertChannelActionCount( 1 );
assertSessionChangesCount( 1 );
}
@Test
public void bulkSubscribe_ForUpdate_whereBulkUpdateHookIsUsed()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
42,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
true,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2 = new ChannelAddress( ch1.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
final TestFilter originalFilter = new TestFilter( 41 );
final TestFilter filter = new TestFilter( 42 );
final SubscriptionEntry e1 = session.createSubscriptionEntry( address1 );
e1.setFilter( originalFilter );
final SubscriptionEntry e2 = session.createSubscriptionEntry( address2 );
e2.setFilter( originalFilter );
final ArrayList<Integer> subChannelIds = new ArrayList<>();
subChannelIds.add( address1.getSubChannelId() );
subChannelIds.add( address2.getSubChannelId() );
EntityMessageCacheUtil.removeSessionChanges();
assertChannelActionCount( 0 );
assertEntry( e1, false, 0, 0, originalFilter );
assertEntry( e2, false, 0, 0, originalFilter );
sm.markAsBulkCollectDataForSubscriptionUpdate();
assertEquals( sm.getBulkCollectDataForSubscriptionUpdateCallCount(), 0 );
// Attempt to update both channels
sm.bulkSubscribe( session, ch1.getChannelId(), subChannelIds, filter );
// assertEquals( sm.getBulkCollectDataForSubscriptionUpdateCallCount(), 1 );
// the original filter is still set as it is expected that the hook method does the magic
assertEntry( e1, false, 0, 0, originalFilter );
assertEntry( e2, false, 0, 0, originalFilter );
// These are 0 as expected the hook to do magic
assertChannelActionCount( 0 );
assertSessionChangesCount( 0 );
}
@Test
public void linkSubscriptionEntries()
{
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"Roster",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"Resource",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final ChannelAddress address2a = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2b = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
final SubscriptionEntry se1 = session.createSubscriptionEntry( address1 );
final SubscriptionEntry se2a = session.createSubscriptionEntry( address2a );
final SubscriptionEntry se2b = session.createSubscriptionEntry( address2b );
assertEntry( se1, false, 0, 0, null );
assertEntry( se2a, false, 0, 0, null );
assertEntry( se2b, false, 0, 0, null );
sm.linkSubscriptionEntries( se1, se2a );
assertEntry( se1, false, 0, 1, null );
assertEntry( se2a, false, 1, 0, null );
assertEntry( se2b, false, 0, 0, null );
assertTrue( se1.getOutwardSubscriptions().contains( address2a ) );
assertTrue( se2a.getInwardSubscriptions().contains( address1 ) );
sm.linkSubscriptionEntries( se2a, se2b );
assertEntry( se1, false, 0, 1, null );
assertEntry( se2a, false, 1, 1, null );
assertEntry( se2b, false, 1, 0, null );
assertTrue( se2a.getOutwardSubscriptions().contains( address2b ) );
assertTrue( se2b.getInwardSubscriptions().contains( address2a ) );
sm.delinkSubscriptionEntries( se2a, se2b );
assertEntry( se1, false, 0, 1, null );
assertEntry( se2a, false, 1, 0, null );
assertEntry( se2b, false, 0, 0, null );
assertFalse( se2a.getOutwardSubscriptions().contains( address2b ) );
assertFalse( se2b.getInwardSubscriptions().contains( address2a ) );
//Duplicate delink - noop
sm.delinkSubscriptionEntries( se2a, se2b );
assertEntry( se1, false, 0, 1, null );
assertEntry( se2a, false, 1, 0, null );
assertEntry( se2b, false, 0, 0, null );
assertFalse( se2a.getOutwardSubscriptions().contains( address2b ) );
assertFalse( se2b.getInwardSubscriptions().contains( address2a ) );
sm.delinkSubscriptionEntries( se1, se2a );
assertEntry( se1, false, 0, 0, null );
assertEntry( se2a, false, 0, 0, null );
assertEntry( se2b, false, 0, 0, null );
assertFalse( se1.getOutwardSubscriptions().contains( address2a ) );
assertFalse( se2a.getInwardSubscriptions().contains( address1 ) );
}
@Test
public void newReplicantSession()
{
final TestReplicantSessionManager sm = new TestReplicantSessionManager();
final ReplicantSession session = createSession( sm );
assertTrue( session.getId().matches( "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" ) );
}
@Test
public void sendPacket()
throws Exception
{
final TestReplicantSessionManager sm = new TestReplicantSessionManager();
final ReplicantSession session = createSession( sm );
sm.getRegistry().putResource( ServerConstants.REQUEST_ID_KEY, 1 );
sm.sendPacket( session, "X", new ChangeSet() );
final RemoteEndpoint.Basic remote = session.getWebSocketSession().getBasicRemote();
verify( remote ).sendText( "{\"type\":\"update\",\"requestId\":1,\"etag\":\"X\"}" );
assertEquals( sm.getRegistry().getResource( ServerConstants.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void expandLinkIfRequired()
{
EntityMessageCacheUtil.removeSessionChanges();
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch3 =
new ChannelMetaData( 2,
"C3",
42,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2, ch3 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final ChannelAddress address2a = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2b = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address3a = new ChannelAddress( ch3.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address3b = new ChannelAddress( ch3.getChannelId(), ValueUtil.randomInt() );
final ChannelLink link1 = new ChannelLink( address1, address2a );
final ChannelLink link2 = new ChannelLink( address1, address2b );
final ChannelLink link3 = new ChannelLink( address1, address3a );
final ChannelLink link4 = new ChannelLink( address1, address3b );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
//No expand as address1 is not subscribed
assertFalse( sm.expandLinkIfRequired( session, link1, EntityMessageCacheUtil.getSessionChanges() ) );
sm.subscribe( session, address1, new TestFilter( 33 ) );
final SubscriptionEntry entry1 = session.getSubscriptionEntry( address1 );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 0 );
//Expand as address1 is subscribed
assertTrue( sm.expandLinkIfRequired( session, link1, EntityMessageCacheUtil.getSessionChanges() ) );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 1 );
final SubscriptionEntry entry2a = session.getSubscriptionEntry( address2a );
assertFalse( entry2a.isExplicitlySubscribed() );
assertEquals( entry2a.getInwardSubscriptions().size(), 1 );
assertEquals( entry2a.getOutwardSubscriptions().size(), 0 );
//No expand as address2a is already subscribed
assertFalse( sm.expandLinkIfRequired( session, link1, EntityMessageCacheUtil.getSessionChanges() ) );
// Subscribe to 2 explicitly
sm.subscribe( session, address2b, null );
final SubscriptionEntry entry2b = session.getSubscriptionEntry( address2b );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 1 );
assertEquals( entry2b.getInwardSubscriptions().size(), 0 );
assertEquals( entry2b.getOutwardSubscriptions().size(), 0 );
assertFalse( sm.expandLinkIfRequired( session, link2, EntityMessageCacheUtil.getSessionChanges() ) );
//expandLinkIfRequired should still "Link" them even if no subscribe occurs
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 2 );
assertEquals( entry2b.getInwardSubscriptions().size(), 1 );
assertEquals( entry2b.getOutwardSubscriptions().size(), 0 );
//Fails the filter
assertFalse( sm.expandLinkIfRequired( session, link3, EntityMessageCacheUtil.getSessionChanges() ) );
sm.setFollowSource( link3.getSourceChannel() );
//We create a new subscription and copy the filter across
assertTrue( sm.expandLinkIfRequired( session, link3, EntityMessageCacheUtil.getSessionChanges() ) );
final SubscriptionEntry entry3a = session.getSubscriptionEntry( address3a );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 3 );
assertEquals( entry3a.getInwardSubscriptions().size(), 1 );
assertEquals( entry3a.getOutwardSubscriptions().size(), 0 );
assertEquals( entry3a.getFilter(), entry1.getFilter() );
sm.subscribe( session, address3b, new TestFilter( ValueUtil.randomInt() ) );
final SubscriptionEntry entry3b = session.getSubscriptionEntry( address3b );
//Do not update the filter... does this crazyness actually occur?
assertFalse( sm.expandLinkIfRequired( session, link4, EntityMessageCacheUtil.getSessionChanges() ) );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 4 );
assertEquals( entry3b.getInwardSubscriptions().size(), 1 );
assertEquals( entry3b.getOutwardSubscriptions().size(), 0 );
assertNotEquals( entry3b.getFilter(), entry1.getFilter() );
}
@Test
public void expandLink()
{
EntityMessageCacheUtil.removeSessionChanges();
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final ChannelAddress address2a = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2b = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelLink link1 = new ChannelLink( address1, address2a );
final ChannelLink link2 = new ChannelLink( address1, address2b );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
//No expand as address1 is not subscribed
assertFalse( sm.expandLink( session, EntityMessageCacheUtil.getSessionChanges() ) );
assertChannelActionCount( 0 );
sm.subscribe( session, address1, null );
assertChannelActionCount( 1 );
//No expand as no data to expand
assertFalse( sm.expandLink( session, EntityMessageCacheUtil.getSessionChanges() ) );
assertChannelActionCount( 1 );
final HashMap<String, Serializable> routes = new HashMap<>();
final HashMap<String, Serializable> attributes = new HashMap<>();
final HashSet<ChannelLink> links = new LinkedHashSet<>();
links.add( link1 );
links.add( link2 );
final EntityMessage message =
new EntityMessage( ValueUtil.randomInt(), ValueUtil.randomInt(), 0, routes, attributes, links );
EntityMessageCacheUtil.getSessionChanges().merge( new Change( message ) );
assertTrue( sm.expandLink( session, EntityMessageCacheUtil.getSessionChanges() ) );
assertChannelActionCount( 2 );
final SubscriptionEntry entry1 = session.getSubscriptionEntry( address1 );
final SubscriptionEntry entry2a = session.getSubscriptionEntry( address2a );
// Should not subscribe this until second wave
assertNull( session.findSubscriptionEntry( address2b ) );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 1 );
assertEquals( entry2a.getInwardSubscriptions().size(), 1 );
assertEquals( entry2a.getOutwardSubscriptions().size(), 0 );
// Second wave starts now
assertTrue( sm.expandLink( session, EntityMessageCacheUtil.getSessionChanges() ) );
assertChannelActionCount( 3 );
final SubscriptionEntry entry2b = session.getSubscriptionEntry( address2b );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 2 );
assertEquals( entry2a.getInwardSubscriptions().size(), 1 );
assertEquals( entry2a.getOutwardSubscriptions().size(), 0 );
assertEquals( entry2b.getInwardSubscriptions().size(), 1 );
assertEquals( entry2b.getOutwardSubscriptions().size(), 0 );
// No more data to process
assertFalse( sm.expandLink( session, EntityMessageCacheUtil.getSessionChanges() ) );
assertChannelActionCount( 3 );
}
@Test
public void expandLinks()
{
EntityMessageCacheUtil.removeSessionChanges();
final ChannelMetaData ch1 =
new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.DYNAMIC,
String.class,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData ch2 =
new ChannelMetaData( 1,
"C2",
42,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.NONE,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1, ch2 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final ChannelAddress address2a = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelAddress address2b = new ChannelAddress( ch2.getChannelId(), ValueUtil.randomInt() );
final ChannelLink link1 = new ChannelLink( address1, address2a );
final ChannelLink link2 = new ChannelLink( address1, address2b );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final ReplicantSession session = createSession( sm );
assertChannelActionCount( 0 );
sm.subscribe( session, address1, null );
assertChannelActionCount( 1 );
final HashMap<String, Serializable> routes = new HashMap<>();
final HashMap<String, Serializable> attributes = new HashMap<>();
final HashSet<ChannelLink> links = new HashSet<>();
links.add( link1 );
links.add( link2 );
final EntityMessage message =
new EntityMessage( ValueUtil.randomInt(), ValueUtil.randomInt(), 0, routes, attributes, links );
EntityMessageCacheUtil.getSessionChanges().merge( new Change( message ) );
sm.expandLinks( session, EntityMessageCacheUtil.getSessionChanges() );
final SubscriptionEntry entry1 = session.getSubscriptionEntry( address1 );
final SubscriptionEntry entry2a = session.getSubscriptionEntry( address2a );
final SubscriptionEntry entry2b = session.getSubscriptionEntry( address2b );
assertEquals( entry1.getInwardSubscriptions().size(), 0 );
assertEquals( entry1.getOutwardSubscriptions().size(), 2 );
assertEquals( entry2a.getInwardSubscriptions().size(), 1 );
assertEquals( entry2a.getOutwardSubscriptions().size(), 0 );
assertEquals( entry2b.getInwardSubscriptions().size(), 1 );
assertEquals( entry2b.getOutwardSubscriptions().size(), 0 );
assertChannelActionCount( 3 );
}
@Test
public void tryGetCacheEntry()
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final String cacheKey = ValueUtil.randomString();
sm.setCacheKey( cacheKey );
assertFalse( sm.getCacheEntry( address1 ).isInitialized() );
final ChannelCacheEntry entry = sm.tryGetCacheEntry( address1 );
assertNotNull( entry );
assertTrue( entry.isInitialized() );
assertEquals( entry.getDescriptor(), address1 );
assertEquals( entry.getCacheKey(), cacheKey );
assertEquals( entry.getChangeSet().getChanges().size(), 1 );
}
@Test
public void tryGetCacheEntry_entryNotCached()
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
final String cacheKey = ValueUtil.randomString();
sm.setCacheKey( cacheKey );
assertFalse( sm.getCacheEntry( address1 ).isInitialized() );
final ChannelCacheEntry entry = sm.tryGetCacheEntry( address1 );
assertNotNull( entry );
assertTrue( entry.isInitialized() );
assertEquals( entry.getDescriptor(), address1 );
assertEquals( entry.getCacheKey(), cacheKey );
assertEquals( entry.getChangeSet().getChanges().size(), 1 );
}
@Test
public void tryGetCacheEntry_entryNotCached_instanceDeleted()
{
final ChannelMetaData ch1 = new ChannelMetaData( 0,
"C1",
null,
ChannelMetaData.FilterType.NONE,
null,
ChannelMetaData.CacheType.INTERNAL,
false,
true );
final ChannelMetaData[] channels = new ChannelMetaData[]{ ch1 };
final ChannelAddress address1 = new ChannelAddress( ch1.getChannelId(), null );
final TestReplicantSessionManager sm = new TestReplicantSessionManager( channels );
sm.setCacheKey( ValueUtil.randomString() );
sm.markChannelRootAsDeleted();
assertFalse( sm.getCacheEntry( address1 ).isInitialized() );
final ChannelCacheEntry entry = sm.tryGetCacheEntry( address1 );
assertNull( entry );
}
private void assertEntry( @Nonnull final SubscriptionEntry entry,
final boolean explicitlySubscribed,
final int inwardCount,
final int outwardCount,
@Nullable final Object filter )
{
assertEquals( entry.isExplicitlySubscribed(), explicitlySubscribed );
assertEquals( entry.getInwardSubscriptions().size(), inwardCount );
assertEquals( entry.getOutwardSubscriptions().size(), outwardCount );
assertEquals( entry.getFilter(), filter );
}
private Collection<Change> getChanges()
{
return EntityMessageCacheUtil.getSessionChanges().getChanges();
}
private void assertSessionChangesCount( final int sessionChangesCount )
{
assertEquals( getChanges().size(), sessionChangesCount );
}
private LinkedList<ChannelAction> getChannelActions()
{
return EntityMessageCacheUtil.getSessionChanges().getChannelActions();
}
private void assertChannelAction( @Nonnull final ChannelAction channelAction,
@Nonnull final ChannelAddress address,
@Nonnull final ChannelAction.Action action,
@Nullable final String filterAsString )
{
assertEquals( channelAction.getAction(), action );
assertEquals( channelAction.getAddress(), address );
if ( null == filterAsString )
{
assertNull( channelAction.getFilter() );
}
else
{
assertNotNull( channelAction.getFilter() );
assertEquals( channelAction.getFilter().toString(), filterAsString );
}
}
private void assertChannelActionCount( final int channelActionCount )
{
assertEquals( getChannelActions().size(), channelActionCount );
}
static class TestReplicantSessionManager
extends ReplicantSessionManagerImpl
{
private final SystemMetaData _systemMetaData;
private ChannelAddress _followSource;
private String _cacheKey;
private boolean _bulkCollectDataForSubscriptionUpdate;
private int _bulkCollectDataForSubscriptionUpdateCallCount;
private boolean _channelRootDeleted;
private TestReplicantSessionManager()
{
this( new SystemMetaData( ValueUtil.randomString() ) );
}
private TestReplicantSessionManager( final ChannelMetaData[] channels )
{
this( new SystemMetaData( ValueUtil.randomString(), channels ) );
}
private TestReplicantSessionManager( final SystemMetaData systemMetaData )
{
_systemMetaData = systemMetaData;
}
int getBulkCollectDataForSubscriptionUpdateCallCount()
{
return _bulkCollectDataForSubscriptionUpdateCallCount;
}
void markAsBulkCollectDataForSubscriptionUpdate()
{
_bulkCollectDataForSubscriptionUpdate = true;
}
void markChannelRootAsDeleted()
{
_channelRootDeleted = true;
}
private void setCacheKey( final String cacheKey )
{
_cacheKey = cacheKey;
}
@Nonnull
@Override
public SystemMetaData getSystemMetaData()
{
return _systemMetaData;
}
@Override
protected boolean bulkCollectDataForSubscriptionUpdate( @Nonnull final ReplicantSession session,
@Nonnull final List<ChannelAddress> addresses,
@Nullable final Object originalFilter,
@Nullable final Object filter )
{
_bulkCollectDataForSubscriptionUpdateCallCount += 1;
return _bulkCollectDataForSubscriptionUpdate;
}
@Nonnull
@Override
protected SubscribeResult collectDataForSubscribe( @Nonnull final ChannelAddress descriptor,
@Nonnull final ChangeSet changeSet,
@Nullable final Object filter )
{
if ( !_channelRootDeleted )
{
final HashMap<String, Serializable> routingKeys = new HashMap<>();
final HashMap<String, Serializable> attributes = new HashMap<>();
attributes.put( "ID", 79 );
final EntityMessage message = new EntityMessage( 79, 1, 0, routingKeys, attributes, null );
changeSet.merge( new Change( message, descriptor.getChannelId(), descriptor.getSubChannelId() ) );
return new SubscribeResult( false, _cacheKey );
}
else
{
return new SubscribeResult( true, null );
}
}
@Override
protected void collectDataForSubscriptionUpdate( @Nonnull final ChannelAddress descriptor,
@Nonnull final ChangeSet changeSet,
@Nullable final Object originalFilter,
@Nullable final Object filter )
{
final HashMap<String, Serializable> routingKeys = new HashMap<>();
final HashMap<String, Serializable> attributes = new HashMap<>();
attributes.put( "ID", 78 );
//Ugly hack to pass back filters
attributes.put( "OriginalFilter", (Serializable) originalFilter );
attributes.put( "Filter", (Serializable) filter );
final EntityMessage message = new EntityMessage( 78, 1, 0, routingKeys, attributes, null );
changeSet.merge( new Change( message, descriptor.getChannelId(), descriptor.getSubChannelId() ) );
}
private void setFollowSource( final ChannelAddress followSource )
{
_followSource = followSource;
}
@Override
protected boolean shouldFollowLink( @Nonnull final SubscriptionEntry sourceEntry,
@Nonnull final ChannelAddress target )
{
return null != _followSource && _followSource.equals( sourceEntry.getAddress() );
}
@Nonnull
@Override
protected TransactionSynchronizationRegistry getRegistry()
{
return TransactionSynchronizationRegistryUtil.lookup();
}
}
@Nonnull
private ReplicantSession createSession( @Nonnull final TestReplicantSessionManager sm )
{
final Session webSocketSession = mock( Session.class );
when( webSocketSession.getId() ).thenReturn( ValueUtil.randomString() );
when( webSocketSession.isOpen() ).thenReturn( true );
final RemoteEndpoint.Basic remote = mock( RemoteEndpoint.Basic.class );
when( webSocketSession.getBasicRemote() ).thenReturn( remote );
return sm.createSession( webSocketSession );
}
}
|
package hudson.model;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.console.ConsoleNote;
import hudson.console.HyperlinkNote;
import hudson.remoting.Channel;
import hudson.util.StreamTaskListener;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Formatter;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.ProtectedExternally;
/**
* Receives events that happen during some lengthy operation
* that has some chance of failures, such as a build, SCM change polling,
* agent launch, and so on.
*
* <p>
* This interface is implemented by Hudson core and passed to extension points so that
* they can record the progress of the operation without really knowing how those information
* and handled/stored by Hudson.
*
* <p>
* The information is one way or the other made available to users, and
* so the expectation is that when something goes wrong, enough information
* shall be written to a {@link TaskListener} so that the user can diagnose
* what's going wrong.
*
* <p>
* {@link StreamTaskListener} is the most typical implementation of this interface.
*
* <p>
* Implementations are generally expected to be remotable via {@link Channel}.
*
* @author Kohsuke Kawaguchi
*/
public interface TaskListener extends SerializableOnlyOverRemoting {
/**
* This writer will receive the output of the build
*/
@NonNull
PrintStream getLogger();
/**
* A charset to use for methods returning {@link PrintWriter}.
* Should match that used to construct {@link #getLogger}.
* @return by default, UTF-8
*/
@Restricted(ProtectedExternally.class)
@NonNull
default Charset getCharset() {
return StandardCharsets.UTF_8;
}
private PrintWriter _error(String prefix, String msg) {
PrintStream out = getLogger();
out.print(prefix);
out.println(msg);
Charset charset = getCharset();
return new PrintWriter(new OutputStreamWriter(out, charset), true);
}
/**
* Annotates the current position in the output log by using the given annotation.
* If the implementation doesn't support annotated output log, this method might be no-op.
* @since 1.349
*/
@SuppressWarnings("rawtypes")
default void annotate(ConsoleNote ann) throws IOException {
ann.encodeTo(getLogger());
}
/**
* Places a {@link HyperlinkNote} on the given text.
*
* @param url
* If this starts with '/', it's interpreted as a path within the context path.
*/
default void hyperlink(String url, String text) throws IOException {
annotate(new HyperlinkNote(url, text.length()));
getLogger().print(text);
}
/**
* An error in the build.
*
* @return
* A writer to receive details of the error.
*/
@NonNull
default PrintWriter error(String msg) {
return _error("ERROR: ", msg);
}
/**
* {@link Formatter#format(String, Object[])} version of {@link #error(String)}.
*/
@NonNull
default PrintWriter error(String format, Object... args) {
return error(String.format(format, args));
}
/**
* A fatal error in the build.
*
* @return
* A writer to receive details of the error.
*/
@NonNull
default PrintWriter fatalError(String msg) {
return _error("FATAL: ", msg);
}
/**
* {@link Formatter#format(String, Object[])} version of {@link #fatalError(String)}.
*/
@NonNull
default PrintWriter fatalError(String format, Object... args) {
return fatalError(String.format(format, args));
}
/**
* {@link TaskListener} that discards the output.
*/
TaskListener NULL = new NullTaskListener();
}
|
package hudson.tasks;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.console.HyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
import hudson.model.DependecyDeclarer;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import jenkins.model.Jenkins;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.tasks.BuildTrigger.DescriptorImpl.ItemListenerImpl;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Triggers builds of other projects.
*
* <p>
* Despite what the name suggests, this class doesn't actually trigger other jobs
* as a part of {@link #perform} method. Its main job is to simply augment
* {@link DependencyGraph}. Jobs are responsible for triggering downstream jobs
* on its own, because dependencies may come from other sources.
*
* <p>
* This class, however, does provide the {@link #execute(AbstractBuild, BuildListener, BuildTrigger)}
* method as a convenience method to invoke downstream builds.
*
* @author Kohsuke Kawaguchi
*/
public class BuildTrigger extends Recorder implements DependecyDeclarer {
/**
* Comma-separated list of other projects to be scheduled.
*/
private String childProjects;
/**
* Threshold status to trigger other builds.
*
* For compatibility reasons, this field could be null, in which case
* it should read as "SUCCESS".
*/
private final Result threshold;
public BuildTrigger(String childProjects, boolean evenIfUnstable) {
this(childProjects,evenIfUnstable ? Result.UNSTABLE : Result.SUCCESS);
}
@DataBoundConstructor
public BuildTrigger(String childProjects, String threshold) {
this(childProjects, Result.fromString(StringUtils.defaultString(threshold, Result.SUCCESS.toString())));
}
public BuildTrigger(String childProjects, Result threshold) {
if(childProjects==null)
throw new IllegalArgumentException();
this.childProjects = childProjects;
this.threshold = threshold;
}
public BuildTrigger(List<AbstractProject> childProjects, Result threshold) {
this((Collection<AbstractProject>)childProjects,threshold);
}
public BuildTrigger(Collection<? extends AbstractProject> childProjects, Result threshold) {
this(Items.toNameList(childProjects),threshold);
}
public String getChildProjectsValue() {
return childProjects;
}
public Result getThreshold() {
if(threshold==null)
return Result.SUCCESS;
else
return threshold;
}
/**
* @deprecated as of 1.406
* Use {@link #getChildProjects(ItemGroup)}
*/
public List<AbstractProject> getChildProjects() {
return getChildProjects(Jenkins.getInstance());
}
public List<AbstractProject> getChildProjects(AbstractProject owner) {
return getChildProjects(owner==null?null:owner.getParent());
}
public List<AbstractProject> getChildProjects(ItemGroup base) {
return Items.fromNameList(base,childProjects,AbstractProject.class);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/**
* Checks if this trigger has the exact same set of children as the given list.
*/
public boolean hasSame(AbstractProject owner, Collection<? extends AbstractProject> projects) {
List<AbstractProject> children = getChildProjects(owner);
return children.size()==projects.size() && children.containsAll(projects);
}
/**
* @deprecated as of 1.406
* Use {@link #hasSame(AbstractProject, Collection)}
*/
public boolean hasSame(Collection<? extends AbstractProject> projects) {
return hasSame(null,projects);
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
return true;
}
/**
* @deprecated since 1.341; use {@link #execute(AbstractBuild,BuildListener)}
*/
@Deprecated
public static boolean execute(AbstractBuild build, BuildListener listener, BuildTrigger trigger) {
return execute(build, listener);
}
/**
* Convenience method to trigger downstream builds.
*
* @param build
* The current build. Its downstreams will be triggered.
* @param listener
* Receives the progress report.
*/
public static boolean execute(AbstractBuild build, BuildListener listener) {
PrintStream logger = listener.getLogger();
// Check all downstream Project of the project, not just those defined by BuildTrigger
final DependencyGraph graph = Jenkins.getInstance().getDependencyGraph();
List<Dependency> downstreamProjects = new ArrayList<Dependency>(
graph.getDownstreamDependencies(build.getProject()));
// Sort topologically
Collections.sort(downstreamProjects, new Comparator<Dependency>() {
public int compare(Dependency lhs, Dependency rhs) {
// Swapping lhs/rhs to get reverse sort:
return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
}
});
for (Dependency dep : downstreamProjects) {
AbstractProject p = dep.getDownstreamProject();
if (p.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(HyperlinkNote.encodeTo('/'+ p.getUrl(),p.getName())));
continue;
}
List<Action> buildActions = new ArrayList<Action>();
if (dep.shouldTriggerBuild(build, listener, buildActions)) {
// this is not completely accurate, as a new build might be triggered
// between these calls
String name = HyperlinkNote.encodeTo('/'+ p.getUrl(), p.getName())+" #"+p.getNextBuildNumber();
if(p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build),
buildActions.toArray(new Action[buildActions.size()]))) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
}
}
return true;
}
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
for (AbstractProject p : getChildProjects(owner))
graph.addDependency(new Dependency(owner, p) {
@Override
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener,
List<Action> actions) {
return build.getResult().isBetterOrEqualTo(threshold);
}
});
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/**
* Called from {@link ItemListenerImpl} when a job is renamed.
*
* @return true if this {@link BuildTrigger} is changed and needs to be saved.
*/
public boolean onJobRenamed(String oldName, String newName) {
// quick test
if(!childProjects.contains(oldName))
return false;
boolean changed = false;
// we need to do this per string, since old Project object is already gone.
String[] projects = childProjects.split(",");
for( int i=0; i<projects.length; i++ ) {
if(projects[i].trim().equals(oldName)) {
projects[i] = newName;
changed = true;
}
}
if(changed) {
StringBuilder b = new StringBuilder();
for (String p : projects) {
if(b.length()>0) b.append(',');
b.append(p);
}
childProjects = b.toString();
}
return changed;
}
/**
* Correct broken data gracefully (#1537)
*/
private Object readResolve() {
if(childProjects==null)
return childProjects="";
return this;
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.BuildTrigger_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/downstream.html";
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String childProjectsString = formData.getString("childProjects").trim();
if (childProjectsString.endsWith(",")) {
childProjectsString = childProjectsString.substring(0, childProjectsString.length() - 1).trim();
}
return new BuildTrigger(
childProjectsString,
formData.optString("threshold", Result.SUCCESS.toString()));
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public boolean showEvenIfUnstableOption(Class<? extends AbstractProject> jobType) {
// UGLY: for promotion process, this option doesn't make sense.
return !jobType.getName().contains("PromotionProcess");
}
/**
* Form validation method.
*/
public FormValidation doCheck(@AncestorInPath Item project, @QueryParameter String value ) {
if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.getInstance().getItem(projectName,project,Item.class);
if(item==null)
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName,
AbstractProject.findNearest(projectName,project.getParent()).getRelativeNameFrom(project)));
if(!(item instanceof AbstractProject))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteChildProjects(@QueryParameter String value) {
AutoCompletionCandidates candidates = new AutoCompletionCandidates();
List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
for (Job job: jobs) {
if (job.getFullName().startsWith(value)) {
if (job.hasPermission(Item.READ)) {
candidates.add(job.getFullName());
}
}
}
return candidates;
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onRenamed(Item item, String oldName, String newName) {
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for( Project<?,?> p : Jenkins.getInstance().getProjects() ) {
BuildTrigger t = p.getPublishersList().get(BuildTrigger.class);
if(t!=null) {
if(t.onJobRenamed(oldName,newName)) {
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from "+oldName+" to "+newName,e);
}
}
}
}
}
}
}
private static final Logger LOGGER = Logger.getLogger(BuildTrigger.class.getName());
}
|
package net.time4j;
import net.time4j.base.GregorianDate;
import net.time4j.base.MathUtils;
import net.time4j.base.TimeSource;
import net.time4j.base.UnixTime;
import net.time4j.base.WallTime;
import net.time4j.engine.AttributeQuery;
import net.time4j.engine.ChronoDisplay;
import net.time4j.engine.ChronoElement;
import net.time4j.engine.ChronoEntity;
import net.time4j.engine.ChronoException;
import net.time4j.engine.ChronoMerger;
import net.time4j.engine.Chronology;
import net.time4j.engine.ElementRule;
import net.time4j.engine.EpochDays;
import net.time4j.engine.Normalizer;
import net.time4j.engine.Temporal;
import net.time4j.engine.TimeAxis;
import net.time4j.engine.TimeMetric;
import net.time4j.engine.TimePoint;
import net.time4j.engine.TimeSpan;
import net.time4j.engine.UnitRule;
import net.time4j.format.Attributes;
import net.time4j.format.CalendarType;
import net.time4j.format.ChronoFormatter;
import net.time4j.format.ChronoPattern;
import net.time4j.format.Leniency;
import net.time4j.scale.TimeScale;
import net.time4j.tz.TZID;
import net.time4j.tz.Timezone;
import net.time4j.tz.TransitionStrategy;
import net.time4j.tz.ZonalOffset;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static net.time4j.CalendarUnit.DAYS;
import static net.time4j.CalendarUnit.MILLENNIA;
import static net.time4j.CalendarUnit.MONTHS;
import static net.time4j.CalendarUnit.QUARTERS;
import static net.time4j.CalendarUnit.WEEKS;
import static net.time4j.CalendarUnit.YEARS;
import static net.time4j.ClockUnit.HOURS;
import static net.time4j.ClockUnit.MICROS;
import static net.time4j.ClockUnit.MILLIS;
import static net.time4j.ClockUnit.MINUTES;
import static net.time4j.ClockUnit.NANOS;
import static net.time4j.ClockUnit.SECONDS;
import static net.time4j.PlainDate.*;
import static net.time4j.PlainTime.*;
/**
* <p>Represents a plain composition of calendar date and wall time as defined
* in ISO-8601, but without any timezone. </p>
*
* <p>Following elements which are declared as constants are registered by
* this class: </p>
*
* <ul>
* <li>{@link PlainDate#COMPONENT}</li>
* <li>{@link PlainDate#YEAR}</li>
* <li>{@link PlainDate#YEAR_OF_WEEKDATE}</li>
* <li>{@link PlainDate#QUARTER_OF_YEAR}</li>
* <li>{@link PlainDate#MONTH_OF_YEAR}</li>
* <li>{@link PlainDate#MONTH_AS_NUMBER}</li>
* <li>{@link PlainDate#DAY_OF_MONTH}</li>
* <li>{@link PlainDate#DAY_OF_QUARTER}</li>
* <li>{@link PlainDate#DAY_OF_WEEK}</li>
* <li>{@link PlainDate#DAY_OF_YEAR}</li>
* <li>{@link PlainDate#WEEKDAY_IN_MONTH}</li>
* <li>{@link PlainTime#COMPONENT}</li>
* <li>{@link PlainTime#AM_PM_OF_DAY}</li>
* <li>{@link PlainTime#CLOCK_HOUR_OF_AMPM}</li>
* <li>{@link PlainTime#CLOCK_HOUR_OF_DAY}</li>
* <li>{@link PlainTime#DIGITAL_HOUR_OF_AMPM}</li>
* <li>{@link PlainTime#DIGITAL_HOUR_OF_DAY}</li>
* <li>{@link PlainTime#ISO_HOUR}</li>
* <li>{@link PlainTime#MINUTE_OF_HOUR}</li>
* <li>{@link PlainTime#MINUTE_OF_DAY}</li>
* <li>{@link PlainTime#SECOND_OF_MINUTE}</li>
* <li>{@link PlainTime#SECOND_OF_DAY}</li>
* <li>{@link PlainTime#MILLI_OF_SECOND}</li>
* <li>{@link PlainTime#MICRO_OF_SECOND}</li>
* <li>{@link PlainTime#NANO_OF_SECOND}</li>
* <li>{@link PlainTime#MILLI_OF_DAY}</li>
* <li>{@link PlainTime#MICRO_OF_DAY}</li>
* <li>{@link PlainTime#NANO_OF_DAY}</li>
* <li>{@link PlainTime#DECIMAL_HOUR}</li>
* <li>{@link PlainTime#DECIMAL_MINUTE}</li>
* <li>{@link PlainTime#DECIMAL_SECOND}</li>
* </ul>
*
* <p>Furthermore, all elements of class {@link Weekmodel} are supported. As
* timestamp units can be used: {@link CalendarUnit} and {@link ClockUnit}. </p>
*
* <p>Note: The special time value 24:00 is only supported in the factory
* methods which normalize the resulting timestamp to midnight of the following
* day. In element access and manipulations this value is not supported. </p>
*
* @author Meno Hochschild
* @concurrency <immutable>
*/
/*[deutsch]
* <p>Komposition aus Datum und Uhrzeit nach dem ISO-8601-Standard. </p>
*
* <p>Registriert sind folgende als Konstanten deklarierte Elemente: </p>
*
* <ul>
* <li>{@link PlainDate#COMPONENT}</li>
* <li>{@link PlainDate#YEAR}</li>
* <li>{@link PlainDate#YEAR_OF_WEEKDATE}</li>
* <li>{@link PlainDate#QUARTER_OF_YEAR}</li>
* <li>{@link PlainDate#MONTH_OF_YEAR}</li>
* <li>{@link PlainDate#MONTH_AS_NUMBER}</li>
* <li>{@link PlainDate#DAY_OF_MONTH}</li>
* <li>{@link PlainDate#DAY_OF_QUARTER}</li>
* <li>{@link PlainDate#DAY_OF_WEEK}</li>
* <li>{@link PlainDate#DAY_OF_YEAR}</li>
* <li>{@link PlainDate#WEEKDAY_IN_MONTH}</li>
* <li>{@link PlainTime#COMPONENT}</li>
* <li>{@link PlainTime#AM_PM_OF_DAY}</li>
* <li>{@link PlainTime#CLOCK_HOUR_OF_AMPM}</li>
* <li>{@link PlainTime#CLOCK_HOUR_OF_DAY}</li>
* <li>{@link PlainTime#DIGITAL_HOUR_OF_AMPM}</li>
* <li>{@link PlainTime#DIGITAL_HOUR_OF_DAY}</li>
* <li>{@link PlainTime#ISO_HOUR}</li>
* <li>{@link PlainTime#MINUTE_OF_HOUR}</li>
* <li>{@link PlainTime#MINUTE_OF_DAY}</li>
* <li>{@link PlainTime#SECOND_OF_MINUTE}</li>
* <li>{@link PlainTime#SECOND_OF_DAY}</li>
* <li>{@link PlainTime#MILLI_OF_SECOND}</li>
* <li>{@link PlainTime#MICRO_OF_SECOND}</li>
* <li>{@link PlainTime#NANO_OF_SECOND}</li>
* <li>{@link PlainTime#MILLI_OF_DAY}</li>
* <li>{@link PlainTime#MICRO_OF_DAY}</li>
* <li>{@link PlainTime#NANO_OF_DAY}</li>
* <li>{@link PlainTime#DECIMAL_HOUR}</li>
* <li>{@link PlainTime#DECIMAL_MINUTE}</li>
* <li>{@link PlainTime#DECIMAL_SECOND}</li>
* </ul>
*
* <p>Darüberhinaus sind alle Elemente der Klasse {@link Weekmodel}
* nutzbar. Als Zeiteinheiten kommen vor allem {@link CalendarUnit} und
* {@link ClockUnit} in Betracht. </p>
*
* <p>Notiz: Unterstützung für den speziellen Zeitwert T24:00 gibt es
* nur in den Fabrikmethoden, die dann diesen Wert zum nächsten Tag hin
* normalisieren, nicht aber in den Elementen. </p>
*
* @author Meno Hochschild
* @concurrency <immutable>
*/
@CalendarType("iso8601")
public final class PlainTimestamp
extends TimePoint<IsoUnit, PlainTimestamp>
implements GregorianDate,
WallTime,
Temporal<PlainTimestamp>,
Normalizer<IsoUnit> {
private static final int MRD = 1000000000;
private static final PlainTimestamp MIN =
new PlainTimestamp(PlainDate.MIN, PlainTime.MIN);
private static final PlainTimestamp MAX =
new PlainTimestamp(PlainDate.MAX, WALL_TIME.getDefaultMaximum());
private static final Map<Object, ChronoElement<?>> CHILDREN;
private static final TimeAxis<IsoUnit, PlainTimestamp> ENGINE;
private static final TimeMetric<IsoUnit, Duration<IsoUnit>> STD_METRIC;
static {
Map<Object, ChronoElement<?>> children =
new HashMap<Object, ChronoElement<?>>();
children.put(CALENDAR_DATE, WALL_TIME);
children.put(YEAR, MONTH_AS_NUMBER);
children.put(YEAR_OF_WEEKDATE, Weekmodel.ISO.weekOfYear());
children.put(QUARTER_OF_YEAR, DAY_OF_QUARTER);
children.put(MONTH_OF_YEAR, DAY_OF_MONTH);
children.put(MONTH_AS_NUMBER, DAY_OF_MONTH);
children.put(DAY_OF_MONTH, WALL_TIME);
children.put(DAY_OF_WEEK, WALL_TIME);
children.put(DAY_OF_YEAR, WALL_TIME);
children.put(DAY_OF_QUARTER, WALL_TIME);
children.put(WEEKDAY_IN_MONTH, WALL_TIME);
children.put(AM_PM_OF_DAY, DIGITAL_HOUR_OF_AMPM);
children.put(CLOCK_HOUR_OF_AMPM, MINUTE_OF_HOUR);
children.put(CLOCK_HOUR_OF_DAY, MINUTE_OF_HOUR);
children.put(DIGITAL_HOUR_OF_AMPM, MINUTE_OF_HOUR);
children.put(DIGITAL_HOUR_OF_DAY, MINUTE_OF_HOUR);
children.put(ISO_HOUR, MINUTE_OF_HOUR);
children.put(MINUTE_OF_HOUR, SECOND_OF_MINUTE);
children.put(MINUTE_OF_DAY, SECOND_OF_MINUTE);
children.put(SECOND_OF_MINUTE, NANO_OF_SECOND);
children.put(SECOND_OF_DAY, NANO_OF_SECOND);
CHILDREN = Collections.unmodifiableMap(children);
TimeAxis.Builder<IsoUnit, PlainTimestamp> builder =
TimeAxis.Builder
.setUp(
IsoUnit.class,
PlainTimestamp.class,
new Merger(),
MIN,
MAX)
.appendElement(
CALENDAR_DATE,
FieldRule.of(CALENDAR_DATE),
DAYS)
.appendElement(
YEAR,
FieldRule.of(YEAR),
YEARS)
.appendElement(
YEAR_OF_WEEKDATE,
FieldRule.of(YEAR_OF_WEEKDATE),
YOWElement.YOWUnit.WEEK_BASED_YEARS)
.appendElement(
QUARTER_OF_YEAR,
FieldRule.of(QUARTER_OF_YEAR),
QUARTERS)
.appendElement(
MONTH_OF_YEAR,
FieldRule.of(MONTH_OF_YEAR),
MONTHS)
.appendElement(
MONTH_AS_NUMBER,
FieldRule.of(MONTH_AS_NUMBER),
MONTHS)
.appendElement(
DAY_OF_MONTH,
FieldRule.of(DAY_OF_MONTH),
DAYS)
.appendElement(
DAY_OF_WEEK,
FieldRule.of(DAY_OF_WEEK),
DAYS)
.appendElement(
DAY_OF_YEAR,
FieldRule.of(DAY_OF_YEAR),
DAYS)
.appendElement(
DAY_OF_QUARTER,
FieldRule.of(DAY_OF_QUARTER),
DAYS)
.appendElement(
WEEKDAY_IN_MONTH,
FieldRule.of(WEEKDAY_IN_MONTH),
WEEKS)
.appendElement(
WALL_TIME,
FieldRule.of(WALL_TIME))
.appendElement(
AM_PM_OF_DAY,
FieldRule.of(AM_PM_OF_DAY))
.appendElement(
CLOCK_HOUR_OF_AMPM,
FieldRule.of(CLOCK_HOUR_OF_AMPM),
HOURS)
.appendElement(
CLOCK_HOUR_OF_DAY,
FieldRule.of(CLOCK_HOUR_OF_DAY),
HOURS)
.appendElement(
DIGITAL_HOUR_OF_AMPM,
FieldRule.of(DIGITAL_HOUR_OF_AMPM),
HOURS)
.appendElement(
DIGITAL_HOUR_OF_DAY,
FieldRule.of(DIGITAL_HOUR_OF_DAY),
HOURS)
.appendElement(
ISO_HOUR,
FieldRule.of(ISO_HOUR),
HOURS)
.appendElement(
MINUTE_OF_HOUR,
FieldRule.of(MINUTE_OF_HOUR),
MINUTES)
.appendElement(
MINUTE_OF_DAY,
FieldRule.of(MINUTE_OF_DAY),
MINUTES)
.appendElement(
SECOND_OF_MINUTE,
FieldRule.of(SECOND_OF_MINUTE),
SECONDS)
.appendElement(
SECOND_OF_DAY,
FieldRule.of(SECOND_OF_DAY),
SECONDS)
.appendElement(
MILLI_OF_SECOND,
FieldRule.of(MILLI_OF_SECOND),
MILLIS)
.appendElement(
MICRO_OF_SECOND,
FieldRule.of(MICRO_OF_SECOND),
MICROS)
.appendElement(
NANO_OF_SECOND,
FieldRule.of(NANO_OF_SECOND),
NANOS)
.appendElement(
MILLI_OF_DAY,
FieldRule.of(MILLI_OF_DAY),
MILLIS)
.appendElement(
MICRO_OF_DAY,
FieldRule.of(MICRO_OF_DAY),
MICROS)
.appendElement(
NANO_OF_DAY,
FieldRule.of(NANO_OF_DAY),
NANOS)
.appendElement(
DECIMAL_HOUR,
new DecimalRule(DECIMAL_HOUR))
.appendElement(
DECIMAL_MINUTE,
new DecimalRule(DECIMAL_MINUTE))
.appendElement(
DECIMAL_SECOND,
new DecimalRule(DECIMAL_SECOND))
.appendExtension(new WeekExtension());
registerCalendarUnits(builder);
registerClockUnits(builder);
ENGINE = builder.build();
IsoUnit[] units =
{YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, NANOS};
STD_METRIC = Duration.in(units);
}
private static final long serialVersionUID = 7458380065762437714L;
private transient final PlainDate date;
private transient final PlainTime time;
private PlainTimestamp(
PlainDate date,
PlainTime time
) {
super();
if (time.getHour() == 24) { // T24 normalisieren
this.date = date.plus(1, DAYS);
this.time = PlainTime.MIN;
} else if (date == null) {
throw new NullPointerException("Missing date.");
} else {
this.date = date;
this.time = time;
}
}
/**
* <p>Creates a new local timestamp with calendar date and wall time. </p>
*
* <p>The special time value 24:00 will automatically normalized such
* that the resulting timestamp is on starting midnight of following
* day. </p>
*
* @param date calendar date component
* @param time wall time component (24:00 will always be normalized)
* @return timestamp as composition of date and time
* @see #of(int, int, int, int, int)
* @see #of(int, int, int, int, int, int)
*/
/*[deutsch]
* <p>Erzeugt eine neue Instanz mit Datum und Uhrzeit. </p>
*
* <p>Der Spezialwert T24:00 wird automatisch so normalisiert, daß
* der resultierende Zeitstempel auf Mitternacht des Folgetags zeigt. </p>
*
* @param date calendar date component
* @param time wall time component (24:00 will always be normalized)
* @return timestamp as composition of date and time
* @see #of(int, int, int, int, int)
* @see #of(int, int, int, int, int, int)
*/
public static PlainTimestamp of(
PlainDate date,
PlainTime time
) {
return new PlainTimestamp(date, time);
}
/**
* <p>Creates a new local timestamp in minute precision. </p>
*
* <p>The special time value 24:00 will automatically normalized such
* that the resulting timestamp is on starting midnight of following
* day. </p>
*
* @param year proleptic iso year [(-999,999,999)-999,999,999]
* @param month gregorian month in range (1-12)
* @param dayOfMonth day of month in range (1-31)
* @param hour hour in the range {@code 0-23} or {@code 24}
* if minute and second are equal to {@code 0}
* @param minute minute in the range {@code 0-59}
* @return timestamp as composition of date and time
*/
/*[deutsch]
* <p>Erzeugt einen neuen minutengenauen Zeitstempel. </p>
*
* <p>Der Spezialwert T24:00 wird automatisch so normalisiert, daß
* der resultierende Zeitstempel auf Mitternacht des Folgetags zeigt. </p>
*
* @param year proleptic iso year [(-999,999,999)-999,999,999]
* @param month gregorian month in range (1-12)
* @param dayOfMonth day of month in range (1-31)
* @param hour hour in the range {@code 0-23} or {@code 24}
* if minute and second are equal to {@code 0}
* @param minute minute in the range {@code 0-59}
* @return timestamp as composition of date and time
*/
public static PlainTimestamp of(
int year,
int month,
int dayOfMonth,
int hour,
int minute
) {
return PlainTimestamp.of(year, month, dayOfMonth, hour, minute, 0);
}
/**
* <p>Creates a new local timestamp in second precision. </p>
*
* <p>The special time value 24:00 will automatically normalized such
* that the resulting timestamp is on starting midnight of following
* day. </p>
*
* @param year proleptic iso year [(-999,999,999)-999,999,999]
* @param month gregorian month in range (1-12)
* @param dayOfMonth day of month in range (1-31)
* @param hour hour in the range {@code 0-23} or {@code 24}
* if minute and second are equal to {@code 0}
* @param minute minute in the range {@code 0-59}
* @param second second in the range {@code 0-59}
* @return timestamp as composition of date and time
*/
/*[deutsch]
* <p>Erzeugt einen neuen sekundengenauen Zeitstempel. </p>
*
* <p>Der Spezialwert T24:00 wird automatisch so normalisiert, daß
* der resultierende Zeitstempel auf Mitternacht des Folgetags zeigt. </p>
*
* @param year proleptic iso year [(-999,999,999)-999,999,999]
* @param month gregorian month in range (1-12)
* @param dayOfMonth day of month in range (1-31)
* @param hour hour in the range {@code 0-23} or {@code 24}
* if minute and second are equal to {@code 0}
* @param minute minute in the range {@code 0-59}
* @param second second in the range {@code 0-59}
* @return timestamp as composition of date and time
*/
public static PlainTimestamp of(
int year,
int month,
int dayOfMonth,
int hour,
int minute,
int second
) {
return PlainTimestamp.of(
PlainDate.of(year, month, dayOfMonth),
PlainTime.of(hour, minute, second)
);
}
/**
* <p>Provides the calendar date part. </p>
*
* @return calendar date component
*/
/*[deutsch]
* <p>Liefert die Datumskomponente. </p>
*
* @return calendar date component
*/
public PlainDate getCalendarDate() {
return this.date;
}
/**
* <p>Provides the wall time part. </p>
*
* @return wall time component
*/
/*[deutsch]
* <p>Liefert die Uhrzeitkomponente. </p>
*
* @return wall time component
*/
public PlainTime getWallTime() {
return this.time;
}
@Override
public int getYear() {
return this.date.getYear();
}
@Override
public int getMonth() {
return this.date.getMonth();
}
@Override
public int getDayOfMonth() {
return this.date.getDayOfMonth();
}
@Override
public int getHour() {
return this.time.getHour();
}
@Override
public int getMinute() {
return this.time.getMinute();
}
@Override
public int getSecond() {
return this.time.getSecond();
}
@Override
public int getNanosecond() {
return this.time.getNanosecond();
}
/**
* <p>Adjusts this timestamp by given operator. </p>
*
* @param operator element-related operator
* @return changed copy of this timestamp
* @see ChronoEntity#with(net.time4j.engine.ChronoOperator)
*/
/*[deutsch]
* <p>Passt diesen Zeitstempel mit Hilfe des angegebenen Operators an. </p>
*
* @param operator element-related operator
* @return changed copy of this timestamp
* @see ChronoEntity#with(net.time4j.engine.ChronoOperator)
*/
public PlainTimestamp with(ElementOperator<?> operator) {
return this.with(operator.onTimestamp());
}
/**
* <p>Adjusts the calendar part of this timestamp. </p>
*
* @param date new calendar date component
* @return changed copy of this timestamp
*/
/*[deutsch]
* <p>Passt die Datumskomponente an. </p>
*
* @param date new calendar date component
* @return changed copy of this timestamp
*/
public PlainTimestamp with(PlainDate date) {
return this.with(CALENDAR_DATE, date);
}
/**
* <p>Adjusts the wall time part of this timestamp. </p>
*
* @param time new wall time component
* @return changed copy of this timestamp
*/
/*[deutsch]
* <p>Passt die Uhrzeitkomponente an. </p>
*
* @param time new wall time component
* @return changed copy of this timestamp
*/
public PlainTimestamp with(PlainTime time) {
return this.with(WALL_TIME, time);
}
@Override
public boolean isBefore(PlainTimestamp timestamp) {
return (this.compareTo(timestamp) < 0);
}
@Override
public boolean isAfter(PlainTimestamp timestamp) {
return (this.compareTo(timestamp) > 0);
}
@Override
public boolean isSimultaneous(PlainTimestamp timestamp) {
return (this.compareTo(timestamp) == 0);
}
/**
* <p>Defines the temporal order of date and time as natural order. </p>
*
* <p>The comparison is consistent with {@code equals()}. </p>
*
* @see #isBefore(PlainTimestamp)
* @see #isAfter(PlainTimestamp)
*/
/*[deutsch]
* <p>Definiert eine natürliche Ordnung, die auf der zeitlichen
* Position basiert. </p>
*
* <p>Der Vergleich ist konsistent mit {@code equals()}. </p>
*
* @see #isBefore(PlainTimestamp)
* @see #isAfter(PlainTimestamp)
*/
@Override
public int compareTo(PlainTimestamp timestamp) {
if (this.date.isAfter(timestamp.date)) {
return 1;
} else if (this.date.isBefore(timestamp.date)) {
return -1;
}
return this.time.compareTo(timestamp.time);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof PlainTimestamp) {
PlainTimestamp that = (PlainTimestamp) obj;
return (this.date.equals(that.date) && this.time.equals(that.time));
} else {
return false;
}
}
@Override
public int hashCode() {
return 13 * this.date.hashCode() + 37 * this.time.hashCode();
}
/**
* <p>Creates a canonical representation of the form
* "yyyy-MM-dd'T'HH:mm:ss,fffffffff". </p>
*
* <p>Dependent on the precision (that is last non-zero part of time)
* the time representation might be shorter. </p>
*
* @return canonical ISO-8601-formatted string
* @see PlainTime#toString()
*/
/*[deutsch]
* <p>Erzeugt eine kanonische Darstellung im Format
* "yyyy-MM-dd'T'HH:mm:ss,fffffffff". </p>
*
* <p>Je nach Genauigkeit kann der Uhrzeitanteil auch kürzer sein. </p>
*
* @return canonical ISO-8601-formatted string
* @see PlainTime#toString()
*/
@Override
public String toString() {
return this.date.toString() + this.time.toString();
}
public static ChronoFormatter<PlainTimestamp> localFormatter(
String formatPattern,
ChronoPattern patternType
) {
return ChronoFormatter
.setUp(PlainTimestamp.class, Locale.getDefault())
.addPattern(formatPattern, patternType)
.build();
}
public static ChronoFormatter<PlainTimestamp> formatter(
String formatPattern,
ChronoPattern patternType,
Locale locale
) {
return ChronoFormatter
.setUp(PlainTimestamp.class, locale)
.addPattern(formatPattern, patternType)
.build();
}
/**
* <p>Provides a static access to the associated time axis respective
* chronology which contains the chronological rules. </p>
*
* @return chronological system as time axis (never {@code null})
*/
/*[deutsch]
* <p>Liefert die zugehörige Zeitachse, die alle notwendigen
* chronologischen Regeln enthält. </p>
*
* @return chronological system as time axis (never {@code null})
*/
public static TimeAxis<IsoUnit, PlainTimestamp> axis() {
return ENGINE;
}
/**
* <p>Combines this local timestamp with the timezone offset UTC+00:00
* to a global UTC-moment. </p>
*
* @return global UTC-moment based on this local timestamp interpreted
* at offset UTC+00:00
* @see #at(ZonalOffset)
*/
/*[deutsch]
* <p>Kombiniert diesen lokalen Zeitstempel mit UTC+00:00 zu
* einem globalen UTC-Moment. </p>
*
* @return global UTC-moment based on this local timestamp interpreted
* at offset UTC+00:00
* @see #at(ZonalOffset)
*/
public Moment atUTC() {
return this.at(ZonalOffset.UTC);
}
/**
* <p>Combines this local timestamp with the given timezone offset
* to a global UTC-moment. </p>
*
* @param offset timezone offset
* @return global UTC-moment based on this local timestamp interpreted
* at given offset
* @since 1.2
* @see #atUTC()
* @see #in(Timezone)
*/
/*[deutsch]
* <p>Kombiniert diesen lokalen Zeitstempel mit dem angegebenen
* Zeitzonen-Offset zu einem globalen UTC-Moment. </p>
*
* @param offset timezone offset
* @return global UTC-moment based on this local timestamp interpreted
* at given offset
* @since 1.2
* @see #atUTC()
* @see #in(Timezone)
*/
public Moment at(ZonalOffset offset) {
long localSeconds =
MathUtils.safeMultiply(
this.date.getDaysSinceUTC() + 2 * 365,
86400);
localSeconds += (this.time.getHour() * 3600);
localSeconds += (this.time.getMinute() * 60);
localSeconds += this.time.getSecond();
int localNanos = this.time.getNanosecond();
long posixTime = localSeconds - offset.getIntegralAmount();
int posixNanos = localNanos - offset.getFractionalAmount();
if (posixNanos < 0) {
posixNanos += MRD;
posixTime
} else if (posixNanos >= MRD) {
posixNanos -= MRD;
posixTime++;
}
return Moment.of(posixTime, posixNanos, TimeScale.POSIX);
}
/**
* <p>Combines this local timestamp with the system timezone to a global
* UTC-moment. </p>
*
* @return global UTC-moment based on this local timestamp interpreted
* in system timezone
* @since 1.2
* @see Timezone#ofSystem()
* @see #inTimezone(TZID)
*/
/*[deutsch]
* <p>Kombiniert diesen lokalen Zeitstempel mit der System-Zeitzone
* zu einem UTC-Moment. </p>
*
* @return global UTC-moment based on this local timestamp interpreted
* in system timezone
* @since 1.2
* @see Timezone#ofSystem()
* @see #inTimezone(TZID)
*/
public Moment inStdTimezone() {
return this.in(Timezone.ofSystem());
}
public Moment inTimezone(TZID tzid) {
return this.in(Timezone.of(tzid));
}
/**
* <p>Combines this local timestamp with given timezone to a global
* UTC-moment. </p>
*
* @param tz timezone
* @return global UTC-moment based on this local timestamp interpreted
* in given timezone
* @since 1.2
* @see Timezone#of(String)
*/
/*[deutsch]
* <p>Kombiniert diesen lokalen Zeitstempel mit der angegebenen Zeitzone
* zu einem UTC-Moment. </p>
*
* @param tz timezone
* @return global UTC-moment based on this local timestamp interpreted
* in given timezone
* @since 1.2
* @see Timezone#of(String)
*/
public Moment in(Timezone tz) {
if (tz.isFixed()) { // optimization
return this.at(tz.getOffset(this.date, this.time));
}
TransitionStrategy strategy = tz.getStrategy();
long posixTime = strategy.resolve(this.date, this.time, tz);
Moment moment =
Moment.of(posixTime, this.time.getNanosecond(), TimeScale.POSIX);
if (strategy == Timezone.STRICT_MODE) {
Moment.checkNegativeLS(posixTime, this);
}
return moment;
}
public boolean isValid(TZID tzid) {
if (tzid == null) {
return false;
}
return !Timezone.of(tzid).isInvalid(this.date, this.time);
}
/**
* <p>Normalized given timespan using years, months, days and
* all clock units. </p>
*
* <p>This normalizer can also convert from days to months. Example: </p>
*
* <pre>
* Duration<CalendarUnit> dur = Duration.of(30, CalendarUnit.DAYS);
* Duration<IsoUnit> result =
* PlainTimestamp.of(2012, 2, 28, 0, 0).normalize(dur);
* System.out.println(result); // output: P1M1D (leap year!)
* </pre>
*
* @param timespan to be normalized
* @return normalized duration
* @since 2.0
*/
/*[deutsch]
* <p>Normalisiert die angegebene Zeitspanne, indem Jahre, Monate, Tage
* und alle Uhrzeiteinheiten verwendet werden. </p>
*
* <p>Dieser Normalisierer kann auch von Tagen zu Monaten konvertieren.
* Beispiel: </p>
*
* <pre>
* Duration<CalendarUnit> dur = Duration.of(30, CalendarUnit.DAYS);
* Duration<IsoUnit> result =
* PlainTimestamp.of(2012, 2, 28, 0, 0).normalize(dur);
* System.out.println(result); // Ausgabe: P1M1D (Schaltjahr!)
* </pre>
*
* @param timespan to be normalized
* @return normalized duration
* @since 2.0
*/
@Override
public Duration<IsoUnit> normalize(TimeSpan<? extends IsoUnit> timespan) {
return this.until(this.plus(timespan), STD_METRIC);
}
/**
* @exclude
*/
@Override
protected TimeAxis<IsoUnit, PlainTimestamp> getChronology() {
return ENGINE;
}
/**
* @exclude
*/
@Override
protected PlainTimestamp getContext() {
return this;
}
/**
* <p>Erzeugt eine neue Uhrzeit passend zur angegebenen absoluten Zeit. </p>
*
* @param ut unix time in seconds
* @param offset shift of local timestamp relative to UTC
* @return new or cached local timestamp
*/
static PlainTimestamp from(
UnixTime ut,
ZonalOffset offset
) {
long localSeconds = ut.getPosixTime() + offset.getIntegralAmount();
int localNanos = ut.getNanosecond() + offset.getFractionalAmount();
if (localNanos < 0) {
localNanos += MRD;
localSeconds
} else if (localNanos >= MRD) {
localNanos -= MRD;
localSeconds++;
}
PlainDate date =
PlainDate.of(
MathUtils.floorDivide(localSeconds, 86400),
EpochDays.UNIX);
int secondsOfDay = MathUtils.floorModulo(localSeconds, 86400);
int second = secondsOfDay % 60;
int minutesOfDay = secondsOfDay / 60;
int minute = minutesOfDay % 60;
int hour = minutesOfDay / 60;
PlainTime time =
PlainTime.of(
hour,
minute,
second,
localNanos
);
return PlainTimestamp.of(date, time);
}
private static void registerCalendarUnits(
TimeAxis.Builder<IsoUnit, PlainTimestamp> builder
) {
Set<CalendarUnit> monthly = EnumSet.range(MILLENNIA, MONTHS);
Set<CalendarUnit> daily = EnumSet.range(WEEKS, DAYS);
for (CalendarUnit unit : CalendarUnit.values()) {
builder.appendUnit(
unit,
new CompositeUnitRule(unit),
unit.getLength(),
(unit.compareTo(WEEKS) < 0) ? monthly : daily
);
}
}
private static void registerClockUnits(
TimeAxis.Builder<IsoUnit, PlainTimestamp> builder
) {
for (ClockUnit unit : ClockUnit.values()) {
builder.appendUnit(
unit,
new CompositeUnitRule(unit),
unit.getLength(),
EnumSet.allOf(ClockUnit.class)
);
}
}
/**
* @serialData Uses <a href="../../serialized-form.html#net.time4j.SPX">
* a dedicated serialization form</a> as proxy. The layout
* is bit-compressed. The first byte contains within the
* four most significant bits the type id {@code 5}. Then
* the data bytes for date and time component follow.
*
* Schematic algorithm:
*
* <pre>
* out.writeByte(5 << 4);
* out.writeObject(timestamp.getCalendarDate());
* out.writeObject(timestamp.getWallTime());
* </pre>
*/
private Object writeReplace() throws ObjectStreamException {
return new SPX(this, SPX.TIMESTAMP_TYPE);
}
/**
* @serialData Blocks because a serialization proxy is required.
* @throws InvalidObjectException (always)
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new InvalidObjectException("Serialization proxy required.");
}
private static class Merger
implements ChronoMerger<PlainTimestamp> {
@Override
public PlainTimestamp createFrom(
TimeSource<?> clock,
final AttributeQuery attributes
) {
Timezone zone;
if (attributes.contains(Attributes.TIMEZONE_ID)) {
zone = Timezone.of(attributes.get(Attributes.TIMEZONE_ID));
} else {
zone = Timezone.ofSystem();
}
final UnixTime ut = clock.currentTime();
return PlainTimestamp.from(ut, zone.getOffset(ut));
}
@Override
public PlainTimestamp createFrom(
ChronoEntity<?> entity,
AttributeQuery attributes,
boolean preparsing
) {
Leniency leniency =
attributes.get(Attributes.LENIENCY, Leniency.SMART);
if (entity instanceof UnixTime) {
TZID tzid;
if (attributes.contains(Attributes.TIMEZONE_ID)) {
tzid = attributes.get(Attributes.TIMEZONE_ID);
} else if (leniency.isLax()) {
tzid = ZonalOffset.UTC;
} else {
throw new IllegalArgumentException(
"Missing timezone attribute for type conversion.");
}
Moment ut = Moment.from(UnixTime.class.cast(entity));
return ut.toZonalTimestamp(tzid);
}
boolean leapsecond =
preparsing
&& entity.contains(SECOND_OF_MINUTE)
&& (entity.get(SECOND_OF_MINUTE).intValue() == 60);
if (leapsecond) {
entity.with(SECOND_OF_MINUTE, Integer.valueOf(59));
}
PlainDate date = null;
PlainTime time = null;
if (entity.contains(CALENDAR_DATE)) {
date = entity.get(CALENDAR_DATE);
} else {
date = PlainDate.axis().createFrom(entity, attributes, false);
}
if (date == null) {
return null;
} else if (entity.contains(WALL_TIME)) {
time = entity.get(WALL_TIME);
} else {
time = PlainTime.axis().createFrom(entity, attributes, false);
if (
(time == null)
&& leniency.isLax()
) {
time = PlainTime.MIN;
}
}
if (time == null) {
return null;
} else {
if (entity.contains(LongElement.DAY_OVERFLOW)) {
date =
date.plus(
entity.get(LongElement.DAY_OVERFLOW).longValue(),
DAYS);
}
if (
leapsecond
&& entity.isValid(LeapsecondElement.INSTANCE, Boolean.TRUE)
) {
entity.with(
LeapsecondElement.INSTANCE,
Boolean.TRUE);
}
return PlainTimestamp.of(date, time);
}
}
@Override
public ChronoDisplay preformat(
PlainTimestamp context,
AttributeQuery attributes
) {
return context;
}
@Override
public Chronology<?> preparser() {
return null;
}
}
private static class FieldRule<V>
implements ElementRule<PlainTimestamp, V> {
private final ChronoElement<V> element;
private FieldRule(ChronoElement<V> element) {
super();
this.element = element;
}
static <V> FieldRule<V> of(ChronoElement<V> element) {
return new FieldRule<V>(element);
}
@Override
public V getValue(PlainTimestamp context) {
if (this.element.isDateElement()) {
return context.date.get(this.element);
} else if (this.element.isTimeElement()) {
return context.time.get(this.element);
}
throw new ChronoException(
"Missing rule for: " + this.element.name());
}
@Override
public V getMinimum(PlainTimestamp context) {
if (this.element.isDateElement()) {
return context.date.getMinimum(this.element);
} else if (this.element.isTimeElement()) {
return this.element.getDefaultMinimum();
}
throw new ChronoException(
"Missing rule for: " + this.element.name());
}
@Override
public V getMaximum(PlainTimestamp context) {
if (this.element.isDateElement()) {
return context.date.getMaximum(this.element);
} else if (this.element.isTimeElement()) {
return this.element.getDefaultMaximum();
}
throw new ChronoException(
"Missing rule for: " + this.element.name());
}
@Override
public boolean isValid(
PlainTimestamp context,
V value
) {
if (this.element.isDateElement()) {
return context.date.isValid(this.element, value);
} else if (this.element.isTimeElement()) {
if (Number.class.isAssignableFrom(this.element.getType())) {
if (value == null) {
return false;
}
long min = this.toNumber(this.element.getDefaultMinimum());
long max = this.toNumber(this.element.getDefaultMaximum());
long val = this.toNumber(value);
return ((min <= val) && (max >= val));
} else if (
this.element.equals(WALL_TIME)
&& PlainTime.MAX.equals(value)
) {
return false;
} else {
return context.time.isValid(this.element, value);
}
}
throw new ChronoException(
"Missing rule for: " + this.element.name());
}
@Override
public PlainTimestamp withValue(
PlainTimestamp context,
V value,
boolean lenient
) {
if (value.equals(this.getValue(context))) {
return context;
} else if (lenient) { // nur auf numerischen Elementen definiert
IsoUnit unit = ENGINE.getBaseUnit(this.element);
long oldValue = this.toNumber(this.getValue(context));
long newValue = this.toNumber(value);
long amount = MathUtils.safeSubtract(newValue, oldValue);
return context.plus(amount, unit);
} else if (this.element.isDateElement()) {
PlainDate date = context.date.with(this.element, value);
return PlainTimestamp.of(date, context.time);
} else if (this.element.isTimeElement()) {
if (Number.class.isAssignableFrom(this.element.getType())) {
long min = this.toNumber(this.element.getDefaultMinimum());
long max = this.toNumber(this.element.getDefaultMaximum());
long val = this.toNumber(value);
if ((min > val) || (max < val)) {
throw new IllegalArgumentException(
"Out of range: " + value);
}
} else if (
this.element.equals(WALL_TIME)
&& value.equals(PlainTime.MAX)
) {
throw new IllegalArgumentException(
"Out of range: " + value);
}
PlainTime time = context.time.with(this.element, value);
return PlainTimestamp.of(context.date, time);
}
throw new ChronoException(
"Missing rule for: " + this.element.name());
}
// optional
@Override
public ChronoElement<?> getChildAtFloor(PlainTimestamp context) {
return CHILDREN.get(this.element);
}
// optional
@Override
public ChronoElement<?> getChildAtCeiling(PlainTimestamp context) {
return CHILDREN.get(this.element);
}
private long toNumber(V value) {
return Number.class.cast(value).longValue();
}
}
private static class DecimalRule
extends FieldRule<BigDecimal> {
DecimalRule(ChronoElement<BigDecimal> element) {
super(element);
}
@Override
public boolean isValid(
PlainTimestamp context,
BigDecimal value
) {
if (value == null) {
return false;
}
BigDecimal min = super.element.getDefaultMinimum();
BigDecimal max = super.element.getDefaultMaximum();
return (
(min.compareTo(value) <= 0)
&& (value.compareTo(max) <= 0)
);
}
@Override
public PlainTimestamp withValue(
PlainTimestamp context,
BigDecimal value,
boolean lenient
) {
if (!this.isValid(context, value)) {
throw new IllegalArgumentException("Out of range: " + value);
}
PlainTime time = context.time.with(super.element, value);
return PlainTimestamp.of(context.date, time);
}
}
private static class CompositeUnitRule
implements UnitRule<PlainTimestamp> {
private final CalendarUnit calendarUnit;
private final ClockUnit clockUnit;
CompositeUnitRule(CalendarUnit unit) {
super();
this.calendarUnit = unit;
this.clockUnit = null;
}
CompositeUnitRule(ClockUnit unit) {
super();
this.calendarUnit = null;
this.clockUnit = unit;
}
@Override
public PlainTimestamp addTo(
PlainTimestamp timepoint,
long amount
) {
PlainDate d;
PlainTime t;
if (this.calendarUnit != null) {
d = timepoint.date.plus(amount, this.calendarUnit);
t = timepoint.time;
} else {
DayCycles cycles =
timepoint.time.roll(amount, this.clockUnit);
d =
timepoint.date.plus(cycles.getDayOverflow(), DAYS);
t = cycles.getWallTime();
}
return PlainTimestamp.of(d, t);
}
@Override
public long between(
PlainTimestamp start,
PlainTimestamp end
) {
long delta;
if (this.calendarUnit != null) {
delta = this.calendarUnit.between(start.date, end.date);
if (delta != 0) {
boolean needsTimeCorrection;
if (this.calendarUnit == DAYS) {
needsTimeCorrection = true;
} else {
PlainDate d = start.date.plus(delta, this.calendarUnit);
needsTimeCorrection = (d.compareByTime(end.date) == 0);
}
if (needsTimeCorrection) {
PlainTime t1 = start.time;
PlainTime t2 = end.time;
if ((delta > 0) && t1.isAfter(t2)) {
delta
} else if ((delta < 0) && t1.isBefore(t2)) {
delta++;
}
}
}
} else if (start.date.isAfter(end.date)) {
delta = -between(end, start);
} else {
long days = start.date.until(end.date, DAYS);
if (days == 0) {
return this.clockUnit.between(start.time, end.time);
} else if (this.clockUnit.compareTo(SECONDS) <= 0) {
// HOURS, MINUTES, SECONDS
delta =
MathUtils.safeAdd(
MathUtils.safeMultiply(days, 86400),
MathUtils.safeSubtract(
end.time.get(SECOND_OF_DAY).longValue(),
start.time.get(SECOND_OF_DAY).longValue()
)
);
if (start.time.getNanosecond() > end.time.getNanosecond()) {
delta
}
} else {
// MILLIS, MICROS, NANOS
delta =
MathUtils.safeAdd(
MathUtils.safeMultiply(days, 86400L * MRD),
MathUtils.safeSubtract(
end.time.get(NANO_OF_DAY).longValue(),
start.time.get(NANO_OF_DAY).longValue()
)
);
}
switch (this.clockUnit) {
case HOURS:
delta = delta / 3600;
break;
case MINUTES:
delta = delta / 60;
break;
case SECONDS:
break;
case MILLIS:
delta = delta / 1000000;
break;
case MICROS:
delta = delta / 1000;
break;
case NANOS:
break;
default:
throw new UnsupportedOperationException(
this.clockUnit.name());
}
}
return delta;
}
}
}
|
package gov.nih.nci.evs.reportwriter.properties;
import gov.nih.nci.evs.reportwriter.utils.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
/**
* @author EVS Team (Kim Ong, David Yee)
* @version 1.0
*/
public class ReportWriterProperties {
public static final String BUILD_INFO = "BUILD_INFO";
public static final String EVS_SERVICE_URL = "EVS_SERVICE_URL";
public static final String MAIL_SMTP_SERVER = "MAIL_SMTP_SERVER";
public static final String DEBUG_ON = "DEBUG_ON";
public static final String REPORT_DOWNLOAD_DIRECTORY = "REPORT_DOWNLOAD_DIRECTORY";
public static final String MAXIMUM_LEVEL = "MAXIMUM_LEVEL";
public static final String MAXIMUM_RETURN = "MAXIMUM_RETURN";
public static final String CSM_LOCKOUT_TIME = "CSM_LOCKOUT_TIME";
public static final String CSM_ALLOWED_LOGIN_TIME = "CSM_ALLOWED_LOGIN_TIME";
public static final String CSM_ALLOWED_ATTEMPTS = "CSM_ALLOWED_ATTEMPTS";
public static final String ACCOUNT_ADMIN_USER_EMAIL = "ACCOUNT_ADMIN_USER_EMAIL";
private static Logger _logger = Logger
.getLogger(ReportWriterProperties.class);
private static ReportWriterProperties _instance;
private Properties _properties = new Properties();
private String _buildInfo = null;
private ReportWriterProperties() {
loadProperties();
}
public static ReportWriterProperties getInstance() {
if (_instance == null) {
synchronized (ReportWriterProperties.class) {
_instance = new ReportWriterProperties();
}
}
return _instance;
}
private void loadProperties() {
try {
String propertyFile = System
.getProperty("gov.nih.nci.cacore.ncireportwriterProperties");
_logger.info("File location= " + propertyFile);
if (propertyFile == null || propertyFile.length() <= 0)
throw new Exception("Property file not set." +
"\n * Property File: " + propertyFile);
FileInputStream fis = new FileInputStream(new File(propertyFile));
_properties.load(fis);
debugProperties();
} catch (Exception e) {
ExceptionUtils.print(_logger, e);
}
}
private String fetchProperty(String key) {
return _properties.getProperty(key);
}
public static String getProperty(String key) {
return getInstance().fetchProperty(key);
}
public static int getIntProperty(String key, int defaultValue) {
String strValue = getInstance().fetchProperty(key);
try {
if (strValue == null)
return defaultValue;
return Integer.parseInt(strValue);
} catch (Exception e) {
_logger.error("Invalid integer property value for: " + key);
_logger.error(" Value from the property file: " + strValue);
_logger.error(" Defaulting to: " + defaultValue);
return defaultValue;
}
}
public static boolean getBoolProperty(String key, boolean defaultValue) {
String strValue = getInstance().fetchProperty(key);
try {
if (strValue == null)
return defaultValue;
return Boolean.parseBoolean(strValue);
} catch (Exception e) {
_logger.error("Invalid boolean property value for: " + key);
_logger.error(" Value from the property file: " + strValue);
_logger.error(" Defaulting to: " + defaultValue);
return defaultValue;
}
}
private void debugProperties() {
if (! _logger.isDebugEnabled())
return;
ArrayList<String> keys = new ArrayList<String>();
Iterator<?> iterator = _properties.keySet().iterator();
while (iterator.hasNext())
keys.add((String) iterator.next());
SortUtils.quickSort(keys);
_logger.debug("List of properties:");
for (int i=0; i<keys.size(); ++i) {
String key = keys.get(i);
String value = _properties.getProperty(key);
_logger.debug(" " + i + ") " + key + ": " + value);
}
}
public String getBuildInfo() {
if (_buildInfo != null)
return _buildInfo;
try {
_buildInfo = getProperty(BUILD_INFO);
if (_buildInfo == null)
_buildInfo = "null";
} catch (Exception e) {
_buildInfo = e.getMessage();
}
_logger.info("getBuildInfo returns " + _buildInfo);
return _buildInfo;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.