javatips.net counter

Java Examples for org.eclipse.draw2d.Graphics

The following java examples will help you to understand the usage of org.eclipse.draw2d.Graphics. These source code samples are taken from different open source projects.

Example 1
Project: Henshin-Editor-master  File: ExportViewerImageAction.java View source code
/**
	 * Returns the bytes of an encoded image for the specified IFigure in the
	 * specified format.
	 * 
	 * @param figure
	 *            the Figure to create an image for.
	 * @param format
	 *            one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE, SWT.IMAGE_GIF
	 *            SWT.IMAGE_ICO, SWT.IMAGE_JPEG, or SWT.IMAGE_PNG
	 * @return the bytes of an encoded image for the specified Figure
	 */
private byte[] createImage(final IFigure figure, final int format) {
    final Device device = viewer.getControl().getDisplay();
    final Rectangle r = figure.getBounds();
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        image = new Image(device, r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        final ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(result, format);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
    }
    return result.toByteArray();
}
Example 2
Project: rap.incubator.gef-master  File: FlyoutPaletteComposite.java View source code
protected void paintFigure(Graphics graphics) {
    // paint the gradient
    graphics.pushState();
    org.eclipse.draw2d.geometry.Rectangle r = org.eclipse.draw2d.geometry.Rectangle.getSINGLETON();
    r.setBounds(getBounds());
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_LIST_BACKGROUND);
    graphics.setBackgroundColor(PaletteColorUtil.WIDGET_BACKGROUND);
    graphics.fillGradient(r, true);
    // draw bottom border
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_NORMAL_SHADOW);
    graphics.drawLine(r.getBottomLeft().getTranslated(0, -1), r.getBottomRight().getTranslated(0, -1));
    graphics.popState();
    // paint the text and icon
    super.paintFigure(graphics);
    // paint the focus rectangle around the text
    if (hasFocus()) {
        org.eclipse.draw2d.geometry.Rectangle textBounds = getTextBounds();
        // We reduce the width by 1 because FigureUtilities grows it by
        // 1 unnecessarily
        textBounds.width--;
        graphics.drawFocus(bounds.getResized(-1, -1).intersect(textBounds.getExpanded(getInsets())));
    }
}
Example 3
Project: Diver-master  File: QuickClearingFigure.java View source code
/**
	 * Paints this Figure's children. The caller must save the state of the graphics prior to
	 * calling this method, such that <code>graphics.restoreState()</code> may be called
	 * safely, and doing so will return the graphics to its original state when the method was
	 * entered.
	 * <P>
	 * This method must leave the Graphics in its original state upon return.
	 * @param graphics the graphics used to paint
	 * @since 2.0
	 */
protected void paintChildren(Graphics graphics) {
    IFigure child;
    Rectangle clip = Rectangle.SINGLETON;
    for (Iterator<IFigure> i = children.iterator(); i.hasNext(); ) {
        child = i.next();
        if (child.isVisible() && child.intersects(graphics.getClip(clip))) {
            graphics.clipRect(child.getBounds());
            child.paint(graphics);
            graphics.restoreState();
        }
    }
}
Example 4
Project: modellipse-master  File: Utils.java View source code
// Debug purpose
public static void drawRect(IGraphicalEditPart editPart, Rectangle refContentArea) {
    RoundedRectangle rectFeedback = new RoundedRectangle();
    rectFeedback.setBounds(refContentArea);
    rectFeedback.setCornerDimensions(new Dimension(0, 0));
    rectFeedback.setLineWidth(2);
    rectFeedback.setLineStyle(Graphics.LINE_DASH);
    rectFeedback.setForegroundColor(editPart.getFigure().getForegroundColor());
    rectFeedback.setOpaque(true);
    rectFeedback.setFill(false);
    IFigure layer = LayerManager.Helper.find(editPart).getLayer(LayerConstants.FEEDBACK_LAYER);
    layer.add(rectFeedback);
}
Example 5
Project: statecharts-master  File: DirectEditManagerEx.java View source code
public void paint(IFigure figure, Graphics graphics, Insets insets) {
    Rectangle rect = getPaintRectangle(figure, insets);
    graphics.setForegroundColor(ColorConstants.white);
    graphics.drawLine(rect.x, rect.y, rect.x, rect.bottom());
    rect.x++;
    rect.width--;
    rect.resize(-1, -1);
    graphics.setForegroundColor(ColorConstants.black);
    graphics.drawLine(rect.x + 2, rect.bottom(), rect.right(), rect.bottom());
    graphics.drawLine(rect.right(), rect.bottom(), rect.right(), rect.y + 2);
    rect.resize(-1, -1);
    graphics.setForegroundColor(BLUE);
    graphics.drawRectangle(rect);
}
Example 6
Project: gmp.graphiti-master  File: PictogramElementDelegate.java View source code
/**
	 * returns null if the decorator does not produce a figure of its own
	 */
private IFigure decorateFigure(IFigure figure, IDecorator decorator) {
    if (decorator == null) {
        return null;
    }
    String messageText = decorator.getMessage();
    // Variable to store an additional figure for the decorator (needed in
    // case of an image decorator. Cannot be created in the if for image
    // decorators, because a shape can have more than one decorator (also of
    // different kinds)
    IFigure decoratorFigure = null;
    org.eclipse.draw2d.geometry.Rectangle boundsForDecoratorFigure = new org.eclipse.draw2d.geometry.Rectangle(0, 0, 16, 16);
    // Decorate with an image
    if (decorator instanceof IImageDecorator) {
        IImageDecorator imageDecorator = (IImageDecorator) decorator;
        org.eclipse.swt.graphics.Image imageForId = GraphitiUi.getImageService().getImageForId(configurationProvider.getDiagramTypeProvider().getProviderId(), imageDecorator.getImageId());
        ImageFigure imageFigure = new DecoratorImageFigure(imageForId);
        decoratorFigure = imageFigure;
        org.eclipse.swt.graphics.Rectangle imageBounds = imageFigure.getImage().getBounds();
        boundsForDecoratorFigure.setSize(imageBounds.width, imageBounds.height);
        if (decorator instanceof ILocation) {
            ILocation location = (ILocation) decorator;
            boundsForDecoratorFigure.setLocation(location.getX(), location.getY());
        }
        IFigure parent = figure.getParent();
        if (parent != null) {
            org.eclipse.draw2d.geometry.Rectangle ownerBounds = (org.eclipse.draw2d.geometry.Rectangle) parent.getLayoutManager().getConstraint(figure);
            boundsForDecoratorFigure.translate(ownerBounds.getLocation());
        }
        decoratorFigure.setVisible(true);
        if (messageText != null && messageText.length() > 0) {
            decoratorFigure.setToolTip(new Label(messageText));
        }
        if (parent.getLayoutManager() == null) {
            parent.setLayoutManager(new XYLayout());
        }
        parent.add(decoratorFigure, boundsForDecoratorFigure, parent.getChildren().indexOf(figure) + 1);
    }
    // Decorate with text
    if (decorator instanceof ITextDecorator) {
        ITextDecorator textDecorator = (ITextDecorator) decorator;
        String text = textDecorator.getText();
        decoratorFigure = new Label(text);
        Font font = new org.eclipse.swt.graphics.Font(null, textDecorator.getFontName(), textDecorator.getFontSize(), SWT.NORMAL);
        decoratorFontList.add(font);
        Dimension dimension = TextUtilities.INSTANCE.getStringExtents(text, font);
        boundsForDecoratorFigure.setSize(dimension.width, dimension.height);
        decoratorFigure.setFont(font);
        IResourceRegistry resourceRegistry = getConfigurationProvider().getResourceRegistry();
        IColorConstant backgroundColor = textDecorator.getBackgroundColor();
        if (backgroundColor != null) {
            decoratorFigure.setOpaque(true);
            decoratorFigure.setBackgroundColor(resourceRegistry.getSwtColor(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue()));
        }
        IColorConstant foregroundColor = textDecorator.getForegroundColor();
        if (foregroundColor != null) {
            decoratorFigure.setForegroundColor(resourceRegistry.getSwtColor(foregroundColor.getRed(), foregroundColor.getGreen(), foregroundColor.getBlue()));
        }
        if (decorator instanceof ILocation) {
            ILocation location = (ILocation) decorator;
            boundsForDecoratorFigure.setLocation(location.getX(), location.getY());
        }
        IFigure parent = figure.getParent();
        if (parent != null) {
            org.eclipse.draw2d.geometry.Rectangle ownerBounds = (org.eclipse.draw2d.geometry.Rectangle) parent.getLayoutManager().getConstraint(figure);
            boundsForDecoratorFigure.translate(ownerBounds.getLocation());
        }
        decoratorFigure.setVisible(true);
        if (messageText != null && messageText.length() > 0) {
            decoratorFigure.setToolTip(new Label(messageText));
        }
        if (parent.getLayoutManager() == null) {
            parent.setLayoutManager(new XYLayout());
        }
        parent.add(decoratorFigure, boundsForDecoratorFigure, parent.getChildren().indexOf(figure) + 1);
    }
    // Decorate the border of the shape
    if (decorator instanceof IBorderDecorator) {
        IBorderDecorator renderingDecorator = ((IBorderDecorator) decorator);
        IResourceRegistry resourceRegistry = getConfigurationProvider().getResourceRegistry();
        // Get the width for the border (or set to default)
        Integer borderWidth = renderingDecorator.getBorderWidth();
        if (borderWidth == null || borderWidth < 1) {
            borderWidth = 1;
        }
        // Get the style for the border (or set to default)
        Integer borderStyle = renderingDecorator.getBorderStyle();
        if (borderStyle == null || (Graphics.LINE_DASH != borderStyle && Graphics.LINE_DASHDOT != borderStyle && Graphics.LINE_DASHDOTDOT != borderStyle && Graphics.LINE_DOT != borderStyle && Graphics.LINE_SOLID != borderStyle)) {
            borderStyle = Graphics.LINE_SOLID;
        }
        // Get the color for the border (or set to default)
        Color borderColor = null;
        IColorConstant colorConstant = renderingDecorator.getBorderColor();
        if (colorConstant == null) {
            colorConstant = IColorConstant.BLACK;
        }
        borderColor = resourceRegistry.getSwtColor(colorConstant.getRed(), colorConstant.getGreen(), colorConstant.getBlue());
        // Apply border decorations
        figure.setBorder(new LineBorder(borderColor, borderWidth, borderStyle));
    }
    // Decorate using the colors of the shape
    if (decorator instanceof IColorDecorator) {
        IColorDecorator renderingDecorator = ((IColorDecorator) decorator);
        IResourceRegistry resourceRegistry = getConfigurationProvider().getResourceRegistry();
        // Get the background color (or set to default)
        Color backgroundColor = null;
        IColorConstant colorConstant = renderingDecorator.getBackgroundColor();
        if (colorConstant != null) {
            backgroundColor = resourceRegistry.getSwtColor(colorConstant.getRed(), colorConstant.getGreen(), colorConstant.getBlue());
        }
        // Get the foreground color (or set to default)
        Color foregroundColor = null;
        colorConstant = renderingDecorator.getForegroundColor();
        if (colorConstant != null) {
            foregroundColor = resourceRegistry.getSwtColor(colorConstant.getRed(), colorConstant.getGreen(), colorConstant.getBlue());
        }
        // Apply color decorations
        if (foregroundColor != null) {
            figure.setForegroundColor(foregroundColor);
        }
        if (backgroundColor != null) {
            figure.setBackgroundColor(backgroundColor);
        }
        if (figure instanceof Shape) {
            ((Shape) figure).setFill(true);
        }
    }
    // Return additionally created figure
    return decoratorFigure;
}
Example 7
Project: xmind-master  File: StyleFigureUtils.java View source code
public static void drawArrow(Graphics graphics, String arrowValue, Point head, Point tail, int lineWidth) {
    Path shape = new Path(Display.getCurrent());
    boolean fill = true;
    double angle = new PrecisionPoint(tail).getAngle(new PrecisionPoint(head));
    if (Styles.ARROW_SHAPE_DIAMOND.equals(arrowValue)) {
        diamondArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_DOT.equals(arrowValue)) {
        dotArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_HERRINGBONE.equals(arrowValue)) {
        herringBone(shape, head, angle, lineWidth);
        fill = false;
    } else if (Styles.ARROW_SHAPE_SPEARHEAD.equals(arrowValue)) {
        spearhead(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_SQUARE.equals(arrowValue)) {
        square(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_TRIANGLE.equals(arrowValue)) {
        triangle(shape, head, angle, lineWidth);
    } else {
        normalArrow(shape, head, angle, lineWidth);
        fill = false;
    }
    Color fgColor = graphics.getForegroundColor();
    if (fgColor != null) {
        if (fill) {
            graphics.setBackgroundColor(fgColor);
            graphics.fillPath(shape);
        }
        graphics.drawPath(shape);
    }
    shape.dispose();
}
Example 8
Project: mobicents-master  File: ExportDrawing.java View source code
////////////////////////////////////////////////////////////
//
// Utilities
//
////////////////////////////////////////////////////////////
/**
     [email protected] draw2DFigure The figure to save
     [email protected] filename The path where the figure must be saved
     */
private void saveFile(IFigure draw2DFigure, final String filename) {
    if (filename != null) {
        try {
            Rectangle rectangle = draw2DFigure.getClientArea();
            System.out.println("Size of client area before : " + rectangle);
            //IFigure copy = copy(draw2DFigure);
            //                VScalableFigure drawing = new VScalableFigure();
            //                drawing.setContent(copy);
            //                drawing.setFactor(4);
            //                drawing.lessZoom();
            //                
            //                rectangle = drawing.getClientArea();
            //                System.out.println("Size of client area after: " + rectangle);
            final Image image = new Image(null, rectangle.width, rectangle.height);
            GC gc = new GC(image);
            Graphics graphics = new SWTGraphics(gc);
            graphics.translate(draw2DFigure.getBounds().getLocation().getNegated());
            draw2DFigure.paint(graphics);
            //                graphics.translate(drawing.getBounds().getLocation().getNegated());
            //                drawing.paint(graphics);
            //                
            graphics.dispose();
            gc.dispose();
            IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
            progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), new IRunnableWithProgress() {

                public void run(IProgressMonitor monitor) {
                    try {
                        monitor.setTaskName("Save image in " + filename);
                        monitor.subTask(" Get image Data ..");
                        ImageData data = image.getImageData();
                        ImageLoader loader = new ImageLoader();
                        monitor.subTask(" Get Load into Image loader ..");
                        loader.data = new ImageData[1];
                        loader.data[0] = data;
                        System.out.println(" data lenght : =" + data.width + "  , " + data.height);
                        monitor.subTask(" Save Image ..");
                        loader.save(filename, SWT.IMAGE_JPEG);
                        monitor.done();
                    } catch (OutOfMemoryError e) {
                        MessageDialog.openError(new Shell(), "SCE-SE Error", " Sorry: an Out of Memory was caugth");
                    }
                }
            }, null);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            MessageDialog.openError(new Shell(), "SCE-SE Error", " Sorry: an Out of Memory was caugth");
        }
    } else {
        MessageDialog.openError(new Shell(), "SCE-SE Error", " The specified file name is not valid ! \n The image wa not saved");
    }
}
Example 9
Project: XFlow-master  File: TableFigure.java View source code
protected void paintFigure(Graphics graphics) {
    super.paintFigure(graphics);
    graphics.setForegroundColor(ColorConstants.gray);
    // ͨ¹ýGraphicsUtil»æÖƽ¥±äÇøÓò
    Point plusPoint = new Point(getLocation().x, getLocation().y);
    Dimension plusDimension = new Dimension(getBounds().getSize().width, 20);
    GraphicsUtil.paintPlusArea(graphics, plusPoint, plusDimension);
    Rectangle bounds = getBounds();
    graphics.drawRectangle(new Rectangle(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1));
    int y = getBounds().y + getBorder().getInsets(this).bottom + this.tableNameLabel.getSize().height;
    graphics.drawLine(getBounds().x, y, getBounds().x + getBounds().width, y);
}
Example 10
Project: xmind-source-master  File: StyleFigureUtils.java View source code
public static void drawArrow(Graphics graphics, String arrowValue, Point head, Point tail, int lineWidth) {
    Path shape = new Path(Display.getCurrent());
    boolean fill = true;
    double angle = new PrecisionPoint(tail).getAngle(new PrecisionPoint(head));
    if (Styles.ARROW_SHAPE_DIAMOND.equals(arrowValue)) {
        diamondArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_DOT.equals(arrowValue)) {
        dotArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_HERRINGBONE.equals(arrowValue)) {
        herringBone(shape, head, angle, lineWidth);
        fill = false;
    } else if (Styles.ARROW_SHAPE_SPEARHEAD.equals(arrowValue)) {
        spearhead(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_SQUARE.equals(arrowValue)) {
        square(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_TRIANGLE.equals(arrowValue)) {
        triangle(shape, head, angle, lineWidth);
    } else {
        normalArrow(shape, head, angle, lineWidth);
        fill = false;
    }
    if (fill) {
        graphics.setBackgroundColor(graphics.getForegroundColor());
        graphics.fillPath(shape);
    }
    graphics.drawPath(shape);
    shape.dispose();
}
Example 11
Project: xmind3-master  File: StyleFigureUtils.java View source code
public static void drawArrow(Graphics graphics, String arrowValue, Point head, Point tail, int lineWidth) {
    Path shape = new Path(Display.getCurrent());
    boolean fill = true;
    double angle = new PrecisionPoint(tail).getAngle(new PrecisionPoint(head));
    if (Styles.ARROW_SHAPE_DIAMOND.equals(arrowValue)) {
        diamondArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_DOT.equals(arrowValue)) {
        dotArrow(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_HERRINGBONE.equals(arrowValue)) {
        herringBone(shape, head, angle, lineWidth);
        fill = false;
    } else if (Styles.ARROW_SHAPE_SPEARHEAD.equals(arrowValue)) {
        spearhead(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_SQUARE.equals(arrowValue)) {
        square(shape, head, angle, lineWidth);
    } else if (Styles.ARROW_SHAPE_TRIANGLE.equals(arrowValue)) {
        triangle(shape, head, angle, lineWidth);
    } else {
        normalArrow(shape, head, angle, lineWidth);
        fill = false;
    }
    if (fill) {
        graphics.setBackgroundColor(graphics.getForegroundColor());
        graphics.fillPath(shape);
    }
    graphics.drawPath(shape);
    shape.dispose();
}
Example 12
Project: gmf-runtime-master  File: PolylineConnectionEx.java View source code
/**
     * Override the figure method "outlineShape" to draw the actual polyline connection shape.
     * Special code to regenerate the jumplinks, draw the polyline smooth, and round the bendpoints
     * is also done during this method call.
     */
protected void outlineShape(Graphics g) {
    PointList displayPoints = getSmoothPoints(false);
    Hashtable<Point, Integer> originalDisplayPoints = null;
    if (isRoundingBendpoints()) {
        // If rounded bendpoints feature is turned on, remember the original points, will be 
        // needed later.        	
        originalDisplayPoints = new Hashtable<Point, Integer>();
        for (int i = 0; i < displayPoints.size(); i++) {
            originalDisplayPoints.put(displayPoints.getPoint(i), new Integer(i));
        }
    }
    int incline = calculateJumpLinkIncline(isFeedbackLayer());
    if (shouldJumpLinks()) {
        regenerateJumpLinks();
        JumpLinkSet pJumpLinkSet = getJumpLinkSet();
        if (pJumpLinkSet != null && pJumpLinkSet.m_pJumpLinks != null) {
            int nSmoothNess = 0;
            if (isJumpLinksSmooth())
                nSmoothNess = JUMPLINK_DEFAULT_SMOOTHNESS;
            boolean bOnBottom = isJumpLinksOnBottom();
            ListIterator linkIter = pJumpLinkSet.m_pJumpLinks.listIterator();
            while (linkIter.hasNext()) {
                JumpLink pJumpLink = (JumpLink) linkIter.next();
                PointList jumpLinkPoints = PointListUtilities.routeAroundPoint(displayPoints, pJumpLink.m_ptIntersect, pJumpLink.m_nHeight, pJumpLink.m_nWidth, nSmoothNess, incline, !bOnBottom);
                if (jumpLinkPoints != null)
                    displayPoints = jumpLinkPoints;
            }
        }
    }
    if (!isRoundingBendpoints()) {
        g.drawPolyline(displayPoints);
        if (origRoundedBendpointsRad > 0) {
            // we unsuccessfully tried to do rounding, allow the next routing to try again.
            roundedBendpointsRadius = origRoundedBendpointsRad;
            origRoundedBendpointsRad = 0;
        }
    } else {
        // In originalDisplayPoints, each bendpoint will be replaced with two points: start and end point of the arc.
        // If jump links is on, then displayPoints will also contain points identifying jump links, if any.
        int i = 1;
        int rDefault = getRoundedBendpointsRadius();
        while (i < displayPoints.size() - 1) {
            // Consider points at indexes i-1, i, i+1.
            int x0 = 0, y0 = 0;
            boolean firstPointAssigned = false;
            if (shouldJumpLinks()) {
                boolean containsPoint2;
                boolean containsPoint3;
                PointList jumpLinkPoints = new PointList();
                do {
                    // First, check if point at index i or i+1 is start point of a jump link (if the point is not in original points).
                    // If so, draw a polyline ending at the last point of the jump link.           				
                    containsPoint2 = true;
                    containsPoint3 = true;
                    if (i < displayPoints.size()) {
                        containsPoint2 = originalDisplayPoints.containsKey(displayPoints.getPoint(i));
                        if (i < displayPoints.size() - 1) {
                            containsPoint3 = originalDisplayPoints.containsKey(displayPoints.getPoint(i + 1));
                        }
                    }
                    if (!containsPoint2 || !containsPoint3) {
                        // start adding jump link points
                        jumpLinkPoints.addPoint(displayPoints.getPoint(i - 1));
                        // next point to be added to jump link points
                        Point p;
                        // index of the next point in jump link
                        int j;
                        if (!containsPoint2) {
                            // jump link starts somewhere on the segment before the arc begins
                            j = i;
                            p = displayPoints.getPoint(i);
                        } else {
                            // jump link starts within an arc; it means that one part of the arc will be replaced with 
                            // a segment between points at i and i-1, and another part is replaced with the jump link,
                            j = i + 1;
                            p = displayPoints.getPoint(i + 1);
                            jumpLinkPoints.addPoint(displayPoints.getPoint(i));
                        }
                        do {
                            jumpLinkPoints.addPoint(p);
                            j++;
                            p = displayPoints.getPoint(j);
                        } while (!originalDisplayPoints.containsKey(p) && j < displayPoints.size() - 1);
                        // Now, check if p is start point of a line segment or an arc. In first case, index of p in 
                        // the original list is even, in second it's odd.
                        int origIndex = ((Integer) originalDisplayPoints.get(p)).intValue();
                        firstPointAssigned = false;
                        if (origIndex % 2 == 0) {
                            // p is start point of a segment, it means that the jump link finished somewhere within the arc,
                            // so one part of the arc is replaced with the jump link, and another will be replaced with a segment.
                            jumpLinkPoints.addPoint(p);
                            i = j + 1;
                        } else {
                            // p is start point of an arc, the last point in jump link polyline becomes the first point for 
                            // the drawing that follows (p could be the last point too)
                            x0 = jumpLinkPoints.getLastPoint().x;
                            y0 = jumpLinkPoints.getLastPoint().y;
                            i = j;
                            firstPointAssigned = true;
                        }
                        // Jump link algorithm sometimes inserts duplicate points, we need to get rid of those.
                        while (i < displayPoints.size() - 1 && displayPoints.getPoint(i).equals(displayPoints.getPoint(i + 1))) {
                            i++;
                        }
                    }
                } while (!containsPoint2 || !containsPoint3);
                if (jumpLinkPoints != null) {
                    // draw jump link
                    g.drawPolyline(jumpLinkPoints);
                }
            }
            if (// if we still didn't reach the end after drawing jump link polyline
            i < displayPoints.size() - 1) {
                // But first, find points at i-1, i and i+1.
                if (!firstPointAssigned) {
                    x0 = displayPoints.getPoint(i - 1).x;
                    y0 = displayPoints.getPoint(i - 1).y;
                }
                int x1;
                ;
                int y1;
                // inserts a point that already exists), just skip the point i        		
                while (i < displayPoints.size() - 1 && x0 == displayPoints.getPoint(i).x && y0 == displayPoints.getPoint(i).y) {
                    i++;
                }
                if (i < displayPoints.size() - 1) {
                    x1 = displayPoints.getPoint(i).x;
                    y1 = displayPoints.getPoint(i).y;
                } else {
                    break;
                }
                // The same goes for point at i and i+1         		
                int x2;
                int y2;
                while (i + 1 < displayPoints.size() - 1 && x1 == displayPoints.getPoint(i + 1).x && y1 == displayPoints.getPoint(i + 1).y) {
                    i++;
                }
                if (i < displayPoints.size() - 1) {
                    x2 = displayPoints.getPoint(i + 1).x;
                    y2 = displayPoints.getPoint(i + 1).y;
                } else {
                    break;
                }
                // Draw the segment
                g.drawLine(x0, y0, x1, y1);
                // Find out if arc size is default, or if it had to be decreased because of lack of space
                int r = rDefault;
                Point p = displayPoints.getPoint(i);
                int origIndex = ((Integer) originalDisplayPoints.get(p)).intValue();
                Object o = rForBendpointArc.get(new Integer((origIndex + 1) / 2));
                if (o != null) {
                    r = ((Integer) o).intValue();
                }
                // Find out the location of enclosing rectangle (x, y), as well as staring angle of the arc.
                int x, y;
                int startAngle;
                if (x0 == x1 && x1 < x2) {
                    x = x1;
                    y = y1 - r;
                    if (y1 > y2) {
                        startAngle = 90;
                    } else {
                        startAngle = 180;
                    }
                } else if (x0 > x1 && x1 > x2) {
                    x = x2;
                    y = y2 - r;
                    if (y1 > y2) {
                        startAngle = 180;
                    } else {
                        startAngle = 90;
                    }
                } else if (x0 == x1 && x1 > x2) {
                    if (y1 > y2) {
                        x = x2 - r;
                        y = y2;
                        startAngle = 0;
                    } else {
                        x = x1 - 2 * r;
                        y = y1 - r;
                        startAngle = 270;
                    }
                } else // x0 < x1 && x1 < x2
                {
                    if (y1 > y2) {
                        x = x2 - 2 * r;
                        y = y2 - r;
                        startAngle = 270;
                    } else {
                        x = x1 - r;
                        y = y1;
                        startAngle = 0;
                    }
                }
                // Draw the arc.
                g.drawArc(x, y, 2 * r, 2 * r, startAngle, 90);
                i += 2;
            }
        }
        // Draw the last segment.
        g.drawLine(displayPoints.getPoint(displayPoints.size() - 2), displayPoints.getLastPoint());
    }
}
Example 13
Project: rce-master  File: WorkflowNodePart.java View source code
@Override
public void paintFigure(Graphics graphics) {
    int offsetX;
    int offsetY;
    if (ci.getShape() == ComponentShape.CIRCLE) {
        offsetX = OFFSET_SMALL_CIRCLE_COMPONENT_ICON;
        offsetY = OFFSET_SMALL_CIRCLE_COMPONENT_ICON;
        graphics.fillOval(this.getBounds());
        graphics.setAntialias(SWT.ON);
        Rectangle b = this.getBounds().getCopy();
        b.width--;
        b.height--;
        graphics.drawOval(b);
        graphics.setAntialias(SWT.OFF);
    } else {
        offsetX = OFFSET_SMALL_SQUARE_COMPONENT_ICON_X;
        offsetY = OFFSET_SMALL_SQUARE_COMPONENT_ICON_Y;
        graphics.fillRectangle(this.getBounds());
        Rectangle b = this.getBounds().getCopy();
        b.width--;
        b.height--;
        graphics.drawRectangle(b);
    }
    graphics.drawImage(icon, new Point(this.getLocation().x + offsetX, this.getLocation().y - 1 + offsetY));
}
Example 14
Project: webtools.jsf-master  File: CSSBlockFlowLayout.java View source code
/**
	 * when the "overflow" is "scroll", we need to paint the scrollbar
	 */
public void paintFigurePostClientArea(Graphics g) {
    ICSSStyle style = this.getCSSStyle();
    if (style != null) {
        Object overflow = style.getStyleProperty(ICSSPropertyID.ATTR_OVERFLOW);
        if (ICSSPropertyID.VAL_SCROLL.equals(overflow) || ICSSPropertyID.VAL_AUTO.equals(overflow)) {
            if (this._needHScroll || this._needVScroll) {
                // as this is using localCoordinate, so translate to
                // relative to left/up corder of whole
                // blockbox.
                g.translate(-_blockBox.getBorderPaddingInsets().left, -_blockBox.getBorderPaddingInsets().top);
                Rectangle rect = new Rectangle(0, 0, _blockBox.getWidth(), _blockBox.getHeight());
                rect.crop(_blockBox.getBorderInsets());
                if (this._needHScroll && this._needVScroll) {
                    BorderUtil.drawScrollBar(g, BorderUtil.SCROLL_WIDTH, rect, BorderUtil.BOTH);
                } else if (this._needHScroll) {
                    BorderUtil.drawScrollBar(g, BorderUtil.SCROLL_WIDTH, rect, BorderUtil.HORIZONTAL_BAR);
                } else if (this._needVScroll) {
                    BorderUtil.drawScrollBar(g, BorderUtil.SCROLL_WIDTH, rect, BorderUtil.VERTICAL_BAR);
                }
            }
        }
    }
}
Example 15
Project: windowtester-master  File: Connection.java View source code
/**
 * Returns the lineStyle as String for the Property Sheet
 * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java.lang.Object)
 */
public Object getPropertyValue(Object id) {
    if (id.equals(LINESTYLE_PROP)) {
        if (getLineStyle() == Graphics.LINE_DASH)
            // Dashed is the second value in the combo dropdown
            return new Integer(1);
        // Solid is the first value in the combo dropdown
        return new Integer(0);
    }
    return super.getPropertyValue(id);
}
Example 16
Project: CertWare-master  File: LayoutUtil.java View source code
/**
	 * Moves the label to the center of the figure.
	 * @param label label
	 * @param parent parent figure for dimensions
	 * @param graphics graphics for font metrics
	 */
public static void moveToCenter(WrappingLabel label, Figure parent, Graphics graphics) {
    Rectangle r = parent.getBounds();
    Rectangle newLabelBounds = new Rectangle();
    Point middle = new Point(r.x + r.width / 2, r.y + r.height / 2);
    int textWidth = (label.getText().length() + 2) * graphics.getFontMetrics().getAverageCharWidth();
    int textHeight = graphics.getFontMetrics().getHeight();
    newLabelBounds.x = middle.x - textWidth / 2;
    newLabelBounds.y = middle.y - textHeight / 2;
    newLabelBounds.width = textWidth;
    newLabelBounds.height = textHeight;
    // use as much space as possible to enable wrapped text to display
    /*
		Rectangle clientArea = parent.getClientArea();
		newLabelBounds.x = middle.x - textWidth/2;
		newLabelBounds.y = middle.y - textHeight/2;
		newLabelBounds.width = textWidth;
		newLabelBounds.height = clientArea.height;
		*/
    label.setBounds(newLabelBounds);
}
Example 17
Project: dawn-isenciaui-master  File: DirectorFigure.java View source code
protected void fillShape(Graphics graphics) {
    graphics.pushState();
    graphics.setForegroundColor(ColorConstants.white);
    graphics.setBackgroundColor(getBackgroundColor());
    final Rectangle bounds = getBounds();
    graphics.fillGradient(bounds.x + 1, bounds.y + 1, bounds.width - 2, bounds.height - 2, false);
    graphics.popState();
}
Example 18
Project: ermaster-b-master  File: Activator.java View source code
public void run() {
    GC figureCanvasGC = null;
    GC imageGC = null;
    try {
        ScalableFreeformRootEditPart rootEditPart = (ScalableFreeformRootEditPart) viewer.getRootEditPart();
        rootEditPart.refresh();
        IFigure rootFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);
        EditPart editPart = viewer.getContents();
        editPart.refresh();
        ERDiagram diagram = (ERDiagram) editPart.getModel();
        Rectangle rootFigureBounds = ExportToImageAction.getBounds(diagram, rootEditPart, rootFigure.getBounds());
        Control figureCanvas = viewer.getControl();
        figureCanvasGC = new GC(figureCanvas);
        img = new Image(Display.getCurrent(), rootFigureBounds.width + 20, rootFigureBounds.height + 20);
        imageGC = new GC(img);
        imageGC.setBackground(figureCanvasGC.getBackground());
        imageGC.setForeground(figureCanvasGC.getForeground());
        imageGC.setFont(figureCanvasGC.getFont());
        imageGC.setLineStyle(figureCanvasGC.getLineStyle());
        imageGC.setLineWidth(figureCanvasGC.getLineWidth());
        imageGC.setAntialias(SWT.OFF);
        // imageGC.setInterpolation(SWT.HIGH);
        Graphics imgGraphics = new SWTGraphics(imageGC);
        imgGraphics.setBackgroundColor(figureCanvas.getBackground());
        imgGraphics.fillRectangle(0, 0, rootFigureBounds.width + 20, rootFigureBounds.height + 20);
        imgGraphics.translate(ExportToImageAction.translateX(rootFigureBounds.x), ExportToImageAction.translateY(rootFigureBounds.y));
        rootFigure.paint(imgGraphics);
    } finally {
        if (figureCanvasGC != null) {
            figureCanvasGC.dispose();
        }
        if (imageGC != null) {
            imageGC.dispose();
        }
    }
}
Example 19
Project: FRaMED-master  File: ShadowRoundedRectangle.java View source code
/**
   * @see Shape#outlineShape(Graphics)
   */
protected void outlineShape(final Graphics graphics) {
    final Rectangle f = Rectangle.SINGLETON.setBounds(getBounds());
    final Insets shadowInset = new Insets(lineWidth / 2, lineWidth / 2, lineWidth + SHADOW_INSET, lineWidth + SHADOW_INSET);
    f.crop(shadowInset);
    graphics.drawRoundRectangle(f, Math.max(0, corner.width - SHADOW_INSET), Math.max(0, corner.height - SHADOW_INSET));
}
Example 20
Project: gmf-tooling-master  File: OrganizeImportsPostprocessorTest.java View source code
public void testFullQualifiedArrays() throws Exception {
    String testClassName = "FullQualifiedArrays";
    List<Class<?>> typeRefs = Arrays.asList(new Class<?>[] { ArrayList.class, List.class, Map.class, Map.Entry.class });
    final String[] conflictedTypeNames = new String[] { "javax.some.Map" };
    final List<String> typeNameRefs = new ArrayList<String>(typeRefs.size() + conflictedTypeNames.length);
    for (Class<?> next : typeRefs) {
        typeNameRefs.add(getInnerClassAwareName(next));
    }
    String localVariable = typeNameRefs.get(2) + ".SMTH.ourEntries";
    //String localVariable2 = "org.eclipse.draw2d.Graphics";
    typeNameRefs.add(localVariable);
    //typeNameRefs.add(localVariable2);
    typeNameRefs.addAll(Arrays.asList(conflictedTypeNames));
    StringBuffer buf = new StringBuffer();
    buf.append("import ").append(typeNameRefs.get(0)).append(";").append(nl);
    buf.append(nl);
    buf.append("public class ").append(testClassName).append(" {").append(nl);
    buf.append(nl);
    buf.append("    private ").append(typeNameRefs.get(1)).append("[] list;").append(nl);
    buf.append("    private ").append(typeNameRefs.get(2)).append("[] entry = new ").append(typeNameRefs.get(4)).append("[0];").append(nl);
    buf.append("    private ").append(typeNameRefs.get(3)).append("[] maps;").append(nl);
    buf.append("    private ").append(typeRefs.get(0).getSimpleName()).append("[] arrayLists;").append(nl);
    buf.append("    private ").append(typeNameRefs.get(5)).append(" conflictEntry;").append(nl);
    buf.append("    private int style = setLineStyle(").append(localVariable).append(".LINE_DASH);");
    buf.append(nl);
    buf.append("    private static int setLineStyle(int style) {");
    buf.append("        return 0;");
    buf.append("    }");
    buf.append(nl);
    buf.append("}").append(nl);
    ICompilationUnit icu = JavaProjectHelper.createJavaFile(testClassName + ".java", buf.toString());
    new OrganizeImportsPostprocessor().organizeImports(icu, null);
    icu.save(null, true);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(icu);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    List imports = cu.imports();
    assertEquals("Failed to generate enough import statements: " + imports, typeRefs.size(), imports.size());
    for (int i = 0; i < imports.size(); i++) {
        String nextImport = ((ImportDeclaration) imports.get(i)).getName().getFullyQualifiedName();
        assertEquals("Unexpected import found", typeNameRefs.get(i), nextImport);
    }
    cu.accept(new ASTVisitor() {

        public boolean visit(FieldDeclaration node) {
            node.getType().accept(new ExpectedSimpleNamesVisitor(typeNameRefs) {

                public boolean visit(QualifiedName node) {
                    assertEquals("Unexpected full-qualified name found!", conflictedTypeNames[0], node.getFullyQualifiedName());
                    return false;
                }
            });
            return super.visit(node);
        }
    });
    assertEquals("Failed to leave unqualified only 1 reference", conflictedTypeNames.length, typeNameRefs.size() - 1);
}
Example 21
Project: jbosstools-base-master  File: GEFLabel.java View source code
protected void paintFigure(Graphics graphics) {
    Rectangle bounds = getBounds();
    graphics.translate(bounds.x, bounds.y);
    if (graphics.getForegroundColor().equals(normalColor))
        graphics.setForegroundColor(ColorConstants.black);
    if (getIcon() != null)
        graphics.drawImage(getIcon(), getIconLocation());
    graphics.drawText(getSubStringText(), getTextLocation());
    graphics.translate(-bounds.x, -bounds.y);
}
Example 22
Project: KompicsIDE-master  File: TestLabel.java View source code
@Override
protected void paintFigure(Graphics g) {
    super.paintFigure(g);
    Rectangle r = getTextBounds();
    r.resize(-1, -1);
    r.expand(1, 1);
    r.width -= 1;
    r.x -= 2;
    // Top line
    g.drawLine(r.x, r.y, r.right(), r.y);
    // Bottom line
    g.drawLine(r.x, r.bottom(), r.right(), r.bottom());
    // left line
    g.drawLine(r.x, r.bottom(), r.x, r.y);
    g.drawLine(r.right() + 7, r.y + r.height / 2, r.right(), r.y);
    g.drawLine(r.right() + 7, r.y + r.height / 2, r.right(), r.bottom());
}
Example 23
Project: limpet-master  File: JFreeChartFigure.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    super.paintFigure(graphics);
    Rectangle clientArea = getClientArea();
    JFreeChart freeChart = ChartBuilder.build(chart);
    BufferedImage image = freeChart.createBufferedImage(clientArea.width, clientArea.height);
    Image srcImage = new Image(Display.getCurrent(), convertToSWT(image));
    graphics.drawImage(srcImage, clientArea.x, clientArea.y);
    srcImage.dispose();
}
Example 24
Project: org.openscada.dakara-master  File: ScalableLayeredPane.java View source code
/**
     * @see org.eclipse.draw2d.Figure#paintClientArea(Graphics)
     */
@Override
protected void paintClientArea(final Graphics graphics) {
    if (getChildren().isEmpty()) {
        return;
    }
    if (this.scale == 1.0) {
        super.paintClientArea(graphics);
    } else {
        final ScaledGraphics g = new ScaledGraphics(graphics);
        final boolean optimizeClip = getBorder() == null || getBorder().isOpaque();
        if (!optimizeClip) {
            g.clipRect(getBounds().getCropped(getInsets()));
        }
        g.scale(this.scale);
        g.pushState();
        paintChildren(g);
        g.dispose();
        graphics.restoreState();
    }
}
Example 25
Project: swtbot-master  File: LEDFigure.java View source code
/**
 * @see org.eclipse.draw2d.Figure#paintFigure(Graphics)
 */
protected void paintFigure(Graphics g) {
    Rectangle r = getBounds().getCopy();
    g.translate(r.getLocation());
    g.setBackgroundColor(LogicColorConstants.logicGreen);
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.fillRectangle(0, 2, r.width, r.height - 4);
    int right = r.width - 1;
    g.drawLine(0, Y1, right, Y1);
    g.drawLine(0, Y1, 0, Y2);
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.drawLine(0, Y2, right, Y2);
    g.drawLine(right, Y1, right, Y2);
    // Draw the gaps for the connectors
    g.setForegroundColor(ColorConstants.listBackground);
    for (int i = 0; i < 4; i++) {
        g.drawLine(GAP_CENTERS_X[i] - 2, Y1, GAP_CENTERS_X[i] + 3, Y1);
        g.drawLine(GAP_CENTERS_X[i] - 2, Y2, GAP_CENTERS_X[i] + 3, Y2);
    }
    // Draw the connectors
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.setBackgroundColor(LogicColorConstants.connectorGreen);
    for (int i = 0; i < 4; i++) {
        connector.translate(GAP_CENTERS_X[i], 0);
        g.fillPolygon(connector);
        g.drawPolygon(connector);
        connector.translate(-GAP_CENTERS_X[i], 0);
        bottomConnector.translate(GAP_CENTERS_X[i], r.height - 1);
        g.fillPolygon(bottomConnector);
        g.drawPolygon(bottomConnector);
        bottomConnector.translate(-GAP_CENTERS_X[i], -r.height + 1);
    }
    // Draw the display
    g.setBackgroundColor(LogicColorConstants.logicHighlight);
    g.fillRectangle(displayHighlight);
    g.setBackgroundColor(DISPLAY_SHADOW);
    g.fillRectangle(displayShadow);
    g.setBackgroundColor(ColorConstants.black);
    g.fillRectangle(displayRectangle);
    // Draw the value
    g.setFont(DISPLAY_FONT);
    g.setForegroundColor(DISPLAY_TEXT);
    g.drawText(value, valuePoint);
}
Example 26
Project: swtbot-original-master  File: LEDFigure.java View source code
/**
 * @see org.eclipse.draw2d.Figure#paintFigure(Graphics)
 */
protected void paintFigure(Graphics g) {
    Rectangle r = getBounds().getCopy();
    g.translate(r.getLocation());
    g.setBackgroundColor(LogicColorConstants.logicGreen);
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.fillRectangle(0, 2, r.width, r.height - 4);
    int right = r.width - 1;
    g.drawLine(0, Y1, right, Y1);
    g.drawLine(0, Y1, 0, Y2);
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.drawLine(0, Y2, right, Y2);
    g.drawLine(right, Y1, right, Y2);
    // Draw the gaps for the connectors
    g.setForegroundColor(ColorConstants.listBackground);
    for (int i = 0; i < 4; i++) {
        g.drawLine(GAP_CENTERS_X[i] - 2, Y1, GAP_CENTERS_X[i] + 3, Y1);
        g.drawLine(GAP_CENTERS_X[i] - 2, Y2, GAP_CENTERS_X[i] + 3, Y2);
    }
    // Draw the connectors
    g.setForegroundColor(LogicColorConstants.connectorGreen);
    g.setBackgroundColor(LogicColorConstants.connectorGreen);
    for (int i = 0; i < 4; i++) {
        connector.translate(GAP_CENTERS_X[i], 0);
        g.fillPolygon(connector);
        g.drawPolygon(connector);
        connector.translate(-GAP_CENTERS_X[i], 0);
        bottomConnector.translate(GAP_CENTERS_X[i], r.height - 1);
        g.fillPolygon(bottomConnector);
        g.drawPolygon(bottomConnector);
        bottomConnector.translate(-GAP_CENTERS_X[i], -r.height + 1);
    }
    // Draw the display
    g.setBackgroundColor(LogicColorConstants.logicHighlight);
    g.fillRectangle(displayHighlight);
    g.setBackgroundColor(DISPLAY_SHADOW);
    g.fillRectangle(displayShadow);
    g.setBackgroundColor(ColorConstants.black);
    g.fillRectangle(displayRectangle);
    // Draw the value
    g.setFont(DISPLAY_FONT);
    g.setForegroundColor(DISPLAY_TEXT);
    g.drawText(value, valuePoint);
}
Example 27
Project: teiid-designer-master  File: SummaryExtentFigure.java View source code
@Override
protected void paintOutline(Graphics graphics) {
    //        System.out.println("[SummaryExtentFigure.paintOutline] TOP " );
    PointList pts = extentOutline.getPoints();
    //      System.out.println("\n[SummaryExtentFigure.paintOutline] Label size: " + numberLabel.getBounds() );
    //      System.out.println("[SummaryExtentFigure.paintOutline] SE Figure size: " + this.getBounds() );
    //      if ( getSomeMappingClassesAreVisible() == true ) {
    //          System.out.println("[SummaryExtentFigure.paintOutline] Should be Pointed Face - " + createDisplayString() );
    //          System.out.println("[SummaryExtentFigure.paintOutline] SE Figure size: " + this.getBounds() );
    //          System.out.println("[SummaryExtentFigure.paintOutline] pts.getPoint(2): " + pts.getPoint(2) );
    //      } else {
    //          System.out.println("[SummaryExtentFigure.paintOutline] Should be Flat Face - " + createDisplayString() );
    //          System.out.println("[SummaryExtentFigure.paintOutline] SE Figure size: " + this.getBounds() );
    //          System.out.println("[SummaryExtentFigure.paintOutline] pts.getPoint(2): " + pts.getPoint(2) );
    //      }
    int orgX = this.getBounds().x;
    int orgY = this.getBounds().y;
    //        System.out.println("[SummaryExtentFigure.paintOutline]  point list size: " + pts.size() );            
    graphics.setLineWidth(1);
    graphics.setForegroundColor(ColorConstants.buttonDarkest);
    //        System.out.println("[SummaryExtentFigure.paintOutline] About to call first drawLine " );
    graphics.drawLine(orgX + pts.getPoint(0).x, orgY + pts.getPoint(0).y + 1, orgX + pts.getPoint(1).x, orgY + pts.getPoint(1).y + 1);
    graphics.drawLine(orgX + pts.getPoint(1).x, orgY + pts.getPoint(1).y, orgX + pts.getPoint(2).x - 1, orgY + pts.getPoint(2).y);
    graphics.setForegroundColor(ColorConstants.buttonDarkest);
    graphics.drawLine(orgX + pts.getPoint(2).x - 1, orgY + pts.getPoint(2).y, orgX + pts.getPoint(3).x, orgY + pts.getPoint(3).y - 2);
    graphics.drawLine(orgX + pts.getPoint(3).x, orgY + pts.getPoint(3).y - 2, orgX + pts.getPoint(4).x, orgY + pts.getPoint(4).y - 2);
    //        System.out.println("[SummaryExtentFigure.paintOutline] After calling drawLine 4 x" );
    // jh experiment:
    graphics.drawLine(orgX + pts.getPoint(4).x, orgY + pts.getPoint(4).y - 2, orgX + pts.getPoint(5).x, orgY + pts.getPoint(5).y - 2);
//        System.out.println("[SummaryExtentFigure.paintOutline] BOT " );
}
Example 28
Project: gef-gwt-master  File: FlyoutPaletteComposite.java View source code
protected void paintFigure(Graphics graphics) {
    // paint the gradient
    graphics.pushState();
    org.eclipse.draw2d.geometry.Rectangle r = org.eclipse.draw2d.geometry.Rectangle.SINGLETON;
    r.setBounds(getBounds());
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_LIST_BACKGROUND);
    graphics.setBackgroundColor(PaletteColorUtil.WIDGET_BACKGROUND);
    graphics.fillGradient(r, true);
    // draw bottom border
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_NORMAL_SHADOW);
    graphics.drawLine(r.getBottomLeft().getTranslated(0, -1), r.getBottomRight().getTranslated(0, -1));
    graphics.popState();
    // paint the text and icon
    super.paintFigure(graphics);
    // paint the focus rectangle around the text
    if (hasFocus()) {
        org.eclipse.draw2d.geometry.Rectangle textBounds = getTextBounds();
        // We reduce the width by 1 because FigureUtilities grows it by
        // 1 unnecessarily
        textBounds.width--;
        graphics.drawFocus(bounds.getResized(-1, -1).intersect(textBounds.getExpanded(getInsets())));
    }
}
Example 29
Project: savara-tools-eclipse-master  File: GenerateImageAction.java View source code
private void saveEditorContentsAsImage(IEditorPart editorPart, GraphicalViewer viewer, String saveFilePath, int format) {
    /* 1. First get the figure whose visuals we want to save as image.
		 * So we would like to save the rooteditpart which actually hosts all the printable layers.
		 * 
		 * NOTE: ScalableRootEditPart manages layers and is registered graphicalviewer's editpartregistry with
		 * the key LayerManager.ID ... well that is because ScalableRootEditPart manages all layers that
		 * are hosted on a FigureCanvas. Many layers exist for doing different things */
    //ScalableRootEditPart rootEditPart = (ScalableRootEditPart)viewer.getEditPartRegistry().get(LayerManager.ID);
    org.eclipse.gef.editparts.LayerManager lm = (org.eclipse.gef.editparts.LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID);
    IFigure rootFigure = lm.getLayer(LayerConstants.PRINTABLE_LAYERS);
    Rectangle rootFigureBounds = null;
    Rectangle additionalBounds = null;
    java.util.List children = null;
    if (lm instanceof org.eclipse.gef.RootEditPart) {
        org.eclipse.gef.EditPart ep = ((org.eclipse.gef.RootEditPart) lm).getContents();
        if (ep instanceof ScenarioEditPart) {
            children = ep.getChildren();
            rootFigureBounds = ((ScenarioEditPart) ep).getComponentBoundsWithoutIdentityDetails();
            additionalBounds = ((ScenarioEditPart) ep).getIdentityDetailsBounds();
        }
    }
    if (rootFigureBounds == null) {
        rootFigureBounds = rootFigure.getBounds();
    }
    /* 2. Now we want to get the GC associated with the control on which all figures are
		 * painted by SWTGraphics. For that first get the SWT Control associated with the viewer on which the
		 * rooteditpart is set as contents */
    Control figureCanvas = viewer.getControl();
    GC figureCanvasGC = new GC(figureCanvas);
    /* 3. Create a new Graphics for an Image onto which we want to paint rootFigure */
    Image img = new Image(null, rootFigureBounds.width, rootFigureBounds.height);
    GC imageGC = new GC(img);
    imageGC.setBackground(figureCanvasGC.getBackground());
    imageGC.setForeground(figureCanvasGC.getForeground());
    imageGC.setFont(figureCanvasGC.getFont());
    imageGC.setLineStyle(figureCanvasGC.getLineStyle());
    imageGC.setLineWidth(figureCanvasGC.getLineWidth());
    imageGC.setXORMode(figureCanvasGC.getXORMode());
    Graphics imgGraphics = new SWTGraphics(imageGC);
    /* 4. Draw rootFigure onto image. After that image will be ready for save */
    rootFigure.paint(imgGraphics);
    /* 5. Save image */
    ImageData[] imgData = new ImageData[1];
    imgData[0] = img.getImageData();
    ImageLoader imgLoader = new ImageLoader();
    imgLoader.data = imgData;
    imgLoader.save(saveFilePath, format);
    /* release OS resources */
    imageGC.dispose();
    img.dispose();
    if (additionalBounds != null && additionalBounds.width > 0 && additionalBounds.height > 0) {
        /* 3. Create a new Graphics for an Image onto which we want to paint rootFigure */
        int width = additionalBounds.width;
        if (rootFigureBounds.width > width) {
            width = rootFigureBounds.width;
        }
        img = new Image(null, width, rootFigureBounds.height + additionalBounds.height);
        imageGC = new GC(img);
        imageGC.setBackground(figureCanvasGC.getBackground());
        imageGC.setForeground(figureCanvasGC.getForeground());
        imageGC.setFont(figureCanvasGC.getFont());
        imageGC.setLineStyle(figureCanvasGC.getLineStyle());
        imageGC.setLineWidth(figureCanvasGC.getLineWidth());
        imageGC.setXORMode(figureCanvasGC.getXORMode());
        imgGraphics = new SWTGraphics(imageGC);
        /* 4. Draw rootFigure onto image. After that image will be ready for save */
        rootFigure.paint(imgGraphics);
        Image copy = new Image(null, additionalBounds.width, additionalBounds.height);
        imageGC.copyArea(copy, 0, rootFigureBounds.height);
        StringBuffer filepath = new StringBuffer();
        filepath.append(saveFilePath);
        int ind = saveFilePath.lastIndexOf('.');
        if (ind != -1) {
            filepath.insert(ind, "-ids");
        } else {
            filepath.append("-ids");
        }
        /* 5. Save image */
        imgData = new ImageData[1];
        imgData[0] = copy.getImageData();
        imgLoader = new ImageLoader();
        imgLoader.data = imgData;
        imgLoader.save(filepath.toString(), format);
        /* release OS resources */
        figureCanvasGC.dispose();
        imageGC.dispose();
        img.dispose();
        copy.dispose();
    // Write message link information in tabular form
    //saveMessageLinkTable(editorPart, filepath.toString(), children);
    }
    figureCanvasGC.dispose();
}
Example 30
Project: spring-ide-master  File: GraphEditor.java View source code
/**
	 * Returns the bytes of an encoded image from this viewer.
	 * @param format one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE, SWT.IMAGE_GIF SWT.IMAGE_ICO, SWT.IMAGE_JPEG or
	 * SWT.IMAGE_PNG
	 * @return the bytes of an encoded image for the specified viewer
	 */
public byte[] createImage(int format) {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Device device = getGraphicalViewer().getControl().getDisplay();
    LayerManager lm = (LayerManager) getGraphicalViewer().getEditPartRegistry().get(LayerManager.ID);
    IFigure figure = lm.getLayer(LayerConstants.PRINTABLE_LAYERS);
    Rectangle r = figure.getClientArea();
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        image = new Image(device, r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(result, format);
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
    }
    return result.toByteArray();
}
Example 31
Project: ssSKB-master  File: FlyoutPaletteComposite.java View source code
protected void paintFigure(Graphics graphics) {
    // paint the gradient
    graphics.pushState();
    org.eclipse.draw2d.geometry.Rectangle r = org.eclipse.draw2d.geometry.Rectangle.SINGLETON;
    r.setBounds(getBounds());
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_LIST_BACKGROUND);
    graphics.setBackgroundColor(PaletteColorUtil.WIDGET_BACKGROUND);
    graphics.fillGradient(r, true);
    // draw bottom border
    graphics.setForegroundColor(PaletteColorUtil.WIDGET_NORMAL_SHADOW);
    graphics.drawLine(r.getBottomLeft().getTranslated(0, -1), r.getBottomRight().getTranslated(0, -1));
    graphics.popState();
    // paint the text and icon
    super.paintFigure(graphics);
    // paint the focus rectangle around the text
    if (hasFocus()) {
        org.eclipse.draw2d.geometry.Rectangle textBounds = getTextBounds();
        // We reduce the width by 1 because FigureUtilities grows it by 1 unnecessarily
        textBounds.width--;
        graphics.drawFocus(bounds.getResized(-1, -1).intersect(textBounds.getExpanded(getInsets())));
    }
}
Example 32
Project: starschema-talend-plugins-master  File: AbstractTalendEditor.java View source code
/**
     * Save the outline picture for this editor.
     * 
     * @param viewer
     */
protected void saveOutlinePicture(ScrollingGraphicalViewer viewer) {
    GlobalConstant.generatingScreenShoot = true;
    LayerManager layerManager = (LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID);
    // save image using swt
    // get root figure
    IFigure backgroundLayer = layerManager.getLayer(LayerConstants.GRID_LAYER);
    IFigure contentLayer = layerManager.getLayer(LayerConstants.PRINTABLE_LAYERS);
    // create image from root figure
    int width = contentLayer.getSize().width;
    int height = contentLayer.getSize().height;
    Image img = new Image(null, width, height);
    GC gc = new GC(img);
    Graphics graphics = new SWTGraphics(gc);
    Point point = contentLayer.getBounds().getTopLeft();
    graphics.translate(-point.x, -point.y);
    IProcess2 process = getProcess();
    process.setPropertyValue(IProcess.SCREEN_OFFSET_X, String.valueOf(-point.x));
    process.setPropertyValue(IProcess.SCREEN_OFFSET_Y, String.valueOf(-point.y));
    backgroundLayer.paint(graphics);
    contentLayer.paint(graphics);
    graphics.dispose();
    gc.dispose();
    process.setScreenshot(ImageUtils.saveImageToData(img));
    img.dispose();
    // service.getProxyRepositoryFactory().refreshJobPictureFolder(outlinePicturePath);
    GlobalConstant.generatingScreenShoot = false;
}
Example 33
Project: iee-master  File: ChartFigure.java View source code
@Override
protected void paintClientArea(Graphics graphics) {
    // first determine the size of the chart rendering area...
    // TODO workout insets for SWT
    org.eclipse.draw2d.geometry.Rectangle available = getBounds();
    // skip if chart is null
    if (this.chart == null) {
        graphics.drawRectangle(available.x, available.y, available.width, available.height);
        return;
    }
    // work out if scaling is required...
    int drawWidth = available.width;
    int drawHeight = available.height;
    if (drawWidth == 0.0 || drawHeight == 0.0)
        return;
    this.scaleX = 1.0;
    this.scaleY = 1.0;
    if (drawWidth < this.minimumDrawWidth) {
        this.scaleX = (double) drawWidth / this.minimumDrawWidth;
        drawWidth = this.minimumDrawWidth;
    } else if (drawWidth > this.maximumDrawWidth) {
        this.scaleX = (double) drawWidth / this.maximumDrawWidth;
        drawWidth = this.maximumDrawWidth;
    }
    if (drawHeight < this.minimumDrawHeight) {
        this.scaleY = (double) drawHeight / this.minimumDrawHeight;
        drawHeight = this.minimumDrawHeight;
    } else if (drawHeight > this.maximumDrawHeight) {
        this.scaleY = (double) drawHeight / this.maximumDrawHeight;
        drawHeight = this.maximumDrawHeight;
    }
    org.eclipse.draw2d.geometry.Rectangle bounds = getBounds();
    graphics.translate(bounds.x, bounds.y);
    renderer.prepareRendering(graphics);
    Graphics2D graphics2d = renderer.getGraphics2D();
    this.chart.draw(graphics2d, new Rectangle2D.Double(0, 0, bounds.width, bounds.height), getAnchor(), this.info);
    renderer.render(graphics);
    graphics.translate(-bounds.x, -bounds.y);
    Rectangle area = getScreenDataArea();
    if (this.horizontalAxisTrace && area.x < this.verticalTraceLineX && area.x + area.width > this.verticalTraceLineX) {
        graphics.drawLine(this.verticalTraceLineX, area.y, this.verticalTraceLineX, area.y + area.height);
    }
    if (this.verticalAxisTrace && area.y < this.horizontalTraceLineY && area.y + area.height > this.horizontalTraceLineY) {
        graphics.drawLine(area.x, this.horizontalTraceLineY, area.x + area.width, this.horizontalTraceLineY);
    }
    this.verticalTraceLineX = 0;
    this.horizontalTraceLineY = 0;
    if (this.zoomRectangle != null) {
        graphics.drawRectangle(this.zoomRectangle);
    }
}
Example 34
Project: monticore-master  File: ImageSaveUtil.java View source code
private static void saveEditorContentsAsImage(IEditorPart editorPart, GraphicalViewer viewer, String saveFilePath, int format) {
    /*
     * 1. First get the figure whose visuals we want to save as image. So we
     * would like to save the rooteditpart which actually hosts all the
     * printable layers. NOTE: ScalableRootEditPart manages layers and is
     * registered graphicalviewer's editpartregistry with the key
     * LayerManager.ID ... well that is because ScalableRootEditPart manages all
     * layers that are hosted on a FigureCanvas. Many layers exist for doing
     * different things
     */
    ScalableRootEditPart rootEditPart = (ScalableRootEditPart) viewer.getEditPartRegistry().get(LayerManager.ID);
    // rootEditPart.getFigure();
    IFigure rootFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);
    Rectangle rootFigureBounds = rootFigure.getBounds();
    /*
     * 2. Now we want to get the GC associated with the control on which all
     * figures are painted by SWTGraphics. For that first get the SWT Control
     * associated with the viewer on which the rooteditpart is set as contents
     */
    Control figureCanvas = viewer.getControl();
    GC figureCanvasGC = new GC(figureCanvas);
    /*
     * 3. Create a new Graphics for an Image onto which we want to paint
     * rootFigure
     */
    Image img = new Image(null, rootFigureBounds.width, rootFigureBounds.height);
    GC imageGC = new GC(img);
    imageGC.setBackground(figureCanvasGC.getBackground());
    imageGC.setForeground(figureCanvasGC.getForeground());
    imageGC.setFont(figureCanvasGC.getFont());
    imageGC.setLineStyle(figureCanvasGC.getLineStyle());
    imageGC.setLineWidth(figureCanvasGC.getLineWidth());
    // imageGC.setXORMode(figureCanvasGC.getXORMode());
    Graphics imgGraphics = new SWTGraphics(imageGC);
    /* 4. Draw rootFigure onto image. After that image will be ready for save */
    rootFigure.paint(imgGraphics);
    /* 5. Save image */
    ImageData[] imgData = new ImageData[1];
    imgData[0] = img.getImageData();
    ImageLoader imgLoader = new ImageLoader();
    imgLoader.data = imgData;
    imgLoader.save(saveFilePath, format);
    /* release OS resources */
    figureCanvasGC.dispose();
    imageGC.dispose();
    img.dispose();
}
Example 35
Project: petals-studio-master  File: ExportDiagramAction.java View source code
/*
	 * (non-Jsdoc)
	 * @see org.eclipse.jface.action.Action
	 * #run()
	 */
@Override
public void run() {
    // Determine the export location
    FileDialog dlg = new FileDialog(new Shell(), SWT.SAVE);
    dlg.setText("Image Export");
    dlg.setOverwrite(true);
    dlg.setFilterNames(new String[] { "JPEG Files (*.jpg)", "PNG Files (*.png)", "GIF Files (*.gif)" });
    String[] extensions = new String[] { "*.jpg", "*.png", "*.gif" };
    dlg.setFilterExtensions(extensions);
    String path = dlg.open();
    if (path != null) {
        String ext = extensions[dlg.getFilterIndex()].substring(1);
        if (!path.endsWith(ext))
            path += ext;
        // Only print printable layers
        ScalableFreeformRootEditPart rootEditPart = (ScalableFreeformRootEditPart) this.graphicalViewer.getEditPartRegistry().get(LayerManager.ID);
        IFigure rootFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);
        IFigure eipChainFigure = null;
        for (Object o : rootFigure.getChildren()) {
            if (o instanceof FreeformLayer)
                eipChainFigure = (FreeformLayer) o;
        }
        Rectangle bounds = eipChainFigure == null ? rootFigure.getBounds() : eipChainFigure.getBounds();
        GC figureCanvasGC = new GC(this.graphicalViewer.getControl());
        // Add 20 pixels to write the title of the diagram on the image
        Image img = new Image(null, bounds.width, bounds.height);
        GC gc = new GC(img);
        gc.setBackground(figureCanvasGC.getBackground());
        gc.setForeground(figureCanvasGC.getForeground());
        gc.setFont(figureCanvasGC.getFont());
        gc.setLineStyle(figureCanvasGC.getLineStyle());
        gc.setLineWidth(figureCanvasGC.getLineWidth());
        Graphics imgGraphics = new SWTGraphics(gc);
        // Paint it...
        rootFigure.paint(imgGraphics);
        // Prepare the next step
        Font font = new Font(Display.getCurrent(), "Arial", 14, SWT.BOLD);
        gc.setFont(font);
        int height = Dialog.convertHeightInCharsToPixels(gc.getFontMetrics(), 1);
        gc.dispose();
        // Create a second image with the title and diagram version
        // Write the title and its border
        bounds.height += height + (height % 2 == 0 ? 6 : 7);
        // Add a border + some margin
        bounds.height += 3 * BORDER_MARGIN_UPDOWN + 2;
        // Add a border
        bounds.width += 2 * BORDER_MARGIN_SIDES + 2;
        Image finalImg = new Image(null, bounds.width, bounds.height);
        gc = new GC(finalImg);
        // Draw a surrounding border
        gc.setAntialias(SWT.ON);
        gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
        gc.drawLine(BORDER_MARGIN_SIDES, BORDER_MARGIN_UPDOWN, BORDER_MARGIN_SIDES, bounds.height - BORDER_MARGIN_UPDOWN);
        gc.drawLine(BORDER_MARGIN_SIDES, bounds.height - BORDER_MARGIN_UPDOWN, bounds.width - BORDER_MARGIN_SIDES, bounds.height - BORDER_MARGIN_UPDOWN);
        gc.drawLine(BORDER_MARGIN_SIDES, BORDER_MARGIN_UPDOWN, bounds.width - BORDER_MARGIN_SIDES, BORDER_MARGIN_UPDOWN);
        gc.drawLine(bounds.width - BORDER_MARGIN_SIDES, BORDER_MARGIN_UPDOWN, bounds.width - BORDER_MARGIN_SIDES, bounds.height - BORDER_MARGIN_UPDOWN);
        // Draw the title
        gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
        gc.setFont(font);
        gc.setClipping((Region) null);
        gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
        String title = this.eipChain.getTitle() != null ? this.eipChain.getTitle() : "No diagram title";
        if (!StringUtils.isEmpty(this.eipChain.getVersion()))
            title += " - Version " + this.eipChain.getVersion().trim();
        int width = Dialog.convertWidthInCharsToPixels(gc.getFontMetrics(), title.length());
        if (width > bounds.width) {
            title = Dialog.shortenText(title, this.graphicalViewer.getControl());
            width = Dialog.convertWidthInCharsToPixels(gc.getFontMetrics(), title.length());
        }
        gc.drawText(title, 6 + BORDER_MARGIN_SIDES, 4 + BORDER_MARGIN_UPDOWN, true);
        // Draw a surrounding shape for the title
        gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
        Rectangle titleRectangle = new Rectangle(BORDER_MARGIN_SIDES, BORDER_MARGIN_UPDOWN, BORDER_MARGIN_SIDES + width + (width % 2 == 0 ? 10 : 11), BORDER_MARGIN_UPDOWN + height + (height % 2 == 0 ? 6 : 7));
        final int arrowPadding = (titleRectangle.height + bounds.y) / 2;
        gc.drawLine(titleRectangle.x, titleRectangle.height, titleRectangle.width, titleRectangle.height);
        gc.drawLine(titleRectangle.width, titleRectangle.y, titleRectangle.width + arrowPadding, arrowPadding);
        gc.drawLine(titleRectangle.width, titleRectangle.height, titleRectangle.width + arrowPadding, arrowPadding);
        // Draw the image
        gc.drawImage(img, BORDER_MARGIN_SIDES + 1, BORDER_MARGIN_UPDOWN + titleRectangle.height + 1);
        // Save the second image
        ImageData[] imgData = new ImageData[1];
        imgData[0] = finalImg.getImageData();
        int format;
        String tail = path.toLowerCase().substring(path.length() - 4);
        if (tail.endsWith(".jpg"))
            format = SWT.IMAGE_JPEG;
        else if (tail.endsWith(".png"))
            format = SWT.IMAGE_PNG;
        else
            format = SWT.IMAGE_GIF;
        ImageLoader imgLoader = new ImageLoader();
        imgLoader.data = imgData;
        imgLoader.save(path, format);
        // Dispose everything
        figureCanvasGC.dispose();
        gc.dispose();
        img.dispose();
        finalImg.dispose();
        font.dispose();
    }
}
Example 36
Project: ASEME-master  File: HyperlinkFigure.java View source code
protected void paintFigure(Graphics graphics) {
    Color color = graphics.getForegroundColor();
    if (action.isEnabled()) {
        graphics.setForegroundColor(ColorConstants.blue);
    } else {
        graphics.setForegroundColor(ColorConstants.gray);
    }
    super.paintFigure(graphics);
    if (underlined) {
        Rectangle bounds = getBounds();
        int y = bounds.y + bounds.height - 1;
        graphics.drawLine(bounds.x, y, bounds.x + bounds.width, y);
    }
    graphics.setForegroundColor(color);
}
Example 37
Project: bpel-master  File: ProcessEditPart.java View source code
public void switchLayout(boolean horizontal) {
    AlignedFlowLayout handlerLayout = (AlignedFlowLayout) handlerHolder.getLayoutManager();
    handlerLayout.setHorizontal(!horizontal);
    // Adjust the layout of the activityAndHandlerHolder
    ((AlignedFlowLayout) activityAndHandlerHolder.getLayoutManager()).setHorizontal(horizontal);
    // Adjust the layout of the activityHolder
    ((AlignedFlowLayout) activityHolder.getLayoutManager()).setHorizontal(horizontal);
    // Remove the LayoutPolicy which is responsible for creating the implicit links
    removeEditPolicy(EditPolicy.LAYOUT_ROLE);
    if (horizontal) {
        // Handler Holder layout
        handlerLayout.setSecondaryAlignment(AlignedFlowLayout.ALIGN_BEGIN);
        // If we are in horizontal mode we add a top margin 
        activityAndHandlerHolder.setBorder(new MarginBorder(20, 20, 0, 20));
        this.handlerHolder.setBorder(new MarginBorder(0, 20, 0, 0));
        installEditPolicy(EditPolicy.LAYOUT_ROLE, new ProcessOrderedHorizontalLayoutEditPolicy());
    } else {
        // Handler Holder layout
        handlerLayout.setSecondaryAlignment(AlignedFlowLayout.ALIGN_BEGIN);
        // If we are in horizontal mode we remove the border 
        activityAndHandlerHolder.setBorder(null);
        this.handlerHolder.setBorder(new AbstractBorder() {

            public Insets getInsets(IFigure arg0) {
                return new Insets(20, 0, 10, 0);
            }

            public void paint(IFigure arg0, Graphics arg1, Insets arg2) {
            }
        });
        installEditPolicy(EditPolicy.LAYOUT_ROLE, new ProcessOrderedLayoutEditPolicy());
    }
}
Example 38
Project: EPF-Composer-master  File: WrappableLabel.java View source code
/**
	 * @see Figure#paintFigure(Graphics)
	 */
protected void paintFigure(Graphics graphics) {
    if (isSelected()) {
        graphics.pushState();
        graphics.setBackgroundColor(ColorConstants.menuBackgroundSelected);
        graphics.fillRectangle(getSelectionRectangle());
        graphics.popState();
        graphics.setForegroundColor(ColorConstants.white);
    }
    if (hasFocus()) {
        graphics.pushState();
        graphics.setXORMode(true);
        graphics.setForegroundColor(ColorConstants.menuBackgroundSelected);
        graphics.setBackgroundColor(ColorConstants.white);
        graphics.drawFocus(getSelectionRectangle().resize(-1, -1));
        graphics.popState();
    }
    if (isOpaque())
        super.paintFigure(graphics);
    Rectangle bounds = getBounds();
    graphics.translate(bounds.x, bounds.y);
    if (icon != null)
        graphics.drawImage(icon, getIconLocation());
    if (!isEnabled()) {
        graphics.translate(1, 1);
        graphics.setForegroundColor(ColorConstants.buttonLightest);
        graphicsdrawText(graphics);
        graphics.drawText(getSubStringText(), getTextLocation());
        graphics.translate(-1, -1);
        graphics.setForegroundColor(ColorConstants.buttonDarker);
    }
    graphicsdrawText(graphics);
    graphics.translate(-bounds.x, -bounds.y);
}
Example 39
Project: gda-dal-master  File: AbstractChartFigure.java View source code
@Override
protected void draw(final Graphics g, final Point p) {
    //    #
    //   ###
    //  #####
    //   ###
    //    #
    // Note: the call to drawPolygon is required because otherwise
    // for some reason the polygon drawn by fillPolygon is a bit
    // too small (the right edge is drawn one pixel to the left).
    g.drawPolygon(new int[] { p.x - 2, p.y, p.x, p.y - 2, p.x + 2, p.y, p.x, p.y + 2 });
    g.fillPolygon(new int[] { p.x - 2, p.y, p.x, p.y - 2, p.x + 2, p.y, p.x, p.y + 2 });
}
Example 40
Project: gmf-tooling.uml2tools-master  File: CollaborationUse2EditPart.java View source code
/**
		 * @NOT-generated
		 */
@Override
public void paintFigure(Graphics graphics) {
    Rectangle r = getBounds().getCopy();
    double a = r.width / 2;
    double b = r.height / 2;
    double sin45 = Math.sqrt(2) / 2;
    double cos45 = sin45;
    double diagx = a * sin45;
    double diagy = b * cos45;
    int newxmargin = (int) (a - diagx);
    int newymargin = (int) (b - diagy);
    if (newxmargin != myXMargin || newymargin != myYMargin) {
        myXMargin = newxmargin;
        myYMargin = newymargin;
        setBorder(new MarginBorder(myYMargin, myXMargin, myYMargin, myXMargin));
    }
    super.paintFigure(graphics);
}
Example 41
Project: javadude-master  File: DependencyEditPart.java View source code
@Override
protected void refreshVisuals() {
    Dependency dependency = (Dependency) getModel();
    if (!dependency.isExported()) {
        ((PolylineConnection) getFigure()).setLineStyle(Graphics.LINE_DOT);
        lineColor = DependencyEditPart.PINK;
    }
    if (DependencyManager.indirectPathExists(dependency, dependency.getSource(), dependency.getTarget())) {
        lineColor = DependencyEditPart.WHITE;
    }
    figure.setForegroundColor(DependenciesPlugin.getDefault().getColor(lineColor));
}
Example 42
Project: jbosstools-hibernate-master  File: ExportImageAction.java View source code
/***
	 * Returns the bytes of an encoded image for the specified
	 * IFigure in the specified format.
	 *
	 * @param figure the Figure to create an image for.
	 * @param format one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE, SWT.IMAGE_GIF
	 *          SWT.IMAGE_ICO, SWT.IMAGE_JPEG, or SWT.IMAGE_PNG
	 * @return the bytes of an encoded image for the specified Figure
	 */
private byte[] createImage(IFigure figure, int format) {
    //Device device = getDiagramViewer().getEditPartViewer().getControl()
    //		.getDisplay();
    Device device = null;
    Rectangle r = figure.getBounds();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        image = new Image(device, r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(result, format);
    } catch (Throwable e) {
        HibernateConsolePlugin.getDefault().logErrorMessage("ExportImageAction - save:", e);
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
    }
    return result.toByteArray();
}
Example 43
Project: jbosstools-javaee-master  File: JSFEditor.java View source code
public void run() {
    GraphicalViewer viewer;
    viewer = (GraphicalViewer) getWorkbenchPart().getAdapter(GraphicalViewer.class);
    PrintPreviewDialog d = new PrintPreviewDialog(this.getWorkbenchPart().getSite().getShell(), SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
    d.setPrintViewer(viewer);
    d.setEditor(JSFEditor.this);
    Printer printer = new Printer();
    Exception ex = null;
    try {
        printer.getDPI();
    } catch (SWTException ee) {
        ex = ee;
        printer.dispose();
        d = null;
        Status status = new Status(IStatus.ERROR, "org.jboss.tools.jsf.ui", 0, WizardKeys.getString("PRN_ERROR"), ee);
        LogHelper.logError(JsfUiPlugin.PLUGIN_ID, ee);
    }
    //if ex is not null then d is set to null and we cannot access it.
    if (ex == null) {
        d.setPages(new Pages(viewer, new PageFormat(printer, this.getWorkbenchPart().getSite().getShell().getDisplay())));
        String result = d.open();
        if (//$NON-NLS-1$
        result != null && result.equals("ok")) {
            LayerManager lm = (LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID);
            IFigure figure = lm.getLayer(LayerConstants.PRINTABLE_LAYERS);
            PrintDialog dialog = new PrintDialog(viewer.getControl().getShell(), SWT.NULL);
            PrinterData data = dialog.open();
            if (data != null) {
                printer = new Printer(data);
                double scale = d.getPages().getScale();
                double dpiScale = printer.getDPI().x / Display.getCurrent().getDPI().x;
                GC printerGC = new GC(printer);
                SWTGraphics g = new SWTGraphics(printerGC);
                Graphics graphics = new PrinterGraphics(g, printer);
                if (printer.startJob(getWorkbenchPart().getTitle())) {
                    Pages p = d.getPages();
                    for (int i = 0; i < p.getNumberOfPages(); i++) {
                        if (printer.startPage()) {
                            graphics.pushState();
                            Page pg = p.getPrintable(i);
                            Rectangle r1 = pg.getRectangle();
                            Rectangle r = new Rectangle(r1.x + p.ix, r1.y + p.iy, r1.width, r1.height);
                            org.eclipse.draw2d.geometry.Rectangle clipRect = new org.eclipse.draw2d.geometry.Rectangle();
                            graphics.translate(-(int) (r.x * dpiScale * scale), -(int) (r.y * dpiScale * scale));
                            graphics.getClip(clipRect);
                            clipRect.setLocation((int) (r.x * dpiScale * scale), (int) (r.y * dpiScale * scale));
                            graphics.clipRect(clipRect);
                            graphics.scale(dpiScale * scale);
                            figure.paint(graphics);
                            graphics.popState();
                            printer.endPage();
                        }
                    }
                    graphics.dispose();
                    printer.endJob();
                }
            }
        }
    }
}
Example 44
Project: jbosstools-jbpm-master  File: NodeFigure.java View source code
protected void paintBorder(Graphics graphics) {
    Rectangle bounds = getBounds().getCopy();
    Point origin = bounds.getLocation();
    int height = bounds.height;
    int width = bounds.width;
    graphics.translate(origin);
    graphics.setForegroundColor(ColorConstants.lightGray);
    graphics.drawLine(0, 0, width - 2, 0);
    graphics.drawLine(width - 2, 0, width - 2, height - 2);
    graphics.drawLine(width - 2, height - 2, 0, height - 2);
    graphics.drawLine(0, height - 2, 0, 0);
    graphics.setForegroundColor(Constants.veryLightGray);
    graphics.drawLine(width - 1, 1, width - 1, height - 1);
    graphics.drawLine(width - 1, height - 1, 1, height - 1);
}
Example 45
Project: melanee-core-master  File: CustomBorder.java View source code
/**
	 * @see org.eclipse.draw2d.Border#paint(IFigure, Graphics, Insets)
	 */
public void paint(IFigure figure, Graphics graphics, Insets insets) {
    tempRect.setBounds(getPaintRectangle(figure, insets));
    if (getWidth() % 2 == 1) {
        tempRect.width--;
        tempRect.height--;
    }
    tempRect.shrink(getWidth() / 2, getWidth() / 2);
    graphics.setLineWidth(getWidth());
    graphics.setLineStyle(getStyle());
    if (getColor() != null)
        graphics.setForegroundColor(getColor());
    graphics.setForegroundColor(PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_BLACK));
    if (bottom)
        graphics.drawLine(tempRect.getBottomLeft(), tempRect.getBottomRight());
    if (top)
        graphics.drawLine(tempRect.getTopLeft(), tempRect.getTopRight());
    if (left)
        graphics.drawLine(tempRect.getTopLeft(), tempRect.getBottomLeft());
    if (right)
        graphics.drawLine(tempRect.getTopRight(), tempRect.getBottomRight());
}
Example 46
Project: MMI-master  File: TaskFigure.java View source code
@Override
public void paint(Graphics graphics) {
    Rectangle r = getBounds();
    // Define the points of a diamond
    Point p1 = new Point(r.x, r.y + r.height / 2);
    Point p2 = new Point(r.x + r.width / 4, r.y + r.height - 1);
    Point p3 = new Point(r.x + r.width / 4 + r.width / 2, r.y + r.height - 1);
    Point p4 = new Point(r.x + r.width - 1, r.y + r.height / 2);
    Point p5 = new Point(r.x + r.width / 4 + r.width / 2, r.y);
    Point p6 = new Point(r.x + r.width / 4, r.y);
    PointList pointList = new PointList();
    pointList.addPoint(p1);
    pointList.addPoint(p2);
    pointList.addPoint(p3);
    pointList.addPoint(p4);
    pointList.addPoint(p5);
    pointList.addPoint(p6);
    // Fill the shape
    graphics.fillPolygon(pointList);
    graphics.setLineWidth(1);
    // Draw the outline
    graphics.drawLine(p1, p2);
    graphics.drawLine(p2, p3);
    graphics.drawLine(p3, p4);
    graphics.drawLine(p4, p5);
    graphics.drawLine(p5, p6);
    graphics.drawLine(p6, p1);
    for (int i = 0; i < getChildren().size(); i++) {
        WrappingLabel label = (WrappingLabel) getChildren().get(i);
        label.paint(graphics);
    }
}
Example 47
Project: MMINT-master  File: TaskFigure.java View source code
@Override
public void paint(Graphics graphics) {
    Rectangle r = getBounds();
    // Define the points of a diamond
    Point p1 = new Point(r.x, r.y + r.height / 2);
    Point p2 = new Point(r.x + r.width / 4, r.y + r.height - 1);
    Point p3 = new Point(r.x + r.width / 4 + r.width / 2, r.y + r.height - 1);
    Point p4 = new Point(r.x + r.width - 1, r.y + r.height / 2);
    Point p5 = new Point(r.x + r.width / 4 + r.width / 2, r.y);
    Point p6 = new Point(r.x + r.width / 4, r.y);
    PointList pointList = new PointList();
    pointList.addPoint(p1);
    pointList.addPoint(p2);
    pointList.addPoint(p3);
    pointList.addPoint(p4);
    pointList.addPoint(p5);
    pointList.addPoint(p6);
    // Fill the shape
    graphics.fillPolygon(pointList);
    graphics.setLineWidth(1);
    // Draw the outline
    graphics.drawLine(p1, p2);
    graphics.drawLine(p2, p3);
    graphics.drawLine(p3, p4);
    graphics.drawLine(p4, p5);
    graphics.drawLine(p5, p6);
    graphics.drawLine(p6, p1);
    for (int i = 0; i < getChildren().size(); i++) {
        WrappingLabel label = (WrappingLabel) getChildren().get(i);
        label.paint(graphics);
    }
}
Example 48
Project: nebula-master  File: Trace.java View source code
private void drawErrorBar(Graphics graphics, Point dpPos, ISample dp) {
    graphics.pushState();
    graphics.setForegroundColor(errorBarColor);
    graphics.setLineStyle(SWTConstants.LINE_SOLID);
    graphics.setLineWidth(1);
    Point ep;
    switch(yErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() - dp.getYMinusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            if (yErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() + dp.getYPlusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            break;
        default:
            break;
    }
    switch(xErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() - dp.getXMinusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            if (xErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() + dp.getXPlusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            break;
        default:
            break;
    }
    graphics.popState();
}
Example 49
Project: olca-app-master  File: ProcessFigure.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    graphics.pushState();
    graphics.setBackgroundColor(ColorConstants.white);
    graphics.fillRectangle(new Rectangle(getLocation(), getSize()));
    paintTop(graphics);
    if (!node.isMinimized() || Animation.isRunning())
        paintTable(graphics);
    graphics.popState();
    super.paintFigure(graphics);
}
Example 50
Project: org.eclipse.bpel-master  File: ProcessEditPart.java View source code
public void switchLayout(boolean horizontal) {
    AlignedFlowLayout handlerLayout = (AlignedFlowLayout) handlerHolder.getLayoutManager();
    handlerLayout.setHorizontal(!horizontal);
    // Adjust the layout of the activityAndHandlerHolder
    ((AlignedFlowLayout) activityAndHandlerHolder.getLayoutManager()).setHorizontal(horizontal);
    // Adjust the layout of the activityHolder
    ((AlignedFlowLayout) activityHolder.getLayoutManager()).setHorizontal(horizontal);
    // Remove the LayoutPolicy which is responsible for creating the implicit links
    removeEditPolicy(EditPolicy.LAYOUT_ROLE);
    if (horizontal) {
        // Handler Holder layout
        handlerLayout.setSecondaryAlignment(AlignedFlowLayout.ALIGN_BEGIN);
        // If we are in horizontal mode we add a top margin 
        activityAndHandlerHolder.setBorder(new MarginBorder(20, 20, 0, 20));
        this.handlerHolder.setBorder(new MarginBorder(0, 20, 0, 0));
        installEditPolicy(EditPolicy.LAYOUT_ROLE, new ProcessOrderedHorizontalLayoutEditPolicy());
    } else {
        // Handler Holder layout
        handlerLayout.setSecondaryAlignment(AlignedFlowLayout.ALIGN_BEGIN);
        // If we are in horizontal mode we remove the border 
        activityAndHandlerHolder.setBorder(null);
        this.handlerHolder.setBorder(new AbstractBorder() {

            public Insets getInsets(IFigure arg0) {
                return new Insets(20, 0, 10, 0);
            }

            public void paint(IFigure arg0, Graphics arg1, Insets arg2) {
            }
        });
        installEditPolicy(EditPolicy.LAYOUT_ROLE, new ProcessOrderedLayoutEditPolicy());
    }
}
Example 51
Project: Reuseware-master  File: PortInstanceEditPart.java View source code
private void setColors(IFigure shape) {
    setBackgroundColor(ColorConstants.white);
    if (!(shape instanceof PortInstanceFigure)) {
        return;
    }
    PortInstanceFigure figure = (PortInstanceFigure) shape;
    PortInstance port = (PortInstance) ((Node) getModel()).getElement();
    if (port.canContribute()) {
        figure.setForegroundColor(ColorConstants.black);
        figure.setLineStyle(Graphics.LINE_SOLID);
    } else if (port.canReceive()) {
        figure.setForegroundColor(ColorConstants.black);
        figure.setLineStyle(Graphics.LINE_SOLID);
    } else /*configuring*/
    {
        figure.setForegroundColor(ColorConstants.black);
        figure.setLineStyle(Graphics.LINE_DOT);
    }
    if (port.port() == null) {
        figure.setForegroundColor(ColorConstants.darkGray);
    }
}
Example 52
Project: sapphire-master  File: ContextButtonPad.java View source code
// ============================== painting ================================
/**
	 * Outlines this Shape on the given Graphics. This will draw the paths
	 * [email protected] #pathInnerLine}, [email protected] #pathMiddleLine} and
	 * [email protected] #pathOuterLine}.
	 * 
	 * @param graphics
	 *            The Graphics on which to outline this Shape.
	 */
@Override
protected void outlineShape(Graphics graphics) {
    int lw = (int) (getZoomLevel() * getDeclaration().getPadLineWidth());
    graphics.setLineWidth(lw);
    graphics.setForegroundColor(getEditor().getResourceCache().getColor(getDeclaration().getPadInnerLineColor()));
    graphics.drawPath(pathInnerLine);
    graphics.setForegroundColor(getEditor().getResourceCache().getColor(getDeclaration().getPadMiddleLineColor()));
    graphics.drawPath(pathMiddleLine);
    graphics.setForegroundColor(getEditor().getResourceCache().getColor(getDeclaration().getPadOuterLineColor()));
    graphics.drawPath(pathOuterLine);
}
Example 53
Project: smooks-editor-master  File: FreemarkerCSVNodeEditPart.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.jboss.tools.smooks.gef.tree.editparts.TreeNodeEditPart#createFigure()
	 */
@Override
protected IFigure createFigure() {
    CSVNodeModel node = (CSVNodeModel) ((AbstractSmooksGraphicalModel) getModel()).getData();
    if (node.isRecord()) {
        IFigure figure = new TreeNodeFigure((TreeNodeModel) getModel()) {

            /*
				 * (non-Javadoc)
				 * 
				 * @see
				 * org.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#initFigure
				 * ()
				 */
            @Override
            protected void initFigure() {
                super.initFigure();
                SPACE_INT = 0;
                CLICKNODE_HEIGHT = 0;
                CLICKNODE_WIDTH = 0;
                expand = true;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * getPreferredSize(int, int)
				 */
            @Override
            public Dimension getPreferredSize(int hint, int hint2) {
                expand = true;
                return super.getPreferredSize(hint, hint2);
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * createLabelContainerLayout()
				 */
            @Override
            protected LayoutManager createLabelContainerLayout() {
                ToolbarLayout tl = new ToolbarLayout();
                tl.setVertical(false);
                tl.setMinorAlignment(ToolbarLayout.ALIGN_BOTTOMRIGHT);
                return tl;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * drawClickFigure(org.eclipse.draw2d.IFigure,
				 * org.eclipse.draw2d.Graphics)
				 */
            @Override
            protected void drawClickFigure(IFigure clickFigure, Graphics graphics) {
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * needClickFigure()
				 */
            @Override
            protected boolean needClickFigure() {
                Object data = this.getModel().getData();
                if (data instanceof CSVNodeModel) {
                    if (((CSVNodeModel) data).isRecord()) {
                        return true;
                    }
                }
                return false;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * needSpaceFigure()
				 */
            @Override
            protected boolean needSpaceFigure() {
                Object data = this.getModel().getData();
                if (data instanceof CSVNodeModel) {
                    if (((CSVNodeModel) data).isRecord()) {
                        return true;
                    }
                }
                return false;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * createContentFigureLayout()
				 */
            @Override
            protected ToolbarLayout createContentFigureLayout() {
                ToolbarLayout layout = super.createContentFigureLayout();
                layout.setVertical(true);
                return layout;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * createTreeNodeFigureLayout()
				 */
            @Override
            protected ToolbarLayout createTreeNodeFigureLayout() {
                ToolbarLayout layout = super.createTreeNodeFigureLayout();
                // layout.setSpacing(5);
                layout.setMinorAlignment(ToolbarLayout.ALIGN_CENTER);
                return layout;
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @seeorg.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#
				 * collapsedNode()
				 */
            @Override
            public void collapsedNode() {
            }

            /*
				 * (non-Javadoc)
				 * 
				 * @see
				 * org.jboss.tools.smooks.gef.tree.figures.TreeNodeFigure#expandNode
				 * ()
				 */
            @Override
            public void expandNode() {
            }
        };
        return figure;
    }
    return super.createFigure();
}
Example 54
Project: snaker-designer-master  File: FieldBorder.java View source code
public void paint(IFigure figure, Graphics graphics, Insets insets) {
    Rectangle bounds = figure.getBounds();
    Rectangle r = new Rectangle(bounds.x, bounds.y, this.grabBarWidth, bounds.height);
    AbstractBorder.tempRect.setBounds(r);
    graphics.setBackgroundColor(ColorUtils.Blue);
    graphics.setForegroundColor(ColorUtils.xorGate);
    graphics.fillRectangle(AbstractBorder.tempRect);
    figure.setOpaque(false);
    int i = AbstractBorder.tempRect.bottom() - AbstractBorder.tempRect.height / 2;
    graphics.drawText(getText(), AbstractBorder.tempRect.x + this.BLANK_SPACES, i - this.WORD_HEIGHT);
    super.paint(figure, graphics, insets);
}
Example 55
Project: webtools.sourceediting-master  File: TopLevelComponentEditPart.java View source code
public void paint(Graphics graphics) {
    super.paint(graphics);
    if (hasFocus) {
        try {
            graphics.pushState();
            Rectangle r = getBounds();
            graphics.setXORMode(true);
            graphics.drawFocus(r.x, r.y + 1, r.width - 1, r.height - 2);
        } finally {
            graphics.popState();
        }
    }
}
Example 56
Project: whole-master  File: FramesPartFactoryVisitor.java View source code
@Override
public void visit(EntityType entity) {
    part = new EntityTypePart() {

        public IFigure createFigure() {
            IFigure f = super.createFigure();
            f.setBorder(new RoundBracketsBorder() {

                @Override
                protected void setBracketsStyle(Graphics g) {
                    g.setForegroundColor(FigureConstants.contentLighterColor);
                }
            });
            return f;
        }
    };
}
Example 57
Project: antlr-ide-master  File: AntlrDFAViewer.java View source code
public void exportAsImage(File file, int format) {
    IFigure figure = graph.getContents();
    Rectangle r = figure.getBounds();
    OutputStream out = null;
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        image = new Image(getControl().getDisplay(), r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(out, SWT.IMAGE_PNG);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 58
Project: bundlemaker-master  File: DsmViewWidget.java View source code
/**
   * <p>
   * Initializes the [email protected] DsmViewWidget}.
   * </p>
   */
private void init() {
    LightweightSystem lws = new LightweightSystem(this);
    //
    DsmViewWidgetMouseMotionListener motionListener = new DsmViewWidgetMouseMotionListener(this);
    //
    this.addMouseWheelListener(new MouseWheelListener() {

        @Override
        public void mouseScrolled(org.eclipse.swt.events.MouseEvent e) {
            if (e.count > 0) {
                DsmViewWidget.this.setZoom(getZoom() * 1.05f);
            } else if (e.count < 0) {
                DsmViewWidget.this.setZoom(getZoom() * 0.95f);
            }
        }
    });
    //
    // this.addMouseMoveListener(new MyMouseMoveListener(this));
    _mainFigure = new Figure() {

        @Override
        public void paint(Graphics graphics) {
            super.paint(graphics);
            if (_drawToolTip && _x >= _verticalFigureWidth && _y >= _horizontalFigureHeight) {
                graphics.fillRectangle(_x, _y, 100, 100);
                graphics.drawRectangle(_x, _y, 100, 100);
            }
        }
    };
    _mainFigure.setLayoutManager(new XYLayout());
    _mainFigure.addMouseMotionListener(motionListener);
    lws.setContents(_mainFigure);
    _colorScheme = new DefaultMatrixColorScheme();
    _matrixFigure = new Matrix(_dsmContentProvider, _dependencyLabelProvider, _colorScheme);
    _matrixFigure.addMouseMotionListener(motionListener);
    _matrixFigure.addMouseListener(motionListener);
    _zoomableScrollpane = new ZoomableScrollPane(_matrixFigure, ScrollPane.ALWAYS, ScrollPane.ALWAYS);
    _verticalListFigure = new VerticalSideMarker(_dsmContentProvider, _artifactLabelProvider, _colorScheme);
    _verticalListFigure.addMouseMotionListener(motionListener);
    _zoomableScrollpaneVerticalBar = new ZoomableScrollPane(_verticalListFigure, ScrollPane.NEVER, ScrollPane.NEVER);
    _horizontalListFigure = new HorizontalSideMarker(_dsmContentProvider, _artifactLabelProvider, _colorScheme);
    _horizontalListFigure.addMouseMotionListener(motionListener);
    _zoomableScrollpaneHorizontalBar = new ZoomableScrollPane(_horizontalListFigure, ScrollPane.NEVER, ScrollPane.NEVER);
    _matrixFigure.addMouseMotionListener(new MouseMotionListener.Stub() {

        /**
       * [email protected]}
       */
        @Override
        public void mouseExited(org.eclipse.draw2d.MouseEvent me) {
            _drawToolTip = false;
        }
    });
    _matrixFigure.addMatrixListener(new IMatrixListener() {

        @Override
        public void toolTip(MatrixEvent event) {
            _drawToolTip = true;
            _mainFigure.repaint();
        }

        @Override
        public void singleClick(MatrixEvent event) {
            _drawToolTip = false;
            _mainFigure.repaint();
        }

        @Override
        public void doubleClick(MatrixEvent event) {
            _drawToolTip = false;
            _mainFigure.repaint();
        }

        @Override
        public void marked(MatrixEvent event) {
            _mainFigure.repaint();
            _horizontalListFigure.mark(event.getX());
            _verticalListFigure.mark(event.getY());
        }
    });
    // _zoomScrollBar = new ScrollBar();
    // final Label zoomLabel = new Label("Zoom");
    // zoomLabel.setBorder(new SchemeBorder(ButtonBorder.SCHEMES.BUTTON_SCROLLBAR));
    // _zoomScrollBar.setThumb(zoomLabel);
    // _zoomScrollBar.setHorizontal(true);
    // _zoomScrollBar.setMaximum(200);
    // _zoomScrollBar.setMinimum(0);
    // _zoomScrollBar.setExtent(25);
    // _zoomScrollBar.addPropertyChangeListener("value", new PropertyChangeListener() {
    // @Override
    // public void propertyChange(PropertyChangeEvent evt) {
    // float z = (_zoomScrollBar.getValue() + 10) * 0.02f;
    // _zoomableScrollpane.setZoom(z);
    // _zoomableScrollpaneVerticalBar.setZoom(z);
    // _zoomableScrollpaneHorizontalBar.setZoom(z);
    // _zoom = z;
    // }
    // });
    //
    // _useShortendLabelsCheckBox = new CheckBox("Shorten labels");
    // _useShortendLabelsCheckBox.getModel().addChangeListener(new ChangeListener() {
    //
    // @Override
    // public void handleStateChanged(ChangeEvent event) {
    // if ("selected".equals(event.getPropertyName())) {
    // _model.setUseShortendLabels(_useShortendLabelsCheckBox.isSelected());
    // _mainFigure.revalidate();
    // _mainFigure.repaint();
    // }
    // }
    // });
    _zoomableScrollpane.getViewport().addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Viewport viewport = (Viewport) evt.getSource();
            _zoomableScrollpaneVerticalBar.getViewport().setViewLocation(0, viewport.getViewLocation().y);
            _zoomableScrollpaneHorizontalBar.getViewport().setViewLocation(viewport.getViewLocation().x, 0);
            // _zoomableScrollpaneHorizontalBar.getViewport().setViewLocation(0, 0);
            _zoomableScrollpane.getViewport().setViewLocation(viewport.getViewLocation().x, viewport.getViewLocation().y);
            _mainFigure.revalidate();
            _mainFigure.repaint();
        }
    });
    // _mainFigure.add(_zoomScrollBar);
    // _mainFigure.add(_useShortendLabelsCheckBox);
    _mainFigure.add(_zoomableScrollpane);
    _mainFigure.add(_zoomableScrollpaneVerticalBar);
    _mainFigure.add(_zoomableScrollpaneHorizontalBar);
    _mainFigure.addLayoutListener(new LayoutListener.Stub() {

        @Override
        public boolean layout(IFigure container) {
            layoutFigures(container);
            return true;
        }
    });
}
Example 59
Project: dbeaver-master  File: EditableLabel.java View source code
/**
	 * paints figure differently depends on the whether the figure has focus or is selected 
	 */
@Override
protected void paintFigure(Graphics graphics) {
    if (selected) {
        graphics.pushState();
        graphics.setBackgroundColor(ColorConstants.menuBackgroundSelected);
        graphics.fillRectangle(getSelectionRectangle());
        graphics.popState();
        graphics.setForegroundColor(ColorConstants.white);
    }
    super.paintFigure(graphics);
}
Example 60
Project: eu.geclipse.core-master  File: OutputPortFigure.java View source code
/**
   * @see org.eclipse.draw2d.Figure#paintFigure(Graphics)
   */
@Override
protected void paintFigure(final Graphics g) {
    final Rectangle r = getBounds().getCopy();
    final IMapMode mm = MapModeUtil.getMapMode(this);
    r.translate(mm.DPtoLP(2), mm.DPtoLP(2));
    r.setSize(mm.DPtoLP(9), mm.DPtoLP(11));
    // draw a line at the bottom
    //g.drawLine(r.x, r.bottom(), r.right(), r.bottom());
    //draw figure
    g.translate(getLocation());
    final PointList outline = points.getCopy();
    mm.DPtoLP(outline);
    g.fillPolygon(outline);
    g.drawPolyline(outline);
    g.translate(getLocation().getNegated());
}
Example 61
Project: glance-master  File: HighlightFlow.java View source code
@Override
public void paint(final Graphics g) {
    if (!isVisible()) {
        return;
    }
    final String originalText = delegate.getText();
    final String matchString = originalText.substring(match.getOffset(), match.getOffset() + match.getLength());
    g.setBackgroundColor(isSelected() ? ColorManager.getInstance().getSelectedBackgroundColor() : ColorManager.getInstance().getBackgroundColor());
    final Dimension extent = getTextExtents(matchString);
    final Point topLeft = bounds.getTopLeft();
    g.fillRectangle(topLeft.x, topLeft.y, extent.width, extent.height);
    g.setForegroundColor(ColorConstants.black);
    g.setFont(getFont());
    g.drawText(matchString, topLeft.getCopy());
}
Example 62
Project: Hydrograph-master  File: ComponentFigure.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    Rectangle r = getBounds().getCopy();
    graphics.translate(r.getLocation());
    Rectangle q = new Rectangle(4, 4 + componentLabelMargin, r.width - 8, r.height - 8 - componentLabelMargin);
    graphics.fillRoundRectangle(q, 5, 5);
    graphics.drawImage(canvasIcon, new Point(q.width / 2 - 16, q.height / 2 + componentLabelMargin - 11));
    drawPropertyStatus(graphics);
    if ((StringUtils.equalsIgnoreCase(component.getCategory(), Constants.TRANSFORM) && !StringUtils.equalsIgnoreCase(component.getComponentName(), Constants.FILTER) && !StringUtils.equalsIgnoreCase(component.getComponentName(), Constants.UNIQUE_SEQUENCE))) {
        PropertyToolTipInformation propertyToolTipInformation;
        if (component.isContinuousSchemaPropogationAllow()) {
            drawSchemaPropogationInfoImageIfSchemaPropogationBreaks(graphics);
            propertyToolTipInformation = createPropertyToolTipInformation(Messages.CONTINUOUS_SCHEMA_PROPAGATION_STOPPED, Constants.SHOW_TOOLTIP);
        } else {
            propertyToolTipInformation = createPropertyToolTipInformation("", Constants.HIDE_TOOLTIP);
        }
        component.getTooltipInformation().put(Constants.ISSUE_PROPERTY_NAME, propertyToolTipInformation);
    } else if (StringUtils.equalsIgnoreCase(Constants.UNION_ALL, component.getComponentName())) {
        PropertyToolTipInformation propertyToolTipInformation;
        if (component.getProperties().get(Constants.IS_UNION_ALL_COMPONENT_SYNC) != null && StringUtils.equalsIgnoreCase(((String) component.getProperties().get(Constants.IS_UNION_ALL_COMPONENT_SYNC)), Constants.FALSE)) {
            drawSchemaPropogationInfoImageIfSchemaPropogationBreaks(graphics);
            propertyToolTipInformation = createPropertyToolTipInformation(Messages.INPUTS_SCHEMA_ARE_NOT_IN_SYNC, Constants.SHOW_TOOLTIP);
        } else {
            propertyToolTipInformation = createPropertyToolTipInformation("", Constants.HIDE_TOOLTIP);
        }
        component.getTooltipInformation().put(Constants.ISSUE_PROPERTY_NAME, propertyToolTipInformation);
    } else if (component instanceof SubjobComponent) {
        boolean isTransformComponentPresent = SubjobUtility.INSTANCE.checkIfSubJobHasTransformOrUnionAllComponent(component);
        PropertyToolTipInformation propertyToolTipInformation;
        if (isTransformComponentPresent) {
            drawSchemaPropogationInfoImageIfSchemaPropogationBreaks(graphics);
            propertyToolTipInformation = createPropertyToolTipInformation(Messages.CONTINUOUS_SCHEMA_PROPAGATION_STOPPED_IN_SUBJOB, Constants.SHOW_TOOLTIP);
        } else {
            propertyToolTipInformation = createPropertyToolTipInformation("", Constants.HIDE_TOOLTIP);
        }
        component.getTooltipInformation().put(Constants.ISSUE_PROPERTY_NAME, propertyToolTipInformation);
    }
    graphics.drawText(acronym, new Point((q.width - (acronym.length() * 5)) / 2, q.height / 2 + componentLabelMargin - 23));
    if (componentProperties != null && componentProperties.get(StringUtils.lowerCase(Constants.BATCH)) != null) {
        if (String.valueOf(componentProperties.get(StringUtils.lowerCase(Constants.BATCH))).length() > 2) {
            graphics.drawText(StringUtils.substring(String.valueOf(componentProperties.get(StringUtils.lowerCase(Constants.BATCH))), 0, 2) + "..", new Point(q.width - 16, q.height + getComponentLabelMargin() - 20));
        } else {
            graphics.drawText(String.valueOf(componentProperties.get(StringUtils.lowerCase(Constants.BATCH))), new Point(q.width - 14, q.height + getComponentLabelMargin() - 20));
        }
    }
    trackExecution(graphics);
}
Example 63
Project: liferay-ide-master  File: PortletColumnEditPart.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    Rectangle r = Rectangle.SINGLETON.setBounds(getBounds());
    r.width -= 1;
    r.height -= 1;
    //draw the outline
    graphics.drawRoundRectangle(r, 10, 10);
    r.width -= 1;
    r.height -= 1;
    r.x += 1;
    r.y += 1;
    //fill the color
    graphics.fillRoundRectangle(r, 10, 10);
}
Example 64
Project: liquidware_beagleboard_android_sdk-master  File: LayoutFigure.java View source code
/**
     * Paints the "border" for this figure.
     * <p/>
     * The parent [email protected] Figure#paint(Graphics)} calls [email protected] #paintFigure(Graphics)} then
     * [email protected] #paintClientArea(Graphics)} then [email protected] #paintBorder(Graphics)}. Here we thus
     * draw the actual highlight border but also the highlight anchor lines and points so that
     * we can make sure they are all drawn on top of the border.
     * <p/>
     * Note: This method doesn't really need to restore its graphic state. The parent
     * Figure will do it for us.
     * <p/>
     *
     * @param graphics The Graphics object used for painting
     */
@Override
protected void paintBorder(Graphics graphics) {
    super.paintBorder(graphics);
    if (mHighlightInfo == null) {
        return;
    }
    // Draw the border. We want other highlighting to be drawn on top of the border.
    if (mHighlightInfo.drawDropBorder) {
        graphics.setLineWidth(3);
        graphics.setLineStyle(SWT.LINE_SOLID);
        graphics.setForegroundColor(ColorConstants.green);
        graphics.drawRectangle(getInnerBounds().getCopy().shrink(1, 1));
    }
    Rectangle bounds = getBounds();
    int bx = bounds.x;
    int by = bounds.y;
    int w = bounds.width;
    int h = bounds.height;
    // Draw frames of target child parts, if any
    if (mHighlightInfo.childParts != null) {
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_DOT);
        graphics.setForegroundColor(ColorConstants.lightBlue);
        for (UiElementEditPart part : mHighlightInfo.childParts) {
            if (part != null) {
                graphics.drawRectangle(part.getBounds().getCopy().translate(bx, by));
            }
        }
    }
    // Draw the target line, if any
    if (mHighlightInfo.linePoints != null) {
        int x1 = mHighlightInfo.linePoints[0].x;
        int y1 = mHighlightInfo.linePoints[0].y;
        int x2 = mHighlightInfo.linePoints[1].x;
        int y2 = mHighlightInfo.linePoints[1].y;
        // full 2-pixel width be visible.
        if (x1 <= 0)
            x1++;
        if (x2 <= 0)
            x2++;
        if (y1 <= 0)
            y1++;
        if (y2 <= 0)
            y2++;
        if (x1 >= w - 1)
            x1--;
        if (x2 >= w - 1)
            x2--;
        if (y1 >= h - 1)
            y1--;
        if (y2 >= h - 1)
            y2--;
        x1 += bx;
        x2 += bx;
        y1 += by;
        y2 += by;
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_DASH);
        graphics.setLineCap(SWT.CAP_ROUND);
        graphics.setForegroundColor(ColorConstants.orange);
        graphics.drawLine(x1, y1, x2, y2);
    }
    // Draw the anchor point, if any
    if (mHighlightInfo.anchorPoint != null) {
        int x = mHighlightInfo.anchorPoint.x;
        int y = mHighlightInfo.anchorPoint.y;
        // matches the highlight line. It makes it slightly more visible that way.
        if (x <= 0)
            x++;
        if (y <= 0)
            y++;
        if (x >= w - 1)
            x--;
        if (y >= h - 1)
            y--;
        x += bx;
        y += by;
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_SOLID);
        graphics.setLineCap(SWT.CAP_ROUND);
        graphics.setForegroundColor(ColorConstants.orange);
        graphics.drawLine(x - 5, y - 5, x + 5, y + 5);
        graphics.drawLine(x - 5, y + 5, x + 5, y - 5);
        // 7 * cos(45) == 5 so we use 8 for the circle radius (it looks slightly better than 7)
        graphics.setLineWidth(1);
        graphics.drawOval(x - 8, y - 8, 16, 16);
    }
}
Example 65
Project: scout-master  File: Trace.java View source code
private void drawErrorBar(Graphics graphics, Point dpPos, ISample dp) {
    graphics.pushState();
    graphics.setForegroundColor(errorBarColor);
    graphics.setLineStyle(SWTConstants.LINE_SOLID);
    graphics.setLineWidth(1);
    Point ep;
    switch(yErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() - dp.getYMinusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            if (yErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() + dp.getYPlusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            break;
        default:
            break;
    }
    switch(xErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() - dp.getXMinusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            if (xErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() + dp.getXPlusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            break;
        default:
            break;
    }
    graphics.popState();
}
Example 66
Project: scouter-master  File: Trace.java View source code
private void drawErrorBar(Graphics graphics, Point dpPos, ISample dp) {
    graphics.pushState();
    graphics.setForegroundColor(errorBarColor);
    graphics.setLineStyle(SWTConstants.LINE_SOLID);
    graphics.setLineWidth(1);
    Point ep;
    switch(yErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() - dp.getYMinusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            if (yErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue(), false), yAxis.getValuePosition(dp.getYValue() + dp.getYPlusError(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x - errorBarCapWidth / 2, ep.y, ep.x + errorBarCapWidth / 2, ep.y);
            break;
        default:
            break;
    }
    switch(xErrorBarType) {
        case BOTH:
        case MINUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() - dp.getXMinusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            if (xErrorBarType != ErrorBarType.BOTH)
                break;
        case PLUS:
            ep = new Point(xAxis.getValuePosition(dp.getXValue() + dp.getXPlusError(), false), yAxis.getValuePosition(dp.getYValue(), false));
            graphics.drawLine(dpPos, ep);
            graphics.drawLine(ep.x, ep.y - errorBarCapWidth / 2, ep.x, ep.y + errorBarCapWidth / 2);
            break;
        default:
            break;
    }
    graphics.popState();
}
Example 67
Project: TadpoleForDBTools-master  File: SubTableFigureBorder.java View source code
public void paint(IFigure figure, Graphics graphics, Insets insets) {
    Rectangle r = figure.getBounds().getCopy();
    r.crop(insets);
    graphics.setLineWidth(1);
    // solid long edges around border
    graphics.drawLine(r.x + FOLD, r.y, r.x + r.width - 1, r.y);
    graphics.drawLine(r.x, r.y + FOLD, r.x, r.y + r.height - 1);
    graphics.drawLine(r.x + r.width - 1, r.y, r.x + r.width - 1, r.y + r.height - 1);
    // solid short edges
    graphics.drawLine(r.x, r.y + r.height - 1, r.x + r.width - 1, r.y + r.height - 1);
    graphics.drawLine(r.x + FOLD, r.y, r.x + FOLD, r.y + FOLD);
    graphics.drawLine(r.x, r.y + FOLD, r.x + FOLD, r.y + FOLD);
    // gray small triangle
    graphics.setBackgroundColor(ColorConstants.lightGray());
    graphics.fillPolygon(new int[] { r.x, r.y + FOLD, r.x + FOLD, r.y, r.x + FOLD, r.y + FOLD });
    // dotted short diagonal line
    graphics.setLineStyle(SWT.LINE_DOT);
    graphics.drawLine(r.x, r.y + FOLD, r.x + FOLD, r.y);
}
Example 68
Project: xUnit-master  File: CompositeUnitNodeFigure.java View source code
private void initBorder(StructureType type) {
    if (!(type == StructureType.adapter || type == StructureType.decorator))
        return;
    ((ToolbarLayout) getLayoutManager()).setSpacing(V_NODE_SPACE / 2);
    Color color = type == StructureType.adapter ? ADAPTER_TITLE_COLOR : DECORATOR_TITLE_COLOR;
    textBorder = new TitleBarBorder();
    textBorder.setTextAlignment(PositionConstants.CENTER);
    textBorder.setBackgroundColor(color);
    CompoundBorder border = new CompoundBorder(textBorder, new LineBorder(ColorConstants.darkGreen, 1, Graphics.LINE_SOLID));
    setBorder(border);
    footer = new Label(type.name());
    footer.setForegroundColor(color);
    footer.setBorder(new LineBorder(ColorConstants.white, 1, Graphics.LINE_SOLID));
    endPanel.add(footer);
}
Example 69
Project: yang-ide-master  File: FeedbackFigure.java View source code
@Override
protected void outlineShape(Graphics g) {
    int x = getParent().getBounds().x + 15;
    int x2 = x + getParent().getBounds().width - 30;
    g.setForegroundColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
    g.drawPolyline(new int[] { x - 2, position - 2, x, position, x - 2, position + 2 });
    g.drawPolyline(new int[] { x, position, x2, position });
    g.drawPolyline(new int[] { x2 + 3, position - 3, x2, position, x2 + 2, position + 2 });
}
Example 70
Project: d-case_editor-master  File: CustomWrappingLabel.java View source code
/**
     * [email protected]}
     */
@Override
protected void paintClientArea(Graphics graphics) {
    if (!isSelected()) {
        graphics.pushState();
        graphics.setBackgroundColor(backgroundColor);
        graphics.fillRectangle(getVisibleTextBounds());
        graphics.popState();
        graphics.setForegroundColor(getForegroundColor());
    }
    super.paintClientArea(graphics);
}
Example 71
Project: eclipse-gef-imageexport-master  File: Utils.java View source code
/** Paints the figure onto the given graphics */
public static void paintDiagram(Graphics g, IFigure figure) {
    // Store state, so modified state of Graphics (while painting children) can be easily restored
    g.pushState();
    try {
        IClippingStrategy clippingStrategy = figure.getClippingStrategy();
        // supported (like Graphics#setTextAntiAliassing())
        for (Object childObject : figure.getChildren()) {
            if (childObject instanceof Layer) {
                // Found another layer, process it to search for actual figures
                paintDiagram(g, (IFigure) childObject);
            } else {
                // Found something to draw
                // Use same/similar method as being using in Figure#paintChildren() in order to get clipping right
                IFigure child = (IFigure) childObject;
                if (child.isVisible()) {
                    // determine clipping areas for child
                    Rectangle[] clipping = null;
                    if (clippingStrategy != null) {
                        clipping = clippingStrategy.getClip(child);
                    } else {
                        // default clipping behaviour is to clip at bounds
                        clipping = new Rectangle[] { child.getBounds() };
                    }
                    // child may now paint inside the clipping areas
                    for (int j = 0; j < clipping.length; j++) {
                        if (clipping[j].intersects(g.getClip(Rectangle.SINGLETON))) {
                            g.clipRect(clipping[j]);
                            child.paint(g);
                            g.restoreState();
                        }
                    }
                }
            }
        }
    } finally {
        // Always pop the state again to prevent problems
        g.popState();
    }
}
Example 72
Project: LEADT-master  File: GEFImageWriter.java View source code
private static Image drawFigureOnImage(GraphicalViewer viewer) {
    IFigure figure = getRootFigure(viewer);
    Rectangle bounds = figure.getBounds();
    Image image = new Image(null, bounds.width, bounds.height);
    GC imageGC = new GC(image);
    Graphics imgGraphics = new SWTGraphics(imageGC);
    imgGraphics.translate(-bounds.x, -bounds.y);
    figure.paint(imgGraphics);
    imgGraphics.translate(bounds.x, bounds.y);
    imageGC.dispose();
    return image;
}
Example 73
Project: org.nightlabs.jfire.max-master  File: AbstractInputNodeFigure.java View source code
@Override
protected void paintFigure(Graphics g) {
    Rectangle bounds = getBounds();
    g.setBackgroundColor(PageColorUtil.getPageColor(colorIndex));
    g.setForegroundColor(PageColorUtil.getPageColor(colorIndex));
    g.fillRectangle(getBounds());
    g.setBackgroundColor(PageColorUtil.getHeaderColor(colorIndex));
    g.fillRectangle(bounds.x, bounds.y, bounds.width, nameHeight);
    //		g.drawLine(bounds.x, bounds.y + nameHeight - spacerHeight, bounds.x + bounds.width, bounds.y + nameHeight - spacerHeight);
    String text = getName();
    int textWidth = FigureUtilities.getTextWidth(text, getFont());
    int space = bounds.width - textWidth;
    Font normalFont = g.getFont();
    try {
        g.setFont(getBoldFont(g));
        g.setForegroundColor(PageColorUtil.getHeaderFontColor(colorIndex));
        g.fillText(text, bounds.x + space / 2, bounds.y + 3);
    } finally {
        g.setFont(normalFont);
    }
    drawInputConnectors(g, getBounds());
}
Example 74
Project: org.nightlabs.jfire.max.eclipse-master  File: AbstractInputNodeFigure.java View source code
@Override
protected void paintFigure(Graphics g) {
    Rectangle bounds = getBounds();
    g.setBackgroundColor(PageColorUtil.getPageColor(colorIndex));
    g.setForegroundColor(PageColorUtil.getPageColor(colorIndex));
    g.fillRectangle(getBounds());
    g.setBackgroundColor(PageColorUtil.getHeaderColor(colorIndex));
    g.fillRectangle(bounds.x, bounds.y, bounds.width, nameHeight);
    //		g.drawLine(bounds.x, bounds.y + nameHeight - spacerHeight, bounds.x + bounds.width, bounds.y + nameHeight - spacerHeight);
    String text = getName();
    int textWidth = FigureUtilities.getTextWidth(text, getFont());
    int space = bounds.width - textWidth;
    Font normalFont = g.getFont();
    try {
        g.setFont(getBoldFont(g));
        g.setForegroundColor(PageColorUtil.getHeaderFontColor(colorIndex));
        g.fillText(text, bounds.x + space / 2, bounds.y + 3);
    } finally {
        g.setFont(normalFont);
    }
    drawInputConnectors(g, getBounds());
}
Example 75
Project: eclipse-gov.redhawk.core-master  File: ComponentInstantiationFigure.java View source code
@Override
protected void fillShape(final Graphics graphics) {
    final Rectangle r = getBounds().getCopy();
    final Point topLeft = r.getTopLeft();
    final float x = (r.getTopRight().x - r.getTopLeft().x) / 2 + r.getTopLeft().x;
    super.fillShape(graphics);
    // SUPPRESS CHECKSTYLE MagicNumber
    final int height = this.fComponentInstantiationLabelFigure.getBounds().height + 10;
    final Pattern pattern = new Pattern(Display.getCurrent(), x, topLeft.y, x, topLeft.y + height, this.gradientColor, graphics.getBackgroundColor());
    final int oldFillRule = graphics.getFillRule();
    // We do this to support graphics that potentially don't support gradient fill,  for some reason the save as image doesn't support this
    try {
        graphics.setBackgroundPattern(pattern);
        r.setSize(r.width, height);
        graphics.setClip(r);
        graphics.fillRoundRectangle(getBounds(), this.corner.width, this.corner.height);
        graphics.setClip(getBounds());
        graphics.setBackgroundPattern(null);
        graphics.setFillRule(oldFillRule);
    } catch (final RuntimeException e) {
    } finally {
        pattern.dispose();
    }
}
Example 76
Project: Socio-technical-Security-Requirements-master  File: AuthorisationMiddleFigure.java View source code
private IFigure createLabel(StsElement element, Map<IFigure, StsElement> map, final Color startColor, final Color endColor, int alpha) {
    Label l = new Label(element.getName());
    RoundedRectangle e = new RoundedRectangle() {

        @Override
        protected void fillShape(Graphics graphics) {
            graphics.setBackgroundColor(startColor);
            super.fillShape(graphics);
        }
    };
    e.setCornerDimensions(new Dimension(4, 4));
    e.setLayoutManager(new StackLayout() {

        @Override
        protected Dimension calculatePreferredSize(IFigure figure, int wHint, int hHint) {
            Dimension d = super.calculatePreferredSize(figure, wHint, hHint);
            d.height = d.height + 4;
            d.width = d.width + 6;
            return d;
        }
    });
    e.setOutline(false);
    e.add(l);
    map.put(e, element);
    return e;
}
Example 77
Project: WS171-development-master  File: LayoutFigure.java View source code
/**
     * Paints the "border" for this figure.
     * <p/>
     * The parent [email protected] Figure#paint(Graphics)} calls [email protected] #paintFigure(Graphics)} then
     * [email protected] #paintClientArea(Graphics)} then [email protected] #paintBorder(Graphics)}. Here we thus
     * draw the actual highlight border but also the highlight anchor lines and points so that
     * we can make sure they are all drawn on top of the border. 
     * <p/>
     * Note: This method doesn't really need to restore its graphic state. The parent
     * Figure will do it for us.
     * <p/>
     * 
     * @param graphics The Graphics object used for painting
     */
@Override
protected void paintBorder(Graphics graphics) {
    super.paintBorder(graphics);
    if (mHighlightInfo == null) {
        return;
    }
    // Draw the border. We want other highlighting to be drawn on top of the border.
    if (mHighlightInfo.drawDropBorder) {
        graphics.setLineWidth(3);
        graphics.setLineStyle(SWT.LINE_SOLID);
        graphics.setForegroundColor(ColorConstants.green);
        graphics.drawRectangle(getInnerBounds().getCopy().shrink(1, 1));
    }
    Rectangle bounds = getBounds();
    int bx = bounds.x;
    int by = bounds.y;
    int w = bounds.width;
    int h = bounds.height;
    // Draw frames of target child parts, if any
    if (mHighlightInfo.childParts != null) {
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_DOT);
        graphics.setForegroundColor(ColorConstants.lightBlue);
        for (UiElementEditPart part : mHighlightInfo.childParts) {
            if (part != null) {
                graphics.drawRectangle(part.getBounds().getCopy().translate(bx, by));
            }
        }
    }
    // Draw the target line, if any
    if (mHighlightInfo.linePoints != null) {
        int x1 = mHighlightInfo.linePoints[0].x;
        int y1 = mHighlightInfo.linePoints[0].y;
        int x2 = mHighlightInfo.linePoints[1].x;
        int y2 = mHighlightInfo.linePoints[1].y;
        // full 2-pixel width be visible.
        if (x1 <= 0)
            x1++;
        if (x2 <= 0)
            x2++;
        if (y1 <= 0)
            y1++;
        if (y2 <= 0)
            y2++;
        if (x1 >= w - 1)
            x1--;
        if (x2 >= w - 1)
            x2--;
        if (y1 >= h - 1)
            y1--;
        if (y2 >= h - 1)
            y2--;
        x1 += bx;
        x2 += bx;
        y1 += by;
        y2 += by;
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_DASH);
        graphics.setLineCap(SWT.CAP_ROUND);
        graphics.setForegroundColor(ColorConstants.orange);
        graphics.drawLine(x1, y1, x2, y2);
    }
    // Draw the anchor point, if any
    if (mHighlightInfo.anchorPoint != null) {
        int x = mHighlightInfo.anchorPoint.x;
        int y = mHighlightInfo.anchorPoint.y;
        // matches the highlight line. It makes it slightly more visible that way.
        if (x <= 0)
            x++;
        if (y <= 0)
            y++;
        if (x >= w - 1)
            x--;
        if (y >= h - 1)
            y--;
        x += bx;
        y += by;
        graphics.setLineWidth(2);
        graphics.setLineStyle(SWT.LINE_SOLID);
        graphics.setLineCap(SWT.CAP_ROUND);
        graphics.setForegroundColor(ColorConstants.orange);
        graphics.drawLine(x - 5, y - 5, x + 5, y + 5);
        graphics.drawLine(x - 5, y + 5, x + 5, y - 5);
        // 7 * cos(45) == 5 so we use 8 for the circle radius (it looks slightly better than 7)
        graphics.setLineWidth(1);
        graphics.drawOval(x - 8, y - 8, 16, 16);
    }
}
Example 78
Project: cogtool-master  File: GraphicalWidgetBase.java View source code
@Override
protected void paintRightIcon(Graphics g) {
    Rectangle bds = getBounds();
    int x = bds.width - bds.height - 2;
    int y = 4;
    int w = bds.height - 6;
    int h = bds.height - 8;
    if (x < 0) {
        x = 1;
    }
    if (y >= bds.height) {
        y = bds.height;
    }
    if (w <= 0) {
        w = 1;
    }
    if (h <= 0) {
        h = 1;
    }
    int[] triangle = { x, y, x + w, y + (h / 2), x, y + h };
    g.drawPolygon(triangle);
}
Example 79
Project: framesoc-master  File: Snapshot.java View source code
/**
	 * Generate the image
	 * 
	 * @param figure
	 *            Figure from which the image is created
	 * @param format
	 *            format of the generated image
	 * @return an array of bytes corresponding to an image
	 */
private byte[] createImage(Figure figure, int format) {
    Device device = Display.getCurrent();
    Rectangle r = figure.getBounds();
    if (r.width <= 0 || r.height <= 0) {
        logger.debug("Size of figure is 0: stopping generation");
        return null;
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        image = new Image(device, r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(result, format);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
    }
    return result.toByteArray();
}
Example 80
Project: lunifera-sharky-m2m-master  File: Connection.java View source code
/**
	 * Returns the lineStyle as String for the Property Sheet
	 * 
	 * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java.lang.Object)
	 */
public Object getPropertyValue(Object id) {
    if (id.equals(LINESTYLE_PROP)) {
        if (getLineStyle() == Graphics.LINE_DASH)
            // Dashed is the second value in the combo dropdown
            return new Integer(1);
        // Solid is the first value in the combo dropdown
        return new Integer(0);
    }
    return super.getPropertyValue(id);
}
Example 81
Project: org.openscada.orilla-master  File: InputScaleDetails.java View source code
@Override
protected IFigure createMain() {
    final Figure rootFigure = new Figure();
    rootFigure.setLayoutManager(new GridLayout(4, true));
    rootFigure.setBackgroundColor(ColorConstants.white);
    // cell 1,1
    rootFigure.add(new Figure());
    // cell 2,1
    rootFigure.add(this.factorFigure = new RoundedRectangle(), new GridData(GridData.CENTER, GridData.CENTER, true, true));
    this.factorFigure.setBackgroundColor(ColorConstants.lightGray);
    this.factorFigure.setForegroundColor(ColorConstants.black);
    this.factorFigure.setBorder(new MarginBorder(10));
    this.factorFigure.setLayoutManager(new BorderLayout());
    this.factorFigure.add(this.factorLabel = new Label(), BorderLayout.CENTER);
    this.factorFigure.addMouseMotionListener(new MouseMotionListener.Stub() {

        @Override
        public void mouseEntered(final MouseEvent me) {
            InputScaleDetails.this.factorFigure.setLineWidth(2);
        }

        @Override
        public void mouseExited(final MouseEvent me) {
            InputScaleDetails.this.factorFigure.setLineWidth(1);
        }
    });
    // cell 3,1
    rootFigure.add(this.offsetFigure = new RoundedRectangle(), new GridData(GridData.CENTER, GridData.CENTER, true, true));
    this.offsetFigure.setBackgroundColor(ColorConstants.lightGray);
    this.offsetFigure.setForegroundColor(ColorConstants.black);
    this.offsetFigure.setBorder(new MarginBorder(10));
    this.offsetFigure.setLayoutManager(new BorderLayout());
    this.offsetFigure.add(this.offsetLabel = new Label(), BorderLayout.CENTER);
    this.offsetFigure.addMouseMotionListener(new MouseMotionListener.Stub() {

        @Override
        public void mouseEntered(final MouseEvent me) {
            InputScaleDetails.this.offsetFigure.setLineWidth(2);
        }

        @Override
        public void mouseExited(final MouseEvent me) {
            InputScaleDetails.this.offsetFigure.setLineWidth(1);
        }
    });
    // cell 4,1
    rootFigure.add(new Figure());
    // cell 1,2
    rootFigure.add(this.rawFigure = new RoundedRectangle(), new GridData(GridData.CENTER, GridData.CENTER, true, true));
    this.rawFigure.setBackgroundColor(ColorConstants.lightGray);
    this.rawFigure.setForegroundColor(ColorConstants.black);
    this.rawFigure.setBorder(new MarginBorder(10));
    this.rawFigure.setLayoutManager(new BorderLayout());
    this.rawFigure.add(this.rawLabel = new Label(), BorderLayout.CENTER);
    // cell 2,2
    final RectangleFigure factorRect = new RectangleFigure();
    factorRect.setLayoutManager(new BorderLayout());
    factorRect.add(new Label(Messages.InputScaleDetails_Multiply), BorderLayout.CENTER);
    factorRect.setBorder(new MarginBorder(10));
    factorRect.setBackgroundColor(ColorConstants.lightGray);
    factorRect.setForegroundColor(ColorConstants.black);
    factorRect.setLineStyle(Graphics.LINE_SOLID);
    factorRect.setLineWidth(1);
    factorRect.setFill(true);
    factorRect.setOpaque(true);
    rootFigure.add(factorRect, new GridData(GridData.CENTER, GridData.CENTER, true, true));
    // cell 3, 2
    final RectangleFigure offsetRect = new RectangleFigure();
    offsetRect.setLayoutManager(new BorderLayout());
    offsetRect.add(new Label(Messages.InputScaleDetails_Add), BorderLayout.CENTER);
    offsetRect.setBorder(new MarginBorder(10));
    offsetRect.setBackgroundColor(ColorConstants.lightGray);
    offsetRect.setForegroundColor(ColorConstants.black);
    offsetRect.setLineStyle(Graphics.LINE_SOLID);
    offsetRect.setLineWidth(1);
    offsetRect.setFill(true);
    offsetRect.setOpaque(true);
    rootFigure.add(offsetRect, new GridData(GridData.CENTER, GridData.CENTER, true, true));
    // cell 4,2
    rootFigure.add(this.valueFigure = new RoundedRectangle(), new GridData(GridData.CENTER, GridData.CENTER, true, true));
    this.valueFigure.setLayoutManager(new BorderLayout());
    this.valueFigure.setBackgroundColor(ColorConstants.lightGray);
    this.valueFigure.setForegroundColor(ColorConstants.black);
    this.valueFigure.setBorder(new MarginBorder(10));
    this.valueFigure.add(this.valueLabel = new Label(), BorderLayout.CENTER);
    // add connections
    connect(rootFigure, this.factorFigure, factorRect);
    connect(rootFigure, this.rawFigure, factorRect);
    connect(rootFigure, factorRect, offsetRect);
    connect(rootFigure, this.offsetFigure, offsetRect);
    connect(rootFigure, offsetRect, this.valueFigure);
    // hook up entry dialogs
    this.factorFigure.addMouseListener(new MouseListener.Stub() {

        @Override
        public void mouseDoubleClicked(final MouseEvent me) {
            InputScaleDetails.this.triggerFactorInput();
        }
    });
    this.offsetFigure.addMouseListener(new MouseListener.Stub() {

        @Override
        public void mouseDoubleClicked(final MouseEvent me) {
            InputScaleDetails.this.triggerOffsetInput();
        }
    });
    return rootFigure;
}
Example 82
Project: overture-master  File: GenericTabItem.java View source code
public void exportJPG(String fileName) {
    Image theImage = new Image(null, xmax + 50, ymax + 50);
    GC theGC = new GC(theImage);
    Graphics theGraphics = new SWTGraphics(theGC);
    theFigure.paint(theGraphics);
    theGraphics.fillRectangle(xmax + 50, 0, 10, ymax + 50);
    ImageData imgData[] = new ImageData[1];
    imgData[0] = theImage.getImageData();
    ImageLoader theLoader = new ImageLoader();
    theLoader.data = imgData;
    theLoader.save((new StringBuilder(String.valueOf(fileName))).append(".jpg").toString(), 4);
    theGraphics.dispose();
    theGC.dispose();
    theImage.dispose();
}
Example 83
Project: Spoon-master  File: ScrollableThumbnail.java View source code
public void paintFigure(Graphics g) {
    Rectangle bounds = getBounds().getCopy();
    // Avoid drawing images that are 0 in dimension
    if (bounds.width < 5 || bounds.height < 5)
        return;
    // Don't paint the selector figure if the entire source is visible.
    Dimension thumbnailSize = new Dimension(getThumbnailImage());
    // expand to compensate for rounding errors in calculating bounds
    Dimension size = getSize().getExpanded(1, 1);
    if (size.contains(thumbnailSize))
        return;
    bounds.height--;
    bounds.width--;
    g.drawImage(image, iBounds, bounds);
    g.setForegroundColor(ColorConstants.menuBackgroundSelected);
    g.drawRectangle(bounds);
}
Example 84
Project: vespucci-master  File: WarningDecoration.java View source code
private void paintExclamationMark(Graphics graphics) {
    Point lineStartPoint = new Point(LINE_XPOS, LINE_Y1);
    Point lineEndPoint = new Point(LINE_XPOS, DOT_POS_Y + 2);
    graphics.drawLine(transform.getTransformed(lineStartPoint), transform.getTransformed(lineEndPoint));
    graphics.setBackgroundColor(Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
    Point separatorTopLeftPoint = new Point(LINE_XPOS - 2, LINE_Y2);
    Point separatorBottomRightPoint = new Point(LINE_XPOS + 2, DOT_POS_Y);
    PointList separatorPoints = new PointList(5);
    separatorPoints.addPoint(transform.getTransformed(separatorTopLeftPoint));
    separatorPoints.addPoint(transform.getTransformed(new Point(separatorBottomRightPoint.x, separatorTopLeftPoint.y)));
    separatorPoints.addPoint(transform.getTransformed(separatorBottomRightPoint));
    separatorPoints.addPoint(transform.getTransformed(new Point(separatorTopLeftPoint.x, separatorBottomRightPoint.y)));
    separatorPoints.addPoint(transform.getTransformed(separatorTopLeftPoint));
    graphics.fillPolygon(separatorPoints);
}
Example 85
Project: eclipse-gov.redhawk.ide-master  File: PaletteNamespaceFolderFigure.java View source code
/**
	 * Paints the background gradient on the drawer toggle figure.
	 * 
	 * @param g
	 *            the graphics object
	 * @param rect
	 *            the rectangle which the background gradient should cover
	 */
private void paintToggleGradient(Graphics g, Rectangle rect) {
    if (collapseToggle.getModel().isMouseOver()) {
        Color color1 = PaletteColorUtil.WIDGET_BACKGROUND_LIST_BACKGROUND_60;
        Color color2 = PaletteColorUtil.WIDGET_BACKGROUND_NORMAL_SHADOW_90;
        Color color3 = PaletteColorUtil.WIDGET_BACKGROUND_NORMAL_SHADOW_95;
        Color color4 = PaletteColorUtil.WIDGET_BACKGROUND_LIST_BACKGROUND_90;
        g.setForegroundColor(color1);
        g.setBackgroundColor(color2);
        g.fillGradient(rect.x, rect.y, rect.width, rect.height - 4, true);
        g.setForegroundColor(color2);
        g.setBackgroundColor(color3);
        g.fillGradient(rect.x, rect.bottom() - 4, rect.width, 2, true);
        g.setForegroundColor(color3);
        g.setBackgroundColor(color4);
        g.fillGradient(rect.x, rect.bottom() - 2, rect.width, 2, true);
    } else {
        g.setForegroundColor(ColorConstants.white);
        g.fillGradient(rect, true);
    }
}
Example 86
Project: gda-common-rcp-master  File: ColourSliderComposite.java View source code
private IFigure getContents() {
    RectangleFigure boundaryFigure = new RectangleFigure() {

        @Override
        public void paint(Graphics graphics) {
            super.paint(graphics);
            graphics.drawLine(0, bottomLimitInPixel, 30, bottomLimitInPixel);
        }
    };
    boundaryFigure.setLayoutManager(new ColourSliderCompositeLayout());
    boundaryFigure.setBackgroundColor(ColorConstants.white);
    // Top slider figure
    topSliderHolder = new Panel();
    topSliderHolder.setLayoutManager(new XYLayout());
    topTriangleFigure = new Triangle();
    topTriangleFigure.setDirection(PositionConstants.SOUTH);
    topTriangleFigure.setFill(true);
    topTriangleFigure.setBackgroundColor(ColorConstants.buttonDarker);
    topTriangleFigure.setForegroundColor(ColorConstants.black);
    topTriangleFigure.setCursor(Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND));
    topClosureFigure = new RectangleFigure();
    topClosureFigure.setBackgroundColor(ColorConstants.black);
    topClosureFigure.setForegroundColor(ColorConstants.black);
    topClosureFigure.setOpaque(true);
    topClosureFigure.setFill(true);
    topSliderHolder.add(topTriangleFigure, new Rectangle(0, 0, 20, 15));
    topSliderHolder.add(topClosureFigure, new Rectangle(0, 13, 20, 1));
    topSliderDragger = new Dragger();
    topSliderHolder.addMouseMotionListener(topSliderDragger);
    topSliderHolder.addMouseListener(topSliderDragger);
    topSliderHolder.setBounds(new Rectangle(5, 5, 20, 15));
    // Bottom slider figure
    bottomSliderHolder = new Panel();
    bottomSliderHolder.setLayoutManager(new XYLayout());
    bottomTriangleFigure = new Triangle();
    bottomTriangleFigure.setDirection(PositionConstants.NORTH);
    bottomTriangleFigure.setFill(true);
    bottomTriangleFigure.setBackgroundColor(ColorConstants.buttonDarker);
    bottomTriangleFigure.setForegroundColor(ColorConstants.black);
    bottomTriangleFigure.setCursor(Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND));
    bottomClosureFigure = new RectangleFigure();
    bottomClosureFigure.setFill(true);
    bottomClosureFigure.setBackgroundColor(ColorConstants.black);
    bottomClosureFigure.setForegroundColor(ColorConstants.black);
    bottomSliderHolder.add(bottomTriangleFigure);
    bottomSliderHolder.add(bottomClosureFigure);
    bottomSliderDragger = new Dragger();
    bottomSliderHolder.addMouseMotionListener(bottomSliderDragger);
    bottomSliderHolder.addMouseListener(bottomSliderDragger);
    bottomSliderHolder.setBounds(new Rectangle(5, 5, 20, 15));
    //
    upperGradientedFigure = new ColorGradientedFigure(ColorConstants.white, ColorConstants.white);
    //
    lowerGradientedFigure = new ColorGradientedFigure(ColorConstants.white, ColorConstants.white);
    histogramRect = new ColorGradientedFigure(ColorConstants.black, ColorConstants.white);
    boundaryFigure.add(upperGradientedFigure);
    boundaryFigure.add(lowerGradientedFigure);
    boundaryFigure.add(histogramRect);
    boundaryFigure.add(topSliderHolder);
    boundaryFigure.add(bottomSliderHolder);
    return boundaryFigure;
}
Example 87
Project: ocelotl-master  File: Snapshot.java View source code
/**
	 * Generate the image
	 * 
	 * @param figure
	 *            Figure from which the image is created
	 * @param format
	 *            format of the generated image
	 * @return an array of bytes corresponding to an image
	 */
private byte[] createImage(Figure figure, int format) {
    Device device = Display.getCurrent();
    Rectangle r = figure.getBounds();
    if (r.width <= 0 || r.height <= 0) {
        logger.debug("Size of figure is 0: stopping generation");
        return null;
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
        image = new Image(device, r.width, r.height);
        gc = new GC(image);
        g = new SWTGraphics(gc);
        g.translate(r.x * -1, r.y * -1);
        figure.paint(g);
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(result, format);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (g != null) {
            g.dispose();
        }
        if (gc != null) {
            gc.dispose();
        }
        if (image != null) {
            image.dispose();
        }
    }
    return result.toByteArray();
}
Example 88
Project: chrysalix-master  File: FocusTreeCanvas.java View source code
@Override
public void paint(final IFigure figure, final Graphics graphics, final Insets insets) {
    tempRect.setBounds(getPaintRectangle(figure, insets));
    if (getWidth() % 2 == 1) {
        tempRect.width--;
        tempRect.height--;
    }
    tempRect.shrink(getWidth() / 2, getWidth() / 2);
    graphics.setLineWidth(getWidth());
    graphics.setLineStyle(getStyle());
    graphics.setForegroundColor(getColor());
    graphics.drawRoundRectangle(tempRect, 8, 8);
}
Example 89
Project: sloot-editor-master  File: HorizontalEdgeFigure.java View source code
/*
   * (non-Javadoc)
   * 
   * @see org.eclipse.draw2d.Shape#fillShape(org.eclipse.draw2d.Graphics)
   */
@Override
protected void fillShape(Graphics graphics) {
    graphics.setBackgroundColor(ColorConstants.cyan);
    graphics.setForegroundColor(ColorConstants.blue);
    int w = getBounds().x + getBounds().width;
    int h = getBounds().y + getBounds().height;
    graphics.drawLine(getBounds().x, getBounds().y, w, getBounds().y);
}
Example 90
Project: drools-guvnor-plugin-master  File: ConnectionFigure.java View source code
/**
     * Painting antialiased connector
     */
public void paint(Graphics g) {
    g.setAntialias(SWT.ON);
    super.paint(g);
}
Example 91
Project: droolsjbpm-master  File: ConnectionFigure.java View source code
/**
     * Painting antialiased connector
     */
public void paint(Graphics g) {
    g.setAntialias(SWT.ON);
    super.paint(g);
}
Example 92
Project: droolsjbpm-tools-master  File: ConnectionFigure.java View source code
/**
     * Painting antialiased connector
     */
public void paint(Graphics g) {
    g.setAntialias(SWT.ON);
    super.paint(g);
}
Example 93
Project: EMF-IncQuery-Examples-master  File: HumanCircleFigure.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    Rectangle r = getBounds().getCopy();
    setConstraint(rectangle, new Rectangle(0, 0, r.width, r.height));
    setConstraint(label, new Rectangle(0, 0, r.width, r.height));
}
Example 94
Project: plugin.maven-drools-plugin-master  File: ConnectionFigure.java View source code
/**
     * Painting antialiased connector
     */
public void paint(Graphics g) {
    g.setAntialias(SWT.ON);
    super.paint(g);
}
Example 95
Project: Green-UML-master  File: CompartmentFigure.java View source code
/**
		 * @see org.eclipse.draw2d.Border#paint(org.eclipse.draw2d.IFigure, org.eclipse.draw2d.Graphics, org.eclipse.draw2d.geometry.Insets)
		 */
public void paint(IFigure figure, Graphics graphics, Insets insets) {
    graphics.drawLine(getPaintRectangle(figure, insets).getTopLeft(), tempRect.getTopRight());
}
Example 96
Project: ecoretools-master  File: DNodeListEditPartWithAlpha.java View source code
@Override
protected void paintChildren(Graphics graphics) {
    int prevAlpha = graphics.getAlpha();
    graphics.setAlpha(alpha);
    super.paintChildren(graphics);
    graphics.setAlpha(prevAlpha);
}
Example 97
Project: hale-master  File: AbstractPolygonPainter.java View source code
@Override
public void fillShape(Graphics graphics, Rectangle bounds) {
    int[] points = getPoints(bounds, graphics.getLineWidth());
    graphics.fillPolygon(points);
}
Example 98
Project: org.roxgt-master  File: RoxgtTextSelectionEditPolicy.java View source code
protected void paintFigure(Graphics graphics) {
    graphics.drawFocus(getBounds().getResized(-1, -1));
}
Example 99
Project: cdo-master  File: AcoreTextSelectionEditPolicy.java View source code
@Override
protected void paintFigure(Graphics graphics) {
    graphics.drawFocus(getBounds().getResized(-1, -1));
}
Example 100
Project: eclipse-optimus-master  File: TransformationDependencyTextNonResizableEditPolicy.java View source code
protected void paintFigure(Graphics graphics) {
    graphics.drawFocus(getBounds().getResized(-1, -1));
}
Example 101
Project: molic-master  File: MolicTextNonResizableEditPolicy.java View source code
protected void paintFigure(Graphics graphics) {
    graphics.drawFocus(getBounds().getResized(-1, -1));
}

Java Examples for javafx.scene.control.TextArea

The following java examples will help you to understand the usage of javafx.scene.control.TextArea. These source code samples are taken from different open source projects.

Example 1
Project: sandboxes-master  File: ChildrenInHBox.java View source code
@Override
public void start(Stage stage) throws Exception {
    HBox container = new HBox();
    container.setAlignment(Pos.BOTTOM_RIGHT);
    TextArea textArea = new TextArea("some bogus text");
    container.getChildren().addAll(textArea, new Label("With a label"));
    textArea.setMaxHeight(Control.USE_PREF_SIZE);
    stage.setScene(new Scene(container));
    stage.show();
}
Example 2
Project: closurefx-builder-master  File: GSSCopySectionController.java View source code
public AnchorPane create() throws Exception {
    AnchorPane anchorPane = new AnchorPane();
    anchorPane.setId("AnchorPane");
    anchorPane.setMinHeight(Control.USE_PREF_SIZE);
    anchorPane.setMinWidth(Control.USE_PREF_SIZE);
    anchorPane.setPrefHeight(Control.USE_COMPUTED_SIZE);
    anchorPane.setPrefWidth(Control.USE_COMPUTED_SIZE);
    TitledPane titledPane = new TitledPane();
    titledPane.setAnimated(false);
    titledPane.setCollapsible(false);
    titledPane.setPrefHeight(Control.USE_COMPUTED_SIZE);
    titledPane.setPrefWidth(Control.USE_COMPUTED_SIZE);
    titledPane.setText(bundle.getString("GSSCopySection"));
    AnchorPane.setBottomAnchor(titledPane, 0.0);
    AnchorPane.setLeftAnchor(titledPane, 0.0);
    AnchorPane.setRightAnchor(titledPane, 0.0);
    AnchorPane.setTopAnchor(titledPane, 0.0);
    VBox vBox3 = new VBox();
    vBox3.setPrefHeight(Control.USE_COMPUTED_SIZE);
    vBox3.setPrefWidth(Control.USE_COMPUTED_SIZE);
    vBox3.setSpacing(5.0);
    controlCopyrightNotice = new TextArea();
    controlCopyrightNotice.setMinHeight(50.0);
    controlCopyrightNotice.setMinWidth(100.0);
    controlCopyrightNotice.setPrefWidth(Control.USE_COMPUTED_SIZE);
    controlCopyrightNotice.setPromptText(bundle.getString("GSSCopySection_Desc"));
    controlCopyrightNotice.setWrapText(true);
    VBox.setVgrow(controlCopyrightNotice, Priority.ALWAYS);
    vBox3.getChildren().add(controlCopyrightNotice);
    Insets insets5 = new Insets(10.0, 10.0, 10.0, 10.0);
    vBox3.setPadding(insets5);
    titledPane.setContent(vBox3);
    anchorPane.getChildren().add(titledPane);
    initialize(null, bundle);
    return anchorPane;
}
Example 3
Project: griffon-master  File: ApplicationEventHandler.java View source code
public void onThrowableEvent(ThrowableEvent event) {
    uiThreadManager.runInsideUIAsync(() -> {
        TitledPane pane = new TitledPane();
        pane.setCollapsible(false);
        pane.setText("Stacktrace");
        TextArea textArea = new TextArea();
        textArea.setEditable(false);
        pane.setContent(textArea);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        event.getThrowable().printStackTrace(new PrintStream(baos));
        textArea.setText(baos.toString());
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Error");
        alert.setHeaderText("An unexpected error occurred");
        alert.getDialogPane().setContent(pane);
        alert.showAndWait();
    });
}
Example 4
Project: idnadrev-master  File: InsertImage.java View source code
@Override
public void execute(TextArea editor) {
    collectImages();
    if (dialog == null) {
        dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(button.getScene().getWindow());
        dialog.setTitle(Localized.get("select.image"));
    }
    StackPane container = new StackPane();
    container.setPadding(new Insets(5));
    container.getChildren().add(selectImageController.getImagePane());
    Scene scene = new Scene(container);
    dialog.setOnHiding( e -> {
        scene.setRoot(new StackPane());
    });
    dialog.setScene(scene);
    cssSheets.forEach(( sheet) -> {
        scene.getStylesheets().add(sheet);
    });
    dialog.show();
}
Example 5
Project: jabref-master  File: EditorMenus.java View source code
public static List<MenuItem> getDefaultMenu(TextArea textArea) {
    List<MenuItem> menuItems = new ArrayList<>();
    menuItems.add(new CaseChangeMenu(textArea.textProperty()));
    menuItems.add(new ConversionMenu(textArea.textProperty()));
    menuItems.add(new SeparatorMenuItem());
    menuItems.add(new ProtectedTermsMenu(textArea));
    menuItems.add(new SeparatorMenuItem());
    return menuItems;
}
Example 6
Project: JFoenix-master  File: JFXTextArea.java View source code
@Override
public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
    if (STYLEABLES == null) {
        final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Control.getClassCssMetaData());
        styleables.addAll(getClassCssMetaData());
        styleables.addAll(TextArea.getClassCssMetaData());
        STYLEABLES = Collections.unmodifiableList(styleables);
    }
    return STYLEABLES;
}
Example 7
Project: POL-POM-5-master  File: StepRepresentationLicence.java View source code
@Override
protected void drawStepContent() {
    super.drawStepContent();
    TextArea licenceWidget = new TextArea(licenceText);
    licenceWidget.setLayoutX(10);
    licenceWidget.setLayoutY(100);
    licenceWidget.setMinWidth(700);
    licenceWidget.setMaxWidth(700);
    licenceWidget.setMinHeight(308);
    licenceWidget.setMaxHeight(308);
    licenceWidget.setEditable(false);
    CheckBox confirmWidget = new CheckBox(translate("I agree"));
    confirmWidget.setOnAction( event -> {
        isAgree = !isAgree;
        confirmWidget.setSelected(isAgree);
        setNextButtonEnabled(isAgree);
    });
    confirmWidget.setLayoutX(10);
    confirmWidget.setLayoutY(418);
    setNextButtonEnabled(false);
    this.addToContentPane(licenceWidget);
    this.addToContentPane(confirmWidget);
}
Example 8
Project: sphereMiners-master  File: ErrorPopup.java View source code
public static void create(String titleText, String longMessage, @Nullable Throwable t) {
    Alert alert = new Alert(AlertType.ERROR);
    alert.setTitle("A Problem occured while running Sphere Miners");
    alert.setHeaderText(titleText);
    alert.setContentText(longMessage);
    if (t != null) {
        Label label = new Label("The exception stacktrace was:");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        TextArea textArea = new TextArea(sw.toString());
        textArea.setEditable(false);
        textArea.setWrapText(true);
        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        GridPane.setVgrow(textArea, Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);
        GridPane expContent = new GridPane();
        expContent.setMaxWidth(Double.MAX_VALUE);
        expContent.add(label, 0, 0);
        expContent.add(textArea, 0, 1);
        // Set expandable Exception into the dialog pane.
        alert.getDialogPane().setExpandableContent(expContent);
    }
    alert.showAndWait();
}
Example 9
Project: TwitDuke-master  File: Main.java View source code
@Override
public void start(Stage stage) throws Exception {
    if (!existsTwitDukeDir()) {
        DirectoryHelper.createTwitDukeDirectories();
    }
    AccountManager accountManager = AccountManagerFactory.newInstance();
    if (accountManager.hasValidAccount()) {
        FXMLLoader mainLoader = FXMLResources.MAIN.loader();
        FXMLLoader toolbarLoader = FXMLResources.TWEET_TEXTAREA_TOOLBAR.loader();
        FXMLLoader textAreaLoader = FXMLResources.TWEET_TEXTAREA.loader();
        Scene main = new Scene(mainLoader.load());
        MainViewController mainController = mainLoader.getController();
        BorderPane borderPane = toolbarLoader.load();
        TextArea textArea = textAreaLoader.load();
        mainController.setTweetTextAreaToolbar(borderPane);
        mainController.setTweetTextArea(textArea);
        TweetTextareaToolbarController toolbarController = toolbarLoader.getController();
        TweetTextareaController tweetTextareaController = textAreaLoader.getController();
        toolbarController.addTweetTextAreaController(tweetTextareaController);
        toolbarController.setSaveDraftButtonListener(tweetTextareaController);
        applyKeymap(stage);
        stage.setScene(main);
        stage.show();
    } else {
        startOAuth(accountManager, System.out::println);
    }
}
Example 10
Project: bitcoin-exchange-master  File: CashDepositForm.java View source code
public static int addFormForBuyer(GridPane gridPane, int gridRow, PaymentAccountContractData paymentAccountContractData) {
    CashDepositAccountContractData data = (CashDepositAccountContractData) paymentAccountContractData;
    String countryCode = data.getCountryCode();
    String requirements = data.getRequirements();
    boolean showRequirements = requirements != null && !requirements.isEmpty();
    if (data.getHolderTaxId() != null)
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Account holder name / email / " + BankUtil.getHolderIdLabel(countryCode), data.getHolderName() + " / " + data.getHolderEmail() + " / " + data.getHolderTaxId());
    else
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Account holder name / email:", data.getHolderName() + " / " + data.getHolderEmail());
    if (!showRequirements)
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Country of bank:", CountryUtil.getNameAndCode(countryCode));
    else
        requirements += "\nCountry of bank: " + CountryUtil.getNameAndCode(countryCode);
    // We don't want to display more than 6 rows to avoid scrolling, so if we get too many fields we combine them horizontally
    int nrRows = 0;
    if (BankUtil.isBankNameRequired(countryCode))
        nrRows++;
    if (BankUtil.isBankIdRequired(countryCode))
        nrRows++;
    if (BankUtil.isBranchIdRequired(countryCode))
        nrRows++;
    if (BankUtil.isAccountNrRequired(countryCode))
        nrRows++;
    if (BankUtil.isAccountTypeRequired(countryCode))
        nrRows++;
    String bankNameLabel = BankUtil.getBankNameLabel(countryCode);
    String bankIdLabel = BankUtil.getBankIdLabel(countryCode);
    String branchIdLabel = BankUtil.getBranchIdLabel(countryCode);
    String accountNrLabel = BankUtil.getAccountNrLabel(countryCode);
    String accountTypeLabel = BankUtil.getAccountTypeLabel(countryCode);
    boolean accountNrAccountTypeCombined = false;
    boolean bankNameBankIdCombined = false;
    boolean bankIdBranchIdCombined = false;
    boolean bankNameBranchIdCombined = false;
    boolean branchIdAccountNrCombined = false;
    if (nrRows > 2) {
        // Try combine AccountNr + AccountType
        accountNrAccountTypeCombined = BankUtil.isAccountNrRequired(countryCode) && BankUtil.isAccountTypeRequired(countryCode);
        if (accountNrAccountTypeCombined)
            nrRows--;
        if (nrRows > 2) {
            // Next we try BankName + BankId
            bankNameBankIdCombined = BankUtil.isBankNameRequired(countryCode) && BankUtil.isBankIdRequired(countryCode);
            if (bankNameBankIdCombined)
                nrRows--;
            if (nrRows > 2) {
                // Next we try BankId + BranchId
                bankIdBranchIdCombined = !bankNameBankIdCombined && BankUtil.isBankIdRequired(countryCode) && BankUtil.isBranchIdRequired(countryCode);
                if (bankIdBranchIdCombined)
                    nrRows--;
                if (nrRows > 2) {
                    // Next we try BankId + BranchId
                    bankNameBranchIdCombined = !bankNameBankIdCombined && !bankIdBranchIdCombined && BankUtil.isBankNameRequired(countryCode) && BankUtil.isBranchIdRequired(countryCode);
                    if (bankNameBranchIdCombined)
                        nrRows--;
                    if (nrRows > 2) {
                        branchIdAccountNrCombined = !bankNameBranchIdCombined && !bankIdBranchIdCombined && !accountNrAccountTypeCombined && BankUtil.isBranchIdRequired(countryCode) && BankUtil.isAccountNrRequired(countryCode);
                        if (branchIdAccountNrCombined)
                            nrRows--;
                        if (nrRows > 2)
                            log.warn("We still have too many rows....");
                    }
                }
            }
        }
    }
    if (bankNameBankIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel.substring(0, bankNameLabel.length() - 1) + " / " + bankIdLabel.substring(0, bankIdLabel.length() - 1) + ":", data.getBankName() + " / " + data.getBankId());
    }
    if (bankNameBranchIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel.substring(0, bankNameLabel.length() - 1) + " / " + branchIdLabel.substring(0, branchIdLabel.length() - 1) + ":", data.getBankName() + " / " + data.getBranchId());
    }
    if (!bankNameBankIdCombined && !bankNameBranchIdCombined && BankUtil.isBankNameRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel, data.getBankName());
    if (!bankNameBankIdCombined && !bankNameBranchIdCombined && !branchIdAccountNrCombined && bankIdBranchIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankIdLabel.substring(0, bankIdLabel.length() - 1) + " / " + branchIdLabel.substring(0, branchIdLabel.length() - 1) + ":", data.getBankId() + " / " + data.getBranchId());
    }
    if (!bankNameBankIdCombined && !bankIdBranchIdCombined && BankUtil.isBankIdRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankIdLabel, data.getBankId());
    if (!bankNameBranchIdCombined && !bankIdBranchIdCombined && branchIdAccountNrCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, branchIdLabel.substring(0, branchIdLabel.length() - 1) + " / " + accountNrLabel.substring(0, accountNrLabel.length() - 1) + ":", data.getBranchId() + " / " + data.getAccountNr());
    }
    if (!bankNameBranchIdCombined && !bankIdBranchIdCombined && !branchIdAccountNrCombined && BankUtil.isBranchIdRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, branchIdLabel, data.getBranchId());
    if (!branchIdAccountNrCombined && accountNrAccountTypeCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountNrLabel.substring(0, accountNrLabel.length() - 1) + " / " + accountTypeLabel, data.getAccountNr() + " / " + data.getAccountType());
    }
    if (!branchIdAccountNrCombined && !accountNrAccountTypeCombined && BankUtil.isAccountNrRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountNrLabel, data.getAccountNr());
    if (!accountNrAccountTypeCombined && BankUtil.isAccountTypeRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountTypeLabel, data.getAccountType());
    if (showRequirements) {
        TextArea textArea = addLabelTextArea(gridPane, ++gridRow, "Extra requirements:", "").second;
        textArea.setMinHeight(45);
        textArea.setMaxHeight(45);
        textArea.setEditable(false);
        textArea.setId("text-area-disabled");
        textArea.setText(requirements);
    }
    return gridRow;
}
Example 11
Project: bitsquare-master  File: CashDepositForm.java View source code
public static int addFormForBuyer(GridPane gridPane, int gridRow, PaymentAccountContractData paymentAccountContractData) {
    CashDepositAccountContractData data = (CashDepositAccountContractData) paymentAccountContractData;
    String countryCode = data.getCountryCode();
    String requirements = data.getRequirements();
    boolean showRequirements = requirements != null && !requirements.isEmpty();
    if (data.getHolderTaxId() != null)
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Account holder name / email / " + BankUtil.getHolderIdLabel(countryCode), data.getHolderName() + " / " + data.getHolderEmail() + " / " + data.getHolderTaxId());
    else
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Account holder name / email:", data.getHolderName() + " / " + data.getHolderEmail());
    if (!showRequirements)
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Country of bank:", CountryUtil.getNameAndCode(countryCode));
    else
        requirements += "\nCountry of bank: " + CountryUtil.getNameAndCode(countryCode);
    // We don't want to display more than 6 rows to avoid scrolling, so if we get too many fields we combine them horizontally
    int nrRows = 0;
    if (BankUtil.isBankNameRequired(countryCode))
        nrRows++;
    if (BankUtil.isBankIdRequired(countryCode))
        nrRows++;
    if (BankUtil.isBranchIdRequired(countryCode))
        nrRows++;
    if (BankUtil.isAccountNrRequired(countryCode))
        nrRows++;
    if (BankUtil.isAccountTypeRequired(countryCode))
        nrRows++;
    String bankNameLabel = BankUtil.getBankNameLabel(countryCode);
    String bankIdLabel = BankUtil.getBankIdLabel(countryCode);
    String branchIdLabel = BankUtil.getBranchIdLabel(countryCode);
    String accountNrLabel = BankUtil.getAccountNrLabel(countryCode);
    String accountTypeLabel = BankUtil.getAccountTypeLabel(countryCode);
    boolean accountNrAccountTypeCombined = false;
    boolean bankNameBankIdCombined = false;
    boolean bankIdBranchIdCombined = false;
    boolean bankNameBranchIdCombined = false;
    boolean branchIdAccountNrCombined = false;
    if (nrRows > 2) {
        // Try combine AccountNr + AccountType
        accountNrAccountTypeCombined = BankUtil.isAccountNrRequired(countryCode) && BankUtil.isAccountTypeRequired(countryCode);
        if (accountNrAccountTypeCombined)
            nrRows--;
        if (nrRows > 2) {
            // Next we try BankName + BankId
            bankNameBankIdCombined = BankUtil.isBankNameRequired(countryCode) && BankUtil.isBankIdRequired(countryCode);
            if (bankNameBankIdCombined)
                nrRows--;
            if (nrRows > 2) {
                // Next we try BankId + BranchId
                bankIdBranchIdCombined = !bankNameBankIdCombined && BankUtil.isBankIdRequired(countryCode) && BankUtil.isBranchIdRequired(countryCode);
                if (bankIdBranchIdCombined)
                    nrRows--;
                if (nrRows > 2) {
                    // Next we try BankId + BranchId
                    bankNameBranchIdCombined = !bankNameBankIdCombined && !bankIdBranchIdCombined && BankUtil.isBankNameRequired(countryCode) && BankUtil.isBranchIdRequired(countryCode);
                    if (bankNameBranchIdCombined)
                        nrRows--;
                    if (nrRows > 2) {
                        branchIdAccountNrCombined = !bankNameBranchIdCombined && !bankIdBranchIdCombined && !accountNrAccountTypeCombined && BankUtil.isBranchIdRequired(countryCode) && BankUtil.isAccountNrRequired(countryCode);
                        if (branchIdAccountNrCombined)
                            nrRows--;
                        if (nrRows > 2)
                            log.warn("We still have too many rows....");
                    }
                }
            }
        }
    }
    if (bankNameBankIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel.substring(0, bankNameLabel.length() - 1) + " / " + bankIdLabel.substring(0, bankIdLabel.length() - 1) + ":", data.getBankName() + " / " + data.getBankId());
    }
    if (bankNameBranchIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel.substring(0, bankNameLabel.length() - 1) + " / " + branchIdLabel.substring(0, branchIdLabel.length() - 1) + ":", data.getBankName() + " / " + data.getBranchId());
    }
    if (!bankNameBankIdCombined && !bankNameBranchIdCombined && BankUtil.isBankNameRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankNameLabel, data.getBankName());
    if (!bankNameBankIdCombined && !bankNameBranchIdCombined && !branchIdAccountNrCombined && bankIdBranchIdCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankIdLabel.substring(0, bankIdLabel.length() - 1) + " / " + branchIdLabel.substring(0, branchIdLabel.length() - 1) + ":", data.getBankId() + " / " + data.getBranchId());
    }
    if (!bankNameBankIdCombined && !bankIdBranchIdCombined && BankUtil.isBankIdRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, bankIdLabel, data.getBankId());
    if (!bankNameBranchIdCombined && !bankIdBranchIdCombined && branchIdAccountNrCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, branchIdLabel.substring(0, branchIdLabel.length() - 1) + " / " + accountNrLabel.substring(0, accountNrLabel.length() - 1) + ":", data.getBranchId() + " / " + data.getAccountNr());
    }
    if (!bankNameBranchIdCombined && !bankIdBranchIdCombined && !branchIdAccountNrCombined && BankUtil.isBranchIdRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, branchIdLabel, data.getBranchId());
    if (!branchIdAccountNrCombined && accountNrAccountTypeCombined) {
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountNrLabel.substring(0, accountNrLabel.length() - 1) + " / " + accountTypeLabel, data.getAccountNr() + " / " + data.getAccountType());
    }
    if (!branchIdAccountNrCombined && !accountNrAccountTypeCombined && BankUtil.isAccountNrRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountNrLabel, data.getAccountNr());
    if (!accountNrAccountTypeCombined && BankUtil.isAccountTypeRequired(countryCode))
        addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, accountTypeLabel, data.getAccountType());
    if (showRequirements) {
        TextArea textArea = addLabelTextArea(gridPane, ++gridRow, "Extra requirements:", "").second;
        textArea.setMinHeight(45);
        textArea.setMaxHeight(45);
        textArea.setEditable(false);
        textArea.setId("text-area-disabled");
        textArea.setText(requirements);
    }
    return gridRow;
}
Example 12
Project: javaee7-samples-master  File: GoogleDocClient.java View source code
@Override
public void start(Stage stage) throws Exception {
    final Session session = connectToServer();
    System.out.println("Connected to server: " + session.getId());
    stage.setTitle("Google Docs Emulator using WebSocket");
    textarea = new TextArea();
    textarea.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            System.out.println("New value: " + newValue);
            try {
                session.getBasicRemote().sendText(newValue);
            } catch (IOException ex) {
                Logger.getLogger(GoogleDocClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    textarea.setPrefSize(500, 300);
    textarea.setWrapText(true);
    Scene scene = new Scene(textarea);
    stage.setScene(scene);
    stage.show();
}
Example 13
Project: chunky-master  File: ChunkyErrorDialog.java View source code
/**
   * Add a log record to be displayed by this error dialog.
   */
public synchronized void addErrorMessage(String message) {
    errorCount += 1;
    BorderPane.setMargin(tabPane, new Insets(10, 0, 0, 0));
    BorderPane pane = new BorderPane();
    pane.setPadding(new Insets(10));
    TextArea text = new TextArea();
    text.setText(message);
    text.setEditable(false);
    text.setPrefHeight(Region.USE_COMPUTED_SIZE);
    pane.setPrefHeight(Region.USE_COMPUTED_SIZE);
    pane.setCenter(text);
    Button dismiss = new Button("Dismiss");
    BorderPane.setAlignment(dismiss, Pos.BOTTOM_RIGHT);
    BorderPane.setMargin(dismiss, new Insets(10, 0, 0, 0));
    pane.setBottom(dismiss);
    Tab tab = new Tab("Error " + errorCount, pane);
    tabPane.getTabs().add(tab);
    dismiss.setOnAction( event -> {
        tabPane.getTabs().remove(tab);
        if (tabPane.getTabs().isEmpty()) {
            hide();
        }
    });
}
Example 14
Project: chvote-1-0-master  File: InterruptibleProcessController.java View source code
private void showAlert(ProcessInterruptedException e) {
    Alert alert = new Alert(Alert.AlertType.ERROR);
    ResourceBundle resources = getResourceBundle();
    alert.setTitle(resources.getString("exception_alert.title"));
    alert.setHeaderText(resources.getString("exception_alert.header"));
    alert.setContentText(e.getMessage());
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    String exceptionText = sw.toString();
    Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
    TextArea stackTraceTextArea = new TextArea(exceptionText);
    stackTraceTextArea.setEditable(false);
    stackTraceTextArea.setWrapText(true);
    GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
    GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
    GridPane expandableContent = new GridPane();
    expandableContent.setPrefSize(400, 400);
    expandableContent.setMaxWidth(Double.MAX_VALUE);
    expandableContent.add(stackTraceLabel, 0, 0);
    expandableContent.add(stackTraceTextArea, 0, 1);
    alert.getDialogPane().setExpandableContent(expandableContent);
    // Expandable zones cause the dialog not to resize correctly
    if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
        alert.getDialogPane().setPrefSize(600, 400);
        alert.setResizable(true);
        alert.getDialogPane().setExpanded(true);
    }
    alert.showAndWait();
}
Example 15
Project: joa-master  File: NoteTaskPane.java View source code
@Override
public Scene createScene() throws ComException {
    // The Outlook application interface
    app = Globals.getThisAddin().getApplication();
    // Selected mail
    mailItem = inspector.getCurrentItem().as(MailItem.class);
    // Categories
    final Categories categories = app.GetNamespace("MAPI").getCategories();
    catList = CategoryItem.createObservableListOfCategories(categories);
    catList.sort(( p,  q) -> p.toString().compareTo(q.toString()));
    // ------------------------------------------------------------------------
    // The task panes position might be of interest for building the layout
    // of the scene:
    // MsoCTPDockPosition dockPosition =
    // super.customTaskPane.getDockPosition();
    // int wd = super.customTaskPane.getWidth();
    // int ht = super.customTaskPane.getHeight();
    // Allow to dock the task pane only at the left and right border
    // of the inspector window
    customTaskPane.setDockPositionRestrict(MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoHorizontal);
    // ------------------------------------------------------------------------
    // Initialize note category with mail category
    String mailCats = mailItem.getCategories();
    if (mailCats != null && mailCats.length() != 0) {
        String[] mailCatArr = mailCats.split(categoryListDelimiter);
        String mailCat = mailCatArr.length != 0 ? mailCatArr[mailCatArr.length - 1] : null;
        if (mailCat != null) {
            for (CategoryItem cat : catList) {
                if (cat.toString().equals(mailCat)) {
                    noteGridDefaultBackgColor = cat.getColor();
                    break;
                }
            }
        }
    }
    // ------------------------------------------------------------------------
    // Build the scene
    VBox root = new VBox();
    root.setSpacing(4);
    final Scene scene = new Scene(root);
    scene.getStylesheets().add("com/wilutions/joa/example/cnaddin/stylesheet.css");
    // ------------------------------------------------------------------------
    // The note is displayed in a view based on a GridPane with three
    // columns
    int noteRowIdx = 0;
    noteGrid = new GridPane();
    setNoteGridStyleIfUnsafed(noteGrid, noteGridDefaultBackgColor);
    noteGrid.setPadding(new Insets(2));
    noteGrid.setVgap(2);
    root.getChildren().add(noteGrid);
    // ------------------------------------------------------------------------
    // The note header bar
    int headerRectsSize = 16;
    noteGrid.getRowConstraints().add(new RowConstraints(headerRectsSize, headerRectsSize, headerRectsSize));
    noteGrid.getColumnConstraints().add(new ColumnConstraints(headerRectsSize, headerRectsSize, headerRectsSize));
    noteGrid.getColumnConstraints().add(new ColumnConstraints(headerRectsSize, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));
    noteGrid.getColumnConstraints().add(new ColumnConstraints(headerRectsSize, headerRectsSize, headerRectsSize));
    // Note icon in left column
    Image img = new Image("com/wilutions/joa/example/cnaddin/NoteIcon.png");
    ImageView noteLeftBox = new ImageView(img);
    noteLeftBox.setFitWidth(16);
    noteLeftBox.setFitHeight(16);
    // Note header label (*New*, *Modified*, -Saved-)
    VBox noteHeaderBar = new VBox();
    GridPane.setMargin(noteHeaderBar, new Insets(8, 4, 8, 4));
    noteHeaderBar.setAlignment(Pos.CENTER);
    noteHeaderLabel = new Label();
    noteHeaderLabel.setStyle("-fx-background-color: " + toRGB(noteHeaderColor) + "; -fx-text-fill: white");
    noteHeaderLabel.setMinHeight(16);
    noteHeaderLabel.setMaxHeight(16);
    noteHeaderLabel.setMinWidth(10);
    noteHeaderLabel.setMaxWidth(Double.MAX_VALUE);
    noteHeaderLabel.setAlignment(Pos.CENTER);
    updateNoteState(NoteState.New);
    noteHeaderBar.getChildren().add(noteHeaderLabel);
    // Right square
    Rectangle noteRightBox = new Rectangle(headerRectsSize, headerRectsSize, noteHeaderColor);
    noteGrid.add(noteLeftBox, 0, noteRowIdx);
    noteGrid.add(noteHeaderBar, 1, noteRowIdx);
    noteGrid.add(noteRightBox, 2, noteRowIdx);
    noteRowIdx++;
    // --------------------------------------------------------------------
    // Edit box for note text
    noteText = new TextArea();
    noteText.setPrefRowCount(10);
    noteText.setWrapText(true);
    String subject = mailItem.getSubject();
    if (!subject.isEmpty()) {
        noteText.setText(subject + CRLF);
    }
    noteGrid.add(noteText, 0, noteRowIdx++, 3, 1);
    noteGrid.getRowConstraints().add(new RowConstraints());
    // Add a change listener to set the header label to "*Modified*".
    noteText.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            updateNoteState(NoteState.Modified);
        }
    });
    // The edit box should not eat the TAB key. This listener forwards
    // the focus to the next control, if the TAB key is pressed.
    noteText.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.TAB) {
                TextAreaSkin skin = (TextAreaSkin) noteText.getSkin();
                if (skin.getBehavior() instanceof TextAreaBehavior) {
                    TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior();
                    if (event.isControlDown()) {
                        behavior.callAction("InsertTab");
                    } else if (event.isShiftDown()) {
                        behavior.callAction("TraversePrevious");
                    } else {
                        behavior.callAction("TraverseNext");
                    }
                    event.consume();
                }
            }
        }
    });
    // --------------------------------------------------------------------
    // Line between edit box and date label
    Line noteBottomLine = new Line();
    noteBottomLine.setStartX(0);
    noteBottomLine.setStartY(0);
    noteBottomLine.setEndX(0);
    noteBottomLine.setEndY(0);
    NumberBinding bottomLineBinding = Bindings.add(noteGrid.widthProperty(), 0);
    noteBottomLine.endXProperty().bind(bottomLineBinding.subtract(8));
    noteGrid.add(noteBottomLine, 0, noteRowIdx++, 3, 1);
    noteGrid.getRowConstraints().add(new RowConstraints(3, 3, 3));
    // --------------------------------------------------------------------
    // Date label
    final Text noteDate = new Text();
    noteDate.setStyle("-fx-font: 12px \"Courier\"; -fx-font-weight: bold");
    noteGrid.getRowConstraints().add(new RowConstraints());
    noteGrid.add(noteDate, 0, noteRowIdx++, 3, 1);
    // This timer updates the note date
    timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            Platform.runLater(() -> {
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT);
                ZonedDateTime date = ZonedDateTime.now();
                noteDate.setText(date.format(dateFormatter));
            });
        }
    }, 0, 1000);
    // --------------------------------------------------------------------
    // Checkbox "Display new note"
    ckDisplay = new CheckBox("Display new note");
    ckDisplay.setSelected(reg_displayNote);
    root.getChildren().add(ckDisplay);
    // --------------------------------------------------------------------
    // Checkbox "Assign category to mail"
    ckCatMail = new CheckBox("Assign category to mail");
    ckCatMail.setSelected(reg_alsoCategorizeMail);
    root.getChildren().add(ckCatMail);
    for (CategoryItem cat : catList) {
        Button btn = new Button(cat.toString());
        root.getChildren().add(btn);
        String style = "-fx-background-color: " + toRGB(cat.getColor()) + "; ";
        if (isDarkColor(cat.getColor())) {
            style += "-fx-text-fill: white;";
        }
        btn.setStyle(style);
        btn.setMaxWidth(Double.MAX_VALUE);
        btn.setMaxHeight(20);
        btn.setCursor(Cursor.HAND);
        btn.setTooltip(new Tooltip("Create the note \n and assign it to category \"" + cat.toString() + "\"."));
        // This event handlers color the note view with the color of the
        // category
        btn.setOnMouseEntered(( e) -> setNoteGridStyleIfUnsafed(noteGrid, cat.getColor()));
        btn.setOnMouseExited(( e) -> setNoteGridStyleIfUnsafed(noteGrid, noteGridDefaultBackgColor));
        // This action handler creates the note.
        btn.setOnAction(new CategoryButtonActionEvent(cat));
    }
    return scene;
}
Example 16
Project: ScreenFX-master  File: RunDemo.java View source code
@Override
public void start(final Stage stage) {
    try {
        Stage stage1 = stage;
        stage1.setResizable(true);
        stage1.setWidth(300);
        stage1.setHeight(300);
        stage1.setX(200);
        stage1.setY(200);
        stage1.initStyle(StageStyle.DECORATED);
        stage1.setTitle("ScreenFX 1. stage");
        URL location = getClass().getResource("/examples/RunDemo.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader();
        Parent root = (Parent) fxmlLoader.load(location.openStream());
        Scene sc = new Scene(root);
        ScreenFXDemo fooController = (ScreenFXDemo) fxmlLoader.getController();
        stage1.setScene(sc);
        ScreenFX sfx0 = new ScreenFX();
        sfx0.installOn(fooController.getButtonShowScreenFX(), true);
        sfx0.installOn(fooController.getToggleButtonScreenFX(), false);
        stage1.show();
        Stage infoStage = new Stage(StageStyle.UNIFIED);
        ScreenFX sfx1 = new ScreenFX();
        sfx1.installOn(infoStage);
        infoStage.setTitle("ScreenFX info box");
        AnchorPane secondaryStageRoot = new AnchorPane();
        TextArea description = new TextArea(sfx1.getTooltipText());
        description.setEditable(false);
        description.setWrapText(true);
        AnchorPane.setBottomAnchor(description, 0d);
        AnchorPane.setTopAnchor(description, 0d);
        AnchorPane.setLeftAnchor(description, 0d);
        AnchorPane.setRightAnchor(description, 0d);
        secondaryStageRoot.getChildren().add(description);
        infoStage.setWidth(300);
        infoStage.setHeight(300);
        infoStage.setX(500);
        infoStage.setY(200);
        infoStage.setScene(new Scene(secondaryStageRoot));
        infoStage.show();
        Stage stage2 = new Stage();
        stage2.setTitle("ScreenFX 2. stage");
        AnchorPane stage2root = new AnchorPane();
        stage2.initStyle(StageStyle.DECORATED);
        //			stage2.setResizable(false);
        Button button = new Button("Show ScreenFX");
        stage2root.getChildren().add(button);
        stage2.setWidth(300);
        stage2.setHeight(300);
        stage2.setX(200);
        stage2.setY(500);
        Scene scene = new Scene(stage2root);
        stage2.setScene(scene);
        ScreenFX sfx2 = new ScreenFX();
        // install the resize
        sfx2.installOn(button, false);
        // controller
        // a stage to control another
        // stage
        stage2.show();
        Stage stage3 = new Stage();
        stage3.setTitle("ScreenFX 3. stage");
        AnchorPane stage3root = new AnchorPane();
        stage3root.getChildren().add(button);
        stage3.setWidth(300);
        stage3.setHeight(300);
        stage3.setX(500);
        stage3.setY(500);
        stage3.setScene(new Scene(stage3root));
        stage3.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 17
Project: AoW-Java-API-master  File: JavaFxConsole.java View source code
/**
     * @throws IOException If an error loading the .fxml file occurs.
     */
public Parent build() throws IOException {
    final Parent consoleNode = (Parent) loader.load();
    // Create the terminal.
    final TextArea textArea = (TextArea) consoleNode.lookup("#terminal");
    textArea.setFocusTraversable(false);
    mTerminal = new JavaFxTerminal(textArea);
    // Create the shell.
    final DisplayDriver displayDriver = new TerminalDisplayDriver(mTerminal, configuration);
    final Shell shell = new Shell(fileSystem, displayDriver, welcomeMessage);
    // Create the command line.
    final TextField commandLine = (TextField) consoleNode.lookup("#commandLine");
    final CommandLineDriver commandLineDriver = new JavaFxCommandLineDriver(commandLine);
    // Create the console.
    final Console console = new ConsoleImpl(shell, commandLineDriver, maxCommandHistory);
    // Hook the commandLine to the console.
    commandLine.requestFocus();
    commandLine.addEventFilter(KeyEvent.KEY_PRESSED, new JavaFxConsoleDriver(console));
    return consoleNode;
}
Example 18
Project: CCAutotyper-master  File: FXGuiUtils.java View source code
public static Alert buildLongAlert(String context, String longMessage, Node... additional) {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setHeaderText(context);
    Label label = new Label("Details: ");
    TextArea textArea = new TextArea(longMessage);
    textArea.setEditable(false);
    textArea.setWrapText(false);
    textArea.setMaxHeight(Double.MAX_VALUE);
    textArea.setMaxWidth(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, Priority.ALWAYS);
    GridPane.setHgrow(textArea, Priority.ALWAYS);
    GridPane expanded = new GridPane();
    expanded.setMaxWidth(Double.MAX_VALUE);
    expanded.add(label, 0, 0);
    expanded.add(textArea, 0, 1);
    for (int i = 0; i < additional.length; i++) expanded.add(additional[i], 0, 2 + i);
    alert.getDialogPane().setContent(expanded);
    alert.getDialogPane().setPrefWidth(700);
    alert.getDialogPane().setPrefHeight(400);
    return alert;
}
Example 19
Project: grantmaster-master  File: Utils.java View source code
public static Optional<ButtonType> showSimpleErrorDialog(String title, String message, List<ButtonType> extraButtons) {
    Alert alert = new Alert(Alert.AlertType.ERROR);
    alert.setTitle(Utils.getString(title));
    alert.setResizable(true);
    TextArea text = new TextArea(message);
    text.setWrapText(true);
    text.setEditable(false);
    alert.setGraphic(text);
    if (extraButtons != null) {
        alert.getButtonTypes().addAll(extraButtons);
    }
    return alert.showAndWait();
}
Example 20
Project: htm.java-examples-master  File: BreakingNewsDemoView.java View source code
public DualPanel createInputPane() {
    DualPanel retVal = new DualPanel();
    LabelledRadiusPane left = new LabelledRadiusPane("Input Tweet");
    TextArea lArea = new TextArea();
    lArea.setWrapText(true);
    lArea.setFont(Font.font("Helvetica", FontWeight.MEDIUM, 16));
    lArea.layoutYProperty().bind(left.labelHeightProperty().add(10));
    left.layoutBoundsProperty().addListener(( v,  o,  n) -> {
        lArea.setLayoutX(10);
        lArea.setPrefWidth(n.getWidth() - 20);
        lArea.setPrefHeight(n.getHeight() - left.labelHeightProperty().get() - 20);
    });
    Label queueLabel = new Label("Processing Queue Size:");
    queueLabel.layoutXProperty().bind(lArea.widthProperty().subtract(queueLabel.getLayoutBounds().getWidth() + 330));
    queueLabel.setLayoutY(lArea.getLayoutY() - queueLabel.getLayoutBounds().getHeight() - 35);
    queueLabel.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
    queueLabel.setTextFill(Color.rgb(00, 70, 107));
    queueDisplayProperty.set(queueLabel);
    Label curLabel = new Label("Current Tweet:");
    curLabel.layoutXProperty().bind(lArea.widthProperty().subtract(curLabel.getLayoutBounds().getWidth() + 110));
    curLabel.setLayoutY(lArea.getLayoutY() - curLabel.getLayoutBounds().getHeight() - 35);
    curLabel.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
    curLabel.setTextFill(Color.rgb(00, 70, 107));
    currentLabelProperty.set(curLabel.textProperty());
    left.getChildren().addAll(lArea, queueLabel, curLabel);
    LabelledRadiusPane right = new LabelledRadiusPane("Scrubbed Tweet");
    TextArea rArea = new TextArea();
    rArea.setWrapText(true);
    rArea.setFont(Font.font("Helvetica", FontWeight.MEDIUM, 16));
    rArea.layoutYProperty().bind(right.labelHeightProperty().add(10));
    right.layoutBoundsProperty().addListener(( v,  o,  n) -> {
        rArea.setLayoutX(10);
        rArea.setPrefWidth(n.getWidth() - 20);
        rArea.setPrefHeight(n.getHeight() - right.labelHeightProperty().get() - 20);
    });
    right.getChildren().add(rArea);
    retVal.setLeftPane(left);
    retVal.setRightPane(right);
    inputPaneProperty.set(new Pair<>(lArea, rArea));
    return retVal;
}
Example 21
Project: JacpFX-demos-master  File: ComponentLeftTop.java View source code
/**
     * create the UI on first call
     *
     * @return
     */
private Node createUI() {
    text = new TextArea();
    text.setText("");
    text.setWrapText(true);
    text.setStyle("-fx-background-color: #4D7A97; -fx-text-fill: #e1e1e1; -fx-font-style: oblique;-fx-font-size: 20;");
    HBox.setHgrow(text, Priority.ALWAYS);
    VBox.setVgrow(text, Priority.ALWAYS);
    text.setMaxHeight(250);
    return text;
}
Example 22
Project: JFXScad-master  File: RedirectableStream.java View source code
@Override
public synchronized void write(byte[] buf, int off, int len) {
    if (isRedirectToUi()) {
        invokeAndWait(() -> {
            int i = 0;
            for (TextArea view : views) {
                String s = new String(buf, off, len);
                if (filters.get(i).onMatch(s)) {
                    try {
                        int startOffSet = view.getText().length();
                        view.insertText(startOffSet, s);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    }
                }
                i++;
            }
        });
    //                view.setCaretPosition(startOffSet + len);
    //            } 
    //            catch (BadLocationException e) {
    // e.printStackTrace();
    //            Platform.invokeLater(new Runnable() {
    //
    //                @Override
    //                public void run() {
    //                    // automatically scroll down to the last line
    ////                    view.scrollRectToVisible(
    ////                            new Rectangle(0, view.getHeight() - 1, 1, 1));
    //
    //                }
    //            });
    }
    if (isRedirectToStdOut()) {
        super.write(buf, off, len);
    }
}
Example 23
Project: jfxtras-master  File: PopupReviseAllTest.java View source code
@Test
public void canEditDescribableProperties() {
    VEvent vevent = ICalendarStaticComponents.getDaily1();
    TestUtil.runThenWaitForPaintPulse(() -> {
        getEditComponentPopup().setupData(vevent, LocalDateTime.of(2016, 5, 15, 10, 0), LocalDateTime.of(2016, 5, 15, 11, 0), categories());
    });
    // Get properties
    LocalDateTimeTextField startDateTimeTextField = find("#startDateTimeTextField");
    LocalDateTimeTextField endDateTimeTextField = find("#endDateTimeTextField");
    CheckBox wholeDayCheckBox = find("#wholeDayCheckBox");
    TextField summaryTextField = find("#summaryTextField");
    TextArea descriptionTextArea = find("#descriptionTextArea");
    TextField locationTextField = find("#locationTextField");
    TextField categoryTextField = find("#categoryTextField");
    CategorySelectionGridPane categorySelectionGridPane = find("#categorySelectionGridPane");
    // Check initial state
    assertEquals(LocalDateTime.of(2016, 5, 15, 10, 00), startDateTimeTextField.getLocalDateTime());
    assertEquals(LocalDateTime.of(2016, 5, 15, 11, 00), endDateTimeTextField.getLocalDateTime());
    assertTrue(startDateTimeTextField.isVisible());
    assertTrue(endDateTimeTextField.isVisible());
    assertEquals("Daily1 Summary", summaryTextField.getText());
    assertEquals("Daily1 Description", descriptionTextArea.getText());
    assertEquals("group05", categoryTextField.getText());
    assertFalse(wholeDayCheckBox.isSelected());
    // Edit and check properties
    TestUtil.runThenWaitForPaintPulse(() -> wholeDayCheckBox.setSelected(true));
    LocalDateTextField startDateTextField = find("#startDateTextField");
    LocalDateTextField endDateTextField = find("#endDateTextField");
    assertEquals(LocalDate.of(2016, 5, 15), startDateTextField.getLocalDate());
    assertEquals(LocalDate.of(2016, 5, 16), endDateTextField.getLocalDate());
    assertTrue(startDateTextField.isVisible());
    assertTrue(endDateTextField.isVisible());
    TestUtil.runThenWaitForPaintPulse(() -> wholeDayCheckBox.setSelected(false));
    assertTrue(startDateTimeTextField.isVisible());
    assertTrue(endDateTimeTextField.isVisible());
    // Make changes
    startDateTimeTextField.setLocalDateTime(LocalDateTime.of(2016, 5, 15, 8, 0));
    summaryTextField.setText("new summary");
    descriptionTextArea.setText("new description");
    locationTextField.setText("new location");
    TestUtil.runThenWaitForPaintPulse(() -> categorySelectionGridPane.setCategorySelected(11));
    assertEquals("group11", categoryTextField.getText());
    categoryTextField.setText("new group name");
    // save to all
    clickOn("#saveComponentButton");
    ComboBox<ChangeDialogOption> comboBox = find("#changeDialogComboBox");
    TestUtil.runThenWaitForPaintPulse(() -> {
        comboBox.getSelectionModel().select(ChangeDialogOption.ALL);
    });
    clickOn("#changeDialogOkButton");
    // test iTIP message
    List<VCalendar> vMessages = getEditComponentPopup().iTIPMessagesProperty().get();
    assertEquals(1, vMessages.size());
    VCalendar vMessage = vMessages.get(0);
    assertEquals(1, vMessage.getVEvents().size());
    VEvent revisedVEvent = vMessage.getVEvents().get(0);
    VEvent expectedRevisedVEvent = ICalendarStaticComponents.getDaily1();
    expectedRevisedVEvent.setCategories(null);
    expectedRevisedVEvent.withDateTimeStart(LocalDateTime.of(2015, 11, 9, 8, 0)).withDateTimeEnd(LocalDateTime.of(2015, 11, 9, 9, 0)).withSummary("new summary").withDescription("new description").withLocation("new location").withCategories(Arrays.asList(new Categories("new group name"))).withDateTimeStamp(revisedVEvent.getDateTimeStamp()).withSequence(1);
    assertEquals(expectedRevisedVEvent, revisedVEvent);
    String iTIPMessage = vMessages.stream().map( v -> v.toString()).collect(Collectors.joining(System.lineSeparator()));
    String dtStamp = getEditComponentPopup().iTIPMessagesProperty().get().get(0).getVEvents().get(0).getDateTimeStamp().toString();
    String expectediTIPMessage = "BEGIN:VCALENDAR" + System.lineSeparator() + "METHOD:REQUEST" + System.lineSeparator() + "PRODID:" + ICalendarAgenda.DEFAULT_PRODUCT_IDENTIFIER + System.lineSeparator() + "VERSION:" + Version.DEFAULT_ICALENDAR_SPECIFICATION_VERSION + System.lineSeparator() + "BEGIN:VEVENT" + System.lineSeparator() + "CATEGORIES:new group name" + System.lineSeparator() + "DTSTART:20151109T080000" + System.lineSeparator() + "DTEND:20151109T090000" + System.lineSeparator() + "DESCRIPTION:new description" + System.lineSeparator() + "SUMMARY:new summary" + System.lineSeparator() + dtStamp + System.lineSeparator() + "UID:[email protected]" + System.lineSeparator() + "RRULE:FREQ=DAILY" + System.lineSeparator() + "ORGANIZER;CN=Papa Smurf:mailto:[email protected]" + System.lineSeparator() + "LOCATION:new location" + System.lineSeparator() + "SEQUENCE:1" + System.lineSeparator() + "END:VEVENT" + System.lineSeparator() + "END:VCALENDAR";
    assertEquals(expectediTIPMessage, iTIPMessage);
}
Example 24
Project: jointry-master  File: MainDemo.java View source code
@Override
public void start(Stage stage) {
    stage.setTitle("FX Keyboard (" + System.getProperty("javafx.runtime.version") + ")");
    stage.setResizable(true);
    String fontUrl = this.getClass().getResource("/font/FontKeyboardFX.ttf").toExternalForm();
    Font f = Font.loadFont(fontUrl, -1);
    System.err.println(f);
    /*
         Path numblockLayout = null;
         try {
         numblockLayout = Paths.get(this.getClass().getResource("/xml/numblock").toURI());
         } catch (URISyntaxException e) {
         e.printStackTrace();
         }
         popup = KeyBoardPopupBuilder.create().initScale(1.0).initLocale(Locale.ENGLISH).addIRobot(RobotFactory.createFXRobot()).layerPath(numblockLayout)
         .build();
         */
    popup = KeyBoardPopupBuilder.create().initScale(1.0).initLocale(Locale.ENGLISH).addIRobot(RobotFactory.createFXRobot()).build();
    popup.getKeyBoard().setOnKeyboardCloseButton(new EventHandler<Event>() {

        public void handle(Event event) {
            setPopupVisible(false, null);
        }
    });
    FlowPane pane = new FlowPane();
    pane.setVgap(20);
    pane.setHgap(20);
    pane.setPrefWrapLength(100);
    final TextField tf = new TextField("");
    final TextArea ta = new TextArea("");
    Button okButton = new Button("Ok");
    okButton.setDefaultButton(true);
    Button cancelButton = new Button("Cancel");
    cancelButton.setCancelButton(true);
    pane.getChildren().add(new Label("Text1"));
    pane.getChildren().add(tf);
    pane.getChildren().add(new Label("Text2"));
    pane.getChildren().add(ta);
    pane.getChildren().add(okButton);
    pane.getChildren().add(cancelButton);
    //pane.getChildren().add(KeyBoardBuilder.create().addIRobot(RobotFactory.createFXRobot()).build());
    Scene scene = new Scene(pane, 200, 300);
    // add keyboard scene listener to all text components
    scene.focusOwnerProperty().addListener(new ChangeListener<Node>() {

        @Override
        public void changed(ObservableValue<? extends Node> value, Node n1, Node n2) {
            if (n2 != null && n2 instanceof TextInputControl) {
                setPopupVisible(true, (TextInputControl) n2);
            } else {
                setPopupVisible(false, null);
            }
        }
    });
    String css = this.getClass().getResource("/css/KeyboardButtonStyle.css").toExternalForm();
    scene.getStylesheets().add(css);
    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {

        public void handle(WindowEvent event) {
            System.exit(0);
        }
    });
    stage.setScene(scene);
    popup.show(stage);
    stage.show();
}
Example 25
Project: tilisty-master  File: PropertyPanel.java View source code
/**
	 * Sets up the default properties required by the GridPane
	 * 
	 */
private void setupLayout() {
    this.setHgap(10);
    this.setVgap(10);
    this.setPadding(new Insets(25, 25, 25, 25));
    this.setAlignment(Pos.CENTER);
    jsonView = new TextArea();
    jsonView.setEditable(false);
    jsonView.setPrefHeight(TilistyView.APP_HEIGHT);
    jsonView.setPrefWidth(TilistyView.APP_WIDTH);
    //jsonView.applyCss();
    //set the default title for all properties panels.
    Text scenetitle = new Text("PROPERTIES");
    scenetitle.setFont(Font.font("Arial", FontWeight.NORMAL, 20));
    this.add(scenetitle, 0, 0, 1, 1);
    switchButton = new Button("VIEW JSON");
    switchButton.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            if (currentView != null) {
                if (switchButton.getText().equals("VIEW JSON")) {
                    switchButton.setText("VIEW PROPERTIES");
                    displayJSON();
                } else {
                    switchButton.setText("VIEW JSON");
                    renderPropertiesForView(currentView);
                }
            }
        }
    });
    this.add(switchButton, 1, 0);
}
Example 26
Project: aic-praise-master  File: FXUtil.java View source code
public static void exception(Throwable th) {
    Dialog<ButtonType> dialog = new Dialog<ButtonType>();
    dialog.setTitle("Program exception");
    final DialogPane dialogPane = dialog.getDialogPane();
    dialogPane.setContentText("Details of the problem:");
    dialogPane.getButtonTypes().addAll(ButtonType.OK);
    dialogPane.setContentText(th.getMessage());
    dialog.initModality(Modality.APPLICATION_MODAL);
    Label label = new Label("Exception stacktrace:");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    th.printStackTrace(pw);
    pw.close();
    TextArea textArea = new TextArea(sw.toString());
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, Priority.ALWAYS);
    GridPane.setHgrow(textArea, Priority.ALWAYS);
    GridPane root = new GridPane();
    root.setVisible(false);
    root.setMaxWidth(Double.MAX_VALUE);
    root.add(label, 0, 0);
    root.add(textArea, 0, 1);
    dialogPane.setExpandableContent(root);
    dialog.showAndWait();
}
Example 27
Project: bgfinancas-master  File: Janela.java View source code
public static void showException(Exception ex) {
    Alert alerta = new Alert(AlertType.ERROR);
    alerta.setTitle(idioma.getMensagem("erro"));
    alerta.setHeaderText(null);
    alerta.setContentText(ex.getMessage());
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    String exceptionText = sw.toString();
    TextArea textArea = new TextArea(exceptionText);
    textArea.setBackground(Background.EMPTY);
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    alerta.getDialogPane().setExpandableContent(textArea);
    alerta.showAndWait();
}
Example 28
Project: Bias-master  File: DialogUtil.java View source code
/**
     * Shows an exception [email protected] Dialog} with the specified properties. This is an error [email protected] Dialog} which contains
     * the stack trace of the [email protected] Throwable} as expandable content.
     * <p>
     *
     * @param appCtx the [email protected] ApplicationContext} for the application
     * @param title the title of the [email protected] Dialog}
     * @param header the header of the [email protected] Dialog}
     * @param content the content of the [email protected] Dialog}
     * @param t the [email protected] Throwable} whose stacktrace will be included in the [email protected] Dialog}
     */
public static void showExceptionDialog(ApplicationContext appCtx, String title, String header, String content, Throwable t) {
    Alert alert = new Alert(ERROR);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(content);
    String exceptionText = null;
    try (StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw)) {
        t.printStackTrace(pw);
        exceptionText = sw.toString();
    } catch (IOException ioe) {
    }
    Label label = new Label(appCtx.textFor(CONTENT_LABEL_EXCEPTION));
    TextArea textArea = new TextArea(exceptionText);
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, ALWAYS);
    GridPane.setHgrow(textArea, ALWAYS);
    GridPane expContent = new GridPane();
    expContent.setMaxWidth(Double.MAX_VALUE);
    expContent.add(label, 0, 0);
    expContent.add(textArea, 0, 1);
    // Set expandable Exception into the dialog pane.
    alert.getDialogPane().setExpandableContent(expContent);
    alert.showAndWait();
}
Example 29
Project: blackmarket-master  File: Dialogs.java View source code
public static void showExceptionDialog(Throwable throwable) {
    Alert alert = new Alert(AlertType.ERROR);
    alert.setTitle("Sorry something wrong happened");
    String header = throwable.getMessage();
    header = isBlank(header) ? throwable.getClass().getSimpleName() : header;
    alert.setHeaderText(header);
    //		alert.setGraphic(new ImageView(ImageCache.getInstance().get("/images/gallio/gallio-"
    //				+ comics[RandomUtils.nextInt(0, 3)] +
    //				".png")));
    alert.setGraphic(new ImageView(ImageCache.getInstance().get("/images/gallio/gallio-sad.png")));
    // Create expandable Exception.
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    throwable.printStackTrace(pw);
    String exceptionText = sw.toString();
    StringBuilder sb = new StringBuilder();
    //		sb.append("Error Message: ");
    //		sb.append(System.lineSeparator());
    //		sb.append(throwable.getMessage());
    sb.append("The exception stacktrace was:");
    sb.append(System.lineSeparator());
    sb.append(exceptionText);
    TextArea textArea = new TextArea(sb.toString());
    textArea.setEditable(false);
    textArea.setWrapText(false);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(150);
    // Set expandable Exception into the dialog pane.
    alert.getDialogPane().setExpandableContent(textArea);
    alert.getDialogPane().setExpanded(true);
    alert.showAndWait();
}
Example 30
Project: e-fx-clipse-master  File: MediaPropertiesView.java View source code
@PostConstruct
void init(BorderPane pane) {
    VBox box = new VBox();
    GridPane mediaProperties = new GridPane();
    EMFDataBindingContext dbc = new EMFDataBindingContext();
    {
        Label l = new Label("Title");
        mediaProperties.add(l, 0, 0);
        TextField f = new TextField();
        IEMFValueProperty mProp = EMFProperties.value(MEDIA__TITLE);
        IJFXBeanValueProperty tProp = JFXBeanProperties.value("text");
        dbc.bindValue(tProp.observe(f), mProp.observeDetail(currentSelection));
        mediaProperties.add(f, 1, 0);
        GridPane.setHgrow(f, Priority.ALWAYS);
    }
    {
        Label l = new Label("Description");
        mediaProperties.add(l, 0, 1);
        GridPane.setValignment(l, VPos.TOP);
        TextArea area = new TextArea();
        area.setPrefColumnCount(5);
        mediaProperties.add(area, 1, 1);
        GridPane.setHgrow(area, Priority.ALWAYS);
        dbc.bindValue(EMFProperties.value(MEDIA__DESCRIPTION).observeDetail(currentSelection), JFXBeanProperties.value("text").observe(area));
    }
    TitledPane generalProps = new TitledPane("General Properties", mediaProperties);
    box.getChildren().add(generalProps);
    photoAreas = new TableView<PhotoArea>();
    {
        TableColumn<PhotoArea, String> col = new TableColumn<PhotoArea, String>();
        col.setText("Bounds");
        col.setPrefWidth(50);
        {
            TableColumn<PhotoArea, Double> subCol = new TableColumn<PhotoArea, Double>();
            subCol.setText("x");
            subCol.setPrefWidth(20);
            subCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PhotoArea, Double>, ObservableValue<Double>>() {

                @Override
                public ObservableValue<Double> call(final CellDataFeatures<PhotoArea, Double> param) {
                    return AdapterFactory.adapt(EMFProperties.value(PHOTO_AREA__X).observe(param.getValue()));
                }
            });
            col.getColumns().add(subCol);
        }
        {
            TableColumn<PhotoArea, Double> subCol = new TableColumn<PhotoArea, Double>();
            subCol.setText("y");
            subCol.setPrefWidth(20);
            subCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PhotoArea, Double>, ObservableValue<Double>>() {

                @Override
                public ObservableValue<Double> call(final CellDataFeatures<PhotoArea, Double> param) {
                    return AdapterFactory.adapt(EMFProperties.value(PHOTO_AREA__Y).observe(param.getValue()));
                }
            });
            col.getColumns().add(subCol);
        }
        {
            TableColumn<PhotoArea, Double> subCol = new TableColumn<PhotoArea, Double>();
            subCol.setText("width");
            subCol.setPrefWidth(20);
            subCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PhotoArea, Double>, ObservableValue<Double>>() {

                @Override
                public ObservableValue<Double> call(final CellDataFeatures<PhotoArea, Double> param) {
                    return AdapterFactory.adapt(EMFProperties.value(PHOTO_AREA__WIDTH).observe(param.getValue()));
                }
            });
            col.getColumns().add(subCol);
        }
        {
            TableColumn<PhotoArea, Double> subCol = new TableColumn<PhotoArea, Double>();
            subCol.setText("heigth");
            subCol.setPrefWidth(20);
            subCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PhotoArea, Double>, ObservableValue<Double>>() {

                @Override
                public ObservableValue<Double> call(final CellDataFeatures<PhotoArea, Double> param) {
                    return AdapterFactory.adapt(EMFProperties.value(PHOTO_AREA__HEIGHT).observe(param.getValue()));
                }
            });
            col.getColumns().add(subCol);
        }
        photoAreas.getColumns().add(col);
    }
    {
        TableColumn<PhotoArea, String> col = new TableColumn<PhotoArea, String>();
        col.setText("Description");
        col.setMaxWidth(100);
        col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PhotoArea, String>, ObservableValue<String>>() {

            @Override
            public ObservableValue<String> call(CellDataFeatures<PhotoArea, String> param) {
                //TODO We need to remove the dispose the observable created here
                IObservableValue v = EMFProperties.value(PHOTO_AREA__DESCRIPTION).observe(param.getValue());
                return AdapterFactory.adapt(v);
            }
        });
        col.setCellFactory(new Callback<TableColumn<PhotoArea, String>, TableCell<PhotoArea, String>>() {

            @Override
            public TableCell<PhotoArea, String> call(TableColumn<PhotoArea, String> param) {
                return new EditingCell();
            }
        });
        col.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<PhotoArea, String>>() {

            @Override
            public void handle(CellEditEvent<PhotoArea, String> event) {
                photoAreas.getSelectionModel().getSelectedItem().setDescription(event.getNewValue());
            }
        });
        photoAreas.getColumns().add(col);
    }
    photoAreas.setEditable(true);
    ContextMenu mCtx = new ContextMenu();
    MenuItem mItem = new MenuItem("Remove");
    mItem.setGraphic(new ImageView(new Image(getClass().getClassLoader().getResource("/icons/edit-delete.png").toExternalForm())));
    mItem.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            PhotoArea area = photoAreas.getSelectionModel().getSelectedItem();
            photoAreas.getItems().remove(area);
        }
    });
    mCtx.getItems().add(mItem);
    photoAreas.setContextMenu(mCtx);
    ObservableList<PhotoArea> list = AdapterFactory.adapt(EMFProperties.list(PHOTO__AREAS).observeDetail(currentSelection));
    photoAreas.setItems(list);
    TitledPane areaProps = new TitledPane("Media Area Properties", photoAreas);
    box.getChildren().add(areaProps);
    VBox.setVgrow(areaProps, Priority.ALWAYS);
    pane.setCenter(box);
}
Example 31
Project: honest-profiler-master  File: DialogUtil.java View source code
/**
     * Shows an exception [email protected] Dialog} with the specified properties. This is an error [email protected] Dialog} which contains
     * the stack trace of the [email protected] Throwable} as expandable content.
     * <p>
     *
     * @param appCtx the [email protected] ApplicationContext} for the application
     * @param title the title of the [email protected] Dialog}
     * @param header the header of the [email protected] Dialog}
     * @param content the content of the [email protected] Dialog}
     * @param t the [email protected] Throwable} whose stacktrace will be included in the [email protected] Dialog}
     */
public static void showExceptionDialog(ApplicationContext appCtx, String title, String header, String content, Throwable t) {
    Alert alert = new Alert(ERROR);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(content);
    String exceptionText = null;
    try (StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw)) {
        t.printStackTrace(pw);
        exceptionText = sw.toString();
    } catch (IOException ioe) {
    }
    Label label = new Label(appCtx.textFor(CONTENT_LABEL_EXCEPTION));
    TextArea textArea = new TextArea(exceptionText);
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, ALWAYS);
    GridPane.setHgrow(textArea, ALWAYS);
    GridPane expContent = new GridPane();
    expContent.setMaxWidth(Double.MAX_VALUE);
    expContent.add(label, 0, 0);
    expContent.add(textArea, 0, 1);
    // Set expandable Exception into the dialog pane.
    alert.getDialogPane().setExpandableContent(expContent);
    alert.showAndWait();
}
Example 32
Project: jaci-master  File: JavaFxCliBuilder.java View source code
/**
     * @return A [email protected] Parent} that functions as a CLI built out of this builder's parameters.
     * @throws RuntimeException If an error occurs.
     */
public Parent build() {
    try {
        final CliCommandHierarchy hierarchy = CliCommandHierarchyImpl.from(hierarchyBuilder.build());
        final URL fxmlUrl = getFxmlUrl();
        final FXMLLoader loader = new FXMLLoader(fxmlUrl);
        final Parent cliNode = (Parent) loader.load();
        // Label for 'working directory'.
        final Label workingDirectory = (Label) cliNode.lookup("#workingDirectory");
        final CliGui gui = new JavaFxCliGui(workingDirectory);
        // Printers for cli output.
        final TextArea textArea = (TextArea) cliNode.lookup("#cliOutput");
        textArea.setFocusTraversable(false);
        final CliPrinter out = new CliPrinter(new JavaFxCliOutput(textArea));
        final CliPrinter err = new CliPrinter(new JavaFxCliOutput(textArea));
        // TextField as command line.
        final TextField commandLine = (TextField) cliNode.lookup("#commandLine");
        final CommandLineManager commandLineManager = new JavaFxCommandLineManager(commandLine);
        // Create the shell and the actual CLI.
        final CliShell shell = new CliShell.Builder(hierarchy, gui, out, err).setMaxCommandHistory(maxCommandHistory).build();
        final Cli cli = new Cli(shell, commandLineManager);
        // Hook input events to CLI events.
        commandLine.requestFocus();
        commandLine.addEventFilter(KeyEvent.KEY_PRESSED, new JavaFxCliEventHandler(cli));
        return cliNode;
    } catch (Exception e) {
        throw SneakyException.sneakyThrow(e);
    }
}
Example 33
Project: jidefx-oss-master  File: IntelliHintsDemo.java View source code
public Region getDemoPanel() {
    final String[] fontNames = DemoData.getFontNames();
    // create file text field
    List<String> urls = null;
    try {
        urls = DemoData.readUrls();
    } catch (IOException e) {
        e.printStackTrace();
    }
    TextField urlTextField = new TextField("http://");
    ListDataIntelliHints intelliHints = new ListDataIntelliHints<>(urlTextField, urls);
    intelliHints.setCaseSensitive(false);
    TextField pathTextField = new TextField();
    FileIntelliHints fileIntelliHints = new FileIntelliHints(pathTextField);
    fileIntelliHints.setFilter(new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return !_applyFileFilter.get() || dir.getAbsolutePath().contains("Program") || name.contains("Program");
        }
    });
    fileIntelliHints.setFolderOnly(false);
    fileIntelliHints.setShowFullPath(false);
    // create file text field
    TextField fileTextField = new TextField();
    new FileIntelliHints(fileTextField);
    // create file text field
    TextArea fileTextArea = new TextArea();
    new FileIntelliHints(fileTextArea);
    fileTextArea.setPrefRowCount(4);
    //
    // create font text field
    TextField fontTextField = new TextField();
    ListDataIntelliHints fontIntelliHints = new ListDataIntelliHints<>(fontTextField, fontNames);
    fontIntelliHints.setCaseSensitive(false);
    TextField textField = new TextField();
    new AbstractListIntelliHints<Long>(textField) {

        protected Label _messageLabel;

        @Override
        public Node createHintsNode() {
            BorderPane pane = (BorderPane) super.createHintsNode();
            _messageLabel = new Label();
            pane.setTop(_messageLabel);
            pane.setStyle("-fx-background-color: white; -fx-border-color: gray; -fx-padding: 6;");
            return pane;
        }

        // update list model depending on the data in textfield
        public boolean updateHints(Object value) {
            if (value == null) {
                return false;
            }
            String s = value.toString();
            s = s.trim();
            if (s.length() == 0) {
                return false;
            }
            try {
                long l = Long.parseLong(s);
                boolean prime = isProbablePrime(l);
                _messageLabel.setText("");
                if (prime) {
                    return false;
                } else {
                    List<Long> list = new ArrayList<>();
                    long nextPrime = l;
                    for (int i = 0; i < 10; i++) {
                        nextPrime = nextPrime(nextPrime);
                        list.add(nextPrime);
                    }
                    setAvailableHints(FXCollections.observableArrayList(list));
                    _messageLabel.setText("Next 10 prime numbers:");
                    _messageLabel.setTextFill(Color.BLACK);
                    return true;
                }
            } catch (NumberFormatException e) {
                setAvailableHints(null);
                _messageLabel.setText("Invalid long number");
                _messageLabel.setTextFill(Color.RED);
                return true;
            }
        }
    };
    VBox panel = new VBox(3);
    panel.setPadding(new Insets(10, 10, 10, 10));
    panel.getChildren().addAll(new Label("ListDataIntelliHints TextField for URLs: "), urlTextField, new Box(), new Label("FileIntelliHints TextField for paths (folders only, show partial path): "), pathTextField, new Box(), new Label("FileIntelliHints TextField for files (files and folders, show full path):"), fileTextField, new Box(), new Label("IntelliHints TextField to choose a font: "), fontTextField, new Box(), new Label("FileIntelliHints TextArea for files (each line is for a new file):"), fileTextArea, new Box(), new Label("A custom IntelliHints for prime numbers: "), textField);
    return panel;
}
Example 34
Project: jitwatch-master  File: JITWatchUI.java View source code
@Override
public void start(final Stage stage) {
    StageManager.registerListener(this);
    this.stage = stage;
    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {

        @Override
        public void handle(WindowEvent arg0) {
            StageManager.closeStage(stage);
            stopParsing();
        }
    });
    BorderPane borderPane = new BorderPane();
    Scene scene = UserInterfaceUtil.getScene(borderPane, WINDOW_WIDTH, WINDOW_HEIGHT);
    Button btnChooseWatchFile = new Button("Open Log");
    btnChooseWatchFile.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            stopParsing();
            chooseJITLog();
        }
    });
    btnStart = new Button("Start");
    btnStart.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            if (nothingMountedStage == null) {
                int classCount = getConfig().getConfiguredClassLocations().size();
                int sourceCount = getConfig().getSourceLocations().size();
                if (classCount == 0 && sourceCount == 0) {
                    if (getConfig().isShowNothingMounted()) {
                        nothingMountedStage = new NothingMountedStage(JITWatchUI.this, getConfig());
                        StageManager.addAndShow(JITWatchUI.this.stage, nothingMountedStage);
                        startDelayedByConfig = true;
                    }
                }
            }
            if (!startDelayedByConfig) {
                readLogFile();
            }
        }
    });
    btnStop = new Button("Stop");
    btnStop.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            stopParsing();
        }
    });
    btnConfigure = new Button("Config");
    btnConfigure.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            openConfigStage();
        }
    });
    btnTimeLine = new Button("Timeline");
    btnTimeLine.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            timeLineStage = new TimeLineStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, timeLineStage);
            btnTimeLine.setDisable(true);
        }
    });
    btnHisto = new Button("Histo");
    btnHisto.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            histoStage = new HistoStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, histoStage);
            btnHisto.setDisable(true);
        }
    });
    btnTopList = new Button("TopList");
    btnTopList.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            topListStage = new TopListStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, topListStage);
            btnTopList.setDisable(true);
        }
    });
    btnCodeCacheTimeline = new Button("Cache");
    btnCodeCacheTimeline.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            codeCacheTimelineStage = new CodeCacheStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, codeCacheTimelineStage);
            btnCodeCacheTimeline.setDisable(true);
        }
    });
    btnNMethods = new Button("NMethods");
    btnNMethods.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            codeCacheBlocksStage = new CodeCacheLayoutStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, codeCacheBlocksStage);
            btnNMethods.setDisable(true);
            codeCacheBlocksStage.redraw();
        }
    });
    btnTriView = new Button("TriView");
    btnTriView.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            if (selectedMember == null && selectedMetaClass != null) {
                selectedMember = selectedMetaClass.getFirstConstructor();
            }
            openTriView(selectedMember, false);
        }
    });
    btnReportSuggestions = new Button("Suggest");
    btnReportSuggestions.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            reportStageSuggestions = new ReportStage(JITWatchUI.this, "JITWatch Code Suggestions", ReportStageType.SUGGESTION, reportListSuggestions);
            StageManager.addAndShow(JITWatchUI.this.stage, reportStageSuggestions);
            btnReportSuggestions.setDisable(true);
        }
    });
    btnReportEliminatedAllocations = new Button("-Allocs");
    btnReportEliminatedAllocations.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            reportStageElminatedAllocations = new ReportStage(JITWatchUI.this, "JITWatch Eliminated Allocation Report", ReportStageType.ELIMINATED_ALLOCATION, reportListEliminatedAllocations);
            StageManager.addAndShow(JITWatchUI.this.stage, reportStageElminatedAllocations);
            btnReportEliminatedAllocations.setDisable(true);
        }
    });
    btnReportElidedLocks = new Button("-Locks");
    btnReportElidedLocks.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            reportStageElidedLocks = new ReportStage(JITWatchUI.this, "JITWatch Elided Lock Report", ReportStageType.ELIDED_LOCK, reportListElidedLocks);
            StageManager.addAndShow(JITWatchUI.this.stage, reportStageElidedLocks);
            btnReportElidedLocks.setDisable(true);
        }
    });
    btnOptimizedVirtualCalls = new Button("OVCs");
    btnOptimizedVirtualCalls.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            OptimizedVirtualCallVisitable optimizedVCallVisitable = new OptimizedVirtualCallVisitable();
            List<OptimizedVirtualCall> optimizedVirtualCalls = optimizedVCallVisitable.buildOptimizedCalleeReport(logParser.getModel(), getConfig().getAllClassLocations());
            ovcStage = new OptimizedVirtualCallStage(JITWatchUI.this, optimizedVirtualCalls);
            StageManager.addAndShow(JITWatchUI.this.stage, ovcStage);
            btnOptimizedVirtualCalls.setDisable(true);
        }
    });
    btnSandbox = new Button("Sandbox");
    btnSandbox.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            openSandbox();
        }
    });
    btnErrorLog = new Button("Errors (0)");
    btnErrorLog.setStyle("-fx-padding: 2 6;");
    btnErrorLog.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            openTextViewer("Error Log", errorLog.toString(), false, false);
        }
    });
    btnStats = new Button("Stats");
    btnStats.setStyle("-fx-padding: 2 6;");
    btnStats.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            statsStage = new StatsStage(JITWatchUI.this);
            StageManager.addAndShow(JITWatchUI.this.stage, statsStage);
            btnStats.setDisable(true);
        }
    });
    btnReset = new Button("Reset");
    btnReset.setStyle("-fx-padding: 2 6;");
    btnReset.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            logParser.reset();
            clear();
        }
    });
    lblHeap = new Label();
    lblVmVersion = new Label();
    StringBuilder vmBuilder = new StringBuilder();
    vmBuilder.append("VM is ");
    vmBuilder.append(Runtime.class.getPackage().getImplementationVendor());
    vmBuilder.append(C_SPACE);
    vmBuilder.append(Runtime.class.getPackage().getImplementationVersion());
    lblVmVersion.setText(vmBuilder.toString());
    lblTweakLog = new Label();
    int menuBarHeight = 40;
    int textAreaHeight = 100;
    int statusBarHeight = 25;
    HBox hboxTop = new HBox();
    hboxTop.setPadding(new Insets(10));
    hboxTop.setPrefHeight(menuBarHeight);
    hboxTop.setSpacing(10);
    hboxTop.getChildren().add(btnSandbox);
    hboxTop.getChildren().add(btnChooseWatchFile);
    hboxTop.getChildren().add(btnStart);
    hboxTop.getChildren().add(btnStop);
    hboxTop.getChildren().add(btnConfigure);
    hboxTop.getChildren().add(btnTimeLine);
    hboxTop.getChildren().add(btnHisto);
    hboxTop.getChildren().add(btnTopList);
    hboxTop.getChildren().add(btnCodeCacheTimeline);
    hboxTop.getChildren().add(btnNMethods);
    hboxTop.getChildren().add(btnTriView);
    hboxTop.getChildren().add(btnReportSuggestions);
    hboxTop.getChildren().add(btnReportEliminatedAllocations);
    hboxTop.getChildren().add(btnReportElidedLocks);
    hboxTop.getChildren().add(btnOptimizedVirtualCalls);
    compilationRowList = FXCollections.observableArrayList();
    compilationTable = CompilationTableBuilder.buildTableMemberAttributes(compilationRowList);
    compilationTable.setPlaceholder(new Text("Select a JIT-compiled class member to view compilations."));
    compilationTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<CompilationTableRow>() {

        @Override
        public void changed(ObservableValue<? extends CompilationTableRow> arg0, CompilationTableRow oldVal, CompilationTableRow newVal) {
            if (!selectedProgrammatically) {
                if (selectedMember != null && newVal != null) {
                    selectedMember.setSelectedCompilation(newVal.getIndex());
                    openTriView(selectedMember, true);
                    refreshOnce();
                }
            }
        }
    });
    SplitPane spMethodInfo = new SplitPane();
    spMethodInfo.setOrientation(Orientation.VERTICAL);
    classMemberList = new ClassMemberList(this, getConfig());
    classMemberList.registerListener(this);
    spMethodInfo.getItems().add(classMemberList);
    spMethodInfo.getItems().add(compilationTable);
    classMemberList.prefHeightProperty().bind(scene.heightProperty());
    compilationTable.prefHeightProperty().bind(scene.heightProperty());
    classTree = new ClassTree(this, getConfig());
    classTree.prefWidthProperty().bind(scene.widthProperty());
    SplitPane spMain = new SplitPane();
    spMain.setOrientation(Orientation.VERTICAL);
    SplitPane spCentre = new SplitPane();
    spCentre.getItems().add(classTree);
    spCentre.getItems().add(spMethodInfo);
    spCentre.setDividerPositions(0.33, 0.67);
    textAreaLog = new TextArea();
    textAreaLog.setStyle("-fx-font-family:" + FONT_MONOSPACE_FAMILY + ";-fx-font-size:" + FONT_MONOSPACE_SIZE + "px");
    textAreaLog.setPrefHeight(textAreaHeight);
    log("Welcome to JITWatch by Chris Newland (@chriswhocodes on Twitter) and the AdoptOpenJDK project.\n");
    log("Please send feedback to our mailing list (https://groups.google.com/forum/#!forum/jitwatch) \nor come and find us on GitHub (https://github.com/AdoptOpenJDK/jitwatch).\n");
    log("Includes assembly reference from x86asm.net licenced under http://ref.x86asm.net/index.html#License\n");
    if (jitLogFile == null) {
        if (logParser instanceof HotSpotLogParser) {
            log("HotSpot mode. Choose a JIT log file or open the Sandbox");
        } else {
            log("J9 Mode. Choose a JIT log file (Sandbox only available for HotSpot)");
        }
    } else {
        log("Using JIT log file: " + jitLogFile.getAbsolutePath());
    }
    spMain.getItems().add(spCentre);
    spMain.getItems().add(textAreaLog);
    spMain.setDividerPositions(0.68, 0.32);
    HBox hboxBottom = new HBox();
    Region springLeft = new Region();
    Region springRight = new Region();
    final String labelStyle = "-fx-padding: 3 0 0 0;";
    HBox.setHgrow(springLeft, Priority.ALWAYS);
    HBox.setHgrow(springRight, Priority.ALWAYS);
    lblHeap.setStyle(labelStyle);
    lblVmVersion.setStyle(labelStyle);
    hboxBottom.setPadding(new Insets(4));
    hboxBottom.setPrefHeight(statusBarHeight);
    hboxBottom.setSpacing(4);
    hboxBottom.getChildren().add(lblHeap);
    hboxBottom.getChildren().add(btnErrorLog);
    hboxBottom.getChildren().add(btnStats);
    hboxBottom.getChildren().add(btnReset);
    hboxBottom.getChildren().add(springLeft);
    hboxBottom.getChildren().add(lblTweakLog);
    hboxBottom.getChildren().add(springRight);
    hboxBottom.getChildren().add(lblVmVersion);
    borderPane.setTop(hboxTop);
    borderPane.setCenter(spMain);
    borderPane.setBottom(hboxBottom);
    stage.setTitle("JITWatch - Just In Time Compilation Inspector");
    stage.setScene(scene);
    stage.show();
    int refreshMillis = 1000;
    final Duration oneFrameAmt = Duration.millis(refreshMillis);
    final KeyFrame oneFrame = new KeyFrame(oneFrameAmt, new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            refresh();
        }
    });
    Timeline timeline = new Timeline();
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.getKeyFrames().add(oneFrame);
    timeline.play();
    updateButtons();
}
Example 35
Project: nocturne-master  File: Main.java View source code
@Override
public void start(Stage primaryStage) throws Exception {
    mainStage = primaryStage;
    String[] icons = new String[] { "icon-16", "icon-24", "icon-32", "icon-48", "icon-64", "icon-128", "icon-256", "icon-512" };
    for (String icon : icons) {
        mainStage.getIcons().add(new Image(getClass().getResourceAsStream("/img/icons/" + icon + ".png")));
    }
    loadView(locale);
    Thread.currentThread().setUncaughtExceptionHandler(( thread,  throwable) -> {
        throwable.printStackTrace();
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(resourceBundle.getString("exception.title"));
        alert.setHeaderText(resourceBundle.getString("exception.header"));
        TextFlow description = new TextFlow(new Text(resourceBundle.getString("exception.dialog1") + "\n"), new Text(resourceBundle.getString("exception.dialog2") + "\n\n"), new Text(resourceBundle.getString("exception.dialog3")), new Text(" "), new WebLink("https://github.com/LapisBlue/Nocturne/issues"), new Text("\n\n"), new Text(resourceBundle.getString("exception.dialog4")));
        description.setLayoutX(20);
        description.setLayoutY(25);
        TextArea exceptionText = new TextArea();
        StringWriter exceptionWriter = new StringWriter();
        throwable.printStackTrace(new PrintWriter(exceptionWriter));
        exceptionText.setText(exceptionWriter.toString());
        exceptionText.setLayoutX(20);
        exceptionText.setLayoutY(140);
        Pane contentPane = new Pane(description, exceptionText);
        alert.getDialogPane().setContent(contentPane);
        alert.getButtonTypes().setAll(ButtonType.OK, ButtonType.CLOSE);
        alert.showAndWait();
        if (alert.getResult() == ButtonType.CLOSE) {
            System.exit(0);
        }
    });
}
Example 36
Project: SONDY-master  File: GlobalUI.java View source code
public final void editConfigurationFile() {
    try {
        TextArea textArea = new TextArea();
        textArea.setText(FileUtils.readFileToString(Paths.get("./configuration.properties").toFile()));
        UIUtils.setSize(textArea, Main.columnWidthLEFT / 2 + 10, 100);
        final Stage stage = new Stage();
        stage.setResizable(false);
        stage.initModality(Modality.WINDOW_MODAL);
        stage.initStyle(StageStyle.UTILITY);
        stage.setTitle("Edit configuration");
        Button saveButton = new Button("Save changes");
        UIUtils.setSize(saveButton, Main.columnWidthLEFT / 2 + 10, 24);
        Button cancelButton = new Button("Cancel changes");
        cancelButton.setOnAction((ActionEvent t) -> {
            stage.close();
        });
        saveButton.setOnAction((ActionEvent t) -> {
            try {
                FileUtils.write(Paths.get("./configuration.properties").toFile(), textArea.getText());
                stage.close();
            } catch (IOException ex) {
                Logger.getLogger(GlobalUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        UIUtils.setSize(cancelButton, Main.columnWidthLEFT / 2 + 10, 24);
        Label label = new Label();
        label.setId("smalltext");
        label.setText("SONDY needs to restart for the changes to take effect");
        Scene scene = new Scene(VBoxBuilder.create().children(textArea, label, saveButton, cancelButton).alignment(Pos.CENTER).padding(new Insets(10)).spacing(3).build());
        scene.getStylesheets().add("resources/fr/ericlab/sondy/css/GlobalStyle.css");
        stage.setScene(scene);
        stage.show();
    } catch (IOException ex) {
        Logger.getLogger(GlobalUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Example 37
Project: spdx-edit-master  File: FileIoLogic.java View source code
public static SpdxDocument loadTagValue(File file) throws IOException, InvalidSPDXAnalysisException {
    try (FileInputStream in = new FileInputStream(file)) {
        List<String> warnings = new LinkedList<>();
        SpdxDocumentContainer container = TagToRDF.convertTagFileToRdf(in, "RDF/XML", warnings);
        if (warnings.size() > 0) {
            Alert warningsAlert = new Alert(Alert.AlertType.WARNING, "Warnings occured in parsing Tag document", ButtonType.OK);
            TextArea warningList = new TextArea();
            warningList.setText(Joiner.on("\n").join(warnings));
            warningsAlert.getDialogPane().setExpandableContent(warningList);
            warningsAlert.showAndWait();
        }
        return container.getSpdxDocument();
    } catch (Exception e) {
        if (e instanceof InvalidSPDXAnalysisException)
            throw (InvalidSPDXAnalysisException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw new IOException("Unable to read/parse tag-value file " + file.getAbsolutePath(), e);
    }
}
Example 38
Project: TerasologyLauncher-master  File: LauncherUpdater.java View source code
public boolean showUpdateDialog(Stage parentStage) {
    final String infoText = getUpdateInfo();
    FutureTask<Boolean> dialog = new FutureTask<Boolean>(() -> {
        Parent root = BundleUtils.getFXMLLoader("update_dialog").load();
        ((TextArea) root.lookup("#infoTextArea")).setText(infoText);
        ((TextArea) root.lookup("#changelogTextArea")).setText(changeLog);
        final Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle(BundleUtils.getLabel("message_update_launcher_title"));
        alert.setHeaderText(BundleUtils.getLabel("message_update_launcher"));
        alert.getDialogPane().setContent(root);
        alert.initOwner(parentStage);
        alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO);
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.setResizable(true);
        return alert.showAndWait().filter( response -> response == ButtonType.YES).isPresent();
    });
    Platform.runLater(dialog);
    boolean result = false;
    try {
        result = dialog.get();
    } catch (InterruptedExceptionExecutionException |  e) {
        logger.error("Uh oh, something went wrong with the update dialog!", e);
    }
    return result;
}
Example 39
Project: GitFx-master  File: GitFxDialog.java View source code
/*
     * Implementation of Generic Exception Dialog
     */
@Override
public void gitExceptionDialog(String title, String header, String content, Exception e) {
    Alert alert = new Alert(AlertType.ERROR);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(content);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    String exceptionText = sw.toString();
    Label label = new Label("Exception stack trace:");
    TextArea textArea = new TextArea(exceptionText);
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, Priority.ALWAYS);
    GridPane.setHgrow(textArea, Priority.ALWAYS);
    GridPane expContent = new GridPane();
    expContent.setMaxWidth(Double.MAX_VALUE);
    expContent.add(label, 0, 0);
    expContent.add(textArea, 0, 1);
    alert.getDialogPane().setExpandableContent(expContent);
    alert.showAndWait();
}
Example 40
Project: mqtt-spy-master  File: DialogFactory.java View source code
public static void createExceptionDialog(final String title, final Exception e) {
    final Alert alert = new Alert(AlertType.ERROR);
    alert.setTitle(title);
    alert.setHeaderText(null);
    alert.setContentText(e.getMessage() + " - " + ExceptionUtils.getRootCauseMessage(e));
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    final TextArea textArea = new TextArea(sw.toString());
    textArea.setEditable(false);
    textArea.setWrapText(true);
    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, Priority.ALWAYS);
    GridPane.setHgrow(textArea, Priority.ALWAYS);
    GridPane content = new GridPane();
    content.setMaxWidth(Double.MAX_VALUE);
    content.add(textArea, 0, 0);
    alert.getDialogPane().setExpandableContent(content);
    alert.showAndWait();
}
Example 41
Project: VisibleTesla-master  File: OverviewController.java View source code
@FXML
void detailsButtonHandler(ActionEvent event) {
    AnchorPane pane = new AnchorPane();
    VehicleState car = vtVehicle.vehicleState.get();
    String info = vtVehicle.getVehicle().toString() + "\nFirmware Version: " + car.version + "\nRemote Start Enabled: " + vtVehicle.getVehicle().remoteStartEnabled() + "\nCalendar Enabled: " + vtVehicle.getVehicle().calendarEnabled() + "\nNotifications Enabled: " + vtVehicle.getVehicle().notificationsEnabled() + "\n--------------------------------------------" + "\nLow level information: " + vtVehicle.getVehicle().getUnderlyingValues() + "\nVehicle UUID: " + vtVehicle.getVehicle().getUUID() + "\nApp UUID: " + app.getAppID() + "\n";
    TextArea t = new TextArea(info);
    pane.getChildren().add(t);
    Dialogs.showCustomDialog(app.stage, pane, "Detailed Vehicle Description", "Details", DialogOptions.OK, null);
}
Example 42
Project: jvarkit-master  File: NgsStage.java View source code
@Override
public void run() {
    try {
        this.bindings.put(HEADER_CONTEXT_KEY, this.copyNgsFile.getHeader());
        this.bindings.put(OUT_CONTEXT_KEY, this.out);
        this.bindings.put(ITER_CONTEXT_KEY, this.iter);
        this.compiledScript.eval(this.bindings);
        this.iter.close();
        this.out.flush();
        Platform.runLater(() -> {
            AbstractAwkLike.this.progessLabel.setText("Done.");
        });
        if (this.iter.__stop_flag != 0) {
        //nothing
        } else if (this.out.checkError()) {
            Platform.runLater(() -> {
                final Alert alert = new Alert(AlertType.ERROR, "I/O Error. Check Stream limits in preferences.", ButtonType.OK);
                alert.showAndWait();
            });
        } else if (this.saveToStringWriter != null) {
            final String output = new String(this.saveToStringWriter.toByteArray());
            Platform.runLater(() -> {
                final Stage showResultStage = new Stage();
                showResultStage.setTitle("BioAlcidae");
                showResultStage.setScene(new Scene(new ScrollPane(new TextArea(output))));
                showResultStage.show();
            });
        } else {
            Platform.runLater(() -> {
                final Alert alert = new Alert(AlertType.CONFIRMATION, "Done", ButtonType.OK);
                alert.showAndWait();
            });
        }
        //we close after to avoid check error is user closed the stream
        this.out.close();
        this.out = null;
        this.iter = null;
    } catch (final Exception err) {
        Platform.runLater(() -> {
            AbstractAwkLike.this.progessLabel.setText("Error :" + err.getMessage());
        });
        err.printStackTrace();
    } finally {
        AbstractAwkLike.this.curentrunner = null;
        dispose();
    }
}
Example 43
Project: sea-master  File: Connection.java View source code
public static void getSongFromPleer(TextArea songLabelText) throws IOException {
    String bandArtist;
    String songTitle;
    // these top two dont do anyhting
    bandArtist = deAccent(FXController.bandArtist);
    songTitle = deAccent(FXController.songTitle);
    if (FXController.bandArtist.contains("feat"))
        bandArtist = FXController.bandArtist.split("feat")[0];
    if (FXController.songTitle.contains("feat"))
        songTitle = FXController.songTitle.split("feat")[0];
    if (FXController.bandArtist.contains("Feat"))
        bandArtist = FXController.bandArtist.split("feat")[0];
    if (FXController.songTitle.contains("Feat"))
        songTitle = FXController.songTitle.split("feat")[0];
    String fullURLPath = "http://www.pleer.com/browser-extension/search?limit=100&q=" + bandArtist.replace(" ", "+").replaceAll("[!@#$%^&*(){}:\"<>?]", "") + "+" + songTitle.replace(" ", "+").replaceAll("[!@#$%^&*(){}:\"<>?]", "").replaceAll("\\[.*\\]", "");
    final URL url = new URL(fullURLPath);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    request.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;     rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
    request.connect();
    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    JsonObject rootobj = root.getAsJsonObject();
    JsonArray arr = rootobj.getAsJsonArray("tracks");
    try {
        rootobj = arr.get(0).getAsJsonObject();
    } catch (IndexOutOfBoundsException e) {
        songLabelText.setText("Song not found");
    }
    List<String> fileList = new ArrayList<>();
    List<String> fullTitleList = new ArrayList<>();
    List<String> qualityList = new ArrayList<>();
    Pattern p = Pattern.compile("^[\\x20-\\x7d]*$");
    Matcher m3 = Pattern.compile("rework", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("track").toString());
    Matcher m4 = Pattern.compile("remix", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("track").toString());
    Matcher m5 = Pattern.compile("rework", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("track").toString());
    Matcher m6 = Pattern.compile("cover", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("track").toString());
    Matcher m8 = Pattern.compile("rework", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("artist").toString());
    Matcher m9 = Pattern.compile("remix", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("artist").toString());
    Matcher m10 = Pattern.compile("rework", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("artist").toString());
    Matcher m11 = Pattern.compile("cover", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("artist").toString());
    Matcher m13 = Pattern.compile("mix", Pattern.CASE_INSENSITIVE).matcher(rootobj.get("track").toString());
    for (int i = 0; i < arr.size(); i++) {
        rootobj = arr.get(i).getAsJsonObject();
        Matcher m1 = p.matcher(rootobj.get("artist").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Matcher m2 = p.matcher(rootobj.get("track").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Boolean correctArtist = false;
        Boolean artistInTrack = false;
        if (rootobj.get("artist").toString().toLowerCase().contains(bandArtist.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "")))
            correctArtist = true;
        if (rootobj.get("track").toString().toLowerCase().contains(songTitle.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "").replaceAll("  ", " ")))
            artistInTrack = true;
        // make sure to get only songs that aren't modifications
        if (m1.find() && m2.find() && !m3.find() && !m4.find() && !m5.find() && !m6.find() && !m8.find() && !m9.find() && !m10.find() && !m11.find() && !m13.find() && correctArtist && artistInTrack) {
            // searching through either high or low quality songs, depending on the setting that has been set
            if ((rootobj.get("bitrate").toString().contains("VBR") || !(Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 2)) >= 4)) && !rootobj.get("bitrate").toString().substring(1, 4).contains(" ")) {
                switch(FXController.qualityLevel) {
                    case "high":
                        if (!rootobj.get("bitrate").toString().contains("VBR") && Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 4)) >= 256) {
                            System.out.println("high");
                            fileList.add(rootobj.get("id").toString().replace("\"", ""));
                            fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                            qualityList.add("High");
                        }
                        break;
                    case "low":
                        if (!rootobj.get("bitrate").toString().contains("VBR") && Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 4)) < 256) {
                            System.out.println("low");
                            fileList.add(rootobj.get("id").toString().replace("\"", ""));
                            fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                            qualityList.add("Low");
                        }
                        break;
                    case "VBR":
                        if (rootobj.get("bitrate").toString().contains("VBR")) {
                            System.out.println("VBR");
                            fileList.add(rootobj.get("id").toString().replace("\"", ""));
                            fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                            qualityList.add("VBR");
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
    for (int i = 0; i < arr.size(); i++) {
        rootobj = arr.get(i).getAsJsonObject();
        Matcher m1 = p.matcher(rootobj.get("artist").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Matcher m2 = p.matcher(rootobj.get("track").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Boolean correctArtist = false;
        Boolean artistInTrack = false;
        if (rootobj.get("artist").toString().toLowerCase().contains(bandArtist.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "")))
            correctArtist = true;
        if (rootobj.get("track").toString().toLowerCase().contains(songTitle.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "").replaceAll("  ", " ")))
            artistInTrack = true;
        // make sure to get only songs that aren't modifications
        if (m1.find() && m2.find() && !m3.find() && !m4.find() && !m5.find() && !m6.find() && !m8.find() && !m9.find() && !m10.find() && !m11.find() && !m13.find() && correctArtist && artistInTrack) {
            // searching through either high or low quality songs, depending on the setting that has been set
            if ((rootobj.get("bitrate").toString().contains("VBR") || !(Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 2)) >= 4)) && !rootobj.get("bitrate").toString().substring(1, 4).contains(" ")) {
                if (FXController.qualityLevel.equals("low") || FXController.qualityLevel.equals("VBR")) {
                    if (!rootobj.get("bitrate").toString().contains("VBR") && Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 4)) >= 256) {
                        System.out.println("high");
                        fileList.add(rootobj.get("id").toString().replace("\"", ""));
                        fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                        qualityList.add("High");
                    }
                } else if (FXController.qualityLevel.equals("high")) {
                    if (!rootobj.get("bitrate").toString().contains("VBR") && Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 4)) < 256) {
                        System.out.println("low");
                        fileList.add(rootobj.get("id").toString().replace("\"", ""));
                        fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                        qualityList.add("Low");
                    }
                }
            }
        }
    }
    for (int i = 0; i < arr.size(); i++) {
        rootobj = arr.get(i).getAsJsonObject();
        Matcher m1 = p.matcher(rootobj.get("artist").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Matcher m2 = p.matcher(rootobj.get("track").toString().replace("\"", "").replace("[", "~").replace("]", "~"));
        Boolean correctArtist = false;
        Boolean artistInTrack = false;
        if (rootobj.get("artist").toString().toLowerCase().contains(bandArtist.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "")))
            correctArtist = true;
        if (rootobj.get("track").toString().toLowerCase().contains(songTitle.toLowerCase().replaceAll("\\[.*\\]", "").replaceAll("\\(.*\\)", "").replaceAll("\\(.*\\)", "").replaceAll("  ", " ")))
            artistInTrack = true;
        // make sure to get only songs that aren't modifications
        if (m1.find() && m2.find() && !m3.find() && !m4.find() && !m5.find() && !m6.find() && !m8.find() && !m9.find() && !m10.find() && !m11.find() && !m13.find() && correctArtist && artistInTrack) {
            // searching through either high or low quality songs, depending on the setting that has been set
            if ((rootobj.get("bitrate").toString().contains("VBR") || !(Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 2)) >= 4)) && !rootobj.get("bitrate").toString().substring(1, 4).contains(" ")) {
                if (FXController.qualityLevel.equals("VBR")) {
                    if (!rootobj.get("bitrate").toString().contains("VBR") && Integer.parseInt(rootobj.get("bitrate").toString().substring(1, 4)) < 256) {
                        System.out.println("low");
                        fileList.add(rootobj.get("id").toString().replace("\"", ""));
                        fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                        qualityList.add("Low");
                    }
                } else if (FXController.qualityLevel.equals("low") || FXController.qualityLevel.equals("high")) {
                    if (rootobj.get("bitrate").toString().contains("VBR")) {
                        System.out.println("VBR");
                        fileList.add(rootobj.get("id").toString().replace("\"", ""));
                        fullTitleList.add(rootobj.get("artist").toString().replace("\"", "") + " - " + rootobj.get("track").toString().replace("\"", ""));
                        qualityList.add("VBR");
                    }
                }
            }
        }
    }
    FXController.fileList = (fileList);
    FXController.fullTitleList = (fullTitleList);
    FXController.qualityList = qualityList;
}
Example 44
Project: behaviorsearch-master  File: MainController.java View source code
public void showAboutAction(ActionEvent event) {
    Alert alert = new Alert(AlertType.CONFIRMATION);
    alert.setTitle("About BehaviorSearch...");
    alert.setHeaderText(null);
    alert.setGraphic(null);
    ButtonType browseWebsite = new ButtonType("Browse BehaviorSearch web site");
    ButtonType close = new ButtonType("Close", ButtonData.CANCEL_CLOSE);
    alert.getButtonTypes().setAll(browseWebsite, close);
    TextArea content = new TextArea();
    File creditsFile = new File(GeneralUtils.attemptResolvePathFromBSearchRoot("CREDITS.TXT"));
    File licFile = new File(GeneralUtils.attemptResolvePathFromBSearchRoot("LICENSE.TXT"));
    String creditsText, licText;
    try {
        creditsText = GeneralUtils.stringContentsOfFile(creditsFile);
        licText = GeneralUtils.stringContentsOfFile(licFile);
    } catch (FileNotFoundException ex) {
        creditsText = "ERROR: Either CREDITS.TXT or LICENSE.TXT file not found.";
        licText = "";
    }
    content.setText("BehaviorSearch v" + GeneralUtils.getVersionString() + "\n" + creditsText + "\n*****\n\n" + licText);
    content.setWrapText(true);
    content.setMinHeight(400);
    alert.getDialogPane().setContent(content);
    ;
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == browseWebsite) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                org.nlogo.swing.BrowserLauncher.openURL(null, "http://www.behaviorsearch.org/", false);
            }
        });
    }
// ...otherwise user chose CANCEL or closed the dialog
}
Example 45
Project: itol-master  File: PropertyGridView.java View source code
private PropertyNode makeTextAreaForProperty(Issue issue, PropertyClass pclass) {
    if (log.isLoggable(Level.FINE))
        log.log(Level.FINE, "makeTextAreaForProperty(");
    PropertyNode ret = null;
    try {
        final IssueService srv = Globals.getIssueService();
        final IssuePropertyEditor editor = srv.getPropertyEditor(issueTaskPane, issue, pclass.getId());
        // Create a standard TextArea if no special property editor is provided.
        final TextArea textArea = editor != null ? null : new TextArea();
        if (textArea != null) {
            // Forward to next control on TAB
            textArea.addEventFilter(KeyEvent.KEY_PRESSED, ( e) -> {
                if (e.getCode().equals(KeyCode.TAB)) {
                    TextAreaSkin skin = (TextAreaSkin) textArea.getSkin();
                    if (e.isShiftDown()) {
                        skin.getBehavior().traversePrevious();
                    } else {
                        skin.getBehavior().traverseNext();
                    }
                    e.consume();
                }
            });
            textArea.setWrapText(true);
            textArea.setMinHeight(60);
            textArea.setMaxHeight(Double.MAX_VALUE);
            textArea.setPrefHeight(60);
        }
        VBox vboxEditor = null;
        if (editor != null) {
            final Control editorControl = (Control) editor.getNode();
            VBox.setVgrow(editorControl, Priority.ALWAYS);
            vboxEditor = new VBox();
            vboxEditor.getChildren().clear();
            vboxEditor.getChildren().add(editorControl);
            vboxEditor.setStyle("-fx-border-color: LIGHTGREY;-fx-border-width: 1px;");
            vboxEditor.setMinHeight(100);
            vboxEditor.setMaxHeight(Double.MAX_VALUE);
            vboxEditor.setPrefHeight(100);
        }
        Region nodeRegion = textArea != null ? textArea : vboxEditor;
        ret = new PropertyNode(issue, pclass, nodeRegion) {

            @Override
            public void updateData(boolean save) {
                if (editor != null) {
                    editor.updateData(save);
                } else {
                    if (save) {
                        String text = textArea.getText();
                        issue.setPropertyString(pclass.getId(), text);
                    } else {
                        String text = issue.getPropertyString(pclass.getId(), "");
                        textArea.setText(text);
                    }
                }
            }
        };
    } catch (Exception e) {
        log.log(Level.WARNING, "Failed to create text area for property=" + pclass);
    }
    if (log.isLoggable(Level.FINE))
        log.log(Level.FINE, ")makeTextAreaForProperty");
    return ret;
}
Example 46
Project: Narvaro-master  File: Controller.java View source code
@Override
public void run() {
    MonthData md = null;
    try {
        md = DataManager.Narvaro.getMonthDataForParkAndYearMonth(YearMonth.of(getEnterYear(), getEnterMonth()), getEnterPark());
        // set data on view data tab
        conversionFactorPaidDayUseTF.setText(md.getPduConversionFactor().toString());
        paidDayUseTotalsTF.setText(String.valueOf(md.getPduTotals()));
        specialEventsTF.setText(String.valueOf(md.getPduSpecialEvents()));
        annualDayUseTF.setText(String.valueOf(md.getPduAnnualDayUse()));
        dayUseTF.setText(String.valueOf(md.getPduDayUse()));
        seniorTF.setText(String.valueOf(md.getPduSenior()));
        disabledTF.setText(String.valueOf(md.getPduDisabled()));
        goldenBearTF.setText(String.valueOf(md.getPduGoldenBear()));
        disabledVeteranTF.setText(String.valueOf(md.getPduDisabledVeteran()));
        nonResOHVPassTF.setText(String.valueOf(md.getPduNonResOHVPass()));
        annualPassSaleTF.setText(String.valueOf(md.getPduAnnualPassSale()));
        campingTF.setText(String.valueOf(md.getPduCamping()));
        seniorCampingTF.setText(String.valueOf(md.getPduSeniorCamping()));
        disabledCampingTF.setText(String.valueOf(md.getPduDisabledCamping()));
        conversionFactorFreeDayUseTF.setText(md.getFduConversionFactor().toString());
        freeDayUseTotalsTF.setText(String.valueOf(md.getFduTotals()));
        totalVehiclesTF.setText(String.valueOf(md.getFscTotalVehicles()));
        totalPeopleTF.setText(String.valueOf(md.getFscTotalPeople()));
        ratioTF.setText(md.getFscRatio().toString());
        commentsTB.setText(md.getComment());
        mcTF.setText(String.valueOf(md.getoMC()));
        atvTF.setText(String.valueOf(md.getoATV()));
        fourByFourTF.setText(String.valueOf(md.getO4X4()));
        rovTF.setText(String.valueOf(md.getoROV()));
        aqmaTF.setText(String.valueOf(md.getoAQMA()));
        allStarKartingTF.setText(String.valueOf(md.getoAllStarKarting()));
        hangtownTF.setText(String.valueOf(md.getoHangtown()));
        otherTF.setText(String.valueOf(md.getoOther()));
        browseFileTF.setText(md.getForm449File().toPath().toString());
        showOKOnSubmit();
        resetValidation();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        Object[] o = userDataGroup.getChildren().toArray();
        for (int i = 0; i < o.length; i++) {
            if (o[i] instanceof TextField) {
                ((TextField) o[i]).clear();
            } else if (o[i] instanceof TextArea) {
                ((TextArea) o[i]).clear();
            }
        }
        resetValidation();
    }
    // enable buttons again
    clearSubmitButtonStatusIndicator();
    submitButton.setDisable(false);
    clearButton.setDisable(false);
    browseFileButton.setDisable(false);
}
Example 47
Project: Java-Bytecode-Editor-master  File: MethodController.java View source code
public TextArea getCodeBcel() {
    return codeBcel;
}
Example 48
Project: LibFX-master  File: SceneGraphNavigatorTest.java View source code
@Override
protected Node createSingletonNode() {
    return new TextArea("A node without parents and children.");
}
Example 49
Project: JFTClient-master  File: TerminalPanel.java View source code
public TextArea getTextArea() {
    return textArea;
}
Example 50
Project: sportstracker-master  File: AboutDialogController.java View source code
@Override
protected void setupDialogControls() {
    // Workaround: always show vertical scroll bars (otherwise they are displayed when the TextArea gets the focus)
    Platform.runLater(() -> {
        taAuthors.setWrapText(true);
        taTranslators.setWrapText(true);
    });
}
Example 51
Project: Lily-master  File: ConsolePane.java View source code
public TextArea getTextArea() {
    return textArea;
}
Example 52
Project: FrostBite3Editor-master  File: ModLoaderController.java View source code
public TextArea getDesc() {
    return desc;
}
Example 53
Project: FXForm2-master  File: TextAreaFactory.java View source code
public FXFormNode call(Void aVoid) {
    TextArea textArea = new TextArea();
    textArea.setWrapText(true);
    return new FXFormNodeWrapper(textArea, textArea.textProperty());
}
Example 54
Project: nanobot-master  File: LogHandler.java View source code
static void initialize(final TextArea textArea) {
    for (final Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof LogHandler) {
            ((LogHandler) h).setTextArea(textArea);
        }
    }
}
Example 55
Project: speedment-master  File: DefaultTextAreaItem.java View source code
@Override
protected TextInputControl getInputControl() {
    TextArea area = new TextArea();
    area.setWrapText(true);
    return area;
}
Example 56
Project: Flipit-Map-Creator-master  File: LogManager.java View source code
/**
     * Initialises the LogManager object
     *
     * @param textArea
     */
public void init(TextArea textArea) {
    this.logArea = textArea;
    this.logArea.setText("");
    this.logArea.setEditable(false);
    this.logArea.setWrapText(true);
    this.logMessage = new StringBuilder();
    this.preventNewLineAtFirst = true;
}
Example 57
Project: musicmount-master  File: FXConsole.java View source code
TextArea getTextArea() {
    return textArea;
}
Example 58
Project: javafx-ws-client-master  File: TabRestController.java View source code
TextArea getMasterNode() {
    return masterNode;
}
Example 59
Project: SyncNotes-master  File: NoteViewController.java View source code
public TextArea getBody() {
    return note_body;
}
Example 60
Project: NoticEditor-master  File: NoticeViewController.java View source code
public TextArea getEditor() {
    return editor;
}
Example 61
Project: simplejavayoutubeuploader-master  File: TagTextArea.java View source code
private void initTextArea() {
    final TextArea textArea = new TextArea();
    textArea.setWrapText(true);
    textArea.textProperty().bindBidirectional(tags);
    getChildren().add(textArea);
}
Example 62
Project: JRebirth-master  File: AbstractView.java View source code
/**
     * Build the errorNode to display the error taht occured.
     *
     * @param ce the CoreException to display
     */
private void buildErrorNode(final CoreException ce) {
    final TextArea ta = TextAreaBuilder.create().text(ce.getMessage()).build();
    this.errorNode = PaneBuilder.create().children(ta).build();
}
Example 63
Project: SimpleDialogFX-master  File: Dialog.java View source code
/**
     * Retrieves the <code>TextArea</code> object for the exception area. Allows
     * user to customize FX <code>TextArea</code> object.
     *
     * @return TextArea object
     */
public final TextArea getExceptionArea() {
    return exceptionArea;
}
Example 64
Project: JXTN-master  File: JFX.java View source code
/**
     * [email protected] javafx.scene.control.TextArea}建構器。
     *
     * @return [email protected] javafx.scene.control.TextAreaMaker}
     */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static javafx.scene.control.TextAreaMaker<javafx.scene.control.TextArea, ?> textArea() {
    return new javafx.scene.control.TextAreaMaker();
}
Example 65
Project: XR3Player-master  File: SmartController.java View source code
/**
	 * @return the informationTextArea
	 */
public TextArea getInformationTextArea() {
    return informationTextArea;
}

Java Examples for com.google.gwt.user.client.ui.RootLayoutPanel

The following java examples will help you to understand the usage of com.google.gwt.user.client.ui.RootLayoutPanel. These source code samples are taken from different open source projects.

Example 1
Project: gwt-test-utils-master  File: UiBinderWithSplitLayoutPanelTest.java View source code
@Test
public void uiBinderWithSplitLayoutPanel() {
    // Given
    UiBinderWithSplitLayoutPanel panel = new UiBinderWithSplitLayoutPanel();
    // When
    RootLayoutPanel.get().add(panel);
    // Then
    assertThat(panel.northLabel.getText()).isEqualTo("North");
    assertThat(panel.centerLabel.getText()).isEqualTo("Center");
    assertThat(panel.eastLabel.getText()).isEqualTo("East");
    assertThat(panel.southLabel.getText()).isEqualTo("South");
    assertThat(panel.centerLabel.getText()).isEqualTo("Center");
    assertThat(panel.getLayout().getWidgetDirection(panel.northLabel)).isEqualTo(Direction.NORTH);
    assertThat(panel.westHTML.getHTML()).isEqualTo("<ul><li id=\"li-west0\">west0</li><li id=\"li-west1\">west1</li></ul>");
    LIElement li0 = panel.westHTML.getElement().getFirstChildElement().getChild(0).cast();
    LIElement li1 = panel.westHTML.getElement().getFirstChildElement().getChild(1).cast();
    assertThat(li0.getInnerText()).isEqualTo("west0");
    assertThat(li1.getInnerText()).isEqualTo("west1");
    assertThat(Document.get().getElementById("li-west0")).isEqualTo(li0);
    assertThat(Document.get().getElementById("li-west1")).isEqualTo(li1);
    assertThat(panel.getLayout().getSplitterSize()).isEqualTo(15);
}
Example 2
Project: gadget-server-master  File: ApplicationEntryPoint.java View source code
public void actualModuleLoad() {
    RootLayoutPanel.get().getElement().setId("root-layout");
    Window.addResizeHandler(new ResizeHandler() {

        @Override
        public void onResize(ResizeEvent event) {
            RootLayoutPanel.get().getElement().getStyle().setTop(80, Unit.PX);
            RootLayoutPanel.get().getElement().getStyle().setBottom(5, Unit.PX);
        }
    });
    DelayedBindRegistry.bind(MODULES);
    MODULES.getPlaceManager().revealCurrentPlace();
}
Example 3
Project: gwt-distributed-compiler-master  File: HyperSimple.java View source code
public void onModuleLoad() {
    //	  Document doc = XMLParser.parse(resources.xmlFileWithLongText().getText());
    //	  Node n = doc.getFirstChild().getFirstChild();
    //	  String s = n.getNodeValue();
    Button button = new Button("test");
    LayoutPanel layoutPanel = new LayoutPanel();
    RootPanel.get("foo").add(button);
    RootLayoutPanel.get().add(layoutPanel);
    RootLayoutPanel.get().remove(layoutPanel);
    RootLayoutPanel.get().add(button);
    RootLayoutPanel.get().add(button);
//	  RootPanel.get().clear();
//	  RootPanel.get().add(new Label("" + s.length()));
//	  RootPanel.get().add(new Label(s));
//	  RootPanel.get().add(new TestPanel());
}
Example 4
Project: next-master  File: Utils.java View source code
// The url loaded by this method can be intercepted by
// WebViewClient.shouldOverrideUrlLoading
public static void loadUrl(String url) {
    // Window.open(url, "_tab", "");
    Anchor a = new Anchor("", url, "_tab");
    RootLayoutPanel.get().add(a);
    NativeEvent event = Document.get().createClickEvent(1, 1, 1, 1, 1, false, false, false, false);
    a.getElement().dispatchEvent(event);
    RootLayoutPanel.get().remove(a);
}
Example 5
Project: akjava_gwtlib-master  File: CellBaseEntryPoint.java View source code
@Override
public void onModuleLoad() {
    rootDeck = new DeckLayoutPanel();
    RootLayoutPanel.get().add(rootDeck);
    initialize();
    previewControler = createPreviewControler();
    DockLayoutPanel mainRoot = new DropDockDataUrlRootPanel() {

        @Override
        public void loadFile(String pareht, Optional<File> optional, String dataUrl) {
        //never called.onDropFiles overwrite but need implement
        }

        @Override
        public void onDropFiles(List<FileEntry> files) {
            doDropFiles(files);
        }
    };
    rootDeck.add(mainRoot);
    VerticalPanel topPanel = new VerticalPanel();
    topPanel.setSpacing(16);
    mainRoot.addNorth(topPanel, 48);
    topPanel.setSize("100%", "100%");
    topPanel.getElement().getStyle().setBackgroundColor("#607d8b");
    rootDeck.showWidget(0);
    HorizontalPanel panel = new HorizontalPanel();
    panel.setWidth("100%");
    topPanel.add(panel);
    Label appLabel = new Label(getAppName() + " Ver" + getAppVersion());
    appLabel.getElement().getStyle().setColor("#fff");
    panel.add(appLabel);
    HorizontalPanel rightPanel = new HorizontalPanel();
    panel.add(rightPanel);
    rightPanel.setWidth("100%");
    rightPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
    Anchor setting = new Anchor("Settings");
    setting.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            showSettingWidget();
        }
    });
    rightPanel.add(setting);
    VerticalPanel mainPanel = PanelUtils.createScrolledVerticalPanel(mainRoot, 99);
    mainPanel.setWidth("100%");
    mainPanel.getElement().getStyle().setBackgroundColor("#e8e8e8");
    mainPanel.setSpacing(16);
    mainPanel.add(createInputPanel());
    mainPanel.add(createMainCell());
    //create settings
    DockLayoutPanel settingPanel = new DockLayoutPanel(Unit.PX);
    rootDeck.add(settingPanel);
    VerticalPanel settingTopPanel = new VerticalPanel();
    settingTopPanel.setSpacing(16);
    settingTopPanel.setSize("100%", "100%");
    settingTopPanel.getElement().getStyle().setBackgroundColor("#607d8b");
    settingPanel.addNorth(settingTopPanel, 48);
    Label settingTitleLabel = new Label(getAppName() + " >> " + "Settings");
    settingTitleLabel.getElement().getStyle().setColor("#fff");
    settingTopPanel.add(settingTitleLabel);
    DockLayoutPanel closePanel = new DockLayoutPanel(Unit.PX);
    settingPanel.add(closePanel);
    Button closeBt = new Button("Close", new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            onCloseSettings();
            showMainWidget();
        }
    });
    closePanel.addNorth(closeBt, 48);
    ScrollPanel scroll = new ScrollPanel();
    closePanel.add(scroll);
    scroll.add(createSettingMainPanel());
    //create editor
    createEditor(rootDeck);
    createOtherWidget();
}
Example 6
Project: ballroom-master  File: Showcase.java View source code
public void onModuleLoad2() {
    final Image loadingImage = new Image("images/loading_lite.gif");
    loadingImage.getElement().setAttribute("style", "margin-top:200px;margin-left:auto;margin-right:auto;");
    RootLayoutPanel.get().add(loadingImage);
    GWT.runAsync(new RunAsyncCallback() {

        public void onFailure(Throwable caught) {
            Window.alert("Code download failed");
        }

        public void onSuccess() {
            DelayedBindRegistry.bind(MODULES);
            RootLayoutPanel.get().remove(loadingImage);
            MODULES.getPlaceManager().revealDefaultPlace();
        }
    });
}
Example 7
Project: chessdog-master  File: EmbedEntryPoint.java View source code
public void onModuleLoad() {
    injector.getJavaScriptBindings();
    final GlobalEventBus eventBus = injector.getEventBus();
    GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {

        public void onUncaughtException(Throwable ex) {
            Log.error("Uncaught exception:", ex);
            String errorMessage = buildErrorMessage(ex);
            eventBus.fireEvent(new UncaughtExceptionEvent(errorMessage));
        }
    });
    MainPanelEmbed mainPanel = injector.getMainPanelEmbed();
    clearAnyRemoveMeElement();
    RootLayoutPanel.get().add(mainPanel);
    Log.info("GWT Module " + this.getClass().getName() + " initialized.");
}
Example 8
Project: google-web-toolkit-svnmirror-master  File: CellTreeExample2.java View source code
public void onModuleLoad() {
    // Create a model for the tree.
    TreeViewModel model = new CustomTreeModel();
    /*
     * Create the tree using the model. We use <code>null</code> as the default
     * value of the root node. The default value will be passed to
     * CustomTreeModel#getNodeInfo();
     */
    CellTree tree = new CellTree(model, null);
    tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
    // Open the first playlist by default.
    TreeNode rootNode = tree.getRootTreeNode();
    TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
    firstPlaylist.setChildOpen(0, true);
    // Add the tree to the root layout panel.
    RootLayoutPanel.get().add(tree);
}
Example 9
Project: gwt-contacts-master  File: DesktopApplication.java View source code
public void activate() {
    _navigator.activate();
    new ActivityManager(_masterRegionMapper, _eventBus).setDisplay(_shell.getMasterRegion());
    new ActivityManager(_detailRegionMapper, _eventBus).setDisplay(_shell.getDetailRegion());
    RootLayoutPanel.get().add(_shell);
    // Goes to place represented on URL or default place
    _placeHistoryHandler.handleCurrentHistory();
}
Example 10
Project: gwt-master  File: CellTreeExample2.java View source code
public void onModuleLoad() {
    // Create a model for the tree.
    TreeViewModel model = new CustomTreeModel();
    /*
     * Create the tree using the model. We use <code>null</code> as the default
     * value of the root node. The default value will be passed to
     * CustomTreeModel#getNodeInfo();
     */
    CellTree tree = new CellTree(model, null);
    tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
    // Open the first playlist by default.
    TreeNode rootNode = tree.getRootTreeNode();
    TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
    firstPlaylist.setChildOpen(0, true);
    // Add the tree to the root layout panel.
    RootLayoutPanel.get().add(tree);
}
Example 11
Project: gwt-sandbox-master  File: CellTreeExample2.java View source code
public void onModuleLoad() {
    // Create a model for the tree.
    TreeViewModel model = new CustomTreeModel();
    /*
     * Create the tree using the model. We use <code>null</code> as the default
     * value of the root node. The default value will be passed to
     * CustomTreeModel#getNodeInfo();
     */
    CellTree tree = new CellTree(model, null);
    tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
    // Open the first playlist by default.
    TreeNode rootNode = tree.getRootTreeNode();
    TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
    firstPlaylist.setChildOpen(0, true);
    // Add the tree to the root layout panel.
    RootLayoutPanel.get().add(tree);
}
Example 12
Project: gwt.svn-master  File: CellTreeExample2.java View source code
public void onModuleLoad() {
    // Create a model for the tree.
    TreeViewModel model = new CustomTreeModel();
    /*
     * Create the tree using the model. We use <code>null</code> as the default
     * value of the root node. The default value will be passed to
     * CustomTreeModel#getNodeInfo();
     */
    CellTree tree = new CellTree(model, null);
    tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
    // Open the first playlist by default.
    TreeNode rootNode = tree.getRootTreeNode();
    TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
    firstPlaylist.setChildOpen(0, true);
    // Add the tree to the root layout panel.
    RootLayoutPanel.get().add(tree);
}
Example 13
Project: jagger-master  File: JaggerWebClient.java View source code
public void onModuleLoad() {
    JaggerResources.INSTANCE.css().ensureInjected();
    // Initialize the history handler and activity manager
    EventBus eventBus = new SimpleEventBus();
    ActivityMapper activityMapper = new JaggerActivityMapper(JaggerResources.INSTANCE);
    PlaceHistoryMapper placeHistoryMapper = new JaggerPlaceHistoryMapper();
    PlaceController placeController = new PlaceController(eventBus);
    PlaceHistoryHandler placeHistoryHandler = new PlaceHistoryHandler(placeHistoryMapper);
    placeHistoryHandler.register(placeController, eventBus, new TrendsPlace(NameTokens.SUMMARY));
    MainView mainView = new MainView(eventBus, JaggerResources.INSTANCE);
    RootLayoutPanel.get().add(mainView);
    ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
    activityManager.setDisplay(mainView.getContentContainer());
    placeHistoryHandler.handleCurrentHistory();
}
Example 14
Project: kramerius-master  File: EditorEntryPoint.java View source code
private void initializeUI() {
    EditorPresenter editorPresenter = new EditorPresenter(EditorViewsFactory.getInstance().createEditorView(), new StandardDispatchAsync(new DefaultExceptionHandler()));
    RootLayoutPanel.get().add(editorPresenter.getDisplay().asWidget());
    editorPresenter.bind();
    openEditorsOnStrartup(editorPresenter);
}
Example 15
Project: neighborhoodPSS-master  File: NeighborhoodPSS.java View source code
private void buildUi() {
    ProjectMediator projectMed = new ProjectMediator();
    DockLayoutPanel thePanel = new DockLayoutPanel(Unit.EM);
    RootLayoutPanel.get().add(thePanel);
    final Image visico_img = new Image();
    visico_img.setUrl("res/VISICO.jpg");
    final HorizontalPanel logopanel = new HorizontalPanel();
    logopanel.add(visico_img);
    UserPanel userPanel = new UserPanel(projectMed);
    projectMed.registerUserPanel(userPanel);
    logopanel.add(userPanel);
    thePanel.addNorth(logopanel, 10);
    MainTab panel = new MainTab(projectMed);
    projectMed.registerMainPanel(panel);
    thePanel.add(panel);
}
Example 16
Project: scalagwt-gwt-master  File: CellTreeExample2.java View source code
public void onModuleLoad() {
    // Create a model for the tree.
    TreeViewModel model = new CustomTreeModel();
    /*
     * Create the tree using the model. We use <code>null</code> as the default
     * value of the root node. The default value will be passed to
     * CustomTreeModel#getNodeInfo();
     */
    CellTree tree = new CellTree(model, null);
    tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
    // Open the first playlist by default.
    TreeNode rootNode = tree.getRootTreeNode();
    TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
    firstPlaylist.setChildOpen(0, true);
    // Add the tree to the root layout panel.
    RootLayoutPanel.get().add(tree);
}
Example 17
Project: smonitor-master  File: Admin.java View source code
@Override
public void onModuleLoad() {
    // Rest client configuration
    RestClient.setJacksonMarshallingActive(true);
    RestClient.setApplicationRoot("rs");
    // Disable right click
    RootLayoutPanel.get().addDomHandler(new ContextMenuHandler() {

        @Override
        public void onContextMenu(ContextMenuEvent event) {
            event.preventDefault();
            event.stopPropagation();
        }
    }, ContextMenuEvent.getType());
    // Create main content
    mainLayout = new MainLayout();
    RootLayoutPanel.get().add(mainLayout);
    // init
    mainLayout.init();
}
Example 18
Project: twice-master  File: MobileInterface.java View source code
/**
	 * Switch to a specific component ([email protected] TWICEModule}). If the module has not been accessed yet, it is instantiated and the callback is invoked.
	 * 
	 * @param componentName
	 */
void switchComponent(String componentName) {
    RootLayoutPanel.get().clear();
    if (componentName == null && components.keySet().size() > 0) {
        componentName = (String) components.keySet().toArray()[0];
    }
    // Is it a not yet instantiated module?
    final TWICEModule module = modules.get(componentName);
    if (module != null) {
        // Then instantiate it and add it to the components
        final String moduleComponentName = componentName;
        TWICEModuleController.instantiateModule(module, new AsyncCallback<Widget>() {

            @Override
            public void onSuccess(Widget result) {
                if (currentWidget != null)
                    TWICEModuleController.stop(currentWidget);
                components.put(moduleComponentName, result);
                modules.remove(moduleComponentName);
                AsyncCallback<Widget> callback = callbacks.get(moduleComponentName);
                if (callback != null) {
                    callback.onSuccess(result);
                }
                switchToWidget(moduleComponentName, result);
            }

            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Was not able to initialize module " + moduleComponentName);
            }
        });
    } else {
        Widget w = components.get(componentName);
        if (w == null && components.size() > 0) {
            componentName = (String) components.keySet().toArray()[0];
            w = components.get(componentName);
        }
        switchToWidget(componentName, w);
    }
}
Example 19
Project: CSC-HCI-480-2013-repo-master  File: Entry.java View source code
@Override
public void onModuleLoad() {
    EventBus eventBus = injector.getEventBus();
    PlaceController placeController = injector.getPlaceController();
    // Start ActivityManager for the main widget with our ActivityMapper
    ActivityMapper activityMapper = new AppActivityMapper(injector.getDoublePanelView(), placeController, injector.getH2OServiceAsync());
    ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
    activityManager.setDisplay(container);
    // Start PlaceHistoryHandler with our PlaceHistoryMapper
    //AppPlaceHistoryMapper historyMapper = GWT.create(AppPlaceHistoryMapper.class);
    historyMapper = GWT.create(AppPlaceHistoryMapper.class);
    PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
    historyHandler.register(placeController, eventBus, defaultPlace);
    RootLayoutPanel.get().add(container);
    historyHandler.handleCurrentHistory();
}
Example 20
Project: gwt.create2015-master  File: Showcase.java View source code
/**
   * This is the entry point method.
   */
public void onModuleLoad() {
    // Generate the source code and css for the examples
    GWT.create(GeneratorInfo.class);
    // Inject global styles.
    injectThemeStyleSheet();
    images.css().ensureInjected();
    // Initialize the constants.
    ShowcaseConstants constants = GWT.create(ShowcaseConstants.class);
    // Create the application shell.
    final SingleSelectionModel<ContentWidget> selectionModel = new SingleSelectionModel<ContentWidget>();
    final MainMenuTreeViewModel treeModel = new MainMenuTreeViewModel(constants, selectionModel);
    Set<ContentWidget> contentWidgets = treeModel.getAllContentWidgets();
    shell = new ShowcaseShell(treeModel);
    RootLayoutPanel.get().add(shell);
    // Prefetch examples when opening the Category tree nodes.
    final List<Category> prefetched = new ArrayList<Category>();
    final CellTree mainMenu = shell.getMainMenu();
    mainMenu.addOpenHandler(new OpenHandler<TreeNode>() {

        public void onOpen(OpenEvent<TreeNode> event) {
            Object value = event.getTarget().getValue();
            if (!(value instanceof Category)) {
                return;
            }
            Category category = (Category) value;
            if (!prefetched.contains(category)) {
                prefetched.add(category);
                Prefetcher.prefetch(category.getSplitPoints());
            }
        }
    });
    // Always prefetch.
    Prefetcher.start();
    // Make sure Settings are getting synced with history at the very start.
    Settings.get().ensureUpdatesOnHistoryChange();
    // Change the history token when a main menu item is selected.
    selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

        public void onSelectionChange(SelectionChangeEvent event) {
            ContentWidget selected = selectionModel.getSelectedObject();
            if (selected != null) {
                History.newItem(getContentWidgetToken(selected) + Settings.get().getHistorySuffix(), true);
            }
        }
    });
    // Setup a history handler to reselect the associate menu item.
    final ValueChangeHandler<String> historyHandler = new ValueChangeHandler<String>() {

        public void onValueChange(ValueChangeEvent<String> event) {
            // Get the content widget associated with the history token.
            String historyToken = event.getValue();
            int endOfWidgetToken = historyToken.indexOf("?");
            if (endOfWidgetToken == -1) {
                endOfWidgetToken = historyToken.length();
            }
            ContentWidget contentWidget = treeModel.getContentWidgetForToken(historyToken.substring(0, endOfWidgetToken));
            if (contentWidget == null) {
                return;
            }
            // Expand the tree node associated with the content.
            Category category = treeModel.getCategoryForContentWidget(contentWidget);
            TreeNode node = mainMenu.getRootTreeNode();
            int childCount = node.getChildCount();
            for (int i = 0; i < childCount; i++) {
                if (node.getChildValue(i) == category) {
                    node.setChildOpen(i, true, true);
                    break;
                }
            }
            // Select the node in the tree.
            selectionModel.setSelected(contentWidget, true);
            // Display the content widget.
            displayContentWidget(contentWidget);
        }
    };
    History.addValueChangeHandler(historyHandler);
    // Show the initial example.
    if (History.getToken().length() > 0) {
        History.fireCurrentHistoryState();
    } else {
        // Use the first token available.
        TreeNode root = mainMenu.getRootTreeNode();
        TreeNode category = root.setChildOpen(0, true);
        ContentWidget content = (ContentWidget) category.getChildValue(0);
        selectionModel.setSelected(content, true);
    }
    // Generate a site map.
    createSiteMap(contentWidgets);
}
Example 21
Project: GwtMobile-master  File: Page.java View source code
public void goTo(final Page toPage, final Transition transition) {
    Element focus = Utils.getActiveElement();
    focus.blur();
    final Page fromPage = this;
    toPage.setTransition(transition);
    if (transition != null) {
        transition.start(fromPage, toPage, RootLayoutPanel.get(), false);
    } else {
        Transition.start(fromPage, toPage, RootLayoutPanel.get());
    }
}
Example 22
Project: hexa.tools-master  File: ResizablePanelBad.java View source code
@Override
public void execute() {
    // try to fit to the content size
    int maxWidth = // 20 pixels of
    Window.getClientWidth() - // 20 pixels of
    20;
    // margin
    int w = Math.max(ResizablePanelBad.this.getOffsetWidth(), Math.max(contentWidget.getElement().getScrollWidth(), contentWidget.getElement().getOffsetWidth())) + resizeHandlerSize * 2;
    if (w > maxWidth)
        w = maxWidth;
    int maxHeight = Window.getClientHeight() - 20;
    int h = Math.max(ResizablePanelBad.this.getOffsetHeight(), Math.max(contentWidget.getElement().getScrollHeight(), contentWidget.getElement().getOffsetHeight())) + resizeHandlerSize * 2 + titleSize;
    if (h > maxHeight)
        h = maxHeight;
    PositionAndSize posSize = new PositionAndSize((Window.getClientWidth() - w) / 2, (Window.getClientHeight() - h) / 2, w, h);
    posSize.limit();
    RootLayoutPanel.get().setWidgetLeftWidth(ResizablePanelBad.this, posSize.left, Unit.PX, posSize.width, Unit.PX);
    RootLayoutPanel.get().setWidgetTopHeight(ResizablePanelBad.this, posSize.top, Unit.PX, posSize.height, Unit.PX);
    RootLayoutPanel.get().animate(300);
}
Example 23
Project: KKPortal-master  File: DebugPanel.java View source code
private void ensureWidget() {
    if (panel != null)
        return;
    panel = new HTML();
    panel.getElement().getStyle().setZIndex(200);
    panel.getElement().getStyle().setBackgroundColor("black");
    panel.getElement().getStyle().setColor("green");
    panel.getElement().getStyle().setOverflow(Overflow.SCROLL);
    RootLayoutPanel.get().add(panel);
    updatelog();
}
Example 24
Project: YaCD-master  File: Module.java View source code
@Override
public void onModuleLoad() {
    ClientFactory factory = GWT.create(ClientFactory.class);
    EventBus events = factory.getEventBus();
    PlaceController places = factory.getPlaceController();
    ActivityMapper activityMapper = new ActivityMapperImpl(factory);
    ActivityManager activityManager = new ActivityManager(activityMapper, events);
    activityManager.setDisplay(rootPanel);
    PlaceHistoryMapper historyMapper = GWT.create(IPlaceHistoryMapper.class);
    PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
    historyHandler.register(places, events, home);
    RootLayoutPanel.get().add(rootPanel);
    historyHandler.handleCurrentHistory();
}
Example 25
Project: avro-ui-master  File: AvroUiSandbox.java View source code
private void init() {
    Utils.injectSandboxStyles();
    ClientFactory clientFactory = GWT.create(ClientFactory.class);
    EventBus eventBus = clientFactory.getEventBus();
    PlaceController placeController = clientFactory.getPlaceController();
    ActivityMapper headerActivityMapper = new HeaderActivityMapper(clientFactory);
    ActivityManager headerActivityManager = new ActivityManager(headerActivityMapper, eventBus);
    headerActivityManager.setDisplay(appWidget.getAppHeaderHolder());
    ActivityMapper appActivityMapper = new AvroUiSandboxActivityMapper(clientFactory);
    ActivityManager appActivityManager = new ActivityManager(appActivityMapper, eventBus);
    appActivityManager.setDisplay(appWidget.getAppContentHolder());
    PlaceHistoryMapper historyMapper = GWT.create(AvroUiSandboxPlaceHistoryMapper.class);
    PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
    Place place = new MainPlace();
    historyHandler.register(placeController, eventBus, place);
    RootLayoutPanel.get().add(appWidget);
    // Goes to the place represented on URL else default place
    historyHandler.handleCurrentHistory();
}
Example 26
Project: errai-mvp-master  File: RootView.java View source code
@Override
public void setInSlot(Object slot, Widget content) {
    assert slot == RootPresenter.rootSlot : "Unknown slot used in the root proxy.";
    if (usingRootLayoutPanel) {
        // TODO Next 3 lines are a dirty workaround for
        // http://code.google.com/p/google-web-toolkit/issues/detail?id=4737
        RootPanel.get().clear();
        RootLayoutPanel.get().clear();
        RootPanel.get().add(RootLayoutPanel.get());
        if (content != null) {
            RootLayoutPanel.get().add(content);
        }
    } else {
        // TODO Next 2 lines are a dirty workaround for
        // http://code.google.com/p/google-web-toolkit/issues/detail?id=4737
        RootLayoutPanel.get().clear();
        RootPanel.get().clear();
        if (content != null) {
            RootPanel.get().add(content);
        }
    }
}
Example 27
Project: GWT-Hangouts-master  File: HangoutSoundPlayer.java View source code
protected void onApiReady() {
    storageDataList = new StorageDataList(storageControler, storageKey);
    VerticalPanel main = new VerticalPanel();
    RootPanel.get().add(main);
    //ImageBundle use that!
    //clear.cache.gif sometime,often failed
    final Image img = new Image("http://www.xucker.jpn.org/test/resources/soundplayer_title.png#1");
    //main.add(img);
    //img.setVisible(false);
    /*
		main.add(new Label("SoundPlayer"));
		
		TabLayoutPanel tab=new TabLayoutPanel(25, Unit.PX);
		tab.setSize("400px", "200px");
		RootLayoutPanel.get().add(tab);
		log(RootLayoutPanel.get().getOffsetWidth()+"x"+RootLayoutPanel.get().getOffsetHeight());
		
		tab.add(new Label("hello"),"hello");
		*/
    /*
		StackLayoutPanel test=new StackLayoutPanel(Unit.PX);
		test.setHeight("420px");
		test.setWidth("280px");
		//main.add(test);
		RootLayoutPanel.get().add(test);
		test.add(new Label("OK"),"TEST",25);
		test.showWidget(0,true);
		test.setVisible(false);
		test.setVisible(true);
		*/
    final StackLayoutPanel stacks = new StackLayoutPanel(Unit.PX);
    stacks.setHeight("330px");
    stacks.setWidth("280px");
    main.add(stacks);
    img.addMouseOverHandler(new MouseOverHandler() {

        @Override
        public void onMouseOver(MouseOverEvent event) {
            img.setVisible(false);
            stacks.setVisible(true);
            log("mouse-over");
        }
    });
    VerticalPanel player = new VerticalPanel();
    player.setWidth("100%");
    ScrollPanel playscroll = new ScrollPanel();
    playscroll.setHeight("300px");
    playscroll.setWidth("100%");
    player.add(playscroll);
    playDataContainer = new VerticalPanel();
    playDataContainer.setSpacing(8);
    playscroll.setWidget(playDataContainer);
    stacks.add(player, "Sound Player", 25);
    VerticalPanel editor = new VerticalPanel();
    editor.setWidth("100%");
    stacks.add(editor, "Edit", 25);
    //create add
    HorizontalPanel names = new HorizontalPanel();
    editor.add(names);
    names.add(new Label("sound name:"));
    final TextBox nameBox = new TextBox();
    names.add(nameBox);
    //FileUploadForm support reset.
    final FileUploadForm upload = new FileUploadForm();
    editor.add(upload);
    upload.getFileUpload().addChangeHandler(new ChangeHandler() {

        @Override
        public void onChange(ChangeEvent event) {
            JsArray<File> file = FileUtils.toFile(event.getNativeEvent());
            final FileReader reader = FileReader.createFileReader();
            reader.setOnLoad(new FileHandler() {

                @Override
                public void onLoad() {
                    dataUri = reader.getResultAsString();
                }
            });
            String name = file.get(0).getFileName();
            int index = name.lastIndexOf(".");
            if (index != -1) {
                name = name.substring(0, index);
            }
            if (nameBox.getText().isEmpty()) {
                nameBox.setText(name);
            }
            reader.readAsDataURL(file.get(0));
        }
    });
    editor.add(new Label("Or"));
    HorizontalPanel urls = new HorizontalPanel();
    urls.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
    editor.add(urls);
    urls.add(new Label("URL:"));
    final TextBox urlBox = new TextBox();
    urls.add(urlBox);
    urlBox.setWidth("200px");
    HorizontalPanel loopAndVol = new HorizontalPanel();
    loopAndVol.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
    editor.add(loopAndVol);
    loopAndVol.setSpacing(8);
    final CheckBox loop = new CheckBox("loop");
    loopAndVol.add(loop);
    final VolumeRadioboxes volume = new VolumeRadioboxes();
    loopAndVol.add(new Label("Vol:"));
    loopAndVol.add(volume);
    HorizontalPanel buttons = new HorizontalPanel();
    editor.add(buttons);
    Button addButton = new Button("add sound");
    buttons.add(addButton);
    addButton.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            String name = nameBox.getText();
            if (name.isEmpty()) {
                Window.alert("name and (url or data) are needed");
                return;
            }
            String url = dataUri;
            if (url == null) {
                if (urlBox.getText().isEmpty()) {
                    Window.alert("name and (url or data) are needed");
                    return;
                } else {
                    url = urlBox.getText();
                }
            }
            try {
                String header = name + "\t" + loop.getValue() + "\t" + volume.getVolume();
                //log("add:"+header);
                storageDataList.setDataValue(header, url);
                storageDataList.incrementId();
            } catch (Exception e) {
                String message = e.getMessage();
                if (message.indexOf("QUOTA_EXCEEDED_ERR") != -1) {
                    String error = "Browser Storage 's limit over\ndelate other sound and try again.or sound is too big to store.\nusually maximum total sound size is around 2MB\nupload sound file to server and set url is altenative way";
                    Window.alert(error);
                } else {
                    Window.alert(message);
                }
                return;
            }
            //reset
            dataUri = null;
            nameBox.setText("");
            urlBox.setText("");
            loop.setValue(false);
            volume.setValue(5);
            upload.reset();
            updateEditorDatas();
            updatePlayerDatas();
        }
    });
    Button resetButton = new Button("reset");
    buttons.add(resetButton);
    resetButton.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            dataUri = null;
            nameBox.setText("");
            loop.setValue(false);
            volume.setValue(5);
            upload.reset();
            updateEditorDatas();
            updatePlayerDatas();
        }
    });
    //
    //create list
    ScrollPanel scroll = new ScrollPanel();
    scroll.setHeight("150px");
    scroll.setWidth("100%");
    editor.add(scroll);
    editDataContainer = new VerticalPanel();
    editDataContainer.setSpacing(8);
    scroll.setWidget(editDataContainer);
    VerticalPanel howto = new VerticalPanel();
    howto.setSpacing(16);
    ScrollPanel howtoscroll = new ScrollPanel();
    howtoscroll.setHeight("300px");
    howtoscroll.setWidth("95%");
    stacks.add(howtoscroll, "How to", 25);
    howtoscroll.setWidget(howto);
    howto.add(new HTML("[Notice]"));
    howto.add(new HTML("1.Audio Type are limited\nOnly human voices play well,other sounds would usually cut off as noise."));
    howto.add(new HTML("2.File size you can store to browser are limited\nIt's depend on your browser.Chrome can store around 2MB wave file.it's a few second"));
    howto.add(new HTML("3.Wave file-format you can play are limited\nmost of wave file uploaded to web is not supported.\nI guess it's because of header comment."));
    howto.add(new HTML("4.Number of times you can play are limited\nIt's depend on your computer memory size.Watch out for process of googletalkplugin.exe"));
    Timer timer = new Timer() {

        public void run() {
            updateEditorDatas();
            updatePlayerDatas();
        }
    };
    timer.schedule(1000);
    if (playDataContainer.getWidgetCount() > 0) {
        //player
        stacks.showWidget(0);
    } else {
        //editor
        stacks.showWidget(1);
    }
//test
//stacks.add(new ExtraTest(),"tmp",25);
//stacks.showWidget(3);
}
Example 28
Project: gwt-three.js-test-master  File: TabDemoEntryPoint.java View source code
public void onModuleLoad() {
    /*
		DropVerticalPanelBase rootPanel=new DropVerticalPanelBase();
		rootPanel.setSize("100%", "100%");
		
		//RootLayoutPanel.get().add(rootPanel);
		*/
    //support drag and drop anywhere
    tabPanel = new TabLayoutPanelWithDragAndDrop(tabHeight, Unit.PX);
    ((TabLayoutPanelWithDragAndDrop) tabPanel).addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            TabDemoEntryPoint.this.onDrop(event);
        }
    });
    ((TabLayoutPanelWithDragAndDrop) tabPanel).addDragOverHandler(new DragOverHandler() {

        @Override
        public void onDragOver(DragOverEvent event) {
            TabDemoEntryPoint.this.onDragOver(event);
        }
    });
    ((TabLayoutPanelWithDragAndDrop) tabPanel).addDragLeaveHandler(new DragLeaveHandler() {

        @Override
        public void onDragLeave(DragLeaveEvent event) {
            TabDemoEntryPoint.this.onDragLeave(event);
        }
    });
    RootLayoutPanel.get().add(tabPanel);
    int width = Window.getClientWidth();
    int height = Window.getClientHeight() - tabHeight;
    /**
		 * 
		 * if
			com.google.gwt.core.client.JavaScriptException: (TypeError): Cannot read property 'WebGLRenderer' of undefined
			
			add lines and both js files on same directory with html
			<script type="text/javascript" language="javascript" src="Three.js"></script>
    		<script type="text/javascript" language="javascript" src="stats.js"></script>     
		 */
    //renderer = RendererBuilder.createRenderer();//stop using it cant' contain args
    renderer = THREE.WebGLRenderer(WebGLRendererParameter.create().alpha(true));
    //renderer = THREE.WebGLRenderer(GWTRenderObject.create().preserveDrawingBuffer()); //crash browser?
    renderer.setSize(width, height);
    //renderer.setClearColorHex(0x333333, 1);
    //RootLayoutPanel.get().setStyleName("transparent");
    canvas = new WebGLCanvas(renderer);
    //canvas.setClearColorHex(0);
    //final FocusPanel glCanvas=new FocusPanel(canvas);
    canvas.addMouseUpHandler(new MouseUpHandler() {

        @Override
        public void onMouseUp(MouseUpEvent event) {
            TabDemoEntryPoint.this.onMouseUp(event);
        }
    });
    canvas.addDoubleClickHandler(new DoubleClickHandler() {

        @Override
        public void onDoubleClick(DoubleClickEvent event) {
            TabDemoEntryPoint.this.onDoubleClick(event);
        }
    });
    canvas.addMouseWheelHandler(new MouseWheelHandler() {

        @Override
        public void onMouseWheel(MouseWheelEvent event) {
            TabDemoEntryPoint.this.onMouseWheel(event);
        }
    });
    //hpanel.setFocus(true);
    canvas.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            TabDemoEntryPoint.this.onMouseClick(event);
        }
    });
    canvas.addMouseDownHandler(new MouseDownHandler() {

        @Override
        public void onMouseDown(MouseDownEvent event) {
            TabDemoEntryPoint.this.onMouseDown(event);
        }
    });
    canvas.addMouseOutHandler(new MouseOutHandler() {

        @Override
        public void onMouseOut(MouseOutEvent event) {
            TabDemoEntryPoint.this.onMouseOut(event);
        }
    });
    canvas.addMouseMoveHandler(new MouseMoveHandler() {

        @Override
        public void onMouseMove(MouseMoveEvent event) {
            TabDemoEntryPoint.this.onMouseMove(event);
        }
    });
    //canvas.setStyleName("clear");
    //glCanvas.getElement().getStyle().setBackgroundColor("#fff");
    canvas.setWidth("100%");
    canvas.setHeight("100%");
    tabPanel.add(canvas, getTabTitle());
    //tabPanel.add(new Label("hello"),"test");
    //RootLayoutPanel.get().add(canvas);
    canvasWidth = width;
    canvasHeight = height;
    //log("initialize:"+width+"x"+height);
    initialize(renderer, width, height);
    stats = Stats.insertStatsToRootPanel();
    //for tab header
    stats.setPosition(0, 30);
    dialog = new PopupPanel();
    VerticalPanel dialogRoot = new VerticalPanel();
    dialogRoot.setSpacing(2);
    //dialog.setStyleName("transparent");
    Label label = new Label("Control");
    label.setStyleName("title");
    dialog.add(dialogRoot);
    dialogRoot.add(label);
    main = new DropVerticalPanelBase();
    main.setVisible(false);
    main.addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            TabDemoEntryPoint.this.onDrop(event);
        }
    });
    main.addDragOverHandler(new DragOverHandler() {

        @Override
        public void onDragOver(DragOverEvent event) {
            TabDemoEntryPoint.this.onDragOver(event);
        }
    });
    main.addDragLeaveHandler(new DragLeaveHandler() {

        @Override
        public void onDragLeave(DragLeaveEvent event) {
            TabDemoEntryPoint.this.onDragLeave(event);
        }
    });
    HorizontalPanel hPanel = new HorizontalPanel();
    hPanel.setWidth("100%");
    hPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
    dialogRoot.add(hPanel);
    hideButton = new Button("Hide Control");
    hideButton.setVisible(false);
    hideButton.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            main.setVisible(false);
            hideButton.setVisible(false);
            rightTop(dialog);
        }
    });
    hPanel.add(hideButton);
    dialogRoot.add(main);
    label.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            showControl();
        }
    });
    createControl(main);
    dialog.show();
    rightTop(dialog);
    Window.addResizeHandler(new ResizeHandler() {

        @Override
        public void onResize(ResizeEvent event) {
            //int w=canvas.getOffsetWidth();
            //int h=canvas.getOffsetHeight()-tabHeight;
            int w = Window.getClientWidth();
            int h = Window.getClientHeight() - tabHeight;
            if (w <= 0 || h <= 0) {
                //log("ignore 0 resize");
                return;
            }
            canvasWidth = w;
            canvasHeight = h;
            resized(w, h);
            renderer.setSize(w, h);
            rightTop(dialog);
        }
    });
    Window.addWindowScrollHandler(new ScrollHandler() {

        @Override
        public void onWindowScroll(ScrollEvent event) {
        //log("scroll:"+event.getScrollLeft()+"x"+event.getScrollTop());
        }
    });
    HTMLPanel html = new HTMLPanel(getHtml());
    html.setWidth("100%");
    html.setHeight("20px");
    html.setStyleName("text");
    popupPanel = new PopupPanel();
    popupPanel.add(html);
    popupPanel.setPopupPosition(150, 35);
    popupPanel.setWidth("100%");
    popupPanel.setStyleName("transparent");
    popupPanel.show();
    execute(System.currentTimeMillis());
}
Example 29
Project: gwtmobile-demo-master  File: MobileEntryPoint.java View source code
@Override
public void onModuleLoad() {
    //Remove the address bar (IOS & homescreen bookmark only)
    Window.scrollTo(0, 1);
    //Inject the stylesheet into the head tag
    AppResources.INSTANCE.css().ensureInjected();
    //Enable performance logging for the app
    PerfConfig.setEnableAllClasses(true);
    PerfConfig.setPerfEnabled(true);
    PerfConfig.setLogImmediately(true);
    PerfTimer timer = PerfTimer.get(this, "init");
    //create a 2 column layout
    DockLayoutPanel dockPanel = new DockLayoutPanel(Style.Unit.PCT);
    dockPanel.setStyleName(AppResources.INSTANCE.css().container());
    MobileScrollPanel scrollPanel = new MobileScrollPanel(true);
    final ContactListPanel listPanel = new ContactListPanel();
    scrollPanel.add(listPanel);
    FlowPanel west = new FlowPanel();
    west.add(new Heading("Contacts"));
    west.add(scrollPanel);
    //30%
    dockPanel.addWest(west, 30);
    final DetailPanel detail = new DetailPanel();
    FlowPanel east = new FlowPanel();
    east.add(new Heading("Contact Details"));
    east.add(detail);
    //70%
    dockPanel.addEast(east, 70);
    listPanel.addSelectionHandler(new SelectionHandler<Contact>() {

        @Override
        public void onSelection(SelectionEvent<Contact> contactSelectionEvent) {
            detail.setData(contactSelectionEvent.getSelectedItem());
        }
    });
    MobileRPCService.App.getInstance().getContacts(new AsyncCallback<ArrayList<Contact>>() {

        @Override
        public void onFailure(Throwable caught) {
            Window.alert("Having trouble communicating with the server.");
        }

        @Override
        public void onSuccess(ArrayList<Contact> result) {
            listPanel.setData(result);
        }
    });
    //remove loading indicator
    RootPanel.get("loading").getElement().setInnerHTML("");
    RootLayoutPanel.get().add(dockPanel);
    timer.end();
}
Example 30
Project: Peergos-master  File: Showcase.java View source code
/**
   * This is the entry point method.
   */
public void onModuleLoad() {
    // Generate the source code and css for the examples
    GWT.create(GeneratorInfo.class);
    // Inject global styles.
    injectThemeStyleSheet();
    images.css().ensureInjected();
    // Initialize the constants.
    ShowcaseConstants constants = GWT.create(ShowcaseConstants.class);
    // Create the application shell.
    final SingleSelectionModel<ContentWidget> selectionModel = new SingleSelectionModel<ContentWidget>();
    final MainMenuTreeViewModel treeModel = new MainMenuTreeViewModel(constants, selectionModel);
    Set<ContentWidget> contentWidgets = treeModel.getAllContentWidgets();
    shell = new ShowcaseShell(treeModel);
    RootLayoutPanel.get().add(shell);
    // Prefetch examples when opening the Category tree nodes.
    final List<Category> prefetched = new ArrayList<Category>();
    final CellTree mainMenu = shell.getMainMenu();
    mainMenu.addOpenHandler(new OpenHandler<TreeNode>() {

        public void onOpen(OpenEvent<TreeNode> event) {
            Object value = event.getTarget().getValue();
            if (!(value instanceof Category)) {
                return;
            }
            Category category = (Category) value;
            if (!prefetched.contains(category)) {
                prefetched.add(category);
                Prefetcher.prefetch(category.getSplitPoints());
            }
        }
    });
    // Always prefetch.
    Prefetcher.start();
    // Change the history token when a main menu item is selected.
    selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

        public void onSelectionChange(SelectionChangeEvent event) {
            ContentWidget selected = selectionModel.getSelectedObject();
            if (selected != null) {
                History.newItem(getContentWidgetToken(selected), true);
            }
        }
    });
    // Setup a history handler to reselect the associate menu item.
    final ValueChangeHandler<String> historyHandler = new ValueChangeHandler<String>() {

        public void onValueChange(ValueChangeEvent<String> event) {
            // Get the content widget associated with the history token.
            ContentWidget contentWidget = treeModel.getContentWidgetForToken(event.getValue());
            if (contentWidget == null) {
                return;
            }
            // Expand the tree node associated with the content.
            Category category = treeModel.getCategoryForContentWidget(contentWidget);
            TreeNode node = mainMenu.getRootTreeNode();
            int childCount = node.getChildCount();
            for (int i = 0; i < childCount; i++) {
                if (node.getChildValue(i) == category) {
                    node.setChildOpen(i, true, true);
                    break;
                }
            }
            // Select the node in the tree.
            selectionModel.setSelected(contentWidget, true);
            // Display the content widget.
            displayContentWidget(contentWidget);
        }
    };
    History.addValueChangeHandler(historyHandler);
    // Show the initial example.
    if (History.getToken().length() > 0) {
        History.fireCurrentHistoryState();
    } else {
        // Use the first token available.
        TreeNode root = mainMenu.getRootTreeNode();
        TreeNode category = root.setChildOpen(0, true);
        ContentWidget content = (ContentWidget) category.getChildValue(0);
        selectionModel.setSelected(content, true);
    }
    // Generate a site map.
    createSiteMap(contentWidgets);
}
Example 31
Project: restlet-framework-java-master  File: Mail.java View source code
/**
   * This method constructs the application user interface by instantiating
   * controls and hooking up event handler.
   */
public void onModuleLoad() {
    // Inject global styles.
    GWT.<GlobalResources>create(GlobalResources.class).css().ensureInjected();
    // Create the UI defined in Mail.ui.xml.
    DockLayoutPanel outer = binder.createAndBindUi(this);
    // Get rid of scrollbars, and clear out the window's built-in margin,
    // because we want to take advantage of the entire client area.
    Window.enableScrolling(false);
    Window.setMargin("0px");
    // Special-case stuff to make topPanel overhang a bit.
    Element topElem = outer.getWidgetContainerElement(topPanel);
    topElem.getStyle().setZIndex(2);
    topElem.getStyle().setOverflow(Overflow.VISIBLE);
    // Listen for item selection, displaying the currently-selected item in
    // the detail area.
    mailList.setListener(new MailList.Listener() {

        public void onItemSelected(MailItem item) {
            mailDetail.setItem(item);
        }
    });
    // Add the outer panel to the RootLayoutPanel, so that it will be
    // displayed.
    RootLayoutPanel root = RootLayoutPanel.get();
    root.add(outer);
}
Example 32
Project: rstudio-master  File: Application.java View source code
public void go(final RootLayoutPanel rootPanel, final Command dismissLoadingProgress) {
    rootPanel_ = rootPanel;
    Widget w = view_.getWidget();
    rootPanel.add(w);
    rootPanel.setWidgetTopBottom(w, 0, Style.Unit.PX, 0, Style.Unit.PX);
    rootPanel.setWidgetLeftRight(w, 0, Style.Unit.PX, 0, Style.Unit.PX);
    // attempt init
    pClientInit_.get().execute(new ServerRequestCallback<SessionInfo>() {

        public void onResponseReceived(final SessionInfo sessionInfo) {
            // initialize workbench after verifying agreement
            verifyAgreement(sessionInfo, new Operation() {

                public void execute() {
                    // directly to the user
                    if (ApplicationAction.isSwitchProject()) {
                        new Timer() {

                            @Override
                            public void run() {
                                dismissLoadingProgress.execute();
                            }
                        }.schedule(10000);
                    } else {
                        dismissLoadingProgress.execute();
                    }
                    session_.setSessionInfo(sessionInfo);
                    // initialize workbench
                    initializeWorkbench();
                }
            });
        }

        public void onError(ServerError error) {
            Debug.logError(error);
            dismissLoadingProgress.execute();
            globalDisplay_.showErrorMessage("RStudio Initialization Error", error.getUserMessage());
        }
    });
}
Example 33
Project: turmeric-policy-master  File: PolicyAdminUI.java View source code
/**
     * This is the entry point method.
     */
public void onModuleLoad() {
    Window.setTitle(PolicyAdminUIUtil.constants.title());
    Window.addCloseHandler(new CloseHandler<Window>() {

        public void onClose(CloseEvent<Window> event) {
            //briefly save the login/password combo
            //NOTE when using gwt hosted mode, which is sloooow, the
            //cookie will already have expired before the reload is
            //completed, so don't expect this to work in hosted mode
            Date expiry = new Date(System.currentTimeMillis() + 1000);
            //TODO change to using secure cookies only!
            String cookie = AppUser.toCookie();
            if (cookie != null) {
                Cookies.setCookie(AppKeyUtil.COOKIE_SESSID_KEY, cookie, expiry);
            //expiry, null, null, false);
            }
        }
    });
    final HandlerManager eventBus = new HandlerManager(null);
    Map<SupportedService, PolicyAdminUIService> serviceMap = createServiceMap();
    AppController pageController = new AppController(eventBus, RootLayoutPanel.get(), serviceMap);
    pageController.start();
}
Example 34
Project: umlet-master  File: BaseletGWT.java View source code
@Override
public void onModuleLoad() {
    log.info("Starting GUI ...");
    Program.init(BuildInfoProperties.getVersion(), RuntimeType.GWT);
    SharedConfig.getInstance().setDev_mode(Location.getParameter("dev") != null);
    if (!BrowserStorage.initLocalStorageAndCheckIfAvailable()) {
        if (Browser.get() == Browser.INTERNET_EXPLORER && GWT.getHostPageBaseURL().startsWith("file:")) {
            Notification.showFeatureNotSupported("You have opened this webpage from your filesystem, therefore<br/>Internet Explorer will not support local storage<br/><br/>Please use another browser like Firefox or Chrome,<br/>or open this application using the web url", false);
        } else {
            Notification.showFeatureNotSupported("Sorry, but your browser does not support the required HTML 5 feature 'local storage' (or has cookies disabled)<br/>Suggested browsers are Firefox, Chrome, Opera, Internet Explorer 10+", false);
        }
    } else if (!browserSupportsFileReader()) {
        Notification.showFeatureNotSupported("Sorry, but your browser does not support the required HTML 5 feature 'file reader'<br/>Suggested browsers are Firefox, Chrome, Opera, Internet Explorer 10+", false);
    } else {
        Notification.showInfo("Loading application ... please wait ...");
        GWT.runAsync(new RunAsyncCallback() {

            @Override
            public void onSuccess() {
                Notification.showInfo("");
                RootLayoutPanel.get().add(new MainView());
            }

            @Override
            public void onFailure(Throwable reason) {
                Notification.showFeatureNotSupported("Cannot load application from server", false);
            }
        });
        if (!SharedConfig.getInstance().isDev_mode()) {
            Window.addWindowClosingHandler(new Window.ClosingHandler() {

                @Override
                public void onWindowClosing(Window.ClosingEvent closingEvent) {
                    closingEvent.setMessage("Do you really want to leave the page? You will lose any unsaved changes.");
                }
            });
        }
    }
    log.info("GUI started");
}
Example 35
Project: android-shuffle-master  File: Shuffle.java View source code
/**
     * This method constructs the application user interface by instantiating
     * controls and hooking up event handler.
     */
public void onModuleLoad() {
    // Inject global styles.
    GWT.<GlobalResources>create(GlobalResources.class).css().ensureInjected();
    ShuffleGinjector ginjector = GWT.create(ShuffleGinjector.class);
    Main main = ginjector.getMain();
    // Get rid of scrollbars, and clear out the window's built-in margin,
    // because we want to take advantage of the entire client area.
    Window.enableScrolling(false);
    Window.setMargin("0px");
    RootLayoutPanel.get().add(main);
//        addUploader();
}
Example 36
Project: droolsjbpm-master  File: JBRMSEntryPoint.java View source code
private void showMain() {
    Window.setStatus(((Constants) GWT.create(Constants.class)).LoadingUserPermissions());
    CapabilitiesManager.getInstance().refreshAllowedCapabilities(new Command() {

        public void execute() {
            Window.setStatus(" ");
            RootLayoutPanel.get().add(createMain());
        }
    });
    // Setup a history handler to reselect the associate menu item
    final ValueChangeHandler<String> historyHandler = new ValueChangeHandler<String>() {

        public void onValueChange(ValueChangeEvent<String> event) {
        //TODO: Handle History
        }
    };
    History.addValueChangeHandler(historyHandler);
}
Example 37
Project: eQTL-GWT-Cassandra-master  File: ClientMainWindow.java View source code
public void onModuleLoad() {
    if (RootPanel.get("content").getElement().getElementsByTagName("a").getLength() > 0)
        // user is seeing login error
        return;
    RootLayoutPanel.get().add(uiBinder.createAndBindUi(this));
    new AutoRetry<Map<Integer, String>>() {

        public void success(Map<Integer, String> result) {
            for (final Map.Entry<Integer, String> dataSet : result.entrySet()) {
                MenuItem menuItem = new MenuItem(dataSet.getValue(), new Command() {

                    public void execute() {
                        selectDataSet(dataSet.getKey(), dataSet.getValue());
                    }
                });
                loadMenu.addItem(menuItem);
            }
        }

        public void invoke(AsyncCallback<Map<Integer, String>> callback) {
            dataRetrievalService.enumerateDataSets(callback);
        }
    }.run();
}
Example 38
Project: gwt-mvp-contacts-master  File: ContactsDemo.java View source code
@Override
public void onModuleLoad() {
    northPanel.setStyleName("darkGreyBackground");
    westPanel.setStyleName("greyBackground");
    centerPanel.setStyleName("greyBackground");
    splitLayoutPanel.addWest(westPanel, 223);
    splitLayoutPanel.add(centerPanel);
    splitLayoutPanel.setStyleName("gwt-SplitLayoutPanel");
    dockLayoutPanel.addNorth(northPanel, 4.5);
    dockLayoutPanel.add(splitLayoutPanel);
    clientFactory = GWT.create(IClientFactory.class);
    EventBus eventBus = clientFactory.getEventBus();
    PlaceController placeController = clientFactory.getPlaceController();
    // Start NorthActivityManager for the north widget with the
    // NorthActivityMapper
    ActivityMapper northActivityMapper = new NorthActivityMapper(clientFactory);
    ActivityManager northActivityManager = new ActivityManager(northActivityMapper, eventBus);
    northActivityManager.setDisplay(northDisplay);
    // Start CenterActivityManager for the center widget with the
    // CenterActivityMapper
    ActivityMapper centerActivityMapper = new CenterActivityMapper(clientFactory);
    ActivityManager centerActivityManager = new ActivityManager(centerActivityMapper, eventBus);
    centerActivityManager.setDisplay(centerDisplay);
    // Start WestActivityManager for the west widget with the
    // WestActivityMapper
    ActivityMapper westActivityMapper = new WestActivityMapper(clientFactory);
    ActivityManager westActivityManager = new ActivityManager(westActivityMapper, eventBus);
    westActivityManager.setDisplay(westDisplay);
    // Start PlaceHistoryHandler with our PlaceHistoryMapper
    AppPlaceHistoryMapper historyMapper = GWT.create(AppPlaceHistoryMapper.class);
    PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
    historyHandler.register(placeController, eventBus, defaultPlace);
    RootLayoutPanel.get().add(dockLayoutPanel);
    // Goes to place represented on URL or default place
    historyHandler.handleCurrentHistory();
}
Example 39
Project: gwt-pages-master  File: CompositeLayoutApplicationPresenter.java View source code
public void showPage(LoadedPageContainer page, PageParameters parameters, PageRequestSession session) {
    TokenProvider oracle = session.get(TokenProvider.class, true);
    ApplicationPresenter presenter = null;
    String presenterToken = null;
    if (null == oracle) {
        presenterToken = (String) session.get(PRESENTER_TOKEN_KEY, true);
        if (null == presenterToken) {
            presenterToken = defaultToken;
        }
    } else {
        presenterToken = oracle.getPresenterToken(page, parameters, session);
    }
    if (null != presenterToken)
        presenter = index.get(presenterToken);
    if (null == presenter) {
        if (null == presenterToken)
            throw new NullPointerException("Null presenter token for page '" + page.getPageToken() + "'");
        else
            throw new NullPointerException("No presenter located for token '" + presenterToken + "'");
    }
    if (null == currentPresenter || !currentPresenter.equals(presenter)) {
        if (null != currentPresenter)
            RootLayoutPanel.get().clear();
        RootLayoutPanel.get().add((Widget) presenter.asWidget());
        currentPresenter = presenter;
    }
    try {
        presenter.showPage(page, parameters, session);
    } catch (Throwable t) {
        currentPresenter.clearCurrentPage();
        currentPresenter = null;
        clearCurrentPage();
        if (t instanceof RuntimeException)
            throw (RuntimeException) t;
        else
            throw new RuntimeException(t);
    }
}
Example 40
Project: gwt-rf-queue-master  File: DynaTableRf.java View source code
/**
   * This method sets up the top-level services used by the application.
   */
@Override
public void onModuleLoad() {
    Cookies.removeCookie("authOff");
    Cookies.removeCookie("networkOff");
    final DynaTableRequestFactory requests = GWT.create(DynaTableRequestFactory.class);
    QosRequestTransport transport = new QosRequestTransport();
    QosManager manager = new QosManager();
    manager.setRequestTransport(transport);
    QosQueue root = new QosQueue();
    root.setTarget(manager);
    manager.start();
    transport.setDefaultSource(root);
    requests.initialize(eventBus, transport);
    SimpleNotification sn = new SimpleNotification(manager);
    manager.addQosEventHandler(new QosEventHandler() {

        @Override
        public void onQosEvent(QosEvent qosEvent) {
            queueLength.setText("" + qosEvent.getList().size());
            if (qosEvent.getRetryCount() > 0) {
                retryCount.setText("" + qosEvent.getRetryCount());
            } else {
                retryCount.setText("-");
            }
        }
    });
    transport.setAuthFailureDetector(new AuthFailureDetector() {

        @Override
        public boolean isLoginRedirect(Response response) {
            // works for things like CAS with spring integration.
            String location = response.getHeader("Location");
            boolean authFail = location != null && !location.isEmpty();
            if (authFail) {
                authStatus.setText("Failed");
            } else {
                authStatus.setText("OK");
            }
            return authFail;
        }
    });
    // Add remote logging handler
    //    RequestFactoryLogHandler.LoggingRequestProvider provider = new RequestFactoryLogHandler.LoggingRequestProvider() {
    //      @Override
    //    public LoggingRequest getLoggingRequest() {
    //        return requests.loggingRequest();
    //      }
    //    };
    //    Logger.getLogger("").addHandler(new ErrorDialog().getHandler());
    //    Logger.getLogger("").addHandler(
    //        new RequestFactoryLogHandler(provider, Level.WARNING,
    //            new ArrayList<String>()));
    FavoritesManager manager2 = new FavoritesManager(requests);
    PersonEditorWorkflow.register(eventBus, requests, manager2);
    calendar = new SummaryWidget(eventBus, requests, 15);
    favorites = new FavoritesWidget(eventBus, requests, manager2);
    filter = new DayFilterWidget(eventBus);
    RootLayoutPanel.get().add(GWT.<Binder>create(Binder.class).createAndBindUi(this));
// Fast test to see if the sample is not being run from devmode
//    if (GWT.getHostPageBaseURL().startsWith("file:")) {
//      log.log(Level.SEVERE, "The DynaTableRf sample cannot be run without its"
//          + " server component.  If you are running the sample from a"
//          + " GWT distribution, use the 'ant devmode' target to launch"
//          + " the DTRF server.");
//    }
}
Example 41
Project: GwtMobile-UI-master  File: SerialPageHistory.java View source code
@Override
public void goTo(Page toPage, Object params, Transition transition) {
    Element focus = Utils.getActiveElement();
    focus.blur();
    final Page fromPage = current();
    setNavigateInfo(fromPage, params, false);
    add(toPage);
    toPage.setTransition(transition);
    if (transition != null) {
        transition.start(fromPage, toPage, RootLayoutPanel.get(), false);
    } else {
        Transition.start(fromPage, toPage, RootLayoutPanel.get());
    }
}
Example 42
Project: map4rdf-master  File: Browser.java View source code
@Override
public void onModuleLoad() {
    try {
        injector = GWT.create(Injector.class);
    } catch (Exception e) {
        injector = null;
        Window.alert("An several exception ocurred when load the webpage. " + " Exception: " + e.getMessage() + "." + "Please contact with System Admin");
        return;
    }
    AppController controller = new AppController(injector.getBrowserUi(), injector.getEventBus());
    controller.addPresenter(injector.getDashboard(), Places.DASHBOARD);
    controller.addPresenter(injector.getSelectConfigurationPresenter(), Places.SELECT_CONFIG);
    controller.bind();
    RootLayoutPanel.get().add(controller.getDisplay().asWidget());
    TokenFormatter tokenFormatter = new TokenFormatter() {

        private HashMap<String, PlaceRequest> tokenPlaces = new HashMap<String, PlaceRequest>();

        private HashMap<PlaceRequest, String> placeTokens = new HashMap<PlaceRequest, String>();

        @Override
        public PlaceRequest toPlaceRequest(String token) throws TokenFormatException {
            PlaceRequest toReturn;
            if (tokenPlaces.containsKey(token)) {
                toReturn = tokenPlaces.get(token);
            } else {
                toReturn = new PlaceRequest(token);
                tokenPlaces.put(token, toReturn);
                placeTokens.put(toReturn, token);
            }
            return toReturn;
        }

        @Override
        public String toHistoryToken(PlaceRequest placeRequest) throws TokenFormatException {
            String token;
            if (placeTokens.containsKey(placeRequest)) {
                token = placeTokens.get(placeRequest);
            } else {
                token = placeRequest.getName();
                tokenPlaces.put(token, placeRequest);
                placeTokens.put(placeRequest, token);
            }
            return token;
        }
    };
    PlaceManager placeManager = new DefaultPlaceManager(injector.getEventBus(), tokenFormatter) {
    };
    if (!injector.getConfigID().existsConfigID()) {
        injector.getEventBus().fireEvent(new PlaceChangedEvent(Places.SELECT_CONFIG));
    } else {
        if (History.getToken() == null || History.getToken().length() == 0) {
            // Go to the default place
            injector.getEventBus().fireEvent(new PlaceChangedEvent(Places.DEFAULT));
        }
        // Trigger history tokens.
        // ONLY IS VALID IF THE APP HAVE VALID CONFIG ID
        String parameters[] = Window.Location.getQueryString().substring(1).split("&");
        for (String param : parameters) {
            final String[] parts = param.split("=");
            if (parts[0].equals("uri")) {
                //TODO remove timer and use events.
                Timer timer = new Timer() {

                    @Override
                    public void run() {
                        LoadResourceEvent.fire(parts[1], injector.getEventBus());
                    }
                };
                timer.schedule(2000);
            }
        }
    }
    placeManager.fireCurrentPlace();
}
Example 43
Project: opennms_dashboard-master  File: Application.java View source code
/**
   * This is the entry point method.
   */
public void onModuleLoad() {
    m_chartService = new DefaultChartService();
    Image img = new Image();
    img.setUrl("../images/logo.png");
    img.getElement().getStyle().setPaddingTop(14, Unit.PX);
    img.getElement().getStyle().setPaddingLeft(14, Unit.PX);
    FlowPanel header = new FlowPanel();
    header.getElement().setId("header");
    header.add(img);
    final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.PX);
    dockLayoutPanel.addNorth(header, 75.00);
    RootLayoutPanel.get().add(dockLayoutPanel);
    m_nav = new Navigation();
    m_nav.addLocationUpdateEventHandler(this);
    m_nav.addHostUpdateEventHandler(this);
    m_flowPanel = new FlowPanel();
    Runnable timelineCallback = new Runnable() {

        public void run() {
            m_chartService.getAllLocationsAvailability(new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    if (response.getStatusCode() == 200) {
                        m_timeline = new AnnotatedTimeLine(ChartUtils.convertJSONToDataTable(response.getText()), createTimelineOptions(), "440px", "250px");
                        m_flowPanel.add(m_timeline);
                        m_flowPanel.add(m_nav);
                        dockLayoutPanel.add(m_flowPanel);
                    }
                }

                @Override
                public void onError(Request request, Throwable exception) {
                    Window.alert("Error Initializing Chart");
                }
            });
        }
    };
    VisualizationUtils.loadVisualizationApi(timelineCallback, AnnotatedTimeLine.PACKAGE);
    initializeNav();
}
Example 44
Project: ShockVM-master  File: FlozConfigurator.java View source code
/**
	 * This is called by the GWT EntryPoint interface
	 */
@Override
public void onModuleLoad() {
    History.newItem(HistoryTokens.START, false);
    getElement().setAttribute("id", "mainPanel");
    addNorth(new HTML("<div id=\"Header\"> " + "<h1>Live ShockVM</h1>" + "</div>"), 6);
    footerHTML.getElement().getStyle().setMarginTop(3, Unit.EM);
    addSouth(footerHTML, 4);
    RootLayoutPanel.get().add(this);
    showLoginTable();
}
Example 45
Project: shuffle-gtd-master  File: Shuffle.java View source code
/**
     * This method constructs the application user interface by instantiating
     * controls and hooking up event handler.
     */
public void onModuleLoad() {
    // Inject global styles.
    GWT.<GlobalResources>create(GlobalResources.class).css().ensureInjected();
    ShuffleGinjector ginjector = GWT.create(ShuffleGinjector.class);
    Main main = ginjector.getMain();
    // Get rid of scrollbars, and clear out the window's built-in margin,
    // because we want to take advantage of the entire client area.
    Window.enableScrolling(false);
    Window.setMargin("0px");
    RootLayoutPanel.get().add(main);
//        addUploader();
}
Example 46
Project: android-gps-emulator-master  File: GpsEmulator.java View source code
/**
    * Initialize the UI
    */
private void buildUi() {
    // Create textboxes and set default hostname and port
    _hostname = new TextBox();
    _hostname.setText(DEFAULT_HOST);
    _hostname.getElement().setPropertyString("placeholder", "hostname");
    _port = new TextBox();
    _port.setText(String.valueOf(DEFAULT_PORT));
    _port.getElement().setPropertyString("placeholder", "port");
    // Create button to connect
    _button = new Button("Connect");
    // Create the info/status label, initially not visible
    _info = new InlineLabel();
    _info.setVisible(false);
    // register the button action
    _button.addClickHandler(new ClickHandler() {

        public void onClick(final ClickEvent event) {
            final String hostname = _hostname.getText();
            final int port = Integer.valueOf(_port.getText());
            new PortAsyncCallback(hostname, port).execute();
        }
    });
    // Create panel for textbox, button and info label
    final FlowPanel div = new FlowPanel();
    div.setStylePrimaryName("emulator-controls");
    _hostname.setStyleName("emulator-hostname");
    _port.setStyleName("emulator-port");
    _button.setStyleName("emulator-connect");
    _info.setStyleName("emulator-info");
    div.add(_hostname);
    div.add(_port);
    div.add(_button);
    div.add(_info);
    // Create a map centered on Cawker City, KS USA
    final MapOptions opts = MapOptions.newInstance();
    final LatLng cawkerCity = LatLng.newInstance(39.509, -98.434);
    opts.setCenter(cawkerCity);
    opts.setZoom(4);
    _map = new MapWidget(opts);
    // Register map click handler
    _map.addClickHandler(this);
    // add the controls before the map so that the div doesn't cover the map
    RootLayoutPanel.get().add(div);
    RootLayoutPanel.get().add(_map);
}
Example 47
Project: appfuse-master  File: DesktopApplication.java View source code
protected void showShell() {
    final Element loading = Document.get().getElementById("loading");
    loading.getParentElement().removeChild(loading);
    /* And show the user the shell */
    RootLayoutPanel.get().add(shell);
    RootLayoutPanel.get().getElement().setId("rootPanel");
    // remove gwt extra divs and place shell nodes directly into the
    // document body,
    // (and hope for the best about xbrowser compatibility..)
    shell.getElement().setId("shell");
    final Element shellElement = Document.get().getElementById("shell");
    shellElement.removeFromParent();
    Document.get().getElementById("rootPanel").removeFromParent();
    Element shellChildElement = shellElement.getFirstChildElement();
    while (shellChildElement != null) {
        shellChildElement.removeFromParent();
        Document.get().getBody().appendChild(shellChildElement);
        shellChildElement = shellElement.getFirstChildElement();
    }
}
Example 48
Project: che-master  File: Window.java View source code
/**
     * Displays the [email protected] Window} popup. The popup will animate into view.
     *
     * @param selectAndFocusElement
     *         an [email protected] Focusable} to select and focus on when the panel is
     *         shown. If null, no element will be given focus
     */
public void show(@Nullable final Focusable selectAndFocusElement) {
    setBlocked(false);
    if (isShowing) {
        return;
    }
    isShowing = true;
    // Attach the popup to the body.
    final JsElement popup = view.popup.getElement().cast();
    if (popup.getParentElement() == null) {
        // Hide the popup so it can enter its initial state without flickering.
        popup.getStyle().setVisibility("hidden");
        RootLayoutPanel.get().add(view);
    }
    // The popup may have been hidden before this timer executes.
    if (isShowing) {
        popup.getStyle().removeProperty("visibility");
        // Start the animation after the element is attached.
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {

            @Override
            public void execute() {
                // The popup may have been hidden before this timer executes.
                view.setShowing(true);
                if (selectAndFocusElement != null) {
                    selectAndFocusElement.setFocus(true);
                }
            }
        });
    }
}
Example 49
Project: DevTools-master  File: Window.java View source code
/**
     * Displays the [email protected] Window} popup. The popup will animate into view.
     *
     * @param selectAndFocusElement
     *         an [email protected] Focusable} to select and focus on when the panel is
     *         shown. If null, no element will be given focus
     */
public void show(@Nullable final Focusable selectAndFocusElement) {
    setBlocked(false);
    if (isShowing) {
        return;
    }
    isShowing = true;
    // Attach the popup to the body.
    final JsElement popup = view.popup.getElement().cast();
    if (popup.getParentElement() == null) {
        // Hide the popup so it can enter its initial state without flickering.
        popup.getStyle().setVisibility("hidden");
        RootLayoutPanel.get().add(view);
    }
    // The popup may have been hidden before this timer executes.
    if (isShowing) {
        popup.getStyle().removeProperty("visibility");
        // Start the animation after the element is attached.
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {

            @Override
            public void execute() {
                // The popup may have been hidden before this timer executes.
                view.setShowing(true);
                if (selectAndFocusElement != null) {
                    selectAndFocusElement.setFocus(true);
                }
            }
        });
    }
}
Example 50
Project: google-apis-explorer-master  File: ExplorerEntryPoint.java View source code
@Override
public void onModuleLoad() {
    // Make sure that CSS gets applied.
    Resources.INSTANCE.style().ensureInjected();
    EmbeddedResources.INSTANCE.style().ensureInjected();
    // Set up static resources.
    JsonPrettifier.setResources(Resources.INSTANCE);
    // Set the API key and application name to use for calls from the Explorer.
    Config.setApiKey(ExplorerConfig.API_KEY);
    // If the URL specifies a base URL, use it.
    // If it specifies an API key, use it as well. If no key is specified (and
    // the base URL is), then unset the key -- use no API key. We only want to
    // use the specified key when the base URL is also set -- for requests to
    // the default backend (googleapis.com, defined in Config.java) we always
    // want to use the standard API key.
    String baseUrl = Window.Location.getParameter("base");
    String key = Window.Location.getParameter("key");
    if (baseUrl != null) {
        Config.setBaseUrl(baseUrl);
        Config.setApiKey(key == null ? "" : key);
    }
    // If the user supplied a trace parameter, keep track of it and append it to requests.
    String trace = Window.Location.getParameter("trace");
    if (trace != null) {
        Config.setTraceParameter(trace);
    }
    // Create and display the view.
    AnalyticsManager analytics = new AnalyticsManagerImpl();
    ViewAndHistory fullViewAndHistory = createFullView(analytics);
    RootLayoutPanel.get().add(fullViewAndHistory.fullView);
    // Notify analytics that we have loaded the explorer.
    analytics.trackEventWithValue(AnalyticsEvent.LOAD_EXPLORER, "Full");
    // Load the requested URL.
    fullViewAndHistory.historyManager.processUrl(History.getToken());
}
Example 51
Project: GWTP-master  File: RootPresenter.java View source code
@Override
public void setInSlot(Object slot, IsWidget content) {
    assert slot == rootSlot : "Unknown slot used in the root proxy.";
    if (usingRootLayoutPanel) {
        // TODO Next 3 lines are a dirty workaround for
        // http://code.google.com/p/google-web-toolkit/issues/detail?id=4737
        getAppRootPanel().clear();
        RootLayoutPanel.get().clear();
        getAppRootPanel().add(RootLayoutPanel.get());
        if (content != null) {
            RootLayoutPanel.get().add(content);
        }
    } else {
        // TODO Next 2 lines are a dirty workaround for
        // http://code.google.com/p/google-web-toolkit/issues/detail?id=4737
        RootLayoutPanel.get().clear();
        getAppRootPanel().clear();
        if (content != null) {
            getAppRootPanel().add(content);
        }
    }
}
Example 52
Project: html5gwt-master  File: HTML5Test.java View source code
@Override
public void onModuleLoad() {
    dropPanel = new DropVerticalPanelBase();
    dropPanel.setSize("100%", "100%");
    dropPanel.setBorderWidth(0);
    dropPanel.setStylePrimaryName("border");
    RootLayoutPanel.get().add(dropPanel);
    dropPanel.addDragOverHandler(new DragOverHandler() {

        @Override
        public void onDragOver(DragOverEvent event) {
            event.preventDefault();
            //GWT.log("drag over");
            dropPanel.setBorderWidth(4);
        }
    });
    dropPanel.addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            event.preventDefault();
        //GWT.log("drag over");
        }
    });
    dropPanel.addDragLeaveHandler(new DragLeaveHandler() {

        @Override
        public void onDragLeave(DragLeaveEvent event) {
            event.preventDefault();
            doneDrop();
        //GWT.log("drag leave");
        }
    });
    TabPanel tab = new TabPanel();
    dropPanel.add(tab);
    VerticalPanel root = new VerticalPanel();
    tab.add(root, "File upload");
    root.add(new Label("Text file upload Test,drop a text file at textarea  and show text"));
    firstTextArea = new TextArea();
    firstTextArea.setSize("400px", "200px");
    firstTextArea.addDragOverHandler(new DragOverHandler() {

        @Override
        public void onDragOver(DragOverEvent event) {
            event.preventDefault();
        }
    });
    FileUploadForm fileUpload = FileUtils.createSingleTextFileUploadForm(new DataURLListener() {

        @Override
        public void uploaded(File file, String text) {
            firstTextArea.setText(text);
        }
    }, false);
    root.add(fileUpload);
    firstTextArea.addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            onDropText(event);
        }
    });
    root.add(firstTextArea);
    root.add(new Label("Chrome folder support test,drop folder at textarea and show file list"));
    final TextArea area2 = new TextArea();
    FileUploadForm multiUpload = FileUtils.createMultiFileUploadForm(new DataURLsListener() {

        @Override
        public void uploaded(List<File> files, List<String> values) {
            for (File file : files) {
                String name = file != null ? file.getFileName() : "";
                String size = file != null ? "" + file.getFileSize() : "";
                String newText = "" + "/" + name + "," + size;
                String old = area2.getText();
                area2.setText(old + newText + "\n");
            }
        }
    }, false);
    root.add(multiUpload);
    multiUpload.setTitle("can select multifile,but only same directory");
    area2.setSize("400px", "200px");
    area2.addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            event.preventDefault();
            final FilePathCallback callback = new FilePathCallback() {

                @Override
                public void callback(File file, String path) {
                    log(file);
                    String name = file != null ? file.getFileName() : "";
                    String size = file != null ? "" + file.getFileSize() : "";
                    String newText = path + "/" + name + "," + size;
                    String old = area2.getText();
                    area2.setText(old + newText + "\n");
                }
            };
            final JsArray<Item> items = FileUtils.transferToItem(event.getNativeEvent());
            GWT.log("length:" + items.length());
            if (items.length() > 0) {
                for (int i = 0; i < items.length(); i++) {
                    log(items.get(i).webkitGetAsEntry());
                    FileEntry entry = items.get(i).webkitGetAsEntry();
                    entryCallback(entry, callback, "");
                }
            }
            doneDrop();
        }
    });
    root.add(area2);
    DropVerticalPanelBase dropBase = new DropVerticalPanelBase();
    //need some content
    dropBase.add(new Label("Drop VerticalPanel Test,drop a file below and alert file name"));
    dropBase.addDropHandler(new DropHandler() {

        @Override
        public void onDrop(DropEvent event) {
            final JsArray<File> files = FileUtils.transferToFile(event.getNativeEvent());
            GWT.log("length:" + files.length());
            Window.alert("" + files.get(0).getFileName());
            event.preventDefault();
            doneDrop();
        }
    });
    root.add(dropBase);
    //need this after chrome 27?
    dropBase.addDragOverHandler(new DragOverHandler() {

        @Override
        public void onDragOver(DragOverEvent event) {
        }
    });
    dropBase.setSize("400px", "200px");
    /*
		dropBase.add(new Button("test"));
		dropBase.add(new TextArea());
		Canvas c=Canvas.createIfSupported();
		dropBase.add(c);
		*/
    tab.add(new InputRangeTest(), "Input Range");
    tab.add(new FileWriteTest(), "File Download");
    tab.add(new FileSystemTest(), "File System");
    tab.add(new SpeechTest(), "Speech Synth");
    tab.add(new RecognizeTest(), "Speech Recognize");
    tab.add(new MediaTest(), "Media");
    int index = 0;
    String token = History.getToken();
    List<String> labels = Lists.newArrayList("upload", "range", "download", "filesystem", "synth", "recognize", "media");
    for (int i = 0; i < labels.size(); i++) {
        if (labels.get(i).equals(token)) {
            index = i;
            break;
        }
    }
    tab.selectTab(index);
    dropPanel.add(new Anchor("Github Project Page", "https://github.com/akjava/html5gwt"));
}
Example 53
Project: ide-master  File: BootstrapController.java View source code
/** Displays the IDE */
private void displayIDE() {
    // Start UI
    SimpleLayoutPanel mainPanel = new SimpleLayoutPanel();
    RootLayoutPanel.get().add(mainPanel);
    // Make sure the root panel creates its own stacking context
    RootLayoutPanel.get().getElement().getStyle().setZIndex(0);
    WorkspacePresenter workspacePresenter = workspaceProvider.get();
    // Display 'Update extension' button if IDE is launched in SDK runner
    workspacePresenter.setUpdateButtonVisibility(Config.getStartupParam("h") != null && Config.getStartupParam("p") != null);
    // Display IDE
    workspacePresenter.go(mainPanel);
    Document.get().setTitle(coreLocalizationConstant.codenvyTabTitle());
    processStartupParameters();
    final AnalyticsSessions analyticsSessions = new AnalyticsSessions();
    // Bind browser's window events
    Window.addWindowClosingHandler(new Window.ClosingHandler() {

        @Override
        public void onWindowClosing(Window.ClosingEvent event) {
            onWindowClose(analyticsSessions);
            eventBus.fireEvent(WindowActionEvent.createWindowClosingEvent(event));
        }
    });
    Window.addCloseHandler(new CloseHandler<Window>() {

        @Override
        public void onClose(CloseEvent<Window> event) {
            onWindowClose(analyticsSessions);
            eventBus.fireEvent(WindowActionEvent.createWindowClosedEvent());
        }
    });
    elemental.html.Window window = Browser.getWindow();
    window.addEventListener(Event.FOCUS, new EventListener() {

        @Override
        public void handleEvent(Event evt) {
            onSessionUsage(analyticsSessions, false);
        }
    }, true);
    window.addEventListener(Event.BLUR, new EventListener() {

        @Override
        public void handleEvent(Event evt) {
            onSessionUsage(analyticsSessions, false);
        }
    }, true);
    // This is necessary to forcibly print the very first event
    onSessionUsage(analyticsSessions, true);
}
Example 54
Project: java_learn-master  File: Za.java View source code
/**
	 * This is the entry point method.
	 */
public void onModuleLoad() {
    DockLayoutPanel appPanel = new DockLayoutPanel(Unit.PX);
    RootLayoutPanel.get().add(appPanel);
    SplitLayoutPanel p = new SplitLayoutPanel();
    HTML navHtml = new HTML("navigation");
    p.addWest(navHtml, 128);
    HTML listHtml = new HTML("list(this is a list component)");
    p.addNorth(listHtml, 200);
    //HTML detailsHtml=new HTML("details");
    VerticalPanel detailsPanel = new VerticalPanel();
    detailsPanel.setSpacing(5);
    p.add(detailsPanel);
    appPanel.add(p);
    final Button sendButton = new Button("Send");
    final TextBox nameField = new TextBox();
    nameField.setText("GWT User");
    final Label errorLabel = new Label();
    // We can add style names to widgets
    sendButton.addStyleName("sendButton");
    // Add the nameField and sendButton to the RootPanel
    // Use RootPanel.get() to get the entire body element
    detailsPanel.add(nameField);
    detailsPanel.add(sendButton);
    detailsPanel.add(errorLabel);
    // Focus the cursor on the name field when the app loads
    nameField.setFocus(true);
    nameField.selectAll();
    // Create the popup dialog box
    final DialogBox dialogBox = new DialogBox();
    dialogBox.setText("Remote Procedure Call");
    dialogBox.setAnimationEnabled(true);
    final Button closeButton = new Button("Close");
    // We can set the id of a widget by accessing its Element
    closeButton.getElement().setId("closeButton");
    final Label textToServerLabel = new Label();
    final HTML serverResponseLabel = new HTML();
    VerticalPanel dialogVPanel = new VerticalPanel();
    dialogVPanel.addStyleName("dialogVPanel");
    dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
    dialogVPanel.add(textToServerLabel);
    dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
    dialogVPanel.add(serverResponseLabel);
    dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
    dialogVPanel.add(closeButton);
    dialogBox.setWidget(dialogVPanel);
    // Add a handler to close the DialogBox
    closeButton.addClickHandler(new ClickHandler() {

        public void onClick(ClickEvent event) {
            dialogBox.hide();
            sendButton.setEnabled(true);
            sendButton.setFocus(true);
        }
    });
    // Create a handler for the sendButton and nameField
    class MyHandler implements ClickHandler, KeyUpHandler {

        /**
			 * Fired when the user clicks on the sendButton.
			 */
        public void onClick(ClickEvent event) {
            sendNameToServer();
        }

        /**
			 * Fired when the user types in the nameField.
			 */
        public void onKeyUp(KeyUpEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                sendNameToServer();
            }
        }

        /**
			 * Send the name from the nameField to the server and wait for a response.
			 */
        private void sendNameToServer() {
            // First, we validate the input.
            errorLabel.setText("");
            String textToServer = nameField.getText();
            if (!FieldVerifier.isValidName(textToServer)) {
                errorLabel.setText("Please enter at least four characters");
                return;
            }
            // Then, we send the input to the server.
            sendButton.setEnabled(false);
            textToServerLabel.setText(textToServer);
            serverResponseLabel.setText("");
            greetingService.greetServer(textToServer, new AsyncCallback<String>() {

                public void onFailure(Throwable caught) {
                    // Show the RPC error message to the user
                    dialogBox.setText("Remote Procedure Call - Failure");
                    serverResponseLabel.addStyleName("serverResponseLabelError");
                    serverResponseLabel.setHTML(SERVER_ERROR);
                    dialogBox.center();
                    closeButton.setFocus(true);
                }

                public void onSuccess(String result) {
                    dialogBox.setText("Remote Procedure Call");
                    serverResponseLabel.removeStyleName("serverResponseLabelError");
                    serverResponseLabel.setHTML(result);
                    dialogBox.center();
                    closeButton.setFocus(true);
                }
            });
        }
    }
    // Add a handler to send the name to the server
    MyHandler handler = new MyHandler();
    sendButton.addClickHandler(handler);
    nameField.addKeyUpHandler(handler);
}
Example 55
Project: JMailJetable-master  File: Mail.java View source code
public void displayWebMail(String mail) {
    // Inject global styles.
    GWT.<GlobalResources>create(GlobalResources.class).css().ensureInjected();
    // Create the UI defined in Mail.ui.xml.
    DockLayoutPanel outer = binder.createAndBindUi(this);
    setMail(mail);
    // Get rid of scrollbars, and clear out the window's built-in margin,
    // because we want to take advantage of the entire client area.
    Window.enableScrolling(false);
    Window.setMargin("0px");
    // Special-case stuff to make topPanel overhang a bit.
    Element topElem = outer.getWidgetContainerElement(topPanel);
    topElem.getStyle().setZIndex(2);
    topElem.getStyle().setOverflow(Overflow.VISIBLE);
    // Listen for item selection, displaying the currently-selected item in
    // the detail area.
    mailList.setListener(new MailList.Listener() {

        public void onItemSelected(MailItem item) {
            mailDetail.setItem(item);
        }
    });
    // Add the outer panel to the RootLayoutPanel, so that it will be
    // displayed.
    RootLayoutPanel root = RootLayoutPanel.get();
    //remove everything before
    root.clear();
    root.add(outer);
    reloadMails();
}
Example 56
Project: kaa-master  File: Login.java View source code
@Override
public void onSuccess(Void result) {
    EnterKeyDownHandler loginHandler = new EnterKeyDownHandler();
    view.getLoginButton().addClickHandler(loginHandler);
    view.getUsernameBox().addKeyDownHandler(loginHandler);
    view.getPasswordBox().addKeyDownHandler(loginHandler);
    ForgotPasswordHandler forgotPasswordHandler = new ForgotPasswordHandler();
    view.getForgotPasswordLabel().addClickHandler(forgotPasswordHandler);
    view.clearMessages();
    RootLayoutPanel.get().clear();
    RootLayoutPanel.get().add(view);
}
Example 57
Project: lib-gwt-svg-samples-master  File: Main.java View source code
@Override
public void onModuleLoad() {
    GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {

        public void onUncaughtException(Throwable throwable) {
            String text = "Uncaught exception: ";
            while (throwable != null) {
                StackTraceElement[] stackTraceElements = throwable.getStackTrace();
                text += throwable.toString() + "\n";
                for (int i = 0; i < stackTraceElements.length; i++) {
                    text += "    at " + stackTraceElements[i] + "\n";
                }
                throwable = throwable.getCause();
                if (throwable != null) {
                    text += "Caused by: ";
                }
            }
            DialogBox dialogBox = new DialogBox(true);
            DOM.setStyleAttribute(dialogBox.getElement(), "backgroundColor", "#ABCDEF");
            System.err.print(text);
            text = text.replaceAll(" ", " ");
            dialogBox.setHTML("<pre>" + text + "</pre>");
            dialogBox.center();
        }
    });
    mainBundle.css().ensureInjected();
    // Generate the source code for the examples
    GWT.create(GeneratorInfo.class);
    SplitLayoutPanel panel = binder.createAndBindUi(this);
    // Populate the sample tree
    TreeItem shapesSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " shapes"));
    shapesSample.setUserObject(new ShapesSample());
    TreeItem eventSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " events"));
    eventSample.setUserObject(new EventSample());
    TreeItem parserSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " parser"));
    parserSample.setUserObject(new ParserSample());
    TreeItem featuresSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " features"));
    featuresSample.setUserObject(new FeaturesSample());
    TreeItem widgetsSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " widgets"));
    widgetsSample.setUserObject(new WidgetsSample());
    TreeItem smilSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " SMIL animation"));
    smilSample.setUserObject(new SmilSample());
    TreeItem xpathSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " XPath"));
    xpathSample.setUserObject(new XPathSample());
    if (DOMHelper.hasFeature(SVGConstants.SVG_FEATURE_DND_EVENTS)) {
        TreeItem dndSample = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " Drag-and-Drop"));
        dndSample.setUserObject(new DndSample());
    }
    TreeItem about = tree.addItem(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(mainBundle.treeItem()).getHTML() + " about"));
    about.setUserObject(new AboutSample());
    tree.addSelectionHandler(new SelectionHandler<TreeItem>() {

        @Override
        public void onSelection(SelectionEvent<TreeItem> event) {
            SampleBase currentSample = (SampleBase) event.getSelectedItem().getUserObject();
            selectSample(currentSample.getPanel());
        }
    });
    tree.setSelectedItem(shapesSample);
    RootLayoutPanel.get().add(panel);
}
Example 58
Project: Mashery-Client-API-Examples-master  File: Examples.java View source code
@Override
public void onModuleLoad() {
    DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.PX);
    RootLayoutPanel.get().add(mainPanel);
    DockLayoutPanel headerPanel = new DockLayoutPanel(Unit.PX);
    mainPanel.addNorth(headerPanel, 80d);
    FlexTable rightPanel = new FlexTable();
    headerPanel.addEast(rightPanel, 250d);
    rightPanel.setCellPadding(4);
    rightPanel.setSize("100%", "100%");
    rightPanel.getCellFormatter().setHeight(0, 0, "100%");
    rightPanel.getCellFormatter().setWidth(1, 0, "100%");
    rightPanel.getCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP);
    ((FlexTable.FlexCellFormatter) rightPanel.getCellFormatter()).setColSpan(0, 0, 2);
    final FlowPanel userPanel = new FlowPanel();
    rightPanel.setWidget(0, 0, userPanel);
    LoginServiceAsync loginSvc = GWT.create(LoginService.class);
    loginSvc.getUserEmail(new AsyncCallback<String>() {

        @Override
        public void onSuccess(final String email) {
            final Anchor loginLink = new Anchor();
            loginLink.setHref(email == null ? "/examples/login" : "/examples/login?logout=true");
            loginLink.addClickHandler(new ClickHandler() {

                @Override
                public void onClick(ClickEvent event) {
                    String callbackURL = Window.Location.createUrlBuilder().buildString();
                    StringBuilder buf = new StringBuilder("/examples/login?callbackURL=");
                    buf.append(URL.encodeQueryString(callbackURL));
                    if (email != null)
                        buf.append("&logout=true");
                    loginLink.setHref(buf.toString());
                }
            });
            if (email == null) {
                loginLink.setHTML("Sign in");
            } else {
                loginLink.setHTML("Sign out");
                userPanel.add(new InlineLabel(email));
                userPanel.add(new InlineHTML(" | "));
            }
            userPanel.add(loginLink);
        }

        @Override
        public void onFailure(Throwable caught) {
            userPanel.add(new Label(caught.getLocalizedMessage()));
        }
    });
    mapWidget = new PopupMapWidget();
    rightPanel.setWidget(1, 1, mapWidget);
    Grid logoPanel = new Grid(1, 2);
    logoPanel.setCellSpacing(8);
    logoPanel.getRowFormatter().setVerticalAlign(0, HasVerticalAlignment.ALIGN_TOP);
    headerPanel.add(logoPanel);
    Image masheryLogoImg = new Image("resources/img/mashery.gif");
    Anchor masheryLink = new Anchor();
    masheryLink.setTitle("Mashery, Inc.");
    masheryLink.setHref("http://developer.mashery.com");
    masheryLink.getElement().appendChild(masheryLogoImg.getElement());
    logoPanel.setWidget(0, 0, masheryLink);
    InlineLabel logoLabel = new InlineLabel("Mashery Examples");
    logoLabel.getElement().getStyle().setFontWeight(FontWeight.BOLD);
    logoLabel.getElement().getStyle().setFontSize(28d, Unit.PT);
    logoLabel.getElement().getStyle().setColor("#c1080a");
    logoPanel.setWidget(0, 1, logoLabel);
    SplitLayoutPanel centerPanel = new SplitLayoutPanel();
    mainPanel.add(centerPanel);
    final StackLayoutPanel examplesPanel = new StackLayoutPanel(Unit.PX);
    centerPanel.addWest(examplesPanel, 200d);
    contentPanel = new DeckPanel();
    centerPanel.add(contentPanel);
    contentPanel.getElement().getStyle().setPaddingLeft(8d, Unit.PX);
    contentPanel.setAnimationEnabled(true);
    addExample(new Example("quova", "Quova") {

        @Override
        public Widget createContent() {
            return new QuovaExample(mapWidget);
        }
    }, examplesPanel);
    addExample(new Example("etsy", "Etsy") {

        @Override
        public Widget createContent() {
            return new EtsyExample(mapWidget);
        }
    }, examplesPanel);
    addExample(new Example("weatherbug", "WeatherBug") {

        @Override
        public Widget createContent() {
            return new WeatherBugExample(mapWidget);
        }
    }, examplesPanel);
    addExample(new Example("hotwire", "Hotwire") {

        @Override
        public Widget createContent() {
            return new HotwireExample(mapWidget);
        }
    }, examplesPanel);
    addExample(new Example("active", "Active") {

        @Override
        public Widget createContent() {
            return new ActiveExample(mapWidget);
        }
    }, examplesPanel);
    String historyToken = History.getToken();
    Integer index = exampleIndex.get(historyToken);
    if (index == null)
        index = 0;
    examplesPanel.showWidget(index);
    showExample(index);
    examplesPanel.addSelectionHandler(new SelectionHandler<Integer>() {

        @Override
        public void onSelection(SelectionEvent<Integer> event) {
            int index = event.getSelectedItem();
            Example example = examples.get(index);
            if (example != null)
                History.newItem(example.getId());
        }
    });
    History.addValueChangeHandler(new ValueChangeHandler<String>() {

        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
            Integer index = exampleIndex.get(historyToken);
            if (index != null) {
                examplesPanel.showWidget(index);
                showExample(index);
            }
        }
    });
}
Example 59
Project: test-analytics-master  File: TaEntryPoint.java View source code
/**
   * Entry point for the application.
   */
@Override
public void onModuleLoad() {
    projectService = GWT.create(ProjectRpc.class);
    userService = GWT.create(UserRpc.class);
    dataService = GWT.create(DataRpc.class);
    contentPanel = new LayoutPanel();
    RootLayoutPanel.get().add(contentPanel);
    // Handle history changes. (Such as clicking a navigation hyperlink.)
    History.addValueChangeHandler(new ValueChangeHandler<String>() {

        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
            handleUrl(historyToken);
        }
    });
    handleUrl(History.getToken());
}
Example 60
Project: test-analytics-ng-master  File: TaEntryPoint.java View source code
/**
   * Entry point for the application.
   */
@Override
public void onModuleLoad() {
    projectService = GWT.create(ProjectRpc.class);
    userService = GWT.create(UserRpc.class);
    dataService = GWT.create(DataRpc.class);
    contentPanel = new LayoutPanel();
    RootLayoutPanel.get().add(contentPanel);
    // Handle history changes. (Such as clicking a navigation hyperlink.)
    History.addValueChangeHandler(new ValueChangeHandler<String>() {

        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
            handleUrl(historyToken);
        }
    });
    handleUrl(History.getToken());
}
Example 61
Project: phyloviewer-master  File: Phyloviewer.java View source code
/**
	 * This is the entry point method.
	 */
public void onModuleLoad() {
    widget = new TreeWidget(searchService, eventBus);
    CompositeStyle highlightStyle = new CompositeStyle("highlight", Defaults.DEFAULT_STYLE);
    highlightStyle.setNodeStyle(new NodeStyle("#C2C2F5", Double.NaN));
    highlightStyle.setLabelStyle(new LabelStyle(null));
    highlightStyle.setGlyphStyle(new GlyphStyle(null, "#C2C2F5", Double.NaN));
    highlightStyle.setBranchStyle(new BranchStyle("#C2C2F5", Double.NaN));
    RenderPreferences rp = new RenderPreferences();
    rp.setHighlightStyle(highlightStyle);
    widget.setRenderPreferences(rp);
    MenuBar fileMenu = new MenuBar(true);
    fileMenu.addItem("Open...", new Command() {

        @Override
        public void execute() {
            Phyloviewer.this.displayTrees();
        }
    });
    Command openURL = new Command() {

        @Override
        public void execute() {
            Window.open(widget.exportImageURL(), "_blank", "");
        }
    };
    fileMenu.addItem("Get image (opens in a popup window)", openURL);
    MenuBar layoutMenu = new MenuBar(true);
    layoutMenu.addItem("Rectangular", new Command() {

        @Override
        public void execute() {
            widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_CLADOGRAM);
        }
    });
    layoutMenu.addItem("Circular", new Command() {

        @Override
        public void execute() {
            widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_RADIAL);
        }
    });
    MenuBar styleMenu = new MenuBar(true);
    final TextInputPopup styleTextPopup = new TextInputPopup();
    styleTextPopup.addValueChangeHandler(new ValueChangeHandler<String>() {

        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            StyleByLabel styleMap = new StyleByLabel();
            styleMap.put(event.getValue());
            widget.getView().getDocument().setStyleMap(styleMap);
            widget.render();
        }
    });
    styleTextPopup.setModal(true);
    styleMenu.addItem("Style by CSV", new Command() {

        @Override
        public void execute() {
            styleTextPopup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {

                @Override
                public void setPosition(int offsetWidth, int offsetHeight) {
                    int left = (Window.getClientWidth() - offsetWidth) / 3;
                    int top = (Window.getClientHeight() - offsetHeight) / 3;
                    styleTextPopup.setPopupPosition(left, top);
                }
            });
        }
    });
    // Make a search box
    final SuggestBox searchBox = new SuggestBox(searchService);
    // TODO make scrollable?
    searchBox.setLimit(10);
    searchBox.addSelectionHandler(new SelectionHandler<Suggestion>() {

        @Override
        public void onSelection(SelectionEvent<Suggestion> event) {
            Box2D box = ((RemoteNodeSuggestion) event.getSelectedItem()).getResult().layout.boundingBox;
            widget.show(box);
        }
    });
    // create some styling widgets for the context menu
    NodeStyleWidget nodeStyleWidget = new NodeStyleWidget(widget.getView().getDocument());
    BranchStyleWidget branchStyleWidget = new BranchStyleWidget(widget.getView().getDocument());
    GlyphStyleWidget glyphStyleWidget = new GlyphStyleWidget(widget.getView().getDocument());
    LabelStyleWidget labelStyleWidget = new LabelStyleWidget(widget.getView().getDocument());
    // replace their default TextBoxes with ColorBoxes, which jscolor.js will add a color picker to
    nodeStyleWidget.setColorWidget(createColorBox());
    branchStyleWidget.setStrokeColorWidget(createColorBox());
    glyphStyleWidget.setStrokeColorWidget(createColorBox());
    glyphStyleWidget.setFillColorWidget(createColorBox());
    labelStyleWidget.setColorWidget(createColorBox());
    // add the widgets to separate panels on the context menu
    final ContextMenu contextMenuPanel = new ContextMenu(widget);
    contextMenuPanel.add(new NodeTable(), "Node details", 3);
    contextMenuPanel.add(nodeStyleWidget, "Node", 3);
    contextMenuPanel.add(branchStyleWidget, "Branch", 3);
    contextMenuPanel.add(glyphStyleWidget, "Glyph", 3);
    contextMenuPanel.add(labelStyleWidget, "Label", 3);
    HorizontalPanel searchPanel = new HorizontalPanel();
    searchPanel.add(new Label("Search:"));
    searchPanel.add(searchBox);
    // Make the UI.
    MenuBar menu = new MenuBar();
    final DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.EM);
    mainPanel.addNorth(menu, 2);
    mainPanel.addSouth(searchPanel, 2);
    mainPanel.addWest(contextMenuPanel, 0);
    mainPanel.add(widget);
    RootLayoutPanel.get().add(mainPanel);
    MenuBar viewMenu = new MenuBar(true);
    viewMenu.addItem("Layout", layoutMenu);
    viewMenu.addItem("Style", styleMenu);
    contextMenuPanel.setVisible(false);
    viewMenu.addItem("Toggle Context Panel", new Command() {

        @Override
        public void execute() {
            if (contextMenuPanel.isVisible()) {
                contextMenuPanel.setVisible(false);
                mainPanel.setWidgetSize(contextMenuPanel, 0);
                mainPanel.forceLayout();
            } else {
                contextMenuPanel.setVisible(true);
                mainPanel.setWidgetSize(contextMenuPanel, 20);
                mainPanel.forceLayout();
            }
        }
    });
    menu.addItem("File", fileMenu);
    menu.addItem("View", viewMenu);
    // Draw for the first time.
    RootLayoutPanel.get().forceLayout();
    mainPanel.forceLayout();
    widget.setViewType(ViewType.VIEW_TYPE_CLADOGRAM);
    widget.render();
    initColorPicker();
    String treeIdString = Window.Location.getParameter("treeId");
    if (treeIdString != null && !treeIdString.equals("")) {
        int treeId = Integer.parseInt(treeIdString);
        this.loadTree(null, treeId);
    } else {
        // Present the user the dialog to load a tree.
        this.displayTrees();
    }
}
Example 62
Project: TGAReader-master  File: TexturedCube.java View source code
public void onModuleLoad() {
    Canvas canvas = Canvas.createIfSupported();
    canvas.setStyleName("MyCanvas");
    canvas.setCoordinateSpaceWidth(400);
    canvas.setCoordinateSpaceHeight(400);
    RootLayoutPanel.get().add(canvas);
    gl = (WebGLRenderingContext) canvas.getContext("experimental-webgl");
    gl.viewport(0, 0, 400, 400);
    WebGLBuffer vertexBuffer = gl.createBuffer();
    gl.bindBuffer(ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(ARRAY_BUFFER, Float32Array.create(VERTICES), STATIC_DRAW);
    WebGLShader vertexShader = gl.createShader(VERTEX_SHADER);
    gl.shaderSource(vertexShader, VERTEX_SHADER_SOURCE);
    gl.compileShader(vertexShader);
    WebGLShader fragmentShader = gl.createShader(FRAGMENT_SHADER);
    gl.shaderSource(fragmentShader, FRAGMENT_SHADER_SOURCE);
    gl.compileShader(fragmentShader);
    program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    gl.useProgram(program);
    gl.bindBuffer(ARRAY_BUFFER, vertexBuffer);
    WebGLUniformLocation texture = gl.getUniformLocation(program, "texture");
    gl.uniform1i(texture, 0);
    int posAttr = gl.getAttribLocation(program, "position");
    gl.vertexAttribPointer(posAttr, 3, FLOAT, false, 5 * 4, 0);
    gl.enableVertexAttribArray(posAttr);
    int texAttr = gl.getAttribLocation(program, "texcoord");
    gl.vertexAttribPointer(texAttr, 2, FLOAT, false, 5 * 4, 3 * 4);
    gl.enableVertexAttribArray(texAttr);
    for (int i = 0; i < TEXTURE_URLS.length; i++) {
        loadTexture(TEXTURE_URLS[i], i);
    }
}
Example 63
Project: openjpa-master  File: OpenTrader.java View source code
/**
     * Builds up the widgets once the login is complete i.e. the server has supplied
     * the initialization data.
     * 
     */
void init(Trader trader, String uri, List<Stock> stocks) {
    this.trader = trader;
    _serviceURI = uri;
    Window.setTitle(trader.getName());
    int W = Window.getClientWidth();
    //Window.getClientHeight();
    int H = 900;
    int headerHeight = 05 * H / 100;
    int westWidth = 25 * W / 100;
    int westHeight = 80 * H / 100;
    int centerWidth = 60 * W / 100;
    int centerHeight = 80 * H / 100;
    int footerHeight = 02 * H / 100;
    Unit unit = Unit.PX;
    stockPanel = new MarketDataPanel(this, westWidth - 10, 40 * westHeight / 100);
    int N = stocks.size();
    for (int i = 0; i < N; i++) {
        stockPanel.insert(stocks.get(i));
    }
    soldTradePanel = new TradeHistoryPanel(this, Ask.class, westWidth - 10, 20 * westHeight / 100);
    boughtTradePanel = new TradeHistoryPanel(this, Bid.class, westWidth - 10, 20 * westHeight / 100);
    serverPanel = new ServerLogPanel(this, centerWidth, 40 * centerHeight / 100);
    tradePanel = new TradingWindow(this, centerWidth, 40 * centerHeight / 100);
    orderPanel = new TradeOrderWindow(this, centerWidth, 10 * centerHeight / 100);
    FlowPanel west = new FlowPanel();
    west.setSize((westWidth - 10) + "px", westHeight + "px");
    west.add(decorate(stockPanel));
    west.add(new HTML("<p>"));
    west.add(decorate(soldTradePanel));
    west.add(new HTML("<p>"));
    west.add(decorate(boughtTradePanel));
    FlowPanel center = new FlowPanel();
    center.setSize(centerWidth + "px", centerHeight + "px");
    center.add(decorate(orderPanel));
    center.add(new HTML("<p>"));
    center.add(decorate(tradePanel));
    center.add(new HTML("<p>"));
    center.add(decorate(serverPanel));
    DockLayoutPanel main = new DockLayoutPanel(unit);
    main.addNorth(createHeader(), headerHeight);
    main.addSouth(createFooter(), footerHeight);
    main.addWest(west, westWidth);
    main.add(center);
    RootLayoutPanel.get().add(main);
    main.animate(500);
    setUpHelp();
    stockPanel.startStockWatcher();
    tradePanel.startTradableRefresher();
}
Example 64
Project: Subtitle-TTS-Player-for-Chrome-master  File: SubPlayer.java View source code
@Override
public void onModuleLoad() {
    //pre load resource
    ImageResource icon = Binder.INSTANCE.loadanime();
    loadImg = new Image(icon);
    loadImg.setVisible(false);
    loadImg.addLoadHandler(new LoadHandler() {

        @Override
        public void onLoad(LoadEvent event) {
            RootPanel.get().remove(loadImg);
            loadImg.setVisible(true);
        }
    });
    RootPanel.get().add(loadImg);
    preference = new SubPlayerPreference();
    preference.initialize();
    tab = new TabLayoutPanel(2, Unit.EM);
    tab.setHeight("500px");
    VerticalPanel root = new VerticalPanel();
    root.setWidth("100%");
    root.setHeight("100%");
    //root.setHeight("200px");
    DockLayoutPanel doc = new DockLayoutPanel(Unit.PX);
    doc.addSouth(new HTMLPanel("<div align='center'>Subtitle TTS Player by <a href='http://www.akjava.com'>akjava.com</a></div>"), 40);
    doc.add(tab);
    RootLayoutPanel.get().add(doc);
    //RootLayoutPanel.get().add(new Label("hello"));
    tab.add(root, "PLAY");
    noSubtitle = new Label("Subtitle is empty.load from Load tab");
    noSubtitle.setStyleName("nosubtitle");
    root.add(noSubtitle);
    loadPanel = new LoadPanel();
    loadPanel.setWidth("100%");
    loadPanel.setHeight("100%");
    tab.add(loadPanel, "LOAD");
    loadPanel.setText(preference.getSrtText());
    itemPanel = new VerticalPanel();
    itemPanel.setSpacing(8);
    itemPanelScroll = new ScrollPanel(itemPanel);
    itemPanelScroll.setWidth("100%");
    itemPanelScroll.setHeight("350px");
    root.add(itemPanelScroll);
    /*
		for(int i=0;i<5;i++){
			String text=i+" hello world\n";
			for(int j=0;j<i;j++){
				text+="line\n";
			}
		
		HTMLPanel label=new HTMLPanel(text.replace("\n", "<br/>"));
		FocusPanel panel=new FocusPanel(label);
		panel.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				unselectAll();
				setlectWidget((Widget) event.getSource());
			}
		});
		//label.setHeight("100px");
		itemPanel.add(panel);
		
		}*/
    playerWidget = new PlayerWidget(this);
    root.add(playerWidget);
    DisclosurePanel ds = new DisclosurePanel("show subtitle time [start] - [end]");
    timeLabel = new Label();
    ds.add(timeLabel);
    //ds.add(new Label("0:0:0 - 0:0:12"));
    root.add(ds);
    selectWidgetHandler = new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            unselectAll();
            setlectWidget((Widget) event.getSource());
        }
    };
    DisclosurePanel vs = new DisclosurePanel("Voice Settings");
    root.add(vs);
    voiceSettings = new VoiceSettings();
    vs.add(voiceSettings);
    //if empty load mode.
    if (!loadPanel.getText().isEmpty()) {
        loadSrt(preference.getSrtSelectIndex());
    } else {
        tab.selectTab(1);
    }
}
Example 65
Project: swm-mobile-master  File: SimplePopup.java View source code
@Override
public void execute() {
    // clear "bottom:0" and "right:0" properties from element => getOffsetWidth() and getOffsetHeight()
    // calculate correct values
    getElement().getStyle().clearBottom();
    getElement().getStyle().clearRight();
    Position pos = cb.getPosition(getOffsetWidth(), getOffsetHeight());
    double width = pos.getWidth() > 0 ? pos.getWidth() * 100.0 : getOffsetWidth();
    Unit widthUnit = pos.getWidth() > 0 ? Unit.PCT : Unit.PX;
    RootLayoutPanel.get().setWidgetLeftWidth(instance, pos.getLeft(), Unit.PX, width, widthUnit);
    double height = pos.getHeight() > 0 ? pos.getHeight() * 100.0 : getOffsetHeight();
    Unit heightUnit = pos.getHeight() > 0 ? Unit.PCT : Unit.PX;
    RootLayoutPanel.get().setWidgetTopHeight(instance, pos.getTop(), Unit.PX, height, heightUnit);
    onShow();
    displayed = true;
    setVisible(true);
}
Example 66
Project: smartgwt-master  File: MyContacts.java View source code
private void showCustomers() {
    final NavigationBar customersNavBar = new NavigationBar();
    customersNavBar.setTitle("Customers");
    customersNavBar.setLeftButtonTitle("Back");
    customersNavBar.setShowLeftButton(false);
    customersNavBar.setShowRightButton(false);
    final ListGrid customers = new ListGrid();
    customers.setHeight("*");
    customers.setAutoFetchData(true);
    customers.setDataSource(customersDS);
    customers.setAlternateRecordStyles(false);
    customers.setSelectionType(SelectionStyle.SINGLE);
    customers.setShowAllRecords(true);
    customers.setLeaveScrollbarGap(false);
    customers.setFields(new ListGridField(CUSTOMER_NAME_FIELD.getName(), "Name"));
    customersContainer = new VLayout();
    customersContainer.setWidth100();
    customersContainer.setHeight100();
    customersContainer.setMembers(customersNavBar, customers);
    contactsApp = new VLayout();
    contactsApp.setWidth100();
    contactsApp.setHeight100();
    contactsApp.setBackgroundColor("white");
    contactsApp.setMembers(customersContainer);
    customers.addCellClickHandler(new CellClickHandler() {

        @Override
        public void onCellClick(CellClickEvent event) {
            final ListGridRecord record = event.getRecord();
            final RecordList contacts = new RecordList();
            if ("Acme Inc".equals(record.getAttribute(CUSTOMER_NAME_FIELD.getName()))) {
                final Record contact = new Record();
                contact.setAttribute(CUSTOMER_CONTACT_CONTACT_FIELD.getName(), Boolean.FALSE);
                contact.setAttribute(CUSTOMER_CONTACT_FULL_NAME_FIELD.getName(), "Bill Adams");
                contact.setAttribute(CUSTOMER_CONTACT_GIVEN_NAME_FIELD.getName(), "Bill");
                contact.setAttribute(CUSTOMER_CONTACT_FAMILY_NAME_FIELD.getName(), "Adams");
                contact.setAttribute(CUSTOMER_CONTACT_PHONE_FIELD.getName(), "408-344-5609");
                contact.setAttribute(CUSTOMER_CONTACT_STREET_ADDRESS_FIELD.getName(), "1192 Hedding St.");
                contact.setAttribute(CUSTOMER_CONTACT_LOCALITY_FIELD.getName(), "San Jose");
                contact.setAttribute(CUSTOMER_CONTACT_REGION_FIELD.getName(), "CA");
                contact.setAttribute(CUSTOMER_CONTACT_POSTAL_CODE_FIELD.getName(), "95112");
                contact.setAttribute(CUSTOMER_CONTACT_COUNTRY_FIELD.getName(), "U.S.A.");
                final String contactID = names.get(contact.getAttribute(CUSTOMER_CONTACT_FULL_NAME_FIELD.getName()));
                if (contactID != null) {
                    contact.setAttribute(CUSTOMER_CONTACT_CONTACT_ID_FIELD.getName(), contactID);
                    contact.setAttribute(CUSTOMER_CONTACT_CONTACT_FIELD.getName(), Boolean.TRUE);
                }
                contacts.add(contact);
            } else if ("ABC Co".equals(record.getAttribute(CUSTOMER_NAME_FIELD.getName()))) {
                final Record contact = new Record();
                contact.setAttribute(CUSTOMER_CONTACT_CONTACT_FIELD.getName(), Boolean.FALSE);
                contact.setAttribute(CUSTOMER_CONTACT_FULL_NAME_FIELD.getName(), "Abe Larson");
                contact.setAttribute(CUSTOMER_CONTACT_GIVEN_NAME_FIELD.getName(), "Abe");
                contact.setAttribute(CUSTOMER_CONTACT_FAMILY_NAME_FIELD.getName(), "Larson");
                contact.setAttribute(CUSTOMER_CONTACT_PHONE_FIELD.getName(), "408-901-8887");
                contact.setAttribute(CUSTOMER_CONTACT_STREET_ADDRESS_FIELD.getName(), "201 San Antonio St.");
                contact.setAttribute(CUSTOMER_CONTACT_LOCALITY_FIELD.getName(), "San Jose");
                contact.setAttribute(CUSTOMER_CONTACT_REGION_FIELD.getName(), "CA");
                contact.setAttribute(CUSTOMER_CONTACT_POSTAL_CODE_FIELD.getName(), "95112");
                contact.setAttribute(CUSTOMER_CONTACT_COUNTRY_FIELD.getName(), "U.S.A.");
                final String contactID = names.get(contact.getAttribute(CUSTOMER_CONTACT_FULL_NAME_FIELD.getName()));
                if (contactID != null) {
                    contact.setAttribute(CUSTOMER_CONTACT_CONTACT_ID_FIELD.getName(), contactID);
                    contact.setAttribute(CUSTOMER_CONTACT_CONTACT_FIELD.getName(), Boolean.TRUE);
                }
                contacts.add(contact);
            }
            slideTransition(customersContainer, showCustomerContacts(contacts), contactsApp, false);
        }
    });
    RootLayoutPanel.get().add(contactsApp);
}
Example 67
Project: kune-master  File: KuneSandboxEntryPoint.java View source code
public void completeTests() {
    NotifyUser.info("Started");
    final Navbar simpleNavbar = new Navbar();
    final NavbarHeader header = new NavbarHeader();
    final NavbarCollapseButton navbarCollapseButton = new NavbarCollapseButton();
    navbarCollapseButton.setDataTarget("#test");
    header.add(navbarCollapseButton);
    simpleNavbar.add(header);
    final NavbarCollapse navbarCollapse = new NavbarCollapse();
    navbarCollapse.setId("test");
    simpleNavbar.add(navbarCollapse);
    final NavbarNav navbarNav = new NavbarNav();
    final ComplexDropDownMenu<ListDropDown> listDropDown = new ComplexDropDownMenu<ListDropDown>(new ListDropDown());
    listDropDown.setMenuText("Plain menu");
    listDropDown.setIcon(IconType.GEAR);
    navbarCollapse.add(navbarNav);
    navbarNav.add(listDropDown.getWidget());
    final AnchorListItem simpleAnchor = new AnchorListItem("Anchor 1");
    simpleAnchor.setIcon(IconType.TWITTER_SQUARE);
    navbarNav.add(simpleAnchor);
    navbarNav.add(new AnchorListItem("Anchor 2"));
    navbarNav.add(new AnchorListItem("Anchor 3"));
    final AnchorListItem menuitem1 = new AnchorListItem("Anchor menuitem 1");
    menuitem1.setIcon(IconType.RANDOM);
    listDropDown.add(menuitem1);
    final CheckListItem checkitem = new CheckListItem("Check item");
    checkitem.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(final ClickEvent event) {
            checkitem.setChecked(!checkitem.isChecked());
        }
    });
    listDropDown.add(checkitem);
    final RadioListItem radioitem = new RadioListItem("Check item");
    radioitem.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(final ClickEvent event) {
            radioitem.setChecked(!radioitem.isChecked());
        }
    });
    listDropDown.add(radioitem);
    final CheckListItem checkitem2 = new CheckListItem("Check anchor");
    checkitem2.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(final ClickEvent event) {
            checkitem2.setChecked(!checkitem2.isChecked());
        }
    });
    navbarNav.add(checkitem2);
    listDropDown.add(new AnchorListItem("Anchor menuitem 2"));
    final ComplexAnchorListItem menuitem3 = new ComplexAnchorListItem("Anchor menuitem 3");
    menuitem3.setIconUrl("http://lorempixel.com/100/100");
    listDropDown.add(menuitem3);
    final AnchorListItem item1 = new AnchorListItem("Testingggg");
    item1.setIcon(IconType.HEART);
    listDropDown.add(item1);
    for (int i = 1; i < 50; i++) {
        listDropDown.add(new AnchorListItem("Anchor " + i));
    }
    final ComplexAnchorListItem itemSubmenu = new ComplexAnchorListItem("Testing submenu");
    itemSubmenu.setIcon(KuneIcon.FOLDER);
    final DropDownSubmenu submenu = new DropDownSubmenu();
    submenu.add(new AnchorListItem("sub item 1"));
    submenu.add(new AnchorListItem("sub item 2"));
    submenu.add(new AnchorListItem("sub item 3"));
    itemSubmenu.add(submenu);
    listDropDown.add(itemSubmenu);
    final DropDown dropDown = new DropDown();
    final Anchor dropDownAnchor = new Anchor();
    // FIXME This fails:
    // final BasicThumb thumb = testThumbs();
    final Image thumb = new Image("http://lorempixel.com/30/30");
    dropDownAnchor.add(thumb);
    dropDownAnchor.setDataToggle(Toggle.DROPDOWN);
    dropDown.add(dropDownAnchor);
    final DropDownMenu dropDownMenu = new DropDownMenu();
    dropDown.add(dropDownMenu);
    final ComplexAnchorListItem dditem1 = new ComplexAnchorListItem("Test 1");
    final ComplexAnchorListItem dditem2 = new ComplexAnchorListItem("Test 2");
    dditem1.setIcon(KuneIcon.BARTER);
    dditem2.setIconUrl("http://lorempixel.com/101/101");
    dropDownMenu.add(dditem1);
    dropDownMenu.add(dditem2);
    // The same with descriptors
    final Image thumb2 = new Image("http://lorempixel.com/30/30");
    final WidgetMenuDescriptor widgetMenu = new WidgetMenuDescriptor(thumb2);
    new MenuItemDescriptor(widgetMenu, new BaseAction("Menuitem desc in widget 1", "Some tooltip"));
    new MenuItemDescriptor(widgetMenu, new BaseAction("Menuitem desc in widget 2", "Some tooltip"));
    // Now with a button
    final MenuDescriptor classicMenu = new MenuDescriptor("Button classic menu");
    classicMenu.withIcon("http://lorempixel.com/30/30");
    new MenuItemDescriptor(classicMenu, new BaseAction("Menuitem desc in widget 1", "Some tooltip"));
    new MenuItemDescriptor(classicMenu, new BaseAction("Menuitem desc in widget 2", "Some tooltip"));
    final MenuDescriptor classicMenu2 = new MenuDescriptor("Button classic2 menu");
    classicMenu2.withIcon("http://lorempixel.com/30/30");
    new MenuItemDescriptor(classicMenu2, new BaseAction("Menuitem desc in widget 3", "Some tooltip"));
    new MenuItemDescriptor(classicMenu2, new BaseAction("Menuitem desc in widget 4", "Some tooltip"));
    final CustomButton btn = new CustomButton("Text custom button");
    Tooltip.to(btn, "Show the dropdown at 100,100 position (or hide it)");
    btn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(final ClickEvent event) {
            if (listDropDown.isMenuVisible()) {
                listDropDown.hide();
            } else {
                listDropDown.show(100, 100);
            }
        }
    });
    btn.setIcon(KuneIcon.FOLDER);
    // final cc.kune.bootstrap.client.ui.IconLabel iconLabel = new
    // cc.kune.bootstrap.client.ui.IconLabel(
    // "Text");
    // iconLabel.setIcon(new KuneIcon('g'));
    final FlowPanel flow = mainContainer.getFlow();
    flow.insert(btn, 0);
    flow.insert(new HTML("<br>"), 1);
    flow.insert(dropDown, 2);
    flow.insert(new HTML("<br>"), 3);
    final ToolbarDescriptor bottomToolbar = new ToolbarDescriptor();
    bottomToolbar.setPosition(NavbarPosition.FIXED_BOTTOM);
    final ButtonDescriptor btnDesc = new ButtonDescriptor(new TestAction("Button desc"));
    btnDesc.withIcon(KuneIcon.SETTINGS).withToolTip("Show me a tooltip");
    btnDesc.setParent(bottomToolbar);
    final IconLabelDescriptor labelDesc = new IconLabelDescriptor(new TestAction("IconLabel desc"));
    labelDesc.withIcon(KuneIcon.TASKS).withToolTip("Show me a tooltip");
    labelDesc.setParent(bottomToolbar);
    final MenuDescriptor menu = new MenuDescriptor("Menu btn");
    menu.setParent(bottomToolbar);
    final MenuItemDescriptor menuItemDescriptor = new MenuItemDescriptor(menu, new TestAction("Menu item"));
    menuItemDescriptor.withIcon(IconType.MAGIC);
    final SubMenuDescriptor submenuDesc = new SubMenuDescriptor(menu, "Some submenu");
    submenuDesc.withIcon(KuneIcon.BARTER);
    new MenuItemDescriptor(submenuDesc, new TestAction("Submenu item 1")).withIcon(IconType.FACEBOOK);
    new MenuItemDescriptor(submenuDesc, new TestAction("Submenu item 2")).withIcon(IconType.FAST_BACKWARD);
    // TODO Add more tests here
    final FlowActionExtensible sitebar = new FlowActionExtensible();
    sitebar.add(createSitebarActions());
    final FlowActionExtensible bottombar = new FlowActionExtensible();
    bottombar.add(bottomToolbar);
    // RootPanel.get().add(testActionToolbar());
    final FlowActionExtensible mainFlow = new FlowActionExtensible();
    mainFlow.add(widgetMenu, classicMenu, classicMenu2);
    final PaperFab paperFab = new PaperFab();
    paperFab.setIcon("polymer");
    mainContainer.getSitebar().add(sitebar);
    mainContainer.getFooter().add(bottombar);
    mainContainer.getFooter().add(paperFab);
    final PaperButton paperBtn = new PaperButton();
    mainContainer.getFooter().add(paperBtn);
    flow.add(mainFlow);
    flow.insert(simpleNavbar, 0);
    testBarButtons(flow);
    addNotifyUserTests(flow);
    addSimpleActions(flow);
    flow.add(new Text(LoremUtils.LOREM_MULTI + LoremUtils.LOREM_MULTI));
    RootLayoutPanel.get().add(mainContainer);
}
Example 68
Project: ns2gather-master  File: NS2G.java View source code
/**
     * This is the entry point method.
     */
public void onModuleLoad() {
    setupExceptionHandler();
    RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get();
    rootLayoutPanel.add(splitLayoutPanel_main);
    horizontalPanel_header.setSpacing(5);
    splitLayoutPanel_main.addNorth(horizontalPanel_header, 70.0);
    horizontalPanel_header.setSize("100%", "100%");
    horizontalPanel_header.add(gatherStatusLabel);
    horizontalPanel_header.setCellVerticalAlignment(gatherStatusLabel, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel_header.setCellHorizontalAlignment(gatherStatusLabel, HasHorizontalAlignment.ALIGN_CENTER);
    flexTable_cornerControls.setCellPadding(3);
    horizontalPanel_header.add(flexTable_cornerControls);
    horizontalPanel_header.setCellWidth(flexTable_cornerControls, "1px");
    horizontalPanel_header.setCellHorizontalAlignment(flexTable_cornerControls, HasHorizontalAlignment.ALIGN_RIGHT);
    flexTable_cornerControls.setWidget(0, 0, button_rules);
    button_rules.addClickHandler(new Button_rulesClickHandler());
    horizontalPanel_header.setCellWidth(button_rules, "1px");
    horizontalPanel_header.setCellHorizontalAlignment(button_rules, HasHorizontalAlignment.ALIGN_RIGHT);
    button_setNick.addClickHandler(new Button_setNickClickHandler());
    flexTable_cornerControls.setWidget(0, 1, button_setNick);
    button_setNick.setWidth("150px");
    flexTable_cornerControls.setWidget(0, 2, button_logout);
    button_logout.addClickHandler(new Button_logoutClickHandler());
    horizontalPanel_header.setCellWidth(button_logout, "1px");
    horizontalPanel_header.setCellHorizontalAlignment(button_logout, HasHorizontalAlignment.ALIGN_RIGHT);
    flexTable_cornerControls.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);
    html_version.setText("ВерÑ?иÑ?");
    flexTable_cornerControls.setWidget(1, 0, html_version);
    html_version.setWordWrap(false);
    html_version.addStyleName("version");
    flexTable_cornerControls.getFlexCellFormatter().setColSpan(1, 0, 3);
    flexTable_cornerControls.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
    flexTable_cornerControls.getCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT);
    splitLayoutPanel_main.addSouth(dockLayoutPanel_chat, 300.0);
    horizontalPanel.setSpacing(5);
    dockLayoutPanel_chat.addNorth(horizontalPanel, 3.0);
    horizontalPanel.setSize("100%", "100%");
    horizontalPanel.add(volumeControl);
    horizontalPanel.setCellVerticalAlignment(volumeControl, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel.setCellWidth(volumeControl, "1px");
    horizontalPanel_voteButton.setSpacing(5);
    horizontalPanel.add(horizontalPanel_voteButton);
    horizontalPanel.setCellHorizontalAlignment(horizontalPanel_voteButton, HasHorizontalAlignment.ALIGN_CENTER);
    horizontalPanel.setCellVerticalAlignment(horizontalPanel_voteButton, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel_voteButton.add(button_vote);
    horizontalPanel_voteButton.setCellVerticalAlignment(button_vote, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel.setCellVerticalAlignment(button_vote, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel.setCellHorizontalAlignment(button_vote, HasHorizontalAlignment.ALIGN_CENTER);
    horizontalPanel_voteButton.add(label_voted);
    horizontalPanel_voteButton.setCellVerticalAlignment(label_voted, HasVerticalAlignment.ALIGN_MIDDLE);
    button_enterNewGather.setVisible(false);
    button_enterNewGather.addClickHandler(new Button_enterNewGatherClickHandler());
    horizontalPanel.add(button_enterNewGather);
    horizontalPanel.setCellWidth(button_enterNewGather, "300px");
    horizontalPanel.setCellVerticalAlignment(button_enterNewGather, HasVerticalAlignment.ALIGN_MIDDLE);
    horizontalPanel.setCellHorizontalAlignment(button_enterNewGather, HasHorizontalAlignment.ALIGN_RIGHT);
    flexTable.setCellPadding(5);
    dockLayoutPanel_chat.addSouth(flexTable, 3.0);
    flexTable.setSize("100%", "100%");
    label_nick.setWordWrap(false);
    flexTable.setWidget(0, 0, label_nick);
    textBox_chatText.setMaxLength(ClientSettings.CHAT_MAX_LENGTH);
    textBox_chatText.addKeyDownHandler(new TextBox_chatTextKeyDownHandler());
    flexTable.setWidget(0, 1, textBox_chatText);
    flexTable.getCellFormatter().setWidth(0, 1, "100%");
    textBox_chatText.setWidth("100%");
    flexTable.setWidget(0, 2, button_sendChat);
    button_sendChat.addClickHandler(new Button_sendChatClickHandler());
    dockLayoutPanel_chat.add(splitLayoutPanel_chat);
    scrollPanel_systemChat.setStyleName("border-bs");
    splitLayoutPanel_chat.addEast(scrollPanel_systemChat, 400.0);
    scrollPanel_systemChat.setWidget(system_chat);
    system_chat.setSize("100%", "100%");
    splitLayoutPanel_chat.add(scrollPanel_userChat);
    scrollPanel_userChat.setStyleName("border-bs");
    scrollPanel_userChat.setWidget(user_chat);
    user_chat.setSize("100%", "100%");
    splitLayoutPanel_main.add(splitLayoutPanel_data);
    splitLayoutPanel_data.addWest(dataGrid_players, 400.0);
    dataGrid_players.addColumn(column_voteComm);
    dataGrid_players.setColumnWidth(column_voteComm, "50px");
    dataGrid_players.addColumn(textColumn_playerName, "ИмÑ?");
    splitLayoutPanel_data.addEast(dataGrid_servers, 300.0);
    dataGrid_servers.addColumn(column_voteServer);
    dataGrid_servers.setColumnWidth(column_voteServer, "50px");
    dataGrid_servers.addColumn(textColumn_serverName, "Сервер");
    splitLayoutPanel_data.add(dataGrid_maps);
    dataGrid_maps.addColumn(column_voteMap);
    dataGrid_maps.setColumnWidth(column_voteMap, "50px");
    dataGrid_maps.addColumn(textColumn_mapName, "Карта");
    dataProvider_players.addDataDisplay(dataGrid_players);
    dataProvider_maps.addDataDisplay(dataGrid_maps);
    dataProvider_servers.addDataDisplay(dataGrid_servers);
    dataGrid_servers.addColumn(column_playersList);
    dataGrid_servers.setColumnWidth(column_playersList, "70px");
    init();
    ready = true;
}
Example 69
Project: crux-master  File: ViewFactoryCreator.java View source code
/**
	 * Gets the list of classes used by the ViewFactory.
	 *
     * @return
     */
String[] getImports() {
    String[] imports = new String[] { GWT.class.getCanonicalName(), org.cruxframework.crux.core.client.screen.Screen.class.getCanonicalName(), org.cruxframework.crux.core.client.screen.views.View.class.getCanonicalName(), StringUtils.class.getCanonicalName(), Window.class.getCanonicalName(), ViewFactoryUtils.class.getCanonicalName(), ViewFactory.CreateCallback.class.getCanonicalName(), RootPanel.class.getCanonicalName(), RootLayoutPanel.class.getCanonicalName(), Element.class.getCanonicalName(), Node.class.getCanonicalName(), ViewLoadEvent.class.getCanonicalName(), Panel.class.getCanonicalName(), InterfaceConfigException.class.getCanonicalName(), Widget.class.getCanonicalName(), Crux.class.getCanonicalName() };
    return imports;
}
Example 70
Project: viaja-facil-master  File: Colectivos.java View source code
public void onModuleLoad() {
    final RootLayoutPanel rootPanel = RootLayoutPanel.get();
    //		Window.setTitle(CONSTANTS.appTitle());
    dummyPanel = new AbsolutePanel();
    dummyPanel.setStyleName("gwt-StackLayoutPanel");
    dummyPanel.setSize(resultsWidth + "px", "500px");
    rootPanel.add(dummyPanel);
    dummyPanel.getElement().setAttribute("style", "border-bottom: none;");
    final AbsolutePanel contextMenu = new AbsolutePanel();
    contextMenu.setStyleName("contextMenu");
    contextMenu.setVisible(false);
    DOM.setElementAttribute(contextMenu.getElement(), "id", "contextMenuDiv");
    rootPanel.add(contextMenu);
    final Label lblSetFrom = new Label(CONSTANTS.lblSetFrom_text());
    lblSetFrom.setStyleName("contextMenuLabel");
    contextMenu.add(lblSetFrom);
    final Label lblSetTo = new Label(CONSTANTS.lblSetTo_text());
    lblSetTo.setStyleName("contextMenuLabel");
    contextMenu.add(lblSetTo);
    favouritesMenu = new VerticalPanel();
    favouritesMenu.setStyleName("favouritesMenu");
    favouritesMenu.setVisible(false);
    DOM.setElementAttribute(favouritesMenu.getElement(), "id", "favouritesMenuDiv");
    DOM.setStyleAttribute(favouritesMenu.getElement(), "left", "50px");
    rootPanel.add(favouritesMenu);
    currentStreetPanel = new FlowPanel();
    currentStreetPanel.setStyleName("favouritesMenuItem");
    currentStreetLabel = new Label(CONSTANTS.youCanStoreFavourites());
    currentStreetLabel.addStyleName("favouritesMenuLabel");
    currentStreetPanel.add(currentStreetLabel);
    currentStreetLabel.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            favouritesMenu.setVisible(false);
        }
    });
    starAdd = new Image(resources.starOutline());
    starAdd.addStyleName("favouritesMenuStar");
    starAdd.setTitle(CONSTANTS.addFavourite());
    starAdd.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            UserFavouritePositionProxy fpp;
            if (!currentStreetLabel.getText().equalsIgnoreCase(CONSTANTS.youCanStoreFavourites())) {
                if (fromOrToFavs.equalsIgnoreCase("from")) {
                    fpp = new UserFavouritePositionProxy(txtFrom.getText(), fromMarker.getPosition().getLatitude(), fromMarker.getPosition().getLongitude());
                } else if (fromOrToFavs.equalsIgnoreCase("to")) {
                    fpp = new UserFavouritePositionProxy(txtTo.getText(), toMarker.getPosition().getLatitude(), toMarker.getPosition().getLongitude());
                } else {
                    GWT.log("ERROR in add favourite handler - neither from nor to");
                    fpp = null;
                }
                getPointsService.addFavourite(fpp, new AsyncCallback<UserFavouritePositionProxy>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        showMessageBox(CONSTANTS.errorWhileSavingFavourite());
                    }

                    @Override
                    public void onSuccess(UserFavouritePositionProxy result) {
                        starAdd.setResource(resources.starFull());
                        justsafed = true;
                    }
                });
            }
        }
    });
    starAdd.setAltText(CONSTANTS.addFavourite());
    currentStreetPanel.add(starAdd);
    favouritesMenu.add(currentStreetPanel);
    final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.PX);
    rootPanel.add(dockLayoutPanel);
    int northPanelHeight = 100;
    final AbsolutePanel panelNorth = new AbsolutePanel();
    panelNorth.setStyleName("northPanel");
    dockLayoutPanel.addNorth(panelNorth, northPanelHeight);
    final int distanceFromLeft = 20;
    final int distanceFromTop = 15;
    final int buttonSize = 20;
    // defined in stylesheet
    final int switchButtonWidth = 25;
    final int spacer1 = 5;
    // defined in stylesheet
    final int genericHeight = 30;
    // defined in stylesheet + 10 due to border/padding
    final int textPanelWidth = 360;
    Image imgFrom = new Image(resources.MarkerACircle());
    imgFrom.setAltText(CONSTANTS.from());
    panelNorth.add(imgFrom, distanceFromLeft, distanceFromTop + (genericHeight - buttonSize) / 2);
    imgFrom.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            if (fromMarker != null) {
                mapWidget.getMap().panTo(fromMarker.getPosition());
            }
        }
    });
    txtFrom = new TextBox();
    txtFrom.getElement().setId("textbox-from");
    txtFrom.setTitle(CONSTANTS.instr1());
    panelNorth.add(txtFrom, distanceFromLeft + buttonSize + spacer1, distanceFromTop);
    final Button btnLocate = new Button();
    panelNorth.add(btnLocate, distanceFromLeft + buttonSize + spacer1 + textPanelWidth - 50, distanceFromTop + genericHeight / 2 - buttonSize / 2);
    btnLocate.setStyleName("locateButton");
    btnLocate.setTitle(CONSTANTS.loc());
    Image imgShowFavsFrom = new Image(resources.arrowDown());
    imgShowFavsFrom.setAltText(CONSTANTS.showFavourites());
    imgShowFavsFrom.setTitle(CONSTANTS.showFavourites());
    imgShowFavsFrom.setStyleName("expandImage");
    panelNorth.add(imgShowFavsFrom, distanceFromLeft + buttonSize + spacer1 + textPanelWidth - 25, distanceFromTop + genericHeight / 2 - buttonSize / 2);
    imgShowFavsFrom.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            if (!favouritesMenu.isVisible()) {
                fromOrToFavs = "from";
                if (txtFrom.getText() != null && txtFrom.getText().length() > 5) {
                    currentStreetLabel.setText(txtFrom.getText());
                    starAdd.setResource(resources.starOutline());
                }
                DOM.setStyleAttribute(favouritesMenu.getElement(), "top", txtFrom.getAbsoluteTop() + "px");
                DOM.setStyleAttribute(favouritesMenu.getElement(), "left", "45px");
                DOM.setStyleAttribute(favouritesMenu.getElement(), "height", favouritesMenu.getWidgetCount() * 22 + 5 + "px");
                favouritesMenu.setVisible(true);
            } else {
                favouritesMenu.setVisible(false);
                if (justsafed) {
                    getPointsService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {

                        @Override
                        public void onFailure(Throwable caught) {
                            GWT.log("Error in login service (to update favourites)");
                        }

                        @Override
                        public void onSuccess(LoginInfo result) {
                            updateFavourites(result);
                        }
                    });
                }
            }
        }
    });
    Image imgTo = new Image(resources.MarkerBCircle());
    imgTo.setAltText(CONSTANTS.to());
    panelNorth.add(imgTo, distanceFromLeft, distanceFromTop + genericHeight + spacer1 + (genericHeight - buttonSize) / 2);
    imgTo.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            if (toMarker != null) {
                mapWidget.getMap().panTo(toMarker.getPosition());
            }
        }
    });
    txtTo = new TextBox();
    txtTo.getElement().setId("textbox-to");
    txtTo.setTitle(CONSTANTS.instr1());
    panelNorth.add(txtTo, distanceFromLeft + buttonSize + spacer1, distanceFromTop + genericHeight + spacer1);
    Image imgShowFavsTo = new Image(resources.arrowDown());
    imgShowFavsTo.setAltText(CONSTANTS.showFavourites());
    imgShowFavsTo.setTitle(CONSTANTS.showFavourites());
    imgShowFavsTo.setStyleName("expandImage");
    panelNorth.add(imgShowFavsTo, distanceFromLeft + buttonSize + spacer1 + textPanelWidth - 25, distanceFromTop + genericHeight + spacer1 + genericHeight / 2 - buttonSize / 2);
    imgShowFavsTo.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            if (!favouritesMenu.isVisible()) {
                fromOrToFavs = "to";
                if (txtTo.getText() != null && txtTo.getText().length() > 5) {
                    currentStreetLabel.setText(txtTo.getText());
                    starAdd.setResource(resources.starOutline());
                }
                DOM.setStyleAttribute(favouritesMenu.getElement(), "top", txtTo.getAbsoluteTop() + "px");
                DOM.setStyleAttribute(favouritesMenu.getElement(), "left", "45px");
                DOM.setStyleAttribute(favouritesMenu.getElement(), "height", favouritesMenu.getWidgetCount() * 22 + 5 + "px");
                favouritesMenu.setVisible(true);
            } else {
                favouritesMenu.setVisible(false);
                if (justsafed) {
                    getPointsService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {

                        @Override
                        public void onFailure(Throwable caught) {
                            GWT.log("Error in login service (to update favourites)");
                        }

                        @Override
                        public void onSuccess(LoginInfo result) {
                            updateFavourites(result);
                        }
                    });
                }
            }
        }
    });
    Button btnSwitch = new Button();
    btnSwitch.setStyleName("switchButton");
    btnSwitch.setTitle(CONSTANTS.btnSwitch());
    panelNorth.add(btnSwitch, distanceFromLeft + buttonSize + spacer1 + textPanelWidth + spacer1, distanceFromTop + spacer1 + 10);
    btnSearch = new Button(CONSTANTS.search());
    btnSearch.setStyleName("searchButton");
    panelNorth.add(btnSearch, distanceFromLeft + buttonSize + spacer1 + textPanelWidth + spacer1 + switchButtonWidth + spacer1, distanceFromTop + spacer1 + 5);
    Grid gridSelectLines = new Grid(3, 3);
    gridSelectLines.addStyleName("selectLinesGrid");
    panelNorth.add(gridSelectLines, btnSearch.getAbsoluteLeft() + 80, 15);
    Label lblColectivos = new Label(CONSTANTS.colectivos());
    gridSelectLines.setWidget(0, 0, lblColectivos);
    SimpleCheckBox simpleCheckBoxColectivos = new SimpleCheckBox();
    simpleCheckBoxColectivos.setValue(true);
    simpleCheckBoxColectivos.setEnabled(false);
    gridSelectLines.setWidget(0, 1, simpleCheckBoxColectivos);
    Label lblSubte = new Label(CONSTANTS.lblSubte_text());
    gridSelectLines.setWidget(1, 0, lblSubte);
    simpleCheckBoxSubte = new SimpleCheckBox();
    simpleCheckBoxSubte.setValue(true);
    gridSelectLines.setWidget(1, 1, simpleCheckBoxSubte);
    Label lblTrains = new Label(CONSTANTS.lblTrains_text());
    gridSelectLines.setWidget(2, 0, lblTrains);
    simpleCheckBoxTrains = new SimpleCheckBox();
    simpleCheckBoxTrains.setValue(true);
    gridSelectLines.setWidget(2, 1, simpleCheckBoxTrains);
    Image logo = new Image("img/logo-300.png");
    imgTo.setAltText("Viaja Facil Logo");
    panelNorth.add(logo, 625, 20);
    final FlowPanel selectLanguagePanel = new FlowPanel();
    selectLanguagePanel.setStyleName("selectLanguagePanel");
    panelNorth.add(selectLanguagePanel);
    selectLanguagePanel.setSize("20px", "30px");
    class LanguageChangeHandler implements ClickHandler {

        String lang;

        public LanguageChangeHandler(String lang) {
            this.lang = lang;
        }

        public void onClick(ClickEvent event) {
            if (!LocaleInfo.getCurrentLocale().getLocaleName().equalsIgnoreCase(lang)) {
                Date date = new Date();
                long currentTime = date.getTime();
                date.setTime(currentTime + 2592000000L);
                Cookies.setCookie("locale", lang, date);
                Window.Location.reload();
            }
        }
    }
    Image imgEsp = new Image(resources.languageEsp());
    imgEsp.addClickHandler(new LanguageChangeHandler("es"));
    imgEsp.setAltText(CONSTANTS.esp());
    imgEsp.addStyleName(imgEsp.getStylePrimaryName() + "-selectLanguage");
    selectLanguagePanel.add(imgEsp);
    Image imgEng = new Image(resources.languageEng());
    imgEng.addClickHandler(new LanguageChangeHandler("en"));
    imgEng.setAltText(CONSTANTS.eng());
    imgEng.addStyleName(imgEng.getStylePrimaryName() + "-selectLanguage");
    selectLanguagePanel.add(imgEng);
    final FlowPanel flowPanelEast = new FlowPanel();
    dockLayoutPanel.addEast(flowPanelEast, 160);
    //dockLayoutPanel.addEast(flowPanelEast, 0);
    FlowPanel westPanel = new FlowPanel();
    dockLayoutPanel.addWest(westPanel, resultsWidth);
    int southPanelHeight = 50;
    flowPanelSouth = new FlowPanel();
    flowPanelSouth.setStyleName("southPanel");
    dockLayoutPanel.addSouth(flowPanelSouth, southPanelHeight);
    final Grid gridSouth = new Grid(1, 3);
    gridSouth.getCellFormatter().setWidth(0, 0, "33.33%");
    gridSouth.getCellFormatter().setWidth(0, 1, "33.33%");
    gridSouth.getCellFormatter().setWidth(0, 2, "33.33%");
    gridSouth.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT);
    gridSouth.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_CENTER);
    gridSouth.getCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT);
    gridSouth.setBorderWidth(0);
    flowPanelSouth.add(gridSouth);
    gridSouth.setSize("100%", "100%");
    Anchor lnkImpressum = new Anchor(CONSTANTS.lnkImpressum());
    lnkImpressum.setHref("/impressum.html");
    lnkImpressum.setTarget("_blank");
    lnkImpressum.addStyleName("valignmiddle");
    lnkImpressum.addStyleName("bigmarginleft");
    gridSouth.setWidget(0, 0, lnkImpressum);
    Anchor lnkFAQ = new Anchor(CONSTANTS.lnkFAQ());
    lnkFAQ.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
    lnkFAQ.setHref(CONSTANTS.hrefFAQ());
    lnkFAQ.setTarget("_blank");
    lnkFAQ.addStyleName("valignmiddle");
    gridSouth.setWidget(0, 1, lnkFAQ);
    scrollPanel = new ScrollPanel();
    scrollPanel.setSize(resultsWidth + "px", "100%");
    westPanel.add(scrollPanel);
    resultsPanel = new StackLayoutPanel(Unit.PX);
    resultsPanel.setSize(resultsWidth + "px", 300 + "px");
    resultsPanel.setVisible(false);
    //		resultsPanel.addStyleName("zindex10");
    //		DOM.setStyleAttribute(resultsPanel.getElement(), "z-index", "10");
    scrollPanel.add(resultsPanel);
    final MapOptions options = new MapOptions();
    options.setZoom(11);
    options.setCenter(new LatLng(-34.604389, -58.410873));
    options.setMapTypeId(new MapTypeId().getRoadmap());
    options.setDraggable(true);
    options.setMapTypeControl(true);
    options.setNavigationControl(true);
    options.setScrollwheel(true);
    options.setScaleControl(true);
    mapWidget = new MapWidget(options);
    dockLayoutPanel.add(mapWidget);
    Event.addListener(mapWidget.getMap(), "rightclick", new MouseEventCallback() {

        @Override
        public void callback(HasMouseEvent event) {
            //				GWT.log("rightclick: " + event.getLatLng().getLatitude());
            eventLatLng = event.getLatLng();
            double scale = Math.pow(2, mapWidget.getMap().getZoom());
            LatLng nw = new LatLng(mapWidget.getMap().getBounds().getNorthEast().getLatitude(), mapWidget.getMap().getBounds().getSouthWest().getLongitude());
            HasPoint worldCoordinateNW = mapWidget.getMap().getProjection().fromLatLngToPoint(nw);
            HasPoint worldCoordinate = mapWidget.getMap().getProjection().fromLatLngToPoint(event.getLatLng());
            int mapWidth = mapWidget.getOffsetWidth();
            int mapHeight = mapWidget.getOffsetHeight();
            int menuWidth = contextMenu.getOffsetWidth();
            int menuHeight = contextMenu.getOffsetHeight();
            int x = (int) Math.floor((worldCoordinate.getX() - worldCoordinateNW.getX()) * scale);
            int y = (int) Math.floor((worldCoordinate.getY() - worldCoordinateNW.getY()) * scale);
            if ((mapWidth - x) < menuWidth) {
                x = x - menuWidth;
            }
            if ((mapHeight - y) < menuHeight) {
                y = y - menuHeight;
            }
            x += mapWidget.getAbsoluteLeft();
            y += mapWidget.getAbsoluteTop();
            //			    GWT.log("should display context menu at " + x + ", " + y);
            DOM.setStyleAttribute(contextMenu.getElement(), "left", x + "px");
            DOM.setStyleAttribute(contextMenu.getElement(), "top", y + "px");
            contextMenu.setVisible(true);
        }
    });
    Event.addListener(mapWidget.getMap(), "click", new MouseEventCallback() {

        @Override
        public void callback(HasMouseEvent event) {
            contextMenu.setVisible(false);
        }
    });
    class MyGeocoderCallback extends GeocoderCallback {

        private String fromOrTo;

        private boolean doSearch;

        public MyGeocoderCallback(String fromOrTo, boolean doSearch) {
            super();
            this.fromOrTo = fromOrTo;
            this.doSearch = doSearch;
        }

        @Override
        public void callback(List<HasGeocoderResult> responses, String status) {
            //				GWT.log("geocoder: " + status);
            if (status.equalsIgnoreCase("OK")) {
                HasGeocoderResult resp = responses.get(0);
                if (fromOrTo.equalsIgnoreCase("from")) {
                    fromCoordDirty = false;
                    if (fromMarker == null) {
                        createMarker(resp.getGeometry().getLocation(), "from");
                    } else {
                        fromMarker.setPosition(resp.getGeometry().getLocation());
                    }
                    currentStreetLabel.setText(txtFrom.getText());
                } else if (fromOrTo.equalsIgnoreCase("to")) {
                    toCoordDirty = false;
                    if (toMarker == null) {
                        createMarker(resp.getGeometry().getLocation(), "to");
                    } else {
                        toMarker.setPosition(resp.getGeometry().getLocation());
                    }
                    currentStreetLabel.setText(txtTo.getText());
                } else {
                    GWT.log("Error: neither from nor to in MyGeocoderCallback.");
                }
                currentStreetLabel.getElement().setPropertyDouble("x_coord", resp.getGeometry().getLocation().getLatitude());
                currentStreetLabel.getElement().setPropertyDouble("y_coord", resp.getGeometry().getLocation().getLongitude());
                if (doSearch && !ranSearch && !fromCoordDirty && !toCoordDirty) {
                    ranSearch = true;
                    doSearch();
                } else if (!doSearch) {
                    if (fromOrTo.equalsIgnoreCase("from")) {
                        mapWidget.getMap().setCenter(fromMarker.getPosition());
                    }
                    if (fromOrTo.equalsIgnoreCase("to")) {
                        mapWidget.getMap().setCenter(toMarker.getPosition());
                    }
                    mapWidget.getMap().setZoom(15);
                }
            } else {
                GWT.log("Geocoder failed with status: " + status);
            }
        }
    }
    class MyPositionCallback implements PositionCallback {

        public void onFailure(PositionError error) {
            GWT.log("locate failed");
        }

        public void onSuccess(Position position) {
            //    			GWT.log("Got location");
            Coordinates coords = position.getCoords();
            double lat = coords.getLatitude();
            double lon = coords.getLongitude();
            /*lat = Double.parseDouble(txtFrom.getText());
    			lon = Double.parseDouble(txtTo.getText()); */
            if (// TODO: remove this block, it is only for debugging
            lat > 0) {
                lat = -34.679523;
                lon = -58.370533;
            }
            mapWidget.getMap().setCenter(new LatLng(lat, lon));
            fromCoordDirty = false;
            if (fromMarker == null) {
                createMarker(new LatLng(lat, lon), "from");
            } else {
                fromMarker.setPosition(new LatLng(lat, lon));
            }
            mapWidget.getMap().setZoom(15);
            GeocoderRequest gcReq = new GeocoderRequest();
            if (!GWT.isScript()) {
                removeGwtObjectId(gcReq.getJso());
            }
            gcReq.setLatLng(fromMarker.getPosition());
            gcReq.setRegion("ar");
            Geocoder gc = new Geocoder();
            gc.geocode(gcReq, new MyInverseGeocoderCallback("from"));
            resetSearch();
        }
    }
    /*
	     * also handles the search button
	     */
    class ToHandler implements ChangeHandler, ClickHandler, KeyPressHandler {

        public void onClick(ClickEvent event) {
            search();
        }

        public void onChange(ChangeEvent event) {
            Timer // delayed call so that it is not called if autocomplete was used
            t = new Timer() {

                public void run() {
                    if (typedTo) {
                        textUpdated();
                    }
                }
            };
            t.schedule(150);
        }

        @Override
        public void onKeyPress(KeyPressEvent event) {
            if (event.getCharCode() == KeyCodes.KEY_ENTER) {
                textUpdated();
            } else {
                typedTo = true;
            }
        }

        private void textUpdated() {
            toCoordDirty = true;
            GeocoderRequest gcReq = new GeocoderRequest();
            if (!GWT.isScript()) {
                removeGwtObjectId(gcReq.getJso());
            }
            gcReq.setRegion("ar");
            gcReq.setBounds(mapWidget.getMap().getBounds());
            gcReq.setAddress(txtTo.getText());
            Geocoder gc = new Geocoder();
            gc.geocode(gcReq, new MyGeocoderCallback("to", false));
            resetSearch();
        }

        private void search() {
            ranSearch = false;
            if (fromCoordDirty) {
                GeocoderRequest gcReq1 = new GeocoderRequest();
                if (!GWT.isScript()) {
                    removeGwtObjectId(gcReq1.getJso());
                }
                gcReq1.setRegion("ar");
                gcReq1.setBounds(mapWidget.getMap().getBounds());
                gcReq1.setAddress(txtFrom.getText());
                Geocoder gc1 = new Geocoder();
                gc1.geocode(gcReq1, new MyGeocoderCallback("from", true));
            }
            if (toCoordDirty) {
                GeocoderRequest gcReq2 = new GeocoderRequest();
                if (!GWT.isScript()) {
                    removeGwtObjectId(gcReq2.getJso());
                }
                gcReq2.setRegion("ar");
                gcReq2.setBounds(mapWidget.getMap().getBounds());
                gcReq2.setAddress(txtTo.getText());
                Geocoder gc2 = new Geocoder();
                gc2.geocode(gcReq2, new MyGeocoderCallback("to", true));
            }
            if (!ranSearch && !fromCoordDirty && !toCoordDirty) {
                ranSearch = true;
                doSearch();
            }
        }
    }
    class ContextMenuHandler implements ClickHandler {

        @Override
        public void onClick(ClickEvent event) {
            contextMenu.setVisible(false);
            if (event.getSource() == lblSetFrom) {
                if (fromMarker == null) {
                    createMarker(eventLatLng, "from");
                } else {
                    fromMarker.setPosition(eventLatLng);
                }
                fromCoordDirty = false;
                GeocoderRequest gcReq = new GeocoderRequest();
                if (!GWT.isScript()) {
                    removeGwtObjectId(gcReq.getJso());
                }
                gcReq.setLatLng(fromMarker.getPosition());
                gcReq.setRegion("ar");
                Geocoder gc = new Geocoder();
                gc.geocode(gcReq, new MyInverseGeocoderCallback("from"));
            } else if (event.getSource() == lblSetTo) {
                if (toMarker == null) {
                    createMarker(eventLatLng, "to");
                } else {
                    toMarker.setPosition(eventLatLng);
                }
                toCoordDirty = false;
                GeocoderRequest gcReq = new GeocoderRequest();
                if (!GWT.isScript()) {
                    removeGwtObjectId(gcReq.getJso());
                }
                gcReq.setLatLng(toMarker.getPosition());
                gcReq.setRegion("ar");
                Geocoder gc = new Geocoder();
                gc.geocode(gcReq, new MyInverseGeocoderCallback("to"));
            } else {
                GWT.log("Error: Got event for contextMenu but it did not match any of its labels.");
            }
            resetSearch();
        }
    }
    class FromHandler implements ChangeHandler, KeyPressHandler {

        @Override
        public void onKeyPress(KeyPressEvent event) {
            if (event.getCharCode() == KeyCodes.KEY_ENTER) {
                textUpdated();
            } else {
                typedFrom = true;
            }
        }

        public void onChange(ChangeEvent event) {
            Timer // delayed call so that it is not called if autocomplete was used
            t = new Timer() {

                public void run() {
                    if (typedFrom) {
                        textUpdated();
                    }
                }
            };
            t.schedule(150);
        }

        private void textUpdated() {
            fromCoordDirty = true;
            GeocoderRequest gcReq = new GeocoderRequest();
            if (!GWT.isScript()) {
                removeGwtObjectId(gcReq.getJso());
            }
            gcReq.setRegion("ar");
            gcReq.setBounds(mapWidget.getMap().getBounds());
            gcReq.setAddress(txtFrom.getText());
            Geocoder gc = new Geocoder();
            gc.geocode(gcReq, new MyGeocoderCallback("from", false));
            resetSearch();
        }
    }
    class SwitchHandler implements ClickHandler {

        public void onClick(ClickEvent event) {
            if (toMarker != null && fromMarker != null) {
                String tempStr = txtTo.getText();
                txtTo.setText(txtFrom.getText());
                txtFrom.setText(tempStr);
                boolean tempDirty = toCoordDirty;
                toCoordDirty = fromCoordDirty;
                fromCoordDirty = tempDirty;
                HasLatLng tempLatLng = toMarker.getPosition();
                toMarker.setPosition(fromMarker.getPosition());
                fromMarker.setPosition(tempLatLng);
            }
            resetSearch();
        }
    }
    class LocHandler implements ClickHandler {

        public void onClick(ClickEvent event) {
            if (event.getSource() == btnLocate) {
                if (Geolocation.isSupported()) {
                    Geolocation geo = Geolocation.getGeolocation();
                    PositionOptions pOpts = PositionOptions.create();
                    pOpts.setEnableHighAccuracy(true);
                    geo.getCurrentPosition(new MyPositionCallback(), pOpts);
                }
            }
        }
    }
    ToHandler toHandler = new ToHandler();
    FromHandler fromHandler = new FromHandler();
    LocHandler locHandler = new LocHandler();
    SwitchHandler switchHandler = new SwitchHandler();
    ContextMenuHandler contextMenuHandler = new ContextMenuHandler();
    //		locHandler.locate();
    txtFrom.addChangeHandler(fromHandler);
    txtFrom.addKeyPressHandler(fromHandler);
    btnSearch.addClickHandler(toHandler);
    txtTo.addChangeHandler(toHandler);
    txtTo.addKeyPressHandler(toHandler);
    btnLocate.addClickHandler(locHandler);
    btnSwitch.addClickHandler(switchHandler);
    lblSetFrom.addClickHandler(contextMenuHandler);
    lblSetTo.addClickHandler(contextMenuHandler);
    resultsPanel.addSelectionHandler(new SelectionHandler<Integer>() {

        @Override
        public void onSelection(SelectionEvent<Integer> event) {
            if (resultsPanel.getVisibleIndex() != selectedIndex) {
                selectedIndex = resultsPanel.getVisibleIndex();
                //	                GWT.log("index: " + selectedIndex);
                drawConnection(selectedIndex);
            }
        }
    });
    colors.add("#ff0000");
    colors.add("#0000ff");
    colors.add("#00ff00");
    //		colors.add("#ffff00");
    //		colors.add("#ff9900");
    colors.add("#ff00ff");
    colors.add("#00ffff");
    if (!Window.Navigator.isCookieEnabled()) {
        showMessageBox(CONSTANTS.needsCoockiesEnabled());
    }
    //		if(!(Window.Navigator.getUserAgent().contains("msie") || Window.Navigator.getUserAgent().contains("MSIE"))) {
    try {
        final AutocompletePlace acFrom = new AutocompletePlace("textbox-from");
        if (acFrom != null) {
            Event.addListener(acFrom, "place_changed", new AutocompleteCallback(acFrom, "from"));
        }
        final AutocompletePlace acTo = new AutocompletePlace("textbox-to");
        if (acTo != null) {
            Event.addListener(acTo, "place_changed", new AutocompleteCallback(acTo, "to"));
        }
    } catch (Exception e) {
        GWT.log("Error while adding autocomplete: ", e);
    }
    //		}
    /*
		String jsessionid = Cookies.getCookie("JSESSIONID");
//		GWT.log("Session id: " + jsessionid);
		if(jsessionid == null) {
			getPointsService.sayHello(new AsyncCallback<String>() {

				@Override
				public void onFailure(Throwable caught) {
					GWT.log("Error in sayHello: " + caught);
				}

				@Override
				public void onSuccess(String result) {
					GWT.log("said hello: " + result);
				}
				
			});
		}*/
    FlowPanel spinningCirclePanel = new FlowPanel();
    spinningCirclePanel.setSize("120px", "50px");
    spinningCircle = new DecoratedPopupPanel(false);
    spinningCircle.setWidget(spinningCirclePanel);
    Image spinningImage = new Image("img/spinning.gif");
    spinningImage.setStyleName("spinningImage");
    spinningCirclePanel.add(spinningImage);
    Label searchingLabel = new Label(CONSTANTS.searching() + " ...");
    searchingLabel.setStyleName("searchingLabel");
    spinningCirclePanel.add(searchingLabel);
    //		showSpinningCircle();
    getPointsService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {

        @Override
        public void onFailure(Throwable caught) {
            GWT.log("Error in login service");
        }

        @Override
        public void onSuccess(LoginInfo result) {
            Anchor loginOrOutLink;
            currentLogin = result;
            if (result.isLoggedIn()) {
                loginOrOutLink = new Anchor(CONSTANTS.logout() + " (" + result.getEmailAddress() + ")");
                loginOrOutLink.setHref(result.getLogoutUrl());
            } else {
                loginOrOutLink = new Anchor(CONSTANTS.login());
                loginOrOutLink.setHref(result.getLoginUrl());
                loginOrOutLink.setTitle(CONSTANTS.saveFavs());
            }
            updateFavourites(result);
            loginOrOutLink.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
            loginOrOutLink.addStyleName("valignmiddle");
            loginOrOutLink.addStyleName("bigmarginright");
            gridSouth.setWidget(0, 2, loginOrOutLink);
        }
    });
// new MapsAdvertising(mapWidget.getMap().getJso());
}
Example 71
Project: circuitjs1-master  File: CirSim.java View source code
public void setCanvasSize() {
    int width, height;
    width = (int) RootLayoutPanel.get().getOffsetWidth();
    height = (int) RootLayoutPanel.get().getOffsetHeight();
    height = height - MENUBARHEIGHT;
    width = width - VERTICALPANELWIDTH;
    if (cv != null) {
        cv.setWidth(width + "PX");
        cv.setHeight(height + "PX");
        cv.setCoordinateSpaceWidth(width);
        cv.setCoordinateSpaceHeight(height);
    }
    if (backcv != null) {
        backcv.setWidth(width + "PX");
        backcv.setHeight(height + "PX");
        backcv.setCoordinateSpaceWidth(width);
        backcv.setCoordinateSpaceHeight(height);
    }
    setCircuitArea();
}
Example 72
Project: Kornell-master  File: IpadIos7HeightFix.java View source code
public static void fixHeight() {
    RootLayoutPanel.get().setHeight(getWindowInnerHeight() + "px");
    Window.scrollTo(0, 0);
}
Example 73
Project: LanguageMemoryApp-master  File: LanguageMemory.java View source code
/**
     * This is the entry point method.
     */
@Override
public void onModuleLoad() {
    final RootLayoutPanel widgetTag = RootLayoutPanel.get();
    widgetTag.getElement().setId("widgetTag");
    final AppController appController = new AppController(widgetTag);
    appController.start();
}
Example 74
Project: utilitydss-master  File: UtilityDSS.java View source code
/**
	 * This is the entry point method.
	 */
public void onModuleLoad() {
    RootLayoutPanel.get().add(MainPanel.getInstance());
    MainPanel.getInstance().draw();
}
Example 75
Project: androidrocks-master  File: FCE.java View source code
/**
     * This is the entry point method.
     */
public void onModuleLoad() {
    HandlerManager eventBus = new HandlerManager(null);
    FCEPresenter fCEPresenter = new FCEPresenter(eventBus);
    fCEPresenter.go(RootLayoutPanel.get());
}
Example 76
Project: geomajas-gwt2-quickstart-application-master  File: Application.java View source code
@Override
public void onModuleLoad() {
    ApplicationLayout layout = new ApplicationLayout();
    RootLayoutPanel.get().add(layout);
}
Example 77
Project: gwt-charts-master  File: Showcase.java View source code
/**
	 * This is the entry point method.
	 */
@Override
public void onModuleLoad() {
    Window.enableScrolling(false);
    Window.setMargin("0px");
    Resources.INSTANCE.css().ensureInjected();
    RootLayoutPanel.get().add(getAppMainPanel());
    History.addValueChangeHandler(getAppMainPanel());
    History.fireCurrentHistoryState();
}
Example 78
Project: totoe-master  File: TotoeTester.java View source code
// @formatter:on
@Override
public void onModuleLoad() {
    Resources.INSTANCE.style().ensureInjected();
    Resources.INSTANCE.widgets().ensureInjected();
    RootLayoutPanel.get().add(binder.createAndBindUi(this));
}
Example 79
Project: geomajas-project-client-gwt2-master  File: Example.java View source code
public void onModuleLoad() {
    RootLayoutPanel.get().add(ExampleBase.getLayout());
}
Example 80
Project: guit-master  File: RootLayoutPanelDisplayProvider.java View source code
@Override
public void setWidget(IsWidget w) {
    RootLayoutPanel root = RootLayoutPanel.get();
    root.clear();
    root.add(w);
}
Example 81
Project: onebusaway-application-modules-master  File: StandardApplicationContainer.java View source code
public static void add(Widget widget) {
    RootLayoutPanel panel = RootLayoutPanel.get();
    panel.add(widget);
    panel.setWidgetTopBottom(widget, 43, Unit.PX, 0, Unit.PX);
    StyleInjector.inject(CommonResources.INSTANCE.getApplicationCss().getText());
}
Example 82
Project: PonySDK-master  File: PTRootLayoutPanel.java View source code
@Override
protected RootLayoutPanel createUIObject() {
    return RootLayoutPanel.get();
}
Example 83
Project: soundtransit-rds-master  File: StandardApplicationContainer.java View source code
public static void add(Widget widget) {
    RootLayoutPanel panel = RootLayoutPanel.get();
    panel.add(widget);
    panel.setWidgetTopBottom(widget, 43, Unit.PX, 0, Unit.PX);
    StyleInjector.inject(CommonResources.INSTANCE.getApplicationCss().getText());
}
Example 84
Project: tvguide-sample-parent-master  File: TvGuideApp.java View source code
public void setUser(TvViewerProxy user) {
    // Attach the root view to the page
    RootLayoutPanel.get().add(shell);
    // Go! Fire the current history token
    historyHandler.handleCurrentHistory();
}
Example 85
Project: AT4AMParlamentoElettronicoEdition-master  File: DraftingEditor.java View source code
@Override
protected void initializeUI() {
    draftingController = getInjector().getDraftingController();
    draftingController.registerListeners();
    draftingController.setInjector(getInjector());
    clientFactory.getKeyboardListener().install();
    RootLayoutPanel.get().add(draftingController.getView());
}
Example 86
Project: daxplore-presenter-master  File: AdminEntryPoint.java View source code
/**
	 * This is the entry point method. It is automatically called by GWT to
	 * create the admin web page.
	 */
@Override
public void onModuleLoad() {
    AdminInjector injector = GWT.create(AdminInjector.class);
    AdminController adminController = injector.getAdminController();
    adminController.go(RootLayoutPanel.get());
}
Example 87
Project: nsesa-editor-an-master  File: DraftingEditor.java View source code
@Override
protected void initializeUI() {
    draftingController = getInjector().getDraftingController();
    draftingController.registerListeners();
    draftingController.setInjector(getInjector());
    clientFactory.getKeyboardListener().install();
    RootLayoutPanel.get().add(draftingController.getView());
}
Example 88
Project: sensormix-master  File: SensormixAdminApp.java View source code
/* (non-Javadoc)
   * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
   */
@Override
public void onModuleLoad() {
    final EventBus eventBus = GWT.create(SimpleEventBus.class);
    final GwtSensormixServiceAsync sensormixService = GWT.create(GwtSensormixService.class);
    final SensormixAdminUi ui = new SensormixAdminUi(eventBus, sensormixService);
    RootLayoutPanel.get().add(ui);
}
Example 89
Project: konto-master  File: KontoEntryPoint.java View source code
public void onModuleLoad() {
    RootLayoutPanel.get().add(injector.getMainPresenter().getView());
    if (Window.Location.getParameter("demo") != null)
        enableDemo();
    injector.getPlaceHistoryHandler().handleCurrentHistory();
}
Example 90
Project: uberfire-master  File: Workbench.java View source code
void addLayoutToRootPanel(final WorkbenchLayout layout) {
    RootLayoutPanel.get().add(layout.getRoot());
}

Java Examples for org.apache.maven.artifact.DependencyResolutionRequiredException

The following java examples will help you to understand the usage of org.apache.maven.artifact.DependencyResolutionRequiredException. These source code samples are taken from different open source projects.

Example 1
Project: apt-maven-plugin-master  File: AbstractProcessorMojo.java View source code
@SuppressWarnings("unchecked")
private String buildCompileClasspath() {
    List<String> pathElements = null;
    try {
        if (isForTest()) {
            pathElements = project.getTestClasspathElements();
        } else {
            pathElements = project.getCompileClasspathElements();
        }
    } catch (DependencyResolutionRequiredException e) {
        super.getLog().warn("exception calling getCompileClasspathElements", e);
        return null;
    }
    if (pluginArtifacts != null) {
        for (Artifact a : pluginArtifacts) {
            if (a.getFile() != null) {
                pathElements.add(a.getFile().getAbsolutePath());
            }
        }
    }
    if (pathElements.isEmpty()) {
        return null;
    }
    StringBuilder result = new StringBuilder();
    int i = 0;
    for (i = 0; i < pathElements.size() - 1; ++i) {
        result.append(pathElements.get(i)).append(File.pathSeparatorChar);
    }
    result.append(pathElements.get(i));
    return result.toString();
}
Example 2
Project: ginger-master  File: ClasspathUtils.java View source code
public static List<URL> getResources(MavenProject project, boolean testClasspath) throws MojoExecutionException {
    try {
        Set<String> classpathElements = new HashSet<String>();
        classpathElements.addAll(project.getCompileClasspathElements());
        classpathElements.addAll(project.getRuntimeClasspathElements());
        if (testClasspath) {
            classpathElements.addAll(project.getTestClasspathElements());
        }
        List<URL> projectClasspathList = new ArrayList<URL>();
        for (String element : classpathElements) {
            try {
                projectClasspathList.add(new File(element).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(element + " is an invalid classpath element", e);
            }
        }
        URL[] urls = projectClasspathList.toArray(new URL[projectClasspathList.size()]);
        return Arrays.asList(urls);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Dependency resolution failed", e);
    }
}
Example 3
Project: liquigraph-master  File: ProjectClassLoader.java View source code
public static ClassLoader getClassLoader(MavenProject project) throws DependencyResolutionRequiredException, MalformedURLException {
    List<String> classPathElements = compileClassPathElements(project);
    List<URL> classpathElementUrls = new ArrayList<>(classPathElements.size());
    for (String classPathElement : classPathElements) {
        classpathElementUrls.add(new File(classPathElement).toURI().toURL());
    }
    return new URLClassLoader(classpathElementUrls.toArray(new URL[classpathElementUrls.size()]), Thread.currentThread().getContextClassLoader());
}
Example 4
Project: maven-guvnor-bulk-importer-master  File: ImportFileGeneratorMojo.java View source code
private void addProjectDependenciesToClasspath(MavenProject project) {
    try {
        ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader newClassLoader = new ProjectClasspath().getClassLoader(project, oldClassLoader, getLog());
        Thread.currentThread().setContextClassLoader(newClassLoader);
    } catch (DependencyResolutionRequiredException e) {
        getLog().info("Skipping addition of project artifacts, there appears to be a dependecy resolution problem", e);
    }
}
Example 5
Project: clojureshell-maven-plugin-master  File: AbstractClassloaderMojo.java View source code
private ClassLoader getClassLoader(ClassLoader parent) throws DependencyResolutionRequiredException {
    Scope sc = Scope.valueOf(scope.toUpperCase());
    List<URL> urls = new ArrayList<URL>();
    getLog().debug("Creating class loader...");
    try {
        if (classpath != null) {
            addClasspathElements(Arrays.asList(classpath.split(File.pathSeparator)), urls);
        }
        if (includeStdDirs) {
            addClasspathElement("src/main/clojure", urls);
        }
        addClasspathElements(project.getRuntimeClasspathElements(), urls);
        if (sc == Scope.TEST) {
            if (includeStdDirs) {
                addClasspathElement("src/test/clojure", urls);
            }
            addClasspathElements(project.getTestClasspathElements(), urls);
        }
    } catch (MalformedURLException e) {
        getLog().error(e);
    }
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
}
Example 6
Project: fitnesse-maven-classpath-master  File: MavenClasspathExtractor.java View source code
public List<String> extractClasspathEntries(File pomFile, String scope) throws MavenClasspathExtractionException {
    try {
        MavenRequest mavenRequest = mavenConfiguration();
        mavenRequest.setResolveDependencies(true);
        mavenRequest.setBaseDirectory(pomFile.getParent());
        mavenRequest.setPom(pomFile.getAbsolutePath());
        DependencyResolvingMavenEmbedder dependencyResolvingMavenEmbedder = new DependencyResolvingMavenEmbedder(getClass().getClassLoader(), mavenRequest);
        ProjectBuildingResult projectBuildingResult = dependencyResolvingMavenEmbedder.buildProject(pomFile);
        return getClasspathForScope(projectBuildingResult, scope);
    } catch (MavenEmbedderException mee) {
        throw new MavenClasspathExtractionException(mee);
    } catch (ComponentLookupException cle) {
        throw new MavenClasspathExtractionException(cle);
    } catch (DependencyResolutionRequiredException e) {
        throw new MavenClasspathExtractionException(e);
    } catch (ProjectBuildingException e) {
        throw new MavenClasspathExtractionException(e);
    }
}
Example 7
Project: GMavenPlus-master  File: AbstractGroovyDocMojo.java View source code
/**
     * Generates the GroovyDoc for the specified sources.
     *
     * @param sourceDirectories The source directories to generate GroovyDoc for
     * @param classpath The classpath to use for compilation
     * @param outputDirectory The directory to save the generated GroovyDoc in
     * @throws ClassNotFoundException when a class needed for GroovyDoc generation cannot be found
     * @throws InstantiationException when a class needed for GroovyDoc generation cannot be instantiated
     * @throws IllegalAccessException when a method needed for GroovyDoc generation cannot be accessed
     * @throws InvocationTargetException when a reflection invocation needed for GroovyDoc generation cannot be completed
     * @throws MalformedURLException when a classpath element provides a malformed URL
     */
@SuppressWarnings("unchecked")
protected synchronized void doGroovyDocGeneration(final FileSet[] sourceDirectories, final List classpath, final File outputDirectory) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, MalformedURLException {
    classWrangler = new ClassWrangler(classpath, getLog());
    if (skipGroovyDoc) {
        getLog().info("Skipping generation of GroovyDoc because ${maven.groovydoc.skip} was set to true.");
        return;
    }
    if (sourceDirectories == null || sourceDirectories.length == 0) {
        getLog().info("No source directories specified for GroovyDoc generation.  Skipping.");
        return;
    }
    if (groovyVersionSupportsAction()) {
        classWrangler.logGroovyVersion(mojoExecution.getMojoDescriptor().getGoal());
        logPluginClasspath();
        try {
            getLog().debug("Project compile classpath:\n" + project.getCompileClasspathElements());
        } catch (DependencyResolutionRequiredException e) {
            getLog().warn("Unable to log project compile classpath", e);
        }
    } else {
        getLog().error("Your Groovy version (" + classWrangler.getGroovyVersionString() + ") doesn't support GroovyDoc.  The minimum version of Groovy required is " + minGroovyVersion + ".  Skipping GroovyDoc generation.");
        return;
    }
    if (groovyIs(GROOVY_1_6_0_RC1) || groovyIs(GROOVY_1_5_8)) {
        // Groovy 1.5.8 and 1.6-RC-1 are blacklisted because of their dependency on org.apache.tools.ant.types.Path in GroovyDocTool constructor
        getLog().warn("Groovy " + GROOVY_1_5_8 + " and " + GROOVY_1_6_0_RC1 + " are blacklisted from the supported GroovyDoc versions because of their dependency on Ant.  Skipping GroovyDoc generation.");
        return;
    }
    // get classes we need with reflection
    Class<?> groovyDocToolClass = classWrangler.getClass("org.codehaus.groovy.tools.groovydoc.GroovyDocTool");
    Class<?> outputToolClass = classWrangler.getClass("org.codehaus.groovy.tools.groovydoc.OutputTool");
    Class<?> fileOutputToolClass = classWrangler.getClass("org.codehaus.groovy.tools.groovydoc.FileOutputTool");
    Class<?> resourceManagerClass = classWrangler.getClass("org.codehaus.groovy.tools.groovydoc.ResourceManager");
    Class<?> classpathResourceManagerClass = classWrangler.getClass("org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager");
    // set up GroovyDoc options
    Properties docProperties = setupProperties();
    Object fileOutputTool = invokeConstructor(findConstructor(fileOutputToolClass));
    Object classpathResourceManager = invokeConstructor(findConstructor(classpathResourceManagerClass));
    FileSetManager fileSetManager = new FileSetManager(getLog());
    List<String> sourceDirectoriesStrings = new ArrayList<String>();
    for (FileSet sourceDirectory : sourceDirectories) {
        sourceDirectoriesStrings.add(sourceDirectory.getDirectory());
    }
    GroovyDocTemplateInfo groovyDocTemplateInfo = new GroovyDocTemplateInfo(classWrangler.getGroovyVersion());
    List groovyDocLinks = setupLinks();
    if (groovyOlderThan(GROOVY_1_6_0_RC2)) {
        getLog().warn("Your Groovy version (" + classWrangler.getGroovyVersionString() + ") doesn't support GroovyDoc documentation properties (docTitle, footer, header, displayAuthor, overviewFile, and scope).  You need Groovy 1.6-RC-2 or newer to support this.  Ignoring properties.");
    }
    // prevent Java stubs (which lack Javadoc) from overwriting GroovyDoc by removing Java sources
    List<String> groovyDocSources = setupGroovyDocSources(sourceDirectories, fileSetManager);
    // instantiate GroovyDocTool
    Object groovyDocTool = createGroovyDocTool(groovyDocToolClass, resourceManagerClass, docProperties, classpathResourceManager, sourceDirectoriesStrings, groovyDocTemplateInfo, groovyDocLinks);
    // generate GroovyDoc
    generateGroovyDoc(outputDirectory, groovyDocToolClass, outputToolClass, fileOutputTool, groovyDocSources, groovyDocTool);
    // overwrite stylesheet.css with provided stylesheet (if configured)
    if (stylesheetFile != null) {
        copyStylesheet(outputDirectory);
    }
}
Example 8
Project: Jnario-master  File: XtendTestCompile.java View source code
@SuppressWarnings("deprecation")
protected List<String> getTestClassPath() {
    Set<String> classPath = Sets.newLinkedHashSet();
    classPath.add(project.getBuild().getTestSourceDirectory());
    try {
        classPath.addAll(project.getTestClasspathElements());
    } catch (DependencyResolutionRequiredException e) {
        throw new WrappedException(e);
    }
    addDependencies(classPath, project.getTestArtifacts());
    return newArrayList(filter(classPath, FILE_EXISTS));
}
Example 9
Project: jsonschema2pojo-master  File: Jsonschema2PojoMojo.java View source code
private void addProjectDependenciesToClasspath() {
    try {
        ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader newClassLoader = new ProjectClasspath().getClassLoader(project, oldClassLoader, getLog());
        Thread.currentThread().setContextClassLoader(newClassLoader);
    } catch (DependencyResolutionRequiredException e) {
        getLog().info("Skipping addition of project artifacts, there appears to be a dependecy resolution problem", e);
    }
}
Example 10
Project: maven-openfire-plugin-master  File: OpenfireMojo.java View source code
/**
     * Executes the OpenfireMojo on the current project.
     *
     * @throws MojoExecutionException if an error occured while building the webapp
     */
public void execute() throws MojoExecutionException, MojoFailureException {
    File warFile = getWarFile(new File(outputDirectory), warName, classifier);
    try {
        performPackaging(warFile);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error assembling Openfire Plugin: " + e.getMessage(), e);
    } catch (ManifestException e) {
        throw new MojoExecutionException("Error assembling Openfire Plugin", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error assembling Openfire Plugin", e);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Error assembling Openfire Plugin: " + e.getMessage(), e);
    }
}
Example 11
Project: ocamljava-maven-plugin-master  File: ClassPathGatherer.java View source code
protected Set<String> getClassPathRec(final MavenProject project, final boolean isTest) throws DependencyResolutionRequiredException, MalformedURLException {
    final ImmutableSet.Builder<String> builder = ImmutableSet.<String>builder().addAll(project.getCompileClasspathElements()).addAll(project.getRuntimeClasspathElements()).addAll(project.getSystemClasspathElements());
    if (isTest)
        builder.addAll(project.getTestClasspathElements());
    final List<MavenProject> collectedProjects = project.getCollectedProjects();
    for (final MavenProject mavenProject : collectedProjects) {
        mojo.getLog().info("mavenProject: " + mavenProject.getArtifactId());
        builder.addAll(getClassPathRec(mavenProject, isTest));
    }
    return builder.build();
}
Example 12
Project: Prime-Mover-master  File: TestTransform.java View source code
@Override
protected String getCompileClasspath() throws MojoExecutionException {
    List<?> testClasspathElements;
    try {
        testClasspathElements = project.getTestClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unable to perform test dependency resolution", e);
    }
    getLog().debug(String.format("Runtime classpath elements: %s", testClasspathElements));
    StringBuffer classpath = new StringBuffer();
    classpath.append(getBootClasspath());
    for (Object element : testClasspathElements) {
        classpath.append(':');
        classpath.append(element);
    }
    String pathString = classpath.toString();
    getLog().info(String.format("Test transform classpath: %s", pathString));
    return pathString;
}
Example 13
Project: avro-master  File: IDLProtocolMojo.java View source code
@Override
protected void doCompile(String filename, File sourceDirectory, File outputDirectory) throws IOException {
    try {
        @SuppressWarnings("rawtypes") List runtimeClasspathElements = project.getRuntimeClasspathElements();
        Idl parser;
        List<URL> runtimeUrls = new ArrayList<URL>();
        // Add the source directory of avro files to the classpath so that
        // imports can refer to other idl files as classpath resources
        runtimeUrls.add(sourceDirectory.toURI().toURL());
        // If runtimeClasspathElements is not empty values add its values to Idl path.
        if (runtimeClasspathElements != null && !runtimeClasspathElements.isEmpty()) {
            for (Object runtimeClasspathElement : runtimeClasspathElements) {
                String element = (String) runtimeClasspathElement;
                runtimeUrls.add(new File(element).toURI().toURL());
            }
        }
        URLClassLoader projPathLoader = new URLClassLoader(runtimeUrls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader());
        parser = new Idl(new File(sourceDirectory, filename), projPathLoader);
        Protocol p = parser.CompilationUnit();
        String json = p.toString(true);
        Protocol protocol = Protocol.parse(json);
        SpecificCompiler compiler = new SpecificCompiler(protocol);
        compiler.setStringType(GenericData.StringType.valueOf(stringType));
        compiler.setTemplateDir(templateDirectory);
        compiler.setFieldVisibility(getFieldVisibility());
        compiler.setCreateSetters(createSetters);
        compiler.setEnableDecimalLogicalType(enableDecimalLogicalType);
        compiler.compileToDestination(null, outputDirectory);
    } catch (ParseException e) {
        throw new IOException(e);
    } catch (DependencyResolutionRequiredException drre) {
        throw new IOException(drre);
    }
}
Example 14
Project: codehaus-mojo-master  File: AbstractXmlBeansPlugin.java View source code
/**
     * <p/>
     * Map the parameters to the schema compilers parameter object, make sure the necessary output directories exist,
     * then call on the schema compiler to produce the java objects and supporting resources.
     * </p>
     * 
     * @throws MojoExecutionException Errors occurred during compile.
     * @number MOJO-270
     */
public final void execute() throws MojoExecutionException {
    if (hasSchemas()) {
        try {
            SchemaCompiler.Parameters compilerParams = ParameterAdapter.getCompilerParameters(this);
            boolean stale = isOutputStale();
            if (stale) {
                try {
                    compilerParams.getSrcDir().mkdirs();
                    boolean result = SchemaCompiler.compile(compilerParams);
                    if (!result) {
                        StringBuffer errors = new StringBuffer();
                        for (Iterator iter = compilerParams.getErrorListener().iterator(); iter.hasNext(); ) {
                            Object o = iter.next();
                            errors.append("xml Error").append(o);
                            errors.append("\n");
                        }
                        throw new XmlBeansException(XmlBeansException.COMPILE_ERRORS, errors.toString());
                    }
                    touchStaleFile();
                } catch (IOException ioe) {
                    throw new XmlBeansException(XmlBeansException.STALE_FILE_TOUCH, getStaleFile().getAbsolutePath(), ioe);
                }
            } else if (getLog().isInfoEnabled()) {
                getLog().info("All schema objects are up to date.");
            }
            updateProject(project, compilerParams, stale);
        } catch (DependencyResolutionRequiredException drre) {
            throw new XmlBeansException(XmlBeansException.CLASSPATH_DEPENDENCY, drre);
        }
    } else if (getLog().isInfoEnabled()) {
        getLog().info("Nothing to generate.");
    }
}
Example 15
Project: core-integration-testing-master  File: TestMojo.java View source code
/**
     * Runs this mojo.
     * 
     * @throws MojoExecutionException If the output file could not be created or any dependency could not be resolved.
     */
public void execute() throws MojoExecutionException {
    try {
        writeArtifacts(projectArtifacts, project.getArtifacts());
        writeArtifacts(dependencyArtifacts, project.getDependencyArtifacts());
        writeArtifacts(testArtifacts, project.getTestArtifacts());
        writeClassPath(testClassPath, project.getTestClasspathElements());
        writeClassPathChecksums(testClassPathChecksums, project.getTestClasspathElements());
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Failed to resolve dependencies", e);
    }
}
Example 16
Project: coroutines-master  File: TestInstrumentMojo.java View source code
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();
    File testOutputFolder = new File(getProject().getBuild().getTestOutputDirectory());
    if (!testOutputFolder.isDirectory()) {
        log.warn("Test folder doesn't exist -- nothing to instrument");
        return;
    }
    List<String> classpath;
    try {
        classpath = getProject().getTestClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }
    log.info("Processing test output folder ... ");
    instrumentPath(log, classpath, testOutputFolder);
}
Example 17
Project: evosuite-master  File: GenerateMojo.java View source code
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Going to generate tests with EvoSuite");
    getLog().info("Total memory: " + memoryInMB + "mb");
    getLog().info("Time per class: " + timeInMinutesPerClass + " minutes");
    getLog().info("Number of used cores: " + numberOfCores);
    if (cuts != null) {
        getLog().info("Specified classes under test: " + cuts);
    }
    String target = null;
    String cp = null;
    try {
        //the targets we want to generate tests for, ie the CUTs
        for (String element : project.getCompileClasspathElements()) {
            if (// we only target what has been compiled to a folder
            element.endsWith(".jar")) {
                continue;
            }
            File file = new File(element);
            if (!file.exists()) {
                /*
					 * don't add to target an element that does not exist
					 */
                continue;
            }
            if (!file.getAbsolutePath().startsWith(project.getBasedir().getAbsolutePath())) {
                /*
						This can happen in multi-module projects when module A has dependency on
						module B. Then, both A and B source folders will end up on compile classpath,
						although we are interested only in A
					 */
                continue;
            }
            if (target == null) {
                target = element;
            } else {
                target = target + File.pathSeparator + element;
            }
        }
        //build the classpath
        Set<String> alreadyAdded = new HashSet<>();
        for (String element : project.getTestClasspathElements()) {
            if (element.toLowerCase().contains("powermock")) {
                //PowerMock just leads to a lot of troubles, as it includes tools.jar code
                getLog().warn("Skipping PowerMock dependency at: " + element);
                continue;
            }
            if (element.toLowerCase().contains("jmockit")) {
                //JMockit has same issue
                getLog().warn("Skipping JMockit dependency at: " + element);
                continue;
            }
            getLog().debug("TEST ELEMENT: " + element);
            cp = addPathIfExists(cp, element, alreadyAdded);
        }
    } catch (DependencyResolutionRequiredException e) {
        getLog().error("Error: " + e.getMessage(), e);
        return;
    }
    File basedir = project.getBasedir();
    getLog().info("Target: " + target);
    getLog().debug("Classpath: " + cp);
    getLog().info("Basedir: " + basedir.getAbsolutePath());
    if (target == null || cp == null || basedir == null) {
        getLog().info("Nothing to test");
        return;
    }
    runEvoSuiteOnSeparatedProcess(target, cp, basedir.getAbsolutePath());
}
Example 18
Project: fenix-framework-master  File: DmlZipCreatorMojo.java View source code
@Override
public void execute() throws MojoExecutionException {
    if (mavenProject.getArtifact().getType().equals("pom")) {
        getLog().info("Cannot compute dml files for pom projects");
        return;
    }
    Collection<String> compileClasspathElements;
    try {
        compileClasspathElements = mavenProject.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    List<String> classpath = new ArrayList<String>(compileClasspathElements);
    for (Artifact artifact : mavenProject.getDependencyArtifacts()) {
        if (artifact.getFile() != null && artifact.getFile().isDirectory()) {
            classpath.add(artifact.getFile().getAbsolutePath());
        }
    }
    DmlMojoUtils.augmentClassLoader(getLog(), classpath);
    List<URL> dmlFiles = new ArrayList<URL>();
    if (dmlSourceDirectory.exists()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(dmlSourceDirectory);
        String[] includes = { "**\\*.dml" };
        scanner.setIncludes(includes);
        scanner.scan();
        Resource resource = new Resource();
        resource.setDirectory(dmlSourceDirectory.getAbsolutePath());
        resource.addInclude("*.dml");
        mavenProject.addResource(resource);
        for (String includedFile : scanner.getIncludedFiles()) {
            String filePath = dmlSourceDirectory.getAbsolutePath() + "/" + includedFile;
            File file = new File(filePath);
            try {
                dmlFiles.add(file.toURI().toURL());
            } catch (MalformedURLException e) {
                getLog().error(e);
            }
        }
        Collections.sort(dmlFiles, new Comparator<URL>() {

            @Override
            public int compare(URL o1, URL o2) {
                return o1.toExternalForm().compareTo(o2.toExternalForm());
            }
        });
    }
    try {
        Project project = DmlMojoUtils.getProject(mavenProject, dmlSourceDirectory, zipDestinationDirectory, dmlFiles, getLog(), verbose);
        List<URL> dmls = new ArrayList<URL>();
        for (DmlFile dmlFile : project.getFullDmlSortedList()) {
            dmls.add(dmlFile.getUrl());
        }
        if (dmls.isEmpty()) {
            getLog().info("No dml files found");
            return;
        } else {
            File zipFile = new File(String.format("%s/%s_dmls.zip", zipDestinationDirectory, mavenProject.getArtifactId()));
            zipFile.getParentFile().mkdirs();
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
            Integer i = 1;
            for (URL dmlURL : dmls) {
                String name = String.format("/dmls/domain_model_%02d.dml", i++);
                ZipEntry e = new ZipEntry(name);
                out.putNextEntry(e);
                File f = new File(zipDestinationDirectory + name);
                FileUtils.copyURLToFile(dmlURL, f);
                out.write(FileUtils.readFileToByteArray(f));
                out.closeEntry();
            }
            out.close();
        }
    } catch (Exception e) {
        getLog().error(e);
    }
}
Example 19
Project: idea-plugin-maven-plugin-master  File: PackagingMojo.java View source code
private void addDependenciesToBundle(ZipBuilder zipBuilder) {
    try {
        for (String classPathElement : project.getRuntimeClasspathElements()) {
            if (isOutputDirectory(classPathElement)) {
                continue;
            }
            addToBundle(new File(classPathElement), zipBuilder);
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new RuntimeException(e);
    }
}
Example 20
Project: incubator-streams-master  File: StreamsPojoSourceGeneratorMojo.java View source code
private void addProjectDependenciesToClasspath() {
    try {
        ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader newClassLoader = new ProjectClasspath().getClassLoader(project, oldClassLoader, getLog());
        Thread.currentThread().setContextClassLoader(newClassLoader);
    } catch (DependencyResolutionRequiredException ex) {
        LOGGER.info("Skipping addition of project artifacts, there appears to be a dependecy resolution problem", ex);
    }
}
Example 21
Project: maven-integration-testing-master  File: TestMojo.java View source code
/**
     * Runs this mojo.
     * 
     * @throws MojoExecutionException If the output file could not be created or any dependency could not be resolved.
     */
public void execute() throws MojoExecutionException {
    try {
        writeArtifacts(projectArtifacts, project.getArtifacts());
        writeArtifacts(dependencyArtifacts, project.getDependencyArtifacts());
        writeArtifacts(testArtifacts, project.getTestArtifacts());
        writeClassPath(testClassPath, project.getTestClasspathElements());
        writeClassPathChecksums(testClassPathChecksums, project.getTestClasspathElements());
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Failed to resolve dependencies", e);
    }
}
Example 22
Project: maven-plugins-master  File: AbstractFixJavadocMojo.java View source code
/**
     * @return the classLoader for the given project using lazy instantiation.
     * @throws MojoExecutionException if any
     */
private ClassLoader getProjectClassLoader() throws MojoExecutionException {
    if (projectClassLoader == null) {
        List<String> classPath;
        try {
            classPath = getCompileClasspathElements(project);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
        }
        List<URL> urls = new ArrayList<URL>(classPath.size());
        for (String filename : classPath) {
            try {
                urls.add(new File(filename).toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException("MalformedURLException: " + e.getMessage(), e);
            }
        }
        projectClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
    }
    return projectClassLoader;
}
Example 23
Project: piraso-master  File: WarMojo.java View source code
// ----------------------------------------------------------------------
// Implementation
// ----------------------------------------------------------------------
/**
     * Executes the WarMojo on the current project.
     *
     * @throws org.apache.maven.plugin.MojoExecutionException if an error occurred while building the webapp
     */
public void execute() throws MojoExecutionException, MojoFailureException {
    File warFile = getTargetWarFile();
    try {
        performPackaging(warFile);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    } catch (ManifestException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    }
}
Example 24
Project: axis2-java-master  File: MarMojo.java View source code
/**
     * Generates the mar.
     * 
     * @param marFile
     *            the target mar file
     * @throws IOException
     * @throws ArchiverException
     * @throws ManifestException
     * @throws DependencyResolutionRequiredException
     */
private void performPackaging(File marFile) throws IOException, ArchiverException, ManifestException, DependencyResolutionRequiredException, MojoExecutionException {
    buildExplodedMar();
    // generate mar file
    getLog().info("Generating mar " + marFile.getAbsolutePath());
    MavenArchiver archiver = new MavenArchiver();
    archiver.setArchiver(jarArchiver);
    archiver.setOutputFile(marFile);
    jarArchiver.addDirectory(marDirectory);
    // create archive
    archiver.createArchive(session, project, archive);
    if (classifier != null) {
        projectHelper.attachArtifact(project, "mar", classifier, marFile);
    } else {
        Artifact artifact = project.getArtifact();
        if (primaryArtifact) {
            artifact.setFile(marFile);
        } else if (artifact.getFile() == null || artifact.getFile().isDirectory()) {
            artifact.setFile(marFile);
        } else {
            projectHelper.attachArtifact(project, "mar", marFile);
        }
    }
}
Example 25
Project: camel-master  File: SpringBootAutoConfigurationMojo.java View source code
protected ClassLoader getProjectClassLoader() throws MojoFailureException {
    final List classpathElements;
    try {
        classpathElements = project.getTestClasspathElements();
    } catch (org.apache.maven.artifact.DependencyResolutionRequiredException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
    final URL[] urls = new URL[classpathElements.size()];
    int i = 0;
    for (Iterator it = classpathElements.iterator(); it.hasNext(); i++) {
        try {
            urls[i] = new File((String) it.next()).toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoFailureException(e.getMessage(), e);
        }
    }
    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    return new URLClassLoader(urls, tccl != null ? tccl : getClass().getClassLoader());
}
Example 26
Project: cdk-master  File: AbstractDatasetMojo.java View source code
void configureSchema(DatasetDescriptor.Builder descriptorBuilder, String avroSchemaFile, String avroSchemaReflectClass) throws MojoExecutionException {
    if (avroSchemaFile != null) {
        File avroSchema = new File(avroSchemaFile);
        try {
            if (avroSchema.exists()) {
                descriptorBuilder.schema(avroSchema);
            } else {
                descriptorBuilder.schema(Resources.getResource(avroSchemaFile).openStream());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Problem while reading file " + avroSchemaFile, e);
        }
    } else if (avroSchemaReflectClass != null) {
        try {
            List<URL> classpath = new ArrayList<URL>();
            for (Object element : mavenProject.getCompileClasspathElements()) {
                String path = (String) element;
                classpath.add(new File(path).toURI().toURL());
            }
            // use Maven's classloader, not the system one
            ClassLoader parentClassLoader = getClass().getClassLoader();
            ClassLoader classLoader = new URLClassLoader(classpath.toArray(new URL[classpath.size()]), parentClassLoader);
            descriptorBuilder.schema(Class.forName(avroSchemaReflectClass, true, classLoader));
        } catch (ClassNotFoundException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        }
    }
}
Example 27
Project: com.cedarsoft.rest-master  File: GeneratorMojoTest.java View source code
@Nonnull
private GeneratorMojo createMojo(@Nonnull String name) throws Exception {
    File testPom = new File(getBasedir(), "src/test/resources/unit/" + name + "/plugin-config.xml");
    assertTrue(testPom.getAbsolutePath() + " not found", testPom.exists());
    GeneratorMojo mojo = (GeneratorMojo) lookupMojo("generate", testPom);
    assertNotNull(mojo);
    MavenProjectStub project = new MavenProjectStub() {

        @Override
        public List getCompileClasspathElements() throws DependencyResolutionRequiredException {
            File target = new File(getBasedir(), "target/test-classes");
            return Lists.newArrayList(target.getAbsolutePath());
        }
    };
    mojo.mavenProject = project;
    cleanUp(mojo);
    return mojo;
}
Example 28
Project: com.idega.maven.webapp-master  File: WarMojo.java View source code
/**
     * Executes the WarMojo on the current project.
     *
     * @throws MojoExecutionException if an error occured while building the webapp
     */
public void execute() throws MojoExecutionException {
    File warFile = getWarFile(new File(outputDirectory), warName, classifier);
    try {
        performPackaging(warFile);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    } catch (ManifestException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    }
}
Example 29
Project: cuke4duke-master  File: AbstractJRubyMojo.java View source code
protected Project getProject() throws MojoExecutionException {
    Project project = new Project();
    project.setBaseDir(mavenProject.getBasedir());
    project.setProperty("jruby.home", jrubyHome().getAbsolutePath());
    project.addBuildListener(new LogAdapter());
    Path jrubyClasspath = new Path(project);
    project.addReference("jruby.classpath", jrubyClasspath);
    try {
        append(jrubyClasspath, testClasspathElements);
        append(jrubyClasspath, compileClasspathElements);
        append(jrubyClasspath, pluginArtifacts);
        return project;
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("error resolving dependencies", e);
    }
}
Example 30
Project: k3po-master  File: StartMojo.java View source code
private ClassLoader createScriptLoader() throws DependencyResolutionRequiredException, MalformedURLException {
    List<URL> scriptPath = new LinkedList<>();
    if (scriptDir != null) {
        scriptPath.add(scriptDir.getAbsoluteFile().toURI().toURL());
    }
    for (Object scriptPathEntry : project.getTestClasspathElements()) {
        URI scriptPathURI = new File(scriptPathEntry.toString()).getAbsoluteFile().toURI();
        scriptPath.add(scriptPathURI.toURL());
    }
    ClassLoader parent = getClass().getClassLoader();
    return new URLClassLoader(scriptPath.toArray(new URL[scriptPath.size()]), parent);
}
Example 31
Project: Kite-master  File: AbstractDatasetMojo.java View source code
void configureSchema(DatasetDescriptor.Builder descriptorBuilder, String avroSchemaFile, String avroSchemaReflectClass) throws MojoExecutionException {
    if (avroSchemaFile != null) {
        File avroSchema = new File(avroSchemaFile);
        try {
            if (avroSchema.exists()) {
                descriptorBuilder.schema(avroSchema);
            } else {
                descriptorBuilder.schema(Resources.getResource(avroSchemaFile).openStream());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Problem while reading file " + avroSchemaFile, e);
        }
    } else if (avroSchemaReflectClass != null) {
        try {
            List<URL> classpath = new ArrayList<URL>();
            for (Object element : mavenProject.getCompileClasspathElements()) {
                String path = (String) element;
                classpath.add(new File(path).toURI().toURL());
            }
            // use Maven's classloader, not the system one
            ClassLoader parentClassLoader = getClass().getClassLoader();
            ClassLoader classLoader = new URLClassLoader(classpath.toArray(new URL[classpath.size()]), parentClassLoader);
            descriptorBuilder.schema(Class.forName(avroSchemaReflectClass, true, classLoader));
        } catch (ClassNotFoundException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("Problem finding class " + avroSchemaReflectClass, e);
        }
    }
}
Example 32
Project: maven-anno-mojo-master  File: AnnoMojoDescriptorExtractor.java View source code
@SuppressWarnings({ "unchecked" })
public List<MojoDescriptor> execute(MavenProject project, PluginDescriptor pluginDescriptor) throws InvalidPluginDescriptorException {
    List<String> sourceRoots = project.getCompileSourceRoots();
    Set<String> sourcePathElements = new HashSet<String>();
    String srcRoot = null;
    try {
        for (String sourceRoot : sourceRoots) {
            srcRoot = sourceRoot;
            List<File> files = FileUtils.getFiles(new File(srcRoot), "**/*.java", null, true);
            for (File file : files) {
                String path = file.getPath();
                sourcePathElements.add(path);
            }
        }
    } catch (Exception e) {
        throw new InvalidPluginDescriptorException("Failed to get source files from " + srcRoot, e);
    }
    List<String> argsList = new ArrayList<String>();
    argsList.add("-nocompile");
    argsList.add("-cp");
    StringBuilder cp = new StringBuilder();
    //Add the compile classpath
    List<String> compileClasspathElements;
    try {
        compileClasspathElements = project.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new InvalidPluginDescriptorException("Failed to get compileClasspathElements.", e);
    }
    for (String ccpe : compileClasspathElements) {
        appendToPath(cp, ccpe);
    }
    //Add the current CL classptah
    URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs();
    for (URL url : urls) {
        String path;
        try {
            path = url.getPath();
        } catch (Exception e) {
            throw new InvalidPluginDescriptorException("Failed to get classpath files from " + url, e);
        }
        appendToPath(cp, path);
    }
    // Attempts to add dependencies to the classpath so that parameters inherited from abstract mojos in other
    // projects will be processed.
    Set s = project.getDependencyArtifacts();
    if (s != null) {
        for (Object untypedArtifact : project.getDependencyArtifacts()) {
            if (untypedArtifact instanceof Artifact) {
                Artifact artifact = (Artifact) untypedArtifact;
                File artifactFile = artifact.getFile();
                if (artifactFile != null) {
                    appendToPath(cp, artifactFile.getAbsolutePath());
                }
            }
        }
    }
    String classpath = cp.toString();
    debug("cl=" + classpath);
    argsList.add(classpath);
    argsList.addAll(sourcePathElements);
    String[] args = argsList.toArray(new String[argsList.size()]);
    List<MojoDescriptor> descriptors = new ArrayList<MojoDescriptor>();
    MojoDescriptorTls.setDescriptors(descriptors);
    try {
        Main.process(new MojoApf(pluginDescriptor), new PrintWriter(System.out), args);
    } catch (Throwable t) {
        throw new InvalidPluginDescriptorException("Failed to extract plugin descriptor.", t);
    }
    return MojoDescriptorTls.getDescriptors();
}
Example 33
Project: Maven-Archetype-master  File: JarMojo.java View source code
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        getLog().info("Building archetype jar: " + new File(outputDirectory, finalName));
        File jarFile = manager.archiveArchetype(archetypeDirectory, outputDirectory, finalName);
        checkArchetypeFile(jarFile);
        project.getArtifact().setFile(jarFile);
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException(ex.getMessage(), ex);
    }
}
Example 34
Project: mdl4ui-master  File: AbstractDepsMojo.java View source code
final ClassLoader getClassLoader() throws MojoFailureException {
    final List<?> classpathFiles;
    try {
        classpathFiles = project.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoFailureException(e.getMessage());
    }
    final URL[] urls = new URL[classpathFiles.size() + 1];
    try {
        for (int i = 0; i < classpathFiles.size(); ++i) {
            getLog().debug((String) classpathFiles.get(i));
            urls[i] = new File((String) classpathFiles.get(i)).toURI().toURL();
        }
        urls[classpathFiles.size()] = new File(buildDirectory + "/classes").toURI().toURL();
    } catch (MalformedURLException e) {
        throw new MojoFailureException(e.getMessage());
    }
    return new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
}
Example 35
Project: microjiac-public-master  File: ReducedArchiver.java View source code
/**
     * Return a pre-configured manifest
     *
     * @todo Add user attributes list and user groups list
     */
public Manifest getManifest(MavenProject project, ManifestConfiguration config) throws ManifestException, DependencyResolutionRequiredException {
    // Added basic entries
    Manifest m = new Manifest();
    Manifest.Attribute buildAttr = new Manifest.Attribute("Built-By", System.getProperty("user.name"));
    m.addConfiguredAttribute(buildAttr);
    Manifest.Attribute createdAttr = new Manifest.Attribute("Created-By", "Apache Maven");
    m.addConfiguredAttribute(createdAttr);
    if (config.getPackageName() != null) {
        Manifest.Attribute packageAttr = new Manifest.Attribute("Package", config.getPackageName());
        m.addConfiguredAttribute(packageAttr);
    }
    Manifest.Attribute buildJdkAttr = new Manifest.Attribute("Build-Jdk", System.getProperty("java.version"));
    m.addConfiguredAttribute(buildJdkAttr);
    if (config.isAddClasspath()) {
        StringBuffer classpath = new StringBuffer();
        List artifacts = project.getRuntimeClasspathElements();
        String classpathPrefix = config.getClasspathPrefix();
        for (Iterator iter = artifacts.iterator(); iter.hasNext(); ) {
            File f = new File((String) iter.next());
            if (f.isFile()) {
                if (classpath.length() > 0) {
                    classpath.append(" ");
                }
                classpath.append(classpathPrefix);
                classpath.append(f.getName());
            }
        }
        if (classpath.length() > 0) {
            Manifest.Attribute classpathAttr = new Manifest.Attribute("Class-Path", classpath.toString());
            m.addConfiguredAttribute(classpathAttr);
        }
    }
    String mainClass = config.getMainClass();
    if (mainClass != null && !"".equals(mainClass)) {
        Manifest.Attribute mainClassAttr = new Manifest.Attribute("Main-Class", mainClass);
        m.addConfiguredAttribute(mainClassAttr);
    }
    return m;
}
Example 36
Project: novelang-master  File: BatchProducerMojo.java View source code
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    ConcreteLoggerFactory.setMojoLog(getLog());
    LoggerFactory.configurationComplete();
    final List<String> classpathElements;
    try {
        classpathElements = project.getRuntimeClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Something got wrong", e);
    }
    /*
    for( final String classpathElement : classpathElements ) {
      log.info( "%s - Classpath element: %s", getClass().getSimpleName(), classpathElement ) ;
    }
*/
    final Version version = getVersion();
    final String[] documentNames = documentsToRender.toArray(new String[documentsToRender.size()]);
    DocumentGeneratorDriver.Configuration configuration = Husk.create(DocumentGeneratorDriver.Configuration.class).withJavaClasses(new JavaClasses.ClasspathAndMain(EngineDriver.NOVELANG_BOOTSTRAP_MAIN_CLASS_NAME, classpathElements)).withContentRootDirectory(contentRootDirectory).withOutputDirectory(outputDirectory).withWorkingDirectory(workingDirectory).withProgramArguments(documentNames).withVersion(version);
    if (logDirectory != null) {
        configuration = configuration.withLogDirectory(logDirectory);
    }
    if (jvmHeapSizeMegabytes != null) {
        configuration = configuration.withJvmHeapSizeMegabytes(jvmHeapSizeMegabytes);
    }
    final DocumentGeneratorDriver driver = new DocumentGeneratorDriver(configuration);
    try {
        driver.start(1L, TimeUnit.MINUTES);
        final int exitCode = driver.shutdown(false);
        if (exitCode != 0) {
            throw new Exception("Process ended with exit code " + exitCode);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Driver execution failed", e);
    }
}
Example 37
Project: persistence-jme-master  File: PackageMojo.java View source code
private void unzipDependencies(File outputDirectory) throws IOException, DependencyResolutionRequiredException {
    List compileClasspathElements = project.getCompileClasspathElements();
    List compileDependecies = project.getCompileDependencies();
    for (Iterator iter = compileDependecies.iterator(); iter.hasNext(); ) {
        Dependency dependency = (Dependency) iter.next();
        if ("COMPILE".equalsIgnoreCase(dependency.getScope())) {
            String groupId = dependency.getGroupId().replace('.', File.separatorChar);
            String artifactId = dependency.getArtifactId();
            String version = dependency.getVersion();
            String type = dependency.getType();
            String dependencyName = artifactId + '-' + version + '.' + type;
            String suffix = groupId + File.separatorChar + artifactId + File.separatorChar + version + File.separatorChar + dependencyName;
            for (Iterator iterator = compileClasspathElements.iterator(); iterator.hasNext(); ) {
                String path = (String) iterator.next();
                if (path.endsWith(suffix)) {
                    this.getLog().info("Embbeding the " + dependencyName + " dependency in the final package.");
                    ZipUtils.unzip(new File(path), outputDirectory);
                }
            }
        }
    }
}
Example 38
Project: querydsl-master  File: CompileMojo.java View source code
@SuppressWarnings("unchecked")
private String buildCompileClasspath() {
    List<String> pathElements = null;
    try {
        if (testClasspath) {
            pathElements = project.getTestClasspathElements();
        } else {
            pathElements = project.getCompileClasspathElements();
        }
    } catch (DependencyResolutionRequiredException e) {
        getLog().warn("exception calling getCompileClasspathElements", e);
        return null;
    }
    if (pathElements.isEmpty()) {
        return null;
    }
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < pathElements.size(); i++) {
        if (i > 0) {
            result.append(File.pathSeparatorChar);
        }
        result.append(pathElements.get(i));
    }
    return result.toString();
}
Example 39
Project: rdfbean-master  File: SchemaGenMojo.java View source code
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        URLClassLoader classLoader = getProjectClassLoader();
        final Pattern pattern = Pattern.compile(".*" + toRegex(classes) + "\\.class");
        ArchiveBrowser.Filter filter = new ArchiveBrowser.Filter() {

            public boolean accept(String name) {
                return pattern.matcher(name).matches();
            }
        };
        List<Class<?>> entityClasses = getEntityClasses(classLoader, filter);
        Collections.sort(entityClasses, fileComparator);
        DefaultConfiguration configuration = new DefaultConfiguration();
        configuration.addClasses(entityClasses.toArray(new Class[entityClasses.size()]));
        if (ontology == null) {
            if (namespace.endsWith("#") || namespace.endsWith("/")) {
                ontology = namespace.substring(0, namespace.length() - 1);
            } else {
                ontology = namespace;
            }
        }
        if (schemaFile != null) {
            if (!schemaFile.getParentFile().exists()) {
                if (!schemaFile.getParentFile().mkdirs()) {
                    getLog().info("Creation of " + schemaFile.getParentFile().getPath() + " failed");
                }
            }
            OutputStream out = new FileOutputStream(schemaFile);
            SchemaGen schemaGen = new SchemaGen().setNamespace(prefix, namespace).setOntology(ontology).addExportNamespace(namespace).setConfiguration(configuration);
            if (useTurtle) {
                schemaGen.export(Format.TURTLE, out);
            } else {
                schemaGen.export(Format.RDFXML, out);
            }
        }
        if (classListFile != null) {
            StringBuilder builder = new StringBuilder();
            for (Class<?> clazz : entityClasses) {
                if (builder.length() > 0) {
                    builder.append("\n");
                }
                builder.append(clazz.getName());
            }
            // FileUtils.writeStringToFile(classListFile,
            // builder.toString(), "UTF-8");
            Files.write(builder.toString(), classListFile, Charsets.UTF_8);
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
Example 40
Project: sakai-maven-plugin-master  File: ComponentMojo.java View source code
/**
     * Executes the WarMojo on the current project.
     *
     * @throws MojoExecutionException if an error occured while building the webapp
     */
public void execute() throws MojoExecutionException, MojoFailureException {
    File warFile = getWarFile(new File(outputDirectory), warName, classifier);
    try {
        performPackaging(warFile);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    } catch (ManifestException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error assembling WAR", e);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Error assembling WAR: " + e.getMessage(), e);
    }
}
Example 41
Project: assertj-assertions-generator-maven-plugin-master  File: AssertJAssertionsGeneratorMojo.java View source code
@SuppressWarnings("unchecked")
private ClassLoader getProjectClassLoader() throws DependencyResolutionRequiredException, MalformedURLException {
    List<String> classpathElements = new ArrayList<String>(project.getCompileClasspathElements());
    classpathElements.addAll(project.getTestClasspathElements());
    List<URL> classpathElementUrls = new ArrayList<URL>(classpathElements.size());
    for (int i = 0; i < classpathElements.size(); i++) {
        classpathElementUrls.add(new File(classpathElements.get(i)).toURI().toURL());
    }
    return new URLClassLoader(classpathElementUrls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader());
}
Example 42
Project: byteman-master  File: RuleCheckMojo.java View source code
public void execute() throws MojoExecutionException {
    List<File> scripts;
    if (skip) {
        getLog().info("Checking byteman scripts are skipped");
        return;
    }
    try {
        if (verbose) {
            getLog().info("find byteman script in " + scriptDir);
        }
        StringBuffer includebuf = new StringBuffer();
        for (int i = 0; i < includes.length; i++) {
            includebuf.append(includes[i]);
            if (i != includes.length - 1)
                includebuf.append(",");
        }
        StringBuffer excludebuf = new StringBuffer();
        for (int i = 0; i < excludes.length; i++) {
            excludebuf.append(excludes[i]);
            if (i != excludes.length - 1)
                excludebuf.append(",");
        }
        scripts = FileUtils.getFiles(scriptDir, includebuf.toString(), excludebuf.toString());
    } catch (Exception e) {
        getLog().debug("Can not find " + scriptDir);
        return;
    }
    if (scripts.size() == 0) {
        getLog().info("No byteman script in " + scriptDir);
        return;
    }
    List<String> classpathElements;
    try {
        classpathElements = project.getCompileClasspathElements();
        classpathElements.addAll(project.getRuntimeClasspathElements());
        classpathElements.add(project.getBuild().getOutputDirectory());
        classpathElements.add(project.getBuild().getTestOutputDirectory());
        if (additionalClassPath != null) {
            String[] cps = (additionalClassPath.split(";"));
            for (int i = 0; i < cps.length; i++) {
                File file = new File(cps[i]);
                String path = null;
                if (file.isAbsolute()) {
                    path = cps[i];
                } else {
                    path = project.getBasedir() + File.separator + cps[i];
                }
                classpathElements.add(path);
                if (verbose) {
                    getLog().info("add addional classpath " + path);
                }
            }
        }
        ClassRealm realm = descriptor.getClassRealm();
        for (String element : classpathElements) {
            File elementFile = new File(element);
            if (verbose) {
                getLog().info(element);
            } else {
                getLog().debug(element);
            }
            realm.addURL(elementFile.toURI().toURL());
        }
    } catch (DependencyResolutionRequiredException e) {
        getLog().warn(e);
    } catch (MalformedURLException e) {
        getLog().warn(e);
    }
    RuleCheck checker = new RuleCheck();
    for (File script : scripts) {
        if (verbose) {
            getLog().info("add script " + script);
        } else {
            getLog().debug("add script " + script);
        }
        checker.addRuleFile(script.getAbsolutePath());
    }
    for (int i = 0; i < packages.length; i++) {
        checker.addPackage(packages[i]);
        if (verbose) {
            getLog().info("add package " + packages[i]);
        } else {
            getLog().debug("add package " + packages[i]);
        }
    }
    getLog().info("Checking " + scripts.size() + " byteman scripts in " + scriptDir);
    checker.checkRules();
    RuleCheckResult result = checker.getResult();
    if (result.hasWarning()) {
        List<String> warns = result.getWarningMessages();
        warns.addAll(result.getTypeWarningMessages());
        for (String warn : warns) {
            getLog().warn(warn);
        }
        int totalWarnCount = warns.size();
        if (failOnWarning && expectWarnings != totalWarnCount) {
            throw new MojoExecutionException("check byteman script rules failed with " + totalWarnCount + " warnings. You may config failOnWarning with false or expectWarnings with " + totalWarnCount);
        }
    }
    if (result.hasError()) {
        int totalErrorCount = result.getErrorCount() + result.getParseErrorCount() + result.getTypeErrorCount();
        getLog().error("Checking byteman script rules failed with " + totalErrorCount + " errors");
        List<String> errors = result.getErrorMessages();
        errors.addAll(result.getParseErrorMessages());
        errors.addAll(result.getTypeErrorMessages());
        for (String error : errors) {
            getLog().error(error);
        }
        if (failOnError) {
            throw new MojoExecutionException("check byteman script rules failed with " + totalErrorCount + " errors");
        }
    }
}
Example 43
Project: cq-component-maven-plugin-master  File: ComponentMojo.java View source code
private Set<String> getExcludedClasses() throws DependencyResolutionRequiredException, MalformedURLException {
    getLog().debug("Constructing set of excluded Class names");
    List<String> excludedDependencyPaths = getExcludedDependencyPaths();
    if (excludedDependencyPaths != null) {
        ClassLoader exclusionClassLoader = ComponentMojoUtil.getClassLoader(excludedDependencyPaths, this.getClass().getClassLoader());
        Reflections reflections = ComponentMojoUtil.getReflections(exclusionClassLoader);
        Set<String> excludedClassNames = reflections.getStore().getTypesAnnotatedWith(Component.class.getName());
        return excludedClassNames;
    }
    return null;
}
Example 44
Project: droolsjbpm-integration-master  File: BuildMojo.java View source code
public void execute() throws MojoExecutionException, MojoFailureException {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    List<InternalKieModule> kmoduleDeps = new ArrayList<InternalKieModule>();
    try {
        Set<URL> urls = new HashSet<URL>();
        for (String element : project.getCompileClasspathElements()) {
            urls.add(new File(element).toURI().toURL());
        }
        project.setArtifactFilter(new CumulativeScopeArtifactFilter(Arrays.asList("compile", "runtime")));
        for (Artifact artifact : project.getArtifacts()) {
            File file = artifact.getFile();
            if (file != null) {
                urls.add(file.toURI().toURL());
                KieModuleModel depModel = getDependencyKieModel(file);
                if (depModel != null) {
                    ReleaseId releaseId = new ReleaseIdImpl(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
                    kmoduleDeps.add(new ZipKieModule(releaseId, depModel, file));
                }
            }
        }
        urls.add(outputDirectory.toURI().toURL());
        ClassLoader projectClassLoader = URLClassLoader.newInstance(urls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader());
        Thread.currentThread().setContextClassLoader(projectClassLoader);
        BPMN2ProcessFactory.loadProvider(projectClassLoader);
        DecisionTableFactory.loadProvider(projectClassLoader);
        ProcessBuilderFactory.loadProvider(projectClassLoader);
        PMMLCompilerFactory.loadProvider(projectClassLoader);
        GuidedDecisionTableFactory.loadProvider(projectClassLoader);
        GuidedRuleTemplateFactory.loadProvider(projectClassLoader);
        GuidedScoreCardFactory.loadProvider(projectClassLoader);
    } catch (DependencyResolutionRequiredException e) {
        throw new RuntimeException(e);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    KieServices ks = KieServices.Factory.get();
    try {
        setSystemProperties(properties);
        KieRepository kr = ks.getRepository();
        InternalKieModule kModule = (InternalKieModule) kr.addKieModule(ks.getResources().newFileSystemResource(sourceFolder));
        for (InternalKieModule kmoduleDep : kmoduleDeps) {
            kModule.addKieDependency(kmoduleDep);
        }
        KieContainerImpl kContainer = (KieContainerImpl) ks.newKieContainer(kModule.getReleaseId());
        KieProject kieProject = kContainer.getKieProject();
        ResultsImpl messages = kieProject.verify();
        List<Message> errors = messages.filterMessages(Message.Level.ERROR);
        if (!errors.isEmpty()) {
            for (Message error : errors) {
                getLog().error(error.toString());
            }
            throw new MojoFailureException("Build failed!");
        } else {
            new KieMetaInfoBuilder(new DiskResourceStore(outputDirectory), kModule).writeKieModuleMetaInfo();
        }
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
    getLog().info("KieModule successfully built!");
}
Example 45
Project: eguan-master  File: Javah.java View source code
protected final List getClassPaths() throws MojoExecutionException {
    if (classPaths.isEmpty()) {
        try {
            classPaths.addAll(mojo.getMavenProject().getCompileClasspathElements());
            // Add jar dependencies from the local repository
            ArtifactRepository repository = mojo.getLocalRepository();
            for (Iterator i = mojo.getMavenProject().getDependencyArtifacts().iterator(); i.hasNext(); ) {
                Artifact a = (Artifact) i.next();
                if (Artifact.SCOPE_COMPILE.equals(a.getScope()) && a.getArtifactHandler().isAddedToClasspath())
                    classPaths.add(new File(repository.getBasedir(), repository.pathOf(a)).getAbsolutePath());
            }
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("JAVAH, cannot get classpath", e);
        }
    }
    return classPaths;
}
Example 46
Project: freehep-ncolor-pdf-master  File: Javah.java View source code
protected List getClassPaths() throws MojoExecutionException {
    if (classPaths.isEmpty()) {
        try {
            classPaths.addAll(mojo.getMavenProject().getCompileClasspathElements());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("JAVAH, cannot get classpath", e);
        }
    }
    return classPaths;
}
Example 47
Project: handlebars.java-master  File: PrecompilePluginTest.java View source code
@Test(expected = MojoFailureException.class)
public void mustFailOnUnExpectedException() throws Exception {
    MavenProject project = createMock(MavenProject.class);
    Artifact artifact = createMock(Artifact.class);
    expect(project.getRuntimeClasspathElements()).andThrow(new DependencyResolutionRequiredException(artifact));
    replay(project, artifact);
    PrecompilePlugin plugin = new PrecompilePlugin();
    plugin.setPrefix("src/test/resources/no templates");
    plugin.setSuffix(".html");
    plugin.setOutput("target/no-helpers.js");
    plugin.setProject(project);
    plugin.setHandlebarsJsFile("/handlebars-v4.0.4.js");
    plugin.execute();
}
Example 48
Project: infinispan-master  File: DefaultsExtractorMojo.java View source code
public void execute() throws MojoExecutionException {
    try {
        this.classPaths = mavenProject.getCompileClasspathElements();
        URL[] classLoaderUrls = classPaths.stream().map( strPath -> FileSystems.getDefault().getPath(strPath)).map(this::pathToUrl).toArray(URL[]::new);
        this.classLoader = new URLClassLoader(classLoaderUrls, Thread.currentThread().getContextClassLoader());
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Exception encountered during class extraction", e);
    }
    Set<Class> configClasses = new HashSet<>();
    getClassesFromClasspath(configClasses);
    jars.forEach( jar -> getClassesFromJar(jar, configClasses));
    Map<String, String> defaults = extractDefaults(configClasses);
    writeDefaultsToFile(defaults);
    if (filterXsd)
        filterXsdSchemas();
}
Example 49
Project: jangaroo-tools-master  File: JooTestMojoBase.java View source code
protected List<File> findJars() throws DependencyResolutionRequiredException {
    List<File> jars = new ArrayList<File>();
    for (Object jarUrl : project.getTestClasspathElements()) {
        File file = new File((String) jarUrl);
        if (file.isFile()) {
            // should be a jar--don't add folders!
            jars.add(file);
            getLog().info("Test classpath: " + jarUrl);
        } else {
            getLog().info("Ignoring test classpath: " + jarUrl);
        }
    }
    return jars;
}
Example 50
Project: javadrop-master  File: JavadropMojo.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.apache.maven.plugin.AbstractMojo#execute()
     */
public void execute() throws MojoExecutionException {
    getLog().info("Javadrop Mojo processing started...");
    try {
        if ((mavenProject != null) && (mavenProject.getCompileClasspathElements() != null)) {
            getLog().info("Class augmented with project.");
            for (int index = 0; index < mavenProject.getCompileClasspathElements().size(); index++) {
                String path = (String) mavenProject.getCompileClasspathElements().get(index);
                URL cpUrl = new File(path).toURL();
                addURLToSystemClassLoader(cpUrl);
            }
        }
        initStrategies();
    } catch (MalformedURLException e) {
        getLog().warn("Can't add compile classpath elements to mojo!", e);
    } catch (DependencyResolutionRequiredException e) {
        getLog().warn("Can't add compile classpath elements to mojo!", e);
    } catch (IntrospectionException e) {
        getLog().warn("Can't add compile classpath elements to mojo!", e);
    } catch (ClassNotFoundException e) {
        getLog().warn(e);
    } catch (InstantiationException e) {
        getLog().warn(e);
    } catch (IllegalAccessException e) {
        getLog().warn(e);
    }
    // Process runner scripts in the context of a packager.
    TemplateProcessor processor = new VelocityTemplateProcessorImpl(getLog());
    for (PackagerStrategy packager : packagerStrategies) {
        for (RunnerStrategy runner : runnerStrategies) {
            // Convert scripts
            packager.processTemplates(runner, processor, workingDirectory);
            // Do mappings, renames, whatever in the runner.
            packager.postProcessArtifacts(runner, workingDirectory);
        }
        packager.createPackage(packageDirectory, workingDirectory, filteredRunnerStrats(packager, runnerStrategies), getLog());
    //            packager.createPackage(packageDirectory, workingDirectory,
    //                    runnerStrategies, getLog());
    }
    getLog().info("Javadrop complete.");
}
Example 51
Project: jersey-1.x-old-master  File: AbstractMojoProjectClasspathSupport.java View source code
/**
     * Create a list of classpath elements including declared build dependencies, the build
     * output directory and additionally configured dependencies.
     * @param mavenProject
     * @param additionalDependencies
     * @return a list of classpath elements
     * @throws DependencyResolutionRequiredException
     * @throws ArtifactResolutionException
     * @throws ArtifactNotFoundException
     * @author Martin Grotzke
     */
protected List<String> getClasspathElements(final MavenProject mavenProject, final List<com.sun.jersey.wadl.Dependency> additionalDependencies) throws DependencyResolutionRequiredException, ArtifactResolutionException, ArtifactNotFoundException {
    final List<String> paths = new ArrayList<String>();
    /* Add maven compile classpath elements
         */
    @SuppressWarnings("unchecked") final List<String> compileClasspathElements = mavenProject.getCompileClasspathElements();
    paths.addAll(compileClasspathElements);
    /* Add build dependencies as classpath elements
         */
    @SuppressWarnings("unchecked") final Collection<Dependency> dependencies = mavenProject.getDependencies();
    if (dependencies != null) {
        for (Dependency dependency : dependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier());
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }
    /* Add additional dependencies
         */
    if (additionalDependencies != null) {
        for (com.sun.jersey.wadl.Dependency dependency : additionalDependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding additional dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), "jar", null);
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding additional artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }
    return paths;
}
Example 52
Project: jersey-old-master  File: AbstractMojoProjectClasspathSupport.java View source code
/**
     * Create a list of classpath elements including declared build dependencies, the build
     * output directory and additionally configured dependencies.
     * @param mavenProject
     * @param additionalDependencies
     * @return a list of classpath elements
     * @throws DependencyResolutionRequiredException
     * @throws ArtifactResolutionException
     * @throws ArtifactNotFoundException
     * @author Martin Grotzke
     */
protected List<String> getClasspathElements(final MavenProject mavenProject, final List<com.sun.jersey.wadl.Dependency> additionalDependencies) throws DependencyResolutionRequiredException, ArtifactResolutionException, ArtifactNotFoundException {
    final List<String> paths = new ArrayList<String>();
    /* Add maven compile classpath elements
         */
    @SuppressWarnings("unchecked") final List<String> compileClasspathElements = mavenProject.getCompileClasspathElements();
    paths.addAll(compileClasspathElements);
    /* Add build dependencies as classpath elements
         */
    @SuppressWarnings("unchecked") final Collection<Dependency> dependencies = mavenProject.getDependencies();
    if (dependencies != null) {
        for (Dependency dependency : dependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier());
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }
    /* Add additional dependencies
         */
    if (additionalDependencies != null) {
        for (com.sun.jersey.wadl.Dependency dependency : additionalDependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding additional dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), "jar", null);
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding additional artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }
    return paths;
}
Example 53
Project: jewelcli-master  File: JewelCliReportMojo.java View source code
private ClassLoader getClassLoader() throws MavenReportException {
    final List<URL> urls = new ArrayList<URL>();
    try {
        for (final Object object : project.getCompileClasspathElements()) {
            final String path = (String) object;
            final URL url = new File(path).toURL();
            getLog().debug("adding classpath element " + url);
            urls.add(url);
        }
    } catch (final MalformedURLException e) {
        throw new MavenReportException("Unable to load command line interface class", e);
    } catch (final DependencyResolutionRequiredException e) {
        throw new MavenReportException("Unable to resolve dependencies of project", e);
    }
    return new URLClassLoader(urls.toArray(new URL[] {}), getClass().getClassLoader());
}
Example 54
Project: jgitflow-master  File: AbstractJGitFlowMojo.java View source code
protected String getClasspath() throws MojoExecutionException {
    Set<String> allPaths = new HashSet<String>();
    StringBuffer finalPath = new StringBuffer(File.pathSeparator + project.getBuild().getOutputDirectory());
    try {
        allPaths.addAll(project.getCompileClasspathElements());
        allPaths.addAll(project.getRuntimeClasspathElements());
        allPaths.addAll(project.getSystemClasspathElements());
        URL[] pluginUrls = ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs();
        for (URL pluginUrl : pluginUrls) {
            allPaths.add(new File(pluginUrl.getFile()).getPath());
        }
        for (String path : allPaths) {
            finalPath.append(File.pathSeparator);
            finalPath.append(path);
        }
        return finalPath.toString();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Dependencies must be resolved", e);
    }
}
Example 55
Project: jruby-maven-plugins-master  File: AbstractGemMojo.java View source code
@Override
protected ScriptFactory newScriptFactory(Artifact artifact) throws MojoExecutionException {
    try {
        final GemScriptFactory factory = artifact == null ? new GemScriptFactory(this.logger, this.classRealm, null, getProjectClasspath(), this.jrubyFork, this.gemsConfig) : (JRUBY_CORE.equals(artifact.getArtifactId()) ? new GemScriptFactory(this.logger, this.classRealm, artifact.getFile(), resolveJRubyStdlibArtifact(artifact).getFile(), getProjectClasspath(), this.jrubyFork, this.gemsConfig) : new GemScriptFactory(this.logger, this.classRealm, artifact.getFile(), getProjectClasspath(), this.jrubyFork, this.gemsConfig));
        if (supportNative) {
            factory.addJvmArgs("-Djruby.home=" + setupNativeSupport().getAbsolutePath());
        }
        if (rubySourceDirectory != null && rubySourceDirectory.exists()) {
            if (jrubyVerbose) {
                getLog().info("add to ruby loadpath: " + rubySourceDirectory.getAbsolutePath());
            }
            // add it to the load path for all scripts using that factory
            factory.addSwitch("-I", rubySourceDirectory.getAbsolutePath());
        }
        if (libDirectory != null && libDirectory.exists()) {
            if (jrubyVerbose) {
                getLog().info("add to ruby loadpath: " + libDirectory.getAbsolutePath());
            }
            // add it to the load path for all scripts using that factory
            factory.addSwitch("-I", libDirectory.getAbsolutePath());
        }
        return factory;
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("could not resolve jruby", e);
    } catch (final ScriptException e) {
        throw new MojoExecutionException("could not initialize script factory", e);
    } catch (final IOException e) {
        throw new MojoExecutionException("could not initialize script factory", e);
    }
}
Example 56
Project: jspresso-ce-master  File: SjsMojo.java View source code
private void runSjsCompilation() throws IOException, ResourceException, ScriptException, DependencyResolutionRequiredException {
    Properties projectProperties = project.getProperties();
    projectProperties.put("srcDir", srcDir.getAbsolutePath());
    projectProperties.put("outputDir", outputDir.getAbsolutePath());
    projectProperties.put("modelOutputFileName", modelOutputFileName);
    projectProperties.put("viewOutputFileName", viewOutputFileName);
    projectProperties.put("backOutputFileName", backOutputFileName);
    projectProperties.put("frontOutputFileName", frontOutputFileName);
    List<URL> classpath;
    classpath = new ArrayList<>();
    classpath.add(srcDir.toURI().toURL());
    List<String> compileClasspathElements = project.getCompileClasspathElements();
    for (String element : compileClasspathElements) {
        if (!element.equals(project.getBuild().getOutputDirectory())) {
            File elementFile = new File(element);
            getLog().debug("Adding element to plugin classpath " + elementFile.getPath());
            URL url = elementFile.toURI().toURL();
            classpath.add(url);
        }
    }
    GroovyScriptEngine gse = new GroovyScriptEngine(classpath.toArray(new URL[classpath.size()]));
    Binding binding = new Binding();
    binding.setVariable("project", project);
    binding.setVariable("fail", new FailClosure());
    String refinedApplicationFileName = applicationFileName;
    if (!new File(srcDir + File.separator + applicationFileName).exists()) {
        if (applicationFileName.contains(SJSEXT)) {
            refinedApplicationFileName = applicationFileName.replaceAll(SJSEXT, GROOVY_EXT);
        } else if (applicationFileName.contains(GROOVY_EXT)) {
            refinedApplicationFileName = applicationFileName.replaceAll(GROOVY_EXT, SJSEXT);
        }
    }
    gse.run(refinedApplicationFileName, binding);
}
Example 57
Project: karaf-master  File: GenerateHelpMojo.java View source code
private ClassFinder createFinder(String classloaderType) throws DependencyResolutionRequiredException, MalformedURLException, Exception, MojoFailureException {
    ClassFinder finder;
    if ("project".equals(classloaderType)) {
        List<URL> urls = new ArrayList<URL>();
        for (Object object : project.getCompileClasspathElements()) {
            String path = (String) object;
            urls.add(new File(path).toURI().toURL());
        }
        ClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
        finder = new ClassFinder(loader, urls);
    } else if ("plugin".equals(classLoader)) {
        finder = new ClassFinder(getClass().getClassLoader());
    } else {
        throw new MojoFailureException("classLoader attribute must be 'project' or 'plugin'");
    }
    return finder;
}
Example 58
Project: kotlin-master  File: K2JSCompilerMojo.java View source code
@Override
protected void configureSpecificCompilerArguments(@NotNull K2JSCompilerArguments arguments) throws MojoExecutionException {
    arguments.outputFile = outputFile;
    arguments.noStdlib = true;
    arguments.metaInfo = metaInfo;
    arguments.moduleKind = moduleKind;
    arguments.main = main;
    List<String> libraries = null;
    try {
        libraries = getKotlinJavascriptLibraryFiles();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unresolved dependencies", e);
    }
    getLog().debug("libraries: " + libraries);
    arguments.libraries = StringUtil.join(libraries, File.pathSeparator);
    arguments.sourceMap = sourceMap;
    if (outputFile != null) {
        ConcurrentMap<String, List<String>> collector = getOutputDirectoriesCollector();
        String key = project.getArtifactId();
        List<String> paths = collector.computeIfAbsent(key,  k -> Collections.synchronizedList(new ArrayList<String>()));
        paths.add(new File(outputFile).getParent());
    }
}
Example 59
Project: lazydoc-master  File: LazyDocMojo.java View source code
private ClassLoader getClassLoader() throws MojoExecutionException, DependencyResolutionRequiredException {
    List<URL> classpathURLs = new ArrayList<URL>();
    this.addRelevantPluginDependenciesToClasspath(classpathURLs);
    this.addRelevantProjectDependenciesToClasspath(classpathURLs);
    for (URL classpath : classpathURLs) {
        getLog().debug("Classpath: " + classpath.toString());
    }
    return new URLClassLoader(classpathURLs.toArray(new URL[classpathURLs.size()]));
}
Example 60
Project: maven-ipcstub-generator-master  File: GeneratorModule.java View source code
private Iterable<Class<? extends IpcCommand>> generateCommandList(Set<String> packages) throws MojoExecutionException {
    // create the classpath to use
    final List<File> locations = Lists.newArrayList();
    try {
        for (Object element : project.getRuntimeClasspathElements()) {
            log.debug("Adding runtime classpath element: " + element);
            locations.add(new File((String) element));
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("dependencies not resolved", e);
    }
    // hack: add the required files to the classloader
    boostrapClassloader(Iterables.transform(locations, new Function<File, URL>() {

        @Override
        public URL apply(File from) {
            try {
                return from.toURI().toURL();
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }));
    final String value = Joiner.on(File.pathSeparator).join(locations);
    final Classpath cp = Reflection.classpathOf(value);
    final Predicate<Class<?>> predicate = Reflection.isConcreteClass();
    return cp.restrictTo(packages).filter(IpcCommand.class, predicate);
}
Example 61
Project: maven-native-plugin-master  File: Javah.java View source code
protected final List getClassPaths() throws MojoExecutionException {
    if (this.classPaths.isEmpty()) {
        try {
            this.classPaths.addAll(this.mojo.getMavenProject().getCompileClasspathElements());
        } catch (final DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("JAVAH, cannot get classpath", e);
        }
    }
    return this.classPaths;
}
Example 62
Project: mycontainer-master  File: MycontainerStartMojo.java View source code
@SuppressWarnings("unchecked")
private List<File> getProjectsClasspath(Set<MavenProject> projects) throws MojoExecutionException {
    try {
        getLog().info("Including project classpath. includingTests: " + includeTests);
        List<File> ret = new ArrayList<File>(projects.size());
        for (MavenProject module : projects) {
            List<String> elements = module.getCompileClasspathElements();
            for (String element : elements) {
                debug("Path: " + element);
                ret.add(new File(element));
            }
            if (includeTests) {
                elements = module.getTestClasspathElements();
                for (String element : elements) {
                    debug("Path: " + element);
                    ret.add(new File(element));
                }
            }
        }
        return ret;
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("error", e);
    }
}
Example 63
Project: nar-maven-plugin-master  File: Javah.java View source code
protected final List getClassPaths() throws MojoExecutionException {
    if (this.classPaths.isEmpty()) {
        try {
            this.classPaths.addAll(this.mojo.getMavenProject().getCompileClasspathElements());
        } catch (final DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("JAVAH, cannot get classpath", e);
        }
    }
    return this.classPaths;
}
Example 64
Project: OpenDJ-master  File: GenerateManifestClassPathMojo.java View source code
/** [email protected]} */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        String classPath = getClasspath();
        getLog().info(format("Setting the classpath property: [%s] (debug to see actual value)", classPathProperty));
        getLog().debug(String.format("Setting the classpath property %s to:\n%s", classPathProperty, classPath));
        project.getProperties().put(classPathProperty, classPath);
    } catch (DependencyResolutionRequiredException e) {
        getLog().error(String.format("Unable to set the classpath property %s, an error occured", classPathProperty));
        throw new MojoFailureException(e.getMessage(), e);
    }
}
Example 65
Project: pitest-master  File: MojoToReportOptionsConverterTest.java View source code
public void testParsesExcludedClasspathElements() throws DependencyResolutionRequiredException {
    final String sep = File.pathSeparator;
    final Set<Artifact> artifacts = new HashSet<Artifact>();
    final Artifact dependency = Mockito.mock(Artifact.class);
    when(dependency.getGroupId()).thenReturn("group");
    when(dependency.getArtifactId()).thenReturn("artifact");
    when(dependency.getFile()).thenReturn(new File("group" + sep + "artifact" + sep + "1.0.0" + sep + "group-artifact-1.0.0.jar"));
    artifacts.add(dependency);
    when(this.project.getArtifacts()).thenReturn(artifacts);
    when(this.project.getTestClasspathElements()).thenReturn(Arrays.asList("group" + sep + "artifact" + sep + "1.0.0" + sep + "group-artifact-1.0.0.jar"));
    final ReportOptions actual = parseConfig("<classpathDependencyExcludes>" + "										<param>group:artifact</param>" + "									</classpathDependencyExcludes>");
    assertFalse(actual.getClassPathElements().contains("group" + sep + "artifact" + sep + "1.0.0" + sep + "group-artifact-1.0.0.jar"));
}
Example 66
Project: retrolambda-master  File: ProcessClassesMojo.java View source code
private File getClasspathFile() {
    try {
        String classpath = Joiner.on("\n").join(getClasspathElements());
        File file = File.createTempFile("retrolambda", "classpath");
        file.deleteOnExit();
        Files.write(classpath, file, Charsets.UTF_8);
        return file;
    } catch (DependencyResolutionRequiredException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 67
Project: scala-maven-plugin-master  File: ScalaScriptMojo.java View source code
private void configureClasspath(Set<String> classpath) throws Exception, DependencyResolutionRequiredException {
    Set<String> includes = new TreeSet<String>(Arrays.asList(includeScopes.toLowerCase().split(",")));
    Set<String> excludes = new TreeSet<String>(Arrays.asList(excludeScopes.toLowerCase().split(",")));
    for (Artifact a : project.getArtifacts()) {
        if (includes.contains(a.getScope().toLowerCase()) && !excludes.contains(a.getScope())) {
            addToClasspath(a, classpath, true);
        }
    }
    if (includes.contains("plugin") && !excludes.contains("plugin")) {
        //Plugin plugin = project.getPlugin("scala-maven-plugin");
        for (Plugin p : project.getBuildPlugins()) {
            if ("scala-maven-plugin".equals(p.getArtifactId())) {
                for (Dependency d : p.getDependencies()) {
                    addToClasspath(factory.createDependencyArtifact(d), classpath, true);
                }
            }
        }
        for (Artifact a : project.getPluginArtifacts()) {
            if ("scala-maven-plugin".equals(a.getArtifactId())) {
                addToClasspath(a, classpath, true);
            }
        }
    }
    if (addToClasspath != null) {
        classpath.addAll(Arrays.asList(addToClasspath.split(",")));
    }
    if (removeFromClasspath != null) {
        ArrayList<String> toRemove = new ArrayList<String>();
        String[] jars = removeFromClasspath.trim().split(",");
        for (String string : classpath) {
            for (String jar : jars) {
                if (string.contains(jar.trim())) {
                    toRemove.add(string);
                }
            }
        }
        classpath.removeAll(toRemove);
    }
    //        String outputDirectory = project.getBuild().getOutputDirectory();
    //        if(!outputDirectory.endsWith("/")){
    //            // need it to end with / for URLClassloader
    //            outputDirectory+="/";
    //        }
    //        classpath.add( outputDirectory);
    addCompilerToClasspath(classpath);
    addLibraryToClasspath(classpath);
    //TODO check that every entry from the classpath exists !
    boolean ok = true;
    for (String s : classpath) {
        File f = new File(s);
        getLog().debug("classpath entry for running and compiling scripts: " + f);
        if (!f.exists()) {
            getLog().error("classpath entry for script not found : " + f);
            ok = false;
        }
    }
    if (!ok) {
        throw new MojoFailureException("some script dependencies not found (see log)");
    }
    getLog().debug("Using the following classpath for running and compiling scripts: " + classpath);
}
Example 68
Project: substeps-runner-master  File: SubstepsRunnerMojo.java View source code
private ForkedRunner createForkedRunner() throws MojoExecutionException {
    try {
        return new ForkedRunner(getLog(), this.jmxPort, this.vmArgs, this.project.getTestClasspathElements(), this.stepImplementationArtifacts, this.artifactResolver, this.artifactFactory, this.mavenProjectBuilder, this.localRepository, this.remoteRepositories, this.artifactMetadataSource);
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unable to resolve dependencies", e);
    }
}
Example 69
Project: was-maven-plugin-master  File: AntTaskUtils.java View source code
private static Project generateAntProject(WebSphereModel model, File antBuildFile, MavenProject project, MavenProjectHelper projectHelper, List<Artifact> pluginArtifact, Log logger) throws MojoExecutionException {
    try {
        Project antProject = new Project();
        ProjectHelper.configureProject(antProject, antBuildFile);
        antProject.init();
        setupLogger(antBuildFile, logger, antProject);
        antProject.setBaseDir(project.getBasedir());
        Path p = new Path(antProject);
        p.setPath(StringUtils.join(project.getCompileClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.compile.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(project.getRuntimeClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.runtime.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(project.getTestClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.test.classpath", p);
        antProject.addReference("maven.plugin.classpath", getPathFromArtifacts(pluginArtifact, antProject));
        antProject.addReference(DEFAULT_MAVEN_PROJECT_REFID, project);
        antProject.addReference(DEFAULT_MAVEN_PROJECT_HELPER_REFID, projectHelper);
        initMavenTasks(antProject);
        copyProperties(project, antProject);
        copyProperties(model.getProperties(), antProject);
        return antProject;
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
    } catch (BuildException e) {
        throw new MojoExecutionException("An Ant BuildException has occurred: " + e.getMessage(), e);
    } catch (Throwable e) {
        throw new MojoExecutionException("Error executing ant tasks: " + e.getMessage(), e);
    }
}
Example 70
Project: xapi-master  File: CodeServerMojo.java View source code
public void keepAlive() throws MojoExecutionException {
    final MavenProject project = getProject();
    X_Log.info(getClass(), "Preparing gwt recompiler for " + project, "Include test sources? " + isUseTestSources());
    if (null != project) {
        addSource(project.getBasedir());
        LinkedList<String> modules = new LinkedList<String>();
        if (isUseTestSources()) {
            for (Object o : project.getTestCompileSourceRoots()) {
                File f = new File(String.valueOf(o));
                if (f.exists()) {
                    // Add the source location
                    addTestSource(f);
                    // also scan for .gwt.xml modules
                    try {
                        modules.addAll(findModules(f));
                    } catch (Exception e) {
                        getLog().warn("An error was encountered while searching for .gwt.xml modules", e);
                    }
                } else {
                    X_Log.warn(getClass(), "Test source does not exist", f);
                }
            }
            for (Resource o : project.getTestResources()) {
                File f = new File(o.getDirectory());
                if (f.exists()) {
                    addTestSource(f);
                    // already
                    try {
                        modules.addAll(findModules(f));
                    } catch (Exception e) {
                        getLog().warn("An error was encountered while searching for .gwt.xml modules", e);
                    }
                } else {
                    X_Log.warn(getClass(), "Test resource does not exist", f);
                }
            }
        }
        for (Object o : project.getCompileSourceRoots()) {
            File f = new File(String.valueOf(o));
            if (f.exists()) {
                // Add the source location
                addSource(f);
                // also scan for .gwt.xml modules
                try {
                    modules.addAll(findModules(f));
                } catch (Exception e) {
                    getLog().warn("An error was encountered while searching for .gwt.xml modules in " + f, e);
                }
            }
        }
        for (Resource o : project.getResources()) {
            File f = new File(o.getDirectory());
            if (f.exists()) {
                addSource(f);
                // already
                try {
                    modules.addAll(findModules(f));
                } catch (Exception e) {
                    getLog().warn("An error was encountered while searching for .gwt.xml modules in " + f, e);
                }
            }
        }
        if (modules.size() > 0) {
            setModule(modules.get(0));
        }
        try {
            if (isUseTestSources()) {
                for (Object o : project.getTestClasspathElements()) {
                    File f = new File(String.valueOf(o));
                    if (f.exists()) {
                        if (f.isDirectory()) {
                            // directories are to be handled differently
                            addToTestClasspath(f);
                        } else {
                            addTestSource(f);
                        }
                    } else {
                        X_Log.warn(getClass(), "Test classpath element does not exist", f, "from " + o);
                    }
                }
            } else {
                for (Object o : project.getCompileClasspathElements()) {
                    File f = new File(String.valueOf(o));
                    if (f.exists()) {
                        if (f.isDirectory()) {
                            // directories are to be handled differently
                            addToClasspath(f);
                        } else {
                            addSource(f);
                        }
                    }
                }
            }
        } catch (DependencyResolutionRequiredException e1) {
            getLog().error("Unable to load compile-scoped classpath elements." + "\nIf you are extending this plugin, " + "you may need to include <requiresDependencyResolution>compile</requiresDependencyResolution> " + "in your @Mojo annotation / plugin.xml file", e1);
        }
    }
    setVisible(true);
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            String cp = getClasspath(includeTestSource, ":");
            gwtLocations.findArtifact(cp, "gwt-dev", ":");
            gwtLocations.findArtifact(cp, "gwt-codeserver", ":");
            int before = cp.length();
            gwtLocations.findArtifact(cp, "gwt-user", ":");
            if (before != cp.length()) {
            // Missing gwt-user means we're probably missing org.json and validation apis...
            }
            if (autoCompile) {
                launchServer(includeTestSource, jsInteropMode, logLevel);
            }
        }
    });
    try {
        while (isVisible()) {
            Thread.sleep(1000);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error while waiting on codeserver", e);
    }
}
Example 71
Project: jboss-modules-surefire-plugin-master  File: AbstractSurefireMojo.java View source code
protected SurefireBooter constructSurefireBooter() throws MojoExecutionException, MojoFailureException {
    SurefireBooter surefireBooter = new SurefireBooter();
    Artifact surefireArtifact = (Artifact) getPluginArtifactMap().get("org.jboss.maven.surefire.modular:surefire-booter");
    if (surefireArtifact == null) {
        throw new MojoExecutionException("Unable to locate surefire-booter in the list of plugin artifacts");
    }
    // MNG-2961: before Maven 2.0.8, fixes getBaseVersion to be -SNAPSHOT if needed
    surefireArtifact.isSnapshot();
    Artifact junitArtifact;
    Artifact testNgArtifact;
    try {
        addArtifact(surefireBooter, surefireArtifact);
        junitArtifact = (Artifact) getProjectArtifactMap().get(getJunitArtifactName());
        // SUREFIRE-378, junit can have an alternate artifact name
        if (junitArtifact == null && "junit:junit".equals(getJunitArtifactName())) {
            junitArtifact = (Artifact) getProjectArtifactMap().get("junit:junit-dep");
        }
        // TODO: this is pretty manual, but I'd rather not require the plugin > dependencies section right now
        testNgArtifact = (Artifact) getProjectArtifactMap().get(getTestNGArtifactName());
        if (testNgArtifact != null) {
            VersionRange range = VersionRange.createFromVersionSpec("[4.7,)");
            if (!range.containsVersion(new DefaultArtifactVersion(testNgArtifact.getVersion()))) {
                throw new MojoFailureException("TestNG support requires version 4.7 or above. You have declared version " + testNgArtifact.getVersion());
            }
            convertTestNGParameters();
            if (this.getTestClassesDirectory() != null) {
                getProperties().setProperty("testng.test.classpath", getTestClassesDirectory().getAbsolutePath());
            }
            addArtifact(surefireBooter, testNgArtifact);
            // The plugin uses a JDK based profile to select the right testng. We might be explicity using a
            // different one since its based on the source level, not the JVM. Prune using the filter.
            addProvider(surefireBooter, "surefire-testng", Versions.PROPER_SUREFIRE_VERSION, testNgArtifact);
        } else if (junitArtifact != null && isAnyJunit4(junitArtifact)) {
            if (isAnyConcurrencySelected() && isJunit47Compatible(junitArtifact)) {
                convertJunitCoreParameters();
                addProvider(surefireBooter, "surefire-junit47", Versions.PROPER_SUREFIRE_VERSION, null);
            } else {
                addProvider(surefireBooter, "surefire-junit4", Versions.PROPER_SUREFIRE_VERSION, null);
            }
        } else {
            // add the JUnit provider as default - it doesn't require JUnit to be present,
            // since it supports POJO tests.
            addProvider(surefireBooter, "surefire-junit", Versions.PROPER_SUREFIRE_VERSION, null);
        }
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to locate required surefire provider dependency: " + e.getMessage(), e);
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Error determining the TestNG version requested: " + e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Error to resolving surefire provider dependency: " + e.getMessage(), e);
    }
    if (getSuiteXmlFiles() != null && getSuiteXmlFiles().length > 0 && getTest() == null) {
        if (testNgArtifact == null) {
            throw new MojoExecutionException("suiteXmlFiles is configured, but there is no TestNG dependency");
        }
        // TODO: properties should be passed in here too
        surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGXmlTestSuite", new Object[] { getSuiteXmlFiles(), getTestSourceDirectory().getAbsolutePath(), testNgArtifact.getVersion(), testNgArtifact.getClassifier(), getProperties(), getReportsDirectory() });
    } else {
        List includes;
        List excludes;
        if (getTest() != null) {
            // Check to see if we are running a single test. The raw parameter will
            // come through if it has not been set.
            // FooTest -> **/FooTest.java
            includes = new ArrayList();
            excludes = new ArrayList();
            if (getFailIfNoTests() == null) {
                setFailIfNoTests(Boolean.TRUE);
            }
            String[] testRegexes = StringUtils.split(getTest(), ",");
            for (int i = 0; i < testRegexes.length; i++) {
                String testRegex = testRegexes[i];
                if (testRegex.endsWith(".java")) {
                    testRegex = testRegex.substring(0, testRegex.length() - 5);
                }
                // Allow paths delimited by '.' or '/'
                testRegex = testRegex.replace('.', '/');
                includes.add("**/" + testRegex + ".java");
            }
        } else {
            includes = this.getIncludes();
            excludes = this.getExcludes();
            // Have to wrap in an ArrayList as surefire expects an ArrayList instead of a List for some reason
            if (includes == null || includes.size() == 0) {
                includes = new ArrayList(Arrays.asList(getDefaultIncludes()));
            }
            if (excludes == null || excludes.size() == 0) {
                excludes = new ArrayList(Arrays.asList(new String[] { "**/*$*" }));
            }
        }
        if (testNgArtifact != null) {
            surefireBooter.addTestSuite("org.apache.maven.surefire.testng.TestNGDirectoryTestSuite", new Object[] { getTestClassesDirectory(), includes, excludes, getTestSourceDirectory().getAbsolutePath(), testNgArtifact.getVersion(), testNgArtifact.getClassifier(), getProperties(), getReportsDirectory() });
        } else {
            String junitDirectoryTestSuite;
            if (isAnyConcurrencySelected() && isJunit47Compatible(junitArtifact)) {
                junitDirectoryTestSuite = "org.apache.maven.surefire.junitcore.JUnitCoreDirectoryTestSuite";
                getLog().info("Concurrency config is " + getProperties().toString());
                surefireBooter.addTestSuite(junitDirectoryTestSuite, new Object[] { getTestClassesDirectory(), includes, excludes, getProperties() });
            } else {
                if (isAnyJunit4(junitArtifact)) {
                    junitDirectoryTestSuite = "org.apache.maven.surefire.junit4.JUnit4DirectoryTestSuite";
                } else {
                    // fall back to JUnit, which also contains POJO support. Also it can run
                    // classes compiled against JUnit since it has a dependency on JUnit itself.
                    junitDirectoryTestSuite = "org.apache.maven.surefire.junit.JUnitDirectoryTestSuite";
                }
                surefireBooter.addTestSuite(junitDirectoryTestSuite, new Object[] { getTestClassesDirectory(), includes, excludes });
            }
        }
    }
    List classpathElements = null;
    try {
        classpathElements = generateTestClasspath();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unable to generate test classpath: " + e, e);
    }
    getLog().debug("Test Classpath :");
    for (Iterator i = classpathElements.iterator(); i.hasNext(); ) {
        String classpathElement = (String) i.next();
        getLog().debug("  " + classpathElement);
        surefireBooter.addClassPathUrl(classpathElement);
    }
    Toolchain tc = getToolchain();
    if (tc != null) {
        getLog().info("Toolchain in " + getPluginName() + "-plugin: " + tc);
        if (isForkModeNever()) {
            setForkMode(ForkConfiguration.FORK_ONCE);
        }
        if (getJvm() != null) {
            getLog().warn("Toolchains are ignored, 'executable' parameter is set to " + getJvm());
        } else {
            //NOI18N
            setJvm(tc.findTool("java"));
        }
    }
    // ----------------------------------------------------------------------
    // Forking
    // ----------------------------------------------------------------------
    ForkConfiguration fork = new ForkConfiguration();
    fork.setForkMode(getForkMode());
    processSystemProperties(!fork.isForking());
    if (getLog().isDebugEnabled()) {
        showMap(getInternalSystemProperties(), "system property");
    }
    if (fork.isForking()) {
        setUseSystemClassLoader(getUseSystemClassLoader() == null ? Boolean.TRUE : getUseSystemClassLoader());
        fork.setUseSystemClassLoader(getUseSystemClassLoader().booleanValue());
        fork.setUseManifestOnlyJar(isUseManifestOnlyJar());
        fork.setSystemProperties(getInternalSystemProperties());
        if ("true".equals(getDebugForkedProcess())) {
            setDebugForkedProcess("-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005");
        }
        fork.setDebugLine(getDebugForkedProcess());
        if (getJvm() == null || "".equals(getJvm())) {
            // use the same JVM as the one used to run Maven (the "java.home" one)
            setJvm(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
            getLog().debug("Using JVM: " + getJvm());
        }
        fork.setJvmExecutable(getJvm());
        if (getWorkingDirectory() != null) {
            fork.setWorkingDirectory(getWorkingDirectory());
        } else {
            fork.setWorkingDirectory(getBasedir());
        }
        fork.setArgLine(getArgLine());
        fork.setEnvironmentVariables(getEnvironmentVariables());
        if (getLog().isDebugEnabled()) {
            showMap(getEnvironmentVariables(), "environment variable");
            fork.setDebug(true);
        }
        if (getArgLine() != null) {
            List args = Arrays.asList(getArgLine().split(" "));
            if (args.contains("-da") || args.contains("-disableassertions")) {
                setEnableAssertions(false);
            }
        }
    }
    fork = processForkConfiguration(fork);
    surefireBooter.setFailIfNoTests(getFailIfNoTests() == null ? false : getFailIfNoTests().booleanValue());
    surefireBooter.setForkedProcessTimeoutInSeconds(getForkedProcessTimeoutInSeconds());
    surefireBooter.setRedirectTestOutputToFile(isRedirectTestOutputToFile());
    surefireBooter.setForkConfiguration(fork);
    surefireBooter.setChildDelegation(isChildDelegation());
    surefireBooter.setEnableAssertions(isEnableAssertions());
    surefireBooter.setReportsDirectory(getReportsDirectory());
    addReporters(surefireBooter, fork.isForking());
    return surefireBooter;
}
Example 72
Project: jaxb2-maven-plugin-master  File: TestSchemaGenerationMojo.java View source code
/**
     * [email protected]}
     */
@Override
protected List<String> getClasspath() throws MojoExecutionException {
    List<String> toReturn = null;
    try {
        toReturn = getProject().getTestClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Could not acquire compile classpath elements from MavenProject", e);
    }
    // All done.
    return toReturn;
}
Example 73
Project: lemma-master  File: LemmaMojo.java View source code
public XHTMLTemplateJavadocPipeline createPipeline(List<File> sourceDirectories, List<String> packageNames, MavenProject project) throws Exception {
    // Yep, the Javadoc tool has its own classpath, we abuse the javac system property to get it into the Gaftercode
    String javadocClasspath = null;
    try {
        List<String> classpathElements = (List<String>) project.getTestClasspathElements();
        StringBuilder sb = new StringBuilder();
        for (String classpathElement : classpathElements) {
            sb.append(classpathElement).append(File.pathSeparator);
        }
        if (sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        javadocClasspath = sb.toString();
        if (javadocClasspath != null) {
            getLog().debug("Setting Javadoc classpath: " + javadocClasspath);
            // The Javadoc code reads this env variable!
            System.setProperty("env.class.path", javadocClasspath);
        }
    } catch (DependencyResolutionRequiredException ex) {
        throw new Exception("Can't get test-scope classpath: " + ex.toString(), ex);
    }
    // Hurray for more logging abstractions!
    Handler loggingAdapter = new Handler() {

        Formatter formatter = new Formatter() {

            @Override
            public String format(LogRecord logRecord) {
                return formatMessage(logRecord);
            }
        };

        @Override
        public void publish(LogRecord logRecord) {
            if (logRecord.getLevel().equals(Level.SEVERE) && getLog().isErrorEnabled()) {
                getLog().error(formatter.format(logRecord));
            } else if (logRecord.getLevel().equals(Level.WARNING) && getLog().isWarnEnabled()) {
                getLog().warn(formatter.format(logRecord));
            } else if (logRecord.getLevel().equals(Level.INFO) && getLog().isInfoEnabled()) {
                getLog().info(formatter.format(logRecord));
            } else if (getLog().isDebugEnabled()) {
                getLog().debug(formatter.format(logRecord));
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    loggingAdapter.setLevel(Level.ALL);
    LoggingUtil.resetRootHandler(loggingAdapter);
    LogManager.getLogManager().getLogger("").setLevel(Level.ALL);
    for (File sourceDirectory : sourceDirectories) {
        if (!sourceDirectory.canRead()) {
            throw new Exception("Source directory not found or not readable: " + sourceDirectory);
        }
        if (!sourceDirectory.isDirectory()) {
            throw new Exception("Source directory is not a directory: " + sourceDirectory);
        }
    }
    if (packageNames.size() == 0) {
        for (File sourceDirectory : sourceDirectories) {
            // Default to all sub-directories in source directory
            File[] subdirs = sourceDirectory.listFiles(new FileFilter() {

                public boolean accept(File file) {
                    return file.isDirectory() && file.getName().matches("[a-zA-Z_]+");
                }
            });
            for (File subdir : subdirs) {
                packageNames.add(subdir.getName());
            }
            // Filter duplicates
            packageNames = new ArrayList(new LinkedHashSet(packageNames));
        }
    }
    // Finally, do the work
    return new XHTMLTemplateJavadocPipeline(sourceDirectories, packageNames, true, processXRefs);
}
Example 74
Project: maven-plugin-tools-master  File: GeneratorUtils.java View source code
@SuppressWarnings("unchecked")
public static boolean isMavenReport(String impl, MavenProject project) throws IllegalArgumentException {
    if (impl == null) {
        throw new IllegalArgumentException("mojo implementation should be declared");
    }
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (project != null) {
        List<String> classPathStrings;
        try {
            classPathStrings = project.getCompileClasspathElements();
            if (project.getExecutionProject() != null) {
                classPathStrings.addAll(project.getExecutionProject().getCompileClasspathElements());
            }
        } catch (DependencyResolutionRequiredException e) {
            throw new IllegalArgumentException(e);
        }
        List<URL> urls = new ArrayList<URL>(classPathStrings.size());
        for (String classPathString : classPathStrings) {
            try {
                urls.add(new File(classPathString).toURL());
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException(e);
            }
        }
        classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), classLoader);
    }
    try {
        Class<?> clazz = Class.forName(impl, false, classLoader);
        return MavenReport.class.isAssignableFrom(clazz);
    } catch (ClassNotFoundException e) {
        return false;
    }
}
Example 75
Project: rh-nexus-maven-tooling-master  File: PluginDescriptorMojo.java View source code
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    if (!mavenProject.getPackaging().equals(mapping.getPluginPackaging())) {
        getLog().info("Project is not of packaging type '" + mapping.getPluginPackaging() + "'.");
        return;
    }
    initConfig();
    final PluginMetadataGenerationRequest request = new PluginMetadataGenerationRequest();
    request.setGroupId(mavenProject.getGroupId());
    request.setArtifactId(mavenProject.getArtifactId());
    request.setVersion(mavenProject.getVersion());
    request.setName(mavenProject.getName());
    request.setDescription(mavenProject.getDescription());
    request.setPluginSiteURL(mavenProject.getUrl());
    request.setApplicationId(applicationId);
    request.setApplicationEdition(applicationEdition);
    request.setApplicationMinVersion(applicationMinVersion);
    request.setApplicationMaxVersion(applicationMaxVersion);
    // licenses
    if (mavenProject.getLicenses() != null) {
        for (final License mavenLicenseModel : (List<License>) mavenProject.getLicenses()) {
            request.addLicense(mavenLicenseModel.getName(), mavenLicenseModel.getUrl());
        }
    }
    // scm information
    try {
        final ScmRepository repository = getScmRepository();
        final SvnInfoScmResult scmResult = scmInfo(repository, new ScmFileSet(mavenProject.getBasedir()));
        if (!scmResult.isSuccess()) {
            throw new ScmException(scmResult.getCommandOutput());
        }
        final SvnInfoItem info = (SvnInfoItem) scmResult.getInfoItems().get(0);
        request.setScmVersion(info.getLastChangedRevision());
        request.setScmTimestamp(info.getLastChangedDate());
    } catch (final ScmException e) {
        getLog().warn("Failed to get scm information: " + e.getMessage());
    }
    // dependencies
    final List<Artifact> artifacts = mavenProject.getTestArtifacts();
    final Set<Artifact> classpathArtifacts = new HashSet<Artifact>();
    if (artifacts != null) {
        final Set<String> excludedArtifactIds = new HashSet<String>();
        final ArtifactSelector selector = artifactSet == null ? null : new ArtifactSelector(mavenProject.getArtifact(), artifactSet);
        artifactLoop: for (final Artifact artifact : artifacts) {
            final GAVCoordinate artifactCoordinate = new GAVCoordinate(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier(), artifact.getType());
            if (artifact.getType().equals(mapping.getPluginPackaging())) {
                if (artifact.isSnapshot()) {
                    artifactCoordinate.setVersion(artifact.getBaseVersion());
                }
                if (!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) {
                    throw new MojoFailureException("Plugin dependency \"" + artifact.getDependencyConflictId() + "\" must have the \"provided\" scope!");
                }
                excludedArtifactIds.add(artifact.getId());
                request.addPluginDependency(artifactCoordinate);
            } else if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) || Artifact.SCOPE_TEST.equals(artifact.getScope())) {
                excludedArtifactIds.add(artifact.getId());
            } else if ((Artifact.SCOPE_COMPILE.equals(artifact.getScope()) || Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) && (!mapping.matchesCoreGroupIds(artifact.getGroupId()))) {
                if (artifact.getDependencyTrail() != null) {
                    for (final String trailId : (List<String>) artifact.getDependencyTrail()) {
                        if (excludedArtifactIds.contains(trailId)) {
                            getLog().debug("Dependency artifact: " + artifact.getId() + " is part of the transitive dependency set for a dependency with 'provided' or 'test' scope: " + trailId + "\nThis artifact will be excluded from the plugin classpath.");
                            continue artifactLoop;
                        }
                    }
                }
                if (selector == null || selector.isSelected(artifact)) {
                    if (componentDependencies != null && componentDependencies.contains(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
                        artifactCoordinate.setHasComponents(true);
                    }
                    request.addClasspathDependency(artifactCoordinate);
                    classpathArtifacts.add(artifact);
                } else {
                    getLog().debug("Excluding: " + artifact.getId() + "; excluded by artifactSet.");
                    excludedArtifactIds.add(artifact.getId());
                }
            }
        }
    }
    request.setOutputFile(generatedPluginMetadata);
    request.setClassesDirectory(new File(mavenProject.getBuild().getOutputDirectory()));
    try {
        if (mavenProject.getCompileClasspathElements() != null) {
            for (final String classpathElement : (List<String>) mavenProject.getCompileClasspathElements()) {
                request.getClasspath().add(new File(classpathElement));
            }
        }
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoFailureException("Plugin failed to resolve dependencies: " + e.getMessage(), e);
    }
    request.getAnnotationClasses().add(ExtensionPoint.class);
    request.getAnnotationClasses().add(Managed.class);
    // do the work
    try {
        metadataGenerator.generatePluginDescriptor(request);
    } catch (final GleanerException e) {
        throw new MojoFailureException("Failed to generate plugin xml file: " + e.getMessage(), e);
    }
    try {
        ClasspathUtils.write(classpathArtifacts, mavenProject);
    } catch (final IOException e) {
        throw new MojoFailureException("Failed to generate classpath properties file: " + e.getMessage(), e);
    }
}
Example 76
Project: richfaces-cdk-master  File: AbstractCDKMojo.java View source code
protected ClassLoader createProjectClassLoader(MavenProject project, boolean useCCL) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        List<?> compileClasspathElements = project.getCompileClasspathElements();
        String outputDirectory = project.getBuild().getOutputDirectory();
        URL[] urls = new URL[compileClasspathElements.size() + 1];
        int i = 0;
        urls[i++] = new File(outputDirectory).toURI().toURL();
        for (Iterator<?> iter = compileClasspathElements.iterator(); iter.hasNext(); ) {
            String element = (String) iter.next();
            urls[i++] = new File(element).toURI().toURL();
        }
        if (useCCL) {
            classLoader = new URLClassLoader(urls, classLoader);
        } else {
            classLoader = new URLClassLoader(urls);
        }
    } catch (MalformedURLException e) {
        getLog().error("Bad URL in classpath", e);
    } catch (DependencyResolutionRequiredException e) {
        getLog().error("Dependencies not resolved ", e);
    }
    return classLoader;
}
Example 77
Project: sarl-master  File: AbstractDocumentationMojo.java View source code
/** Replies the current classpath.
	 *
	 * @return the current classpath.
	 * @throws IOException on failure.
	 */
protected List<File> getClassPath() throws IOException {
    final Set<String> classPath = new LinkedHashSet<>();
    classPath.add(this.session.getCurrentProject().getBuild().getSourceDirectory());
    try {
        classPath.addAll(this.session.getCurrentProject().getCompileClasspathElements());
    } catch (DependencyResolutionRequiredException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    }
    for (final Artifact dep : this.session.getCurrentProject().getArtifacts()) {
        classPath.add(dep.getFile().getAbsolutePath());
    }
    classPath.remove(this.session.getCurrentProject().getBuild().getOutputDirectory());
    final List<File> files = new ArrayList<>();
    for (final String filename : classPath) {
        final File file = new File(filename);
        if (file.exists()) {
            files.add(file);
        }
    }
    return files;
}
Example 78
Project: speedment-master  File: AbstractSpeedmentMojo.java View source code
@SuppressWarnings("unchecked")
protected final ClassLoader getClassLoader() throws MojoExecutionException, DependencyResolutionRequiredException {
    final MavenProject project = project();
    final List<String> classpathElements = new ArrayList<>();
    classpathElements.addAll(project.getCompileClasspathElements());
    classpathElements.addAll(project.getRuntimeClasspathElements());
    classpathElements.add(project.getBuild().getOutputDirectory());
    final List<URL> projectClasspathList = new ArrayList<>();
    for (final String element : classpathElements) {
        try {
            projectClasspathList.add(new File(element).toURI().toURL());
        } catch (final MalformedURLException ex) {
            throw new MojoExecutionException(element + " is an invalid classpath element", ex);
        }
    }
    return new URLClassLoader(projectClasspathList.toArray(new URL[projectClasspathList.size()]), Thread.currentThread().getContextClassLoader());
}
Example 79
Project: caliper-maven-plugin-master  File: BenchmarkMojo.java View source code
@SuppressWarnings("unchecked")
protected ClassLoader getBenchmarkClassloader() throws MojoExecutionException {
    try {
        Collection<String> urls = project.getTestClasspathElements();
        URL[] runtimeUrls = new URL[urls.size() + 1];
        int i = 0;
        for (String url : urls) {
            runtimeUrls[i++] = new File(url).toURI().toURL();
        }
        runtimeUrls[i] = getPathToPluginJar();
        return new BenchmarkClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());
    } catch (MalformedURLException e) {
        throw bug(e);
    } catch (DependencyResolutionRequiredException e) {
        throw bug(e);
    } catch (IOException e) {
        throw bug(e);
    }
}
Example 80
Project: junit-contracts-master  File: ContractMojo.java View source code
private ClassLoader buildClassLoader() throws MojoExecutionException {
    final ClassWorld world = new ClassWorld();
    ClassRealm realm;
    try {
        realm = world.newRealm("contract", null);
        // add contract test and it's transient dependencies.
        for (final Artifact elt : getJunitContractsArtifacts()) {
            final String dir = String.format("%s!/", elt.getFile().toURI().toURL());
            if (getLog().isDebugEnabled()) {
                getLog().debug("Checking for imports from: " + dir);
            }
            try {
                final Set<String> classNames = ClassPathUtils.findClasses(dir, "org.xenei.junit.contract");
                for (final String clsName : classNames) {
                    if (getLog().isDebugEnabled()) {
                        getLog().debug("Importing from current classloader: " + clsName);
                    }
                    importFromCurrentClassLoader(realm, Class.forName(clsName));
                }
            } catch (final ClassNotFoundException e) {
                throw new MojoExecutionException(e.toString(), e);
            } catch (final IOException e) {
                throw new MojoExecutionException(e.toString(), e);
            }
        }
        // add source dirs
        for (final String elt : project.getCompileSourceRoots()) {
            final URL url = new File(elt).toURI().toURL();
            realm.addURL(url);
            if (getLog().isDebugEnabled()) {
                getLog().debug("Source root: " + url);
            }
        }
        // add Compile classpath
        for (final String elt : project.getCompileClasspathElements()) {
            final URL url = new File(elt).toURI().toURL();
            realm.addURL(url);
            if (getLog().isDebugEnabled()) {
                getLog().debug("Compile classpath: " + url);
            }
        }
        // add Test classpath
        for (final String elt : project.getTestClasspathElements()) {
            final URL url = new File(elt).toURI().toURL();
            realm.addURL(url);
            if (getLog().isDebugEnabled()) {
                getLog().debug("Test classpath: " + url);
            }
        }
    } catch (final DuplicateRealmException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (final MalformedURLException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    return realm;
}
Example 81
Project: openicf-master  File: DocBookResourceMojo.java View source code
private File generateArchive(File docbkxFiles, String jarFileName) throws ArchiverException, IOException {
    File docbkxJar = new File(buildDirectory, jarFileName);
    if (docbkxJar.exists()) {
        docbkxJar.delete();
    }
    MavenArchiver archiver = new MavenArchiver();
    archiver.setArchiver(jarArchiver);
    archiver.setOutputFile(docbkxJar);
    if (!docbkxFiles.exists()) {
        getLog().warn("JAR will be empty - no content was marked for inclusion!");
    } else {
        archiver.getArchiver().addDirectory(docbkxFiles);
    }
    List<Resource> resources = project.getBuild().getResources();
    for (Resource r : resources) {
        if (r.getDirectory().endsWith("maven-shared-archive-resources")) {
            archiver.getArchiver().addDirectory(new File(r.getDirectory()));
        }
    }
    try {
        archive.setAddMavenDescriptor(false);
        archiver.createArchive(session, project, archive);
    } catch (ManifestException e) {
        throw new ArchiverException("ManifestException: " + e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
        throw new ArchiverException("DependencyResolutionRequiredException: " + e.getMessage(), e);
    }
    return docbkxJar;
}
Example 82
Project: robovm-maven-plugin-master  File: AbstractRoboVMMojo.java View source code
protected Config.Builder configure(Config.Builder builder) throws MojoExecutionException {
    builder.logger(getRoboVMLogger());
    if (os != null) {
        builder.os(OS.valueOf(os));
    }
    if (propertiesFile != null) {
        if (!propertiesFile.exists()) {
            throw new MojoExecutionException("Invalid 'propertiesFile' specified for RoboVM compile: " + propertiesFile);
        }
        try {
            getLog().debug("Including properties file in RoboVM compiler config: " + propertiesFile.getAbsolutePath());
            builder.addProperties(propertiesFile);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to add properties file to RoboVM config: " + propertiesFile);
        }
    } else {
        try {
            builder.readProjectProperties(project.getBasedir(), false);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read RoboVM project properties file(s) in " + project.getBasedir().getAbsolutePath(), e);
        }
    }
    if (configFile != null) {
        if (!configFile.exists()) {
            throw new MojoExecutionException("Invalid 'configFile' specified for RoboVM compile: " + configFile);
        }
        try {
            getLog().debug("Loading config file for RoboVM compiler: " + configFile.getAbsolutePath());
            builder.read(configFile);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to read RoboVM config file: " + configFile);
        }
    } else {
        try {
            builder.readProjectConfig(project.getBasedir(), false);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to read project RoboVM config file in " + project.getBasedir().getAbsolutePath(), e);
        }
    }
    // Read embedded RoboVM <config> if there is one
    Plugin plugin = project.getPlugin("org.robovm:robovm-maven-plugin");
    MavenProject p = project;
    while (p != null && plugin == null) {
        plugin = p.getPluginManagement().getPluginsAsMap().get("org.robovm:robovm-maven-plugin");
        if (plugin == null)
            p = p.getParent();
    }
    if (plugin != null) {
        getLog().debug("Reading RoboVM plugin configuration from " + p.getFile().getAbsolutePath());
        Xpp3Dom configDom = (Xpp3Dom) plugin.getConfiguration();
        if (configDom != null && configDom.getChild("config") != null) {
            StringWriter sw = new StringWriter();
            XMLWriter xmlWriter = new PrettyPrintXMLWriter(sw, "UTF-8", null);
            Xpp3DomWriter.write(xmlWriter, configDom.getChild("config"));
            try {
                builder.read(new StringReader(sw.toString()), project.getBasedir());
            } catch (Exception e) {
                throw new MojoExecutionException("Failed to read RoboVM config embedded in POM", e);
            }
        }
    }
    File tmpDir = new File(project.getBuild().getDirectory(), "robovm.tmp");
    try {
        FileUtils.deleteDirectory(tmpDir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to clean output dir " + tmpDir, e);
    }
    tmpDir.mkdirs();
    Home home = null;
    try {
        home = Home.find();
    } catch (Throwable t) {
    }
    if (home == null || !home.isDev()) {
        home = new Config.Home(unpackRoboVMDist());
    }
    builder.home(home).tmpDir(tmpDir).skipInstall(true).installDir(installDir);
    if (home.isDev()) {
        builder.useDebugLibs(Boolean.getBoolean("robovm.useDebugLibs"));
        builder.dumpIntermediates(true);
    }
    if (debug != null && !debug.equals("false")) {
        builder.debug(true);
        if (debugPort != -1) {
            builder.addPluginArgument("debug:jdwpport=" + debugPort);
        }
        if ("clientmode".equals(debug)) {
            builder.addPluginArgument("debug:clientmode=true");
        }
    }
    if (skipSigning) {
        builder.iosSkipSigning(true);
    } else {
        if (signIdentity != null) {
            getLog().debug("Using explicit signing identity: " + signIdentity);
            builder.iosSignIdentity(SigningIdentity.find(SigningIdentity.list(), signIdentity));
        }
        if (provisioningProfile != null) {
            getLog().debug("Using explicit provisioning profile: " + provisioningProfile);
            builder.iosProvisioningProfile(ProvisioningProfile.find(ProvisioningProfile.list(), provisioningProfile));
        }
        if (keychainPassword != null) {
            builder.keychainPassword(keychainPassword);
        } else if (keychainPasswordFile != null) {
            builder.keychainPasswordFile(keychainPasswordFile);
        }
    }
    if (cacheDir != null) {
        builder.cacheDir(cacheDir);
    }
    builder.clearClasspathEntries();
    try {
        for (Object object : project.getRuntimeClasspathElements()) {
            String path = (String) object;
            if (getLog().isDebugEnabled()) {
                getLog().debug("Including classpath element for RoboVM app: " + path);
            }
            builder.addClasspathEntry(new File(path));
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error resolving application classpath for RoboVM build", e);
    }
    return builder;
}
Example 83
Project: sling-master  File: JspcMojo.java View source code
private void initClassLoader() throws IOException, DependencyResolutionRequiredException {
    List artifacts = project.getCompileArtifacts();
    URL[] path = new URL[artifacts.size() + 1];
    int i = 0;
    for (Iterator ai = artifacts.iterator(); ai.hasNext(); ) {
        Artifact a = (Artifact) ai.next();
        path[i++] = a.getFile().toURI().toURL();
    }
    final String targetDirectory = project.getBuild().getOutputDirectory();
    path[path.length - 1] = new File(targetDirectory).toURI().toURL();
    loader = new URLClassLoader(path, this.getClass().getClassLoader());
}
Example 84
Project: wro4j-master  File: AbstractWro4jMojo.java View source code
/**
   * Update the classpath.
   */
protected final void extendPluginClasspath() throws MojoExecutionException {
    // this code is inspired from http://teleal.org/weblog/Extending%20the%20Maven%20plugin%20classpath.html
    final List<String> classpathElements = new ArrayList<String>();
    try {
        classpathElements.addAll(mavenProject.getRuntimeClasspathElements());
    } catch (final DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Could not get compile classpath elements", e);
    }
    final ClassLoader classLoader = createClassLoader(classpathElements);
    Thread.currentThread().setContextClassLoader(classLoader);
}
Example 85
Project: hbase-maven-plugin-master  File: StartMojo.java View source code
/**
   * Gets the runtime classpath required to run the mini clusters.
   *
   * <p>The maven classloading scheme is nonstandard.  They only put the "classworlds" jar
   * on the classpath, and it takes care of ClassLoading the rest of the jars.  This a
   * problem if we are going to start a mini MapReduce cluster.  The TaskTracker will
   * start a child JVM with the same classpath as this process, and it won't have
   * configured the classworlds class loader.  To work around this, we will put all of
   * our dependencies into the java.class.path system property, which will be read by
   * the TaskRunner's child JVM launcher to build the child JVM classpath.</p>
   *
   * <p>Note that when we say "all of our dependencies" we mean both the dependencies of
   * this plugin as well as the test classes and dependencies of the project that is
   * running the plugin.  We need to include the latter on the classpath because tests are
   * still just .class files at integration-test-time.  There will be no jars available
   * yet to put on the distributed cache via job.setJarByClass().  Hence, all of the
   * test-classes in the project running this plugin need to already be on the classpath
   * of the MapReduce cluster.<p>
   */
private String getClassPath() throws MojoExecutionException {
    // Maintain a set of classpath components added so we can de-dupe.
    Set<String> alreadyAddedComponents = new HashSet<String>();
    // Use this to build up the classpath string.
    StringBuilder classpath = new StringBuilder();
    // Add the existing classpath.
    String existingClasspath = System.getProperty("java.class.path");
    classpath.append(existingClasspath);
    alreadyAddedComponents.addAll(Arrays.asList(existingClasspath.split(":")));
    // Add the test classes and dependencies of the maven project running this plugin.
    //
    // Note: It is important that we add these classes and dependencies before we add this
    // plugin's dependencies in case the maven project needs to override a jar version.
    List<?> testClasspathComponents;
    try {
        testClasspathComponents = mMavenProject.getTestClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unable to retrieve project test classpath", e);
    }
    for (Object testClasspathComponent : testClasspathComponents) {
        String dependency = testClasspathComponent.toString();
        if (alreadyAddedComponents.contains(dependency)) {
            continue;
        }
        classpath.append(":");
        classpath.append(dependency);
        alreadyAddedComponents.add(dependency);
    }
    // Add this plugin's dependencies.
    for (Artifact artifact : mPluginDependencyArtifacts) {
        String dependency = artifact.getFile().getPath();
        if (alreadyAddedComponents.contains(dependency)) {
            continue;
        }
        classpath.append(":");
        classpath.append(dependency);
        alreadyAddedComponents.add(dependency);
    }
    return classpath.toString();
}
Example 86
Project: infer-maven-plugin-master  File: InferMojo.java View source code
@Override
public void execute() throws MojoExecutionException {
    if (inferDir == null) {
        inferDir = new File(System.getProperty(USER_DIR), DEFAULT_MAVEN_BUILD_DIR_NAME).getAbsolutePath();
    }
    if (inferPath != null && !INFER_CMD_NAME.equals(inferPath)) {
        getLog().info(String.format("Infer path set to: %s", inferPath));
    }
    // check if infer is on the PATH and if not, then download it.
    if (inferPath == null && download) {
        inferPath = downloadInfer(new File(inferDir, INFER_DOWNLOAD_DIRETORY_NAME));
    } else if (inferPath == null) {
        inferPath = inferCommand;
    }
    try {
        // get source directory, if it doesn't exist then we're done
        final File sourceDir = new File(project.getBuild().getSourceDirectory());
        if (!sourceDir.exists()) {
            return;
        }
        final File inferOutputDir = getInferOutputDir();
        final SimpleSourceInclusionScanner scanner = new SimpleSourceInclusionScanner(Collections.singleton("**/*.java"), Collections.<String>emptySet());
        scanner.addSourceMapping(new SuffixMapping(JAVA_SRC_EXTENSION, Collections.<String>emptySet()));
        final Collection<File> sourceFiles = scanner.getIncludedSources(sourceDir, null);
        final int numSourceFiles = sourceFiles.size();
        fileCount += numSourceFiles;
        final String classpath = getRuntimeAndCompileClasspath();
        completeInferExecutions(classpath, inferOutputDir, sourceFiles, numSourceFiles);
        reportResults(inferOutputDir, numSourceFiles);
    } catch (final DependencyResolutionRequiredException e) {
        getLog().error(e);
        throw new MojoExecutionException("Unable to get required dependencies to perform Infer check!", e);
    } catch (final InclusionScanException e) {
        getLog().error(e);
        throw new MojoExecutionException("Failed to get sources! Cannot complete Infer check", e);
    }
}
Example 87
Project: license-maven-plugin-master  File: AbstractLicenseMojo.java View source code
@SuppressWarnings({ "unchecked" })
public final void execute(final Callback callback) throws MojoExecutionException, MojoFailureException {
    if (!skip) {
        if (header == null && (this.inlineHeader == null || this.inlineHeader.isEmpty())) {
            warn("No header file specified to check for license");
            return;
        }
        if (!strictCheck) {
            warn("Property 'strictCheck' is not enabled. Please consider adding <strictCheck>true</strictCheck> in your pom.xml file.");
            warn("See http://mycila.github.io/license-maven-plugin for more information.");
        }
        finder = new ResourceFinder(basedir);
        try {
            finder.setCompileClassPath(project.getCompileClasspathElements());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
        finder.setPluginClassPath(getClass().getClassLoader());
        final HeaderSource headerSource = HeaderSource.of(this.inlineHeader, this.header, this.encoding, this.finder);
        final Header h = new Header(headerSource, headerSections);
        debug("Header: %s", h.getLocation());
        if (this.validHeaders == null) {
            this.validHeaders = new String[0];
        }
        final List<Header> validHeaders = new ArrayList<Header>(this.validHeaders.length);
        for (String validHeader : this.validHeaders) {
            final HeaderSource validHeaderSource = HeaderSource.of(null, validHeader, this.encoding, this.finder);
            validHeaders.add(new Header(validHeaderSource, headerSections));
        }
        final List<PropertiesProvider> propertiesProviders = new LinkedList<PropertiesProvider>();
        for (PropertiesProvider provider : ServiceLoader.load(PropertiesProvider.class, Thread.currentThread().getContextClassLoader())) {
            propertiesProviders.add(provider);
        }
        final DocumentPropertiesLoader propertiesLoader = new DocumentPropertiesLoader() {

            @Override
            public Properties load(Document document) {
                Properties props = new Properties();
                for (Map.Entry<String, String> entry : mergeProperties(document).entrySet()) {
                    if (entry.getValue() != null) {
                        props.setProperty(entry.getKey(), entry.getValue());
                    } else {
                        props.remove(entry.getKey());
                    }
                }
                for (PropertiesProvider provider : propertiesProviders) {
                    try {
                        final Map<String, String> providerProperties = provider.getAdditionalProperties(AbstractLicenseMojo.this, props, document);
                        if (getLog().isDebugEnabled()) {
                            getLog().debug("provider: " + provider.getClass() + " brought new properties\n" + providerProperties);
                        }
                        for (Map.Entry<String, String> entry : providerProperties.entrySet()) {
                            if (entry.getValue() != null) {
                                props.setProperty(entry.getKey(), entry.getValue());
                            } else {
                                props.remove(entry.getKey());
                            }
                        }
                    } catch (Exception e) {
                        getLog().warn("failure occured while calling " + provider.getClass(), e);
                    }
                }
                return props;
            }
        };
        final DocumentFactory documentFactory = new DocumentFactory(basedir, buildMapping(), buildHeaderDefinitions(), encoding, keywords, propertiesLoader);
        int nThreads = (int) (Runtime.getRuntime().availableProcessors() * concurrencyFactor);
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
        CompletionService completionService = new ExecutorCompletionService(executorService);
        int count = 0;
        debug("Number of execution threads: %s", nThreads);
        try {
            for (final String file : listSelectedFiles()) {
                completionService.submit(new Runnable() {

                    @Override
                    public void run() {
                        Document document = documentFactory.createDocuments(file);
                        debug("Selected file: %s [header style: %s]", document.getFilePath(), document.getHeaderDefinition());
                        if (document.isNotSupported()) {
                            callback.onUnknownFile(document, h);
                        } else if (document.is(h)) {
                            debug("Skipping header file: %s", document.getFilePath());
                        } else if (document.hasHeader(h, strictCheck)) {
                            callback.onExistingHeader(document, h);
                        } else {
                            boolean headerFound = false;
                            for (Header validHeader : validHeaders) {
                                if (headerFound = document.hasHeader(validHeader, strictCheck)) {
                                    callback.onExistingHeader(document, h);
                                    break;
                                }
                            }
                            if (!headerFound) {
                                callback.onHeaderNotFound(document, h);
                            }
                        }
                    }
                }, null);
                count++;
            }
            while (count-- > 0) {
                try {
                    completionService.take().get();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof Error) {
                        throw (Error) cause;
                    }
                    if (cause instanceof MojoExecutionException) {
                        throw (MojoExecutionException) cause;
                    }
                    if (cause instanceof MojoFailureException) {
                        throw (MojoFailureException) cause;
                    }
                    if (cause instanceof RuntimeException) {
                        throw (RuntimeException) cause;
                    }
                    throw new RuntimeException(cause.getMessage(), cause);
                }
            }
        } finally {
            executorService.shutdownNow();
        }
    }
}
Example 88
Project: maven-duplicate-finder-plugin-master  File: DuplicateFinderMojo.java View source code
private void checkCompileClasspath() throws MojoExecutionException {
    try {
        LOG.info("Checking compile classpath");
        final Set<Artifact> allArtifacts = project.getArtifacts();
        final ImmutableSet.Builder<Artifact> inScopeBuilder = ImmutableSet.builder();
        for (final Artifact artifact : allArtifacts) {
            if (artifact.getArtifactHandler().isAddedToClasspath() && COMPILE_SCOPE.contains(artifact.getScope())) {
                inScopeBuilder.add(artifact);
            }
        }
        final Map<File, Artifact> artifactsByFile = createArtifactsByFileMap(inScopeBuilder.build());
        addOutputDirectory(artifactsByFile);
        checkClasspath(project.getCompileClasspathElements(), artifactsByFile);
    } catch (final DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Could not resolve dependencies", ex);
    }
}
Example 89
Project: maven-shared-master  File: MavenArchiverTest.java View source code
@Test
public void testDashesInClassPath_MSHARED_134() throws IOException, ManifestException, DependencyResolutionRequiredException {
    File jarFile = new File("target/test/dummyWithDashes.jar");
    JarArchiver jarArchiver = getCleanJarArchiver(jarFile);
    MavenArchiver archiver = getMavenArchiver(jarArchiver);
    MavenSession session = getDummySession();
    MavenProject project = getDummyProject();
    Set<Artifact> artifacts = getArtifacts(getMockArtifact1(), getArtifactWithDot(), getMockArtifact2(), getMockArtifact3());
    project.setArtifacts(artifacts);
    MavenArchiveConfiguration config = new MavenArchiveConfiguration();
    config.setForced(false);
    final ManifestConfiguration mftConfig = config.getManifest();
    mftConfig.setMainClass("org.apache.maven.Foo");
    mftConfig.setAddClasspath(true);
    mftConfig.setAddExtensions(true);
    mftConfig.setClasspathPrefix("./lib/");
    archiver.createArchive(session, project, config);
    assertTrue(jarFile.exists());
}
Example 90
Project: monticore-master  File: GenerateMojo.java View source code
/**
   * @return the value of the "modelPaths" configuration parameter.
   */
protected Set<File> getModelPaths() {
    ImmutableSet.Builder<File> modelPaths = ImmutableSet.builder();
    // 1st: we take all modelpaths directly from the configuration
    if (this.modelPaths != null) {
        this.modelPaths.forEach( mP -> modelPaths.add(fromBasePath(mP)));
    }
    // 2nd: if specified we add any grammar directories (default)
    if (addGrammarDirectoriesToModelPath()) {
        for (File grammarFile : getGrammars()) {
            if (grammarFile.isDirectory()) {
                modelPaths.add(grammarFile);
            }
        }
    }
    // 3rd: if specified we add the project source directories (non default)
    if (addSourceDirectoriesToModelPath()) {
        getMavenProject().getCompileSourceRoots().forEach( csR -> modelPaths.add(new File(csR)));
    }
    // default)
    if (addClassPathToModelPath()) {
        try {
            getMavenProject().getCompileClasspathElements().forEach( cpDir -> modelPaths.add(new File(cpDir)));
        } catch (DependencyResolutionRequiredException e) {
            Throwables.propagate(e);
        }
    }
    for (Artifact artifact : getMavenProject().getArtifacts()) {
        // 5th: we add any explicitly specified project dependencies
        if (getModelPathDependencies().contains(getArtifactDescription(artifact.getGroupId(), artifact.getArtifactId()))) {
            modelPaths.add(artifact.getFile());
        } else // the install phase (e.g., mvn dependency:analyze)
        if (getClassifiers().contains(artifact.getClassifier()) && (getScopes().isEmpty() || getScopes().contains(artifact.getScope()))) {
            modelPaths.add(artifact.getFile());
        }
    }
    return modelPaths.build();
}
Example 91
Project: nifi-maven-master  File: NarMojo.java View source code
public File createArchive() throws MojoExecutionException {
    final File outputDirectory = projectBuildDirectory;
    File narFile = getNarFile(outputDirectory, finalName, classifier);
    MavenArchiver archiver = new MavenArchiver();
    archiver.setArchiver(jarArchiver);
    archiver.setOutputFile(narFile);
    archive.setForced(forceCreation);
    try {
        File contentDirectory = getClassesDirectory();
        if (!contentDirectory.exists()) {
            getLog().warn("NAR will be empty - no content was marked for inclusion!");
        } else {
            archiver.getArchiver().addDirectory(contentDirectory, getIncludes(), getExcludes());
        }
        File existingManifest = defaultManifestFile;
        if (useDefaultManifestFile && existingManifest.exists() && archive.getManifestFile() == null) {
            getLog().info("Adding existing MANIFEST to archive. Found under: " + existingManifest.getPath());
            archive.setManifestFile(existingManifest);
        }
        // automatically add the artifact id, group id, and version to the manifest
        archive.addManifestEntry("Nar-Id", narId);
        archive.addManifestEntry("Nar-Group", narGroup);
        archive.addManifestEntry("Nar-Version", narVersion);
        // look for a nar dependency
        NarDependency narDependency = getNarDependency();
        if (narDependency != null) {
            final String narDependencyGroup = notEmpty(this.narDependencyGroup) ? this.narDependencyGroup : narDependency.getGroupId();
            final String narDependencyId = notEmpty(this.narDependencyId) ? this.narDependencyId : narDependency.getArtifactId();
            final String narDependencyVersion = notEmpty(this.narDependencyVersion) ? this.narDependencyVersion : narDependency.getVersion();
            archive.addManifestEntry("Nar-Dependency-Group", narDependencyGroup);
            archive.addManifestEntry("Nar-Dependency-Id", narDependencyId);
            archive.addManifestEntry("Nar-Dependency-Version", narDependencyVersion);
        }
        if (notEmpty(buildTag)) {
            archive.addManifestEntry("Build-Tag", buildTag);
        }
        if (notEmpty(buildBranch)) {
            archive.addManifestEntry("Build-Branch", buildBranch);
        }
        if (notEmpty(buildRevision)) {
            archive.addManifestEntry("Build-Revision", buildRevision);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(BUILD_TIMESTAMP_FORMAT);
        archive.addManifestEntry("Build-Timestamp", dateFormat.format(new Date()));
        archive.addManifestEntry("Clone-During-Instance-Class-Loading", String.valueOf(cloneDuringInstanceClassLoading));
        archiver.createArchive(session, project, archive);
        return narFile;
    } catch (ArchiverExceptionMojoExecutionException | ManifestException | IOException | DependencyResolutionRequiredException |  e) {
        throw new MojoExecutionException("Error assembling NAR", e);
    }
}
Example 92
Project: richfaces-master  File: ProcessMojo.java View source code
protected URL[] getProjectClassPath() {
    try {
        List<String> classpath = new ArrayList<String>();
        classpath.addAll(project.getCompileClasspathElements());
        classpath.add(project.getBuild().getOutputDirectory());
        URL[] urlClasspath = filter(transform(classpath, filePathToURL), notNull()).toArray(EMPTY_URL_ARRAY);
        return urlClasspath;
    } catch (DependencyResolutionRequiredException e) {
        getLog().error("Dependencies not resolved ", e);
    }
    return new URL[0];
}
Example 93
Project: docbookx-tools-master  File: AbstractTransformerMojo.java View source code
protected void executeTasks(Target antTasks, MavenProject mavenProject) throws MojoExecutionException {
    try {
        ExpressionEvaluator exprEvaluator = (ExpressionEvaluator) antTasks.getProject().getReference("maven.expressionEvaluator");
        Project antProject = antTasks.getProject();
        PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
        propertyHelper.setNext(new AntPropertyHelper(exprEvaluator, getLog()));
        DefaultLogger antLogger = new DefaultLogger();
        antLogger.setOutputPrintStream(System.out);
        antLogger.setErrorPrintStream(System.err);
        antLogger.setMessageOutputLevel(2);
        antProject.addBuildListener(antLogger);
        antProject.setBaseDir(mavenProject.getBasedir());
        Path p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getArtifacts().iterator(), File.pathSeparator));
        antProject.addReference("maven.dependency.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.compile.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getRuntimeClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.runtime.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getTestClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.test.classpath", p);
        List artifacts = getArtifacts();
        List list = new ArrayList(artifacts.size());
        File file;
        for (Iterator i = artifacts.iterator(); i.hasNext(); list.add(file.getPath())) {
            Artifact a = (Artifact) i.next();
            file = a.getFile();
            if (file == null)
                throw new DependencyResolutionRequiredException(a);
        }
        p = new Path(antProject);
        p.setPath(StringUtils.join(list.iterator(), File.pathSeparator));
        antProject.addReference("maven.plugin.classpath", p);
        getLog().info("Executing tasks");
        antTasks.execute();
        getLog().info("Executed tasks");
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing ant tasks", e);
    }
}
Example 94
Project: mobicents-master  File: AbstractDuMojo.java View source code
private void generateManagementAntScript(List includedFiles) throws MojoExecutionException, DependencyResolutionRequiredException {
    getLog().info("Generating ant script for management without maven...");
    File buildFile = new File(targetDirectory, "build.xml");
    PrintWriter printWriter = null;
    try {
        // read header and footer
        String header = "";
        String footer = "";
        LinkedList<String> deployElements = new LinkedList<String>();
        LinkedList<String> undeployElements = new LinkedList<String>();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("build.header")));
            String str = "";
            while ((str = in.readLine()) != null) {
                header += str + "\r\n";
            }
            in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("build.footer")));
            while ((str = in.readLine()) != null) {
                footer += str + "\r\n";
            }
        } catch (IOException e) {
            throw new MojoExecutionException("failed to read header and footer of build.xml file", e);
        }
        // first process deploy-config file
        File deployConfigFile = new File(outputDirectory, "META-INF" + File.separator + "deploy-config.xml");
        if (deployConfigFile.exists()) {
            try {
                getLog().info("Parsing deploy-config.xml without validation");
                // parse doc into dom
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder parser = factory.newDocumentBuilder();
                Document document = parser.parse(deployConfigFile);
                // parse dom into DeployConfig
                DeployConfig deployConfig = DeployConfig.parse(document.getDocumentElement());
                for (RAEntity raEntity : deployConfig.getRaEntities()) {
                    // let's start by processing properties
                    Properties properties = new Properties();
                    if (!raEntity.getPropertiesFile().equals("")) {
                        // we have a properties file in META-INF
                        File propertiesFile = new File(outputDirectory, "META-INF" + File.separator + raEntity.getPropertiesFile());
                        if (propertiesFile.exists()) {
                            properties.load(new FileInputStream(propertiesFile));
                        }
                    }
                    // put all properties defined in the deploy-config also
                    properties.putAll(raEntity.getProperties());
                    // ok, now we do the strings for the ant script
                    // the ant call to create and activate the ra entity
                    String xml = "\t\t<antcall target=\"activate-raentity\">\r\n" + "\t\t\t<param name=\"ra.entity\" value=\"" + raEntity.getEntityName() + "\" />\r\n" + "\t\t\t<param name=\"ra.id\" value=\"" + raEntity.getResourceAdaptorId() + "\" />\r\n";
                    if (!properties.isEmpty()) {
                        // generate file in target and add property to ant call
                        xml += "\t\t\t<param name=\"ra.entity.properties.filename\" value=\"" + raEntity.getEntityName() + ".properties\" />\r\n";
                        try {
                            File propertiesFile = new File(outputDirectory, ".." + File.separator + raEntity.getEntityName() + ".properties");
                            properties.store(new FileOutputStream(propertiesFile), null);
                            getLog().info("generated properties file " + raEntity.getEntityName() + ".properties");
                        } catch (IOException e) {
                            throw new MojoExecutionException("failed to write ra entity properties file into output dir", e);
                        }
                    }
                    xml += "\t\t</antcall>\r\n";
                    // add this to the deployElements tail
                    deployElements.addLast(xml);
                    // the ant call to deactivate and remove the ra entity
                    xml = "\t\t<antcall target=\"deactivate-raentity\">\r\n" + "\t\t\t<param name=\"ra.entity\" value=\"" + raEntity.getEntityName() + "\" />\r\n" + "\t\t\t<param name=\"ra.id\" value=\"" + raEntity.getResourceAdaptorId() + "\" />\r\n" + "\t\t</antcall>\r\n";
                    // add this to the undeployElements head
                    undeployElements.addFirst(xml);
                    // second we bind/unbind ra links
                    for (String raLink : raEntity.getRaLinks()) {
                        xml = "\t\t<antcall target=\"bind-ralink\">\r\n" + "\t\t\t<param name=\"ra.entity\" value=\"" + raEntity.getEntityName() + "\" />\r\n" + "\t\t\t<param name=\"ra.link\" value=\"" + raLink + "\" />\r\n" + "\t\t</antcall>\r\n";
                        // add this to the deployElements tail
                        deployElements.addLast(xml);
                        xml = "\t\t<antcall target=\"unbind-ralink\">\r\n" + "\t\t\t<param name=\"ra.entity\" value=\"" + raEntity.getEntityName() + "\" />\r\n" + "\t\t\t<param name=\"ra.link\" value=\"" + raLink + "\" />\r\n" + "\t\t</antcall>\r\n";
                        // add this to the undeployElements head
                        undeployElements.addFirst(xml);
                    }
                }
            } catch (Exception e) {
                throw new MojoExecutionException("failed to parse resource META-INF/deploy-config.xml", e);
            }
        }
        // now the services descriptors
        for (Iterator i = includedFiles.iterator(); i.hasNext(); ) {
            String fileName = (String) i.next();
            if (fileName.startsWith("services" + File.separator)) {
                File serviceDescriptorFile = new File(outputDirectory, fileName);
                try {
                    // http://code.google.com/p/mobicents/issues/detail?id=104
                    getLog().info("Parsing " + fileName + " with validation");
                    // parse doc into dom
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setValidating(true);
                    DocumentBuilder parser = factory.newDocumentBuilder();
                    parser.setEntityResolver(new EntityResolver() {

                        public InputSource resolveEntity(String publicID, String systemID) throws SAXException {
                            InputStream is = null;
                            BufferedReader br = null;
                            String line;
                            StringWriter stringWriter = null;
                            StringReader stringReader = null;
                            try {
                                URI uri = new URI(systemID);
                                getLog().info("Resolving " + systemID + " locally from " + uri);
                                String filename = uri.toString().substring(uri.toString().lastIndexOf("/") + 1, uri.toString().length());
                                getLog().info("Resolved filename " + filename);
                                stringWriter = new StringWriter();
                                is = getClass().getClassLoader().getResourceAsStream(filename);
                                br = new BufferedReader(new InputStreamReader(is));
                                while (null != (line = br.readLine())) {
                                    stringWriter.write(line);
                                }
                                stringWriter.flush();
                                if (stringWriter != null) {
                                    stringWriter.close();
                                }
                                stringReader = new StringReader(stringWriter.getBuffer().toString());
                                return new InputSource(stringReader);
                            } catch (URISyntaxException e) {
                                getLog().error(e);
                            } catch (IOException e) {
                                getLog().error(e);
                            } finally {
                                try {
                                    if (br != null) {
                                        br.close();
                                    }
                                    if (is != null) {
                                        is.close();
                                    }
                                } catch (IOException e) {
                                    getLog().error(e);
                                }
                            }
                            // If no match, returning null makes process continue normally
                            return null;
                        }
                    });
                    parser.setErrorHandler(new ErrorHandler() {

                        public void warning(SAXParseException exception) throws SAXException {
                            getLog().warn(exception.getMessage());
                        }

                        public void fatalError(SAXParseException exception) throws SAXException {
                            getLog().warn(exception.getMessage());
                        }

                        public void error(SAXParseException exception) throws SAXException {
                            getLog().error(exception.getMessage());
                        }
                    });
                    Document document = parser.parse(serviceDescriptorFile);
                    // parse dom into service ids
                    ServiceIds serviceIds = ServiceIds.parse(document.getDocumentElement());
                    for (ServiceID serviceId : serviceIds.getIds()) {
                        String xml = "\r\n\t\t<antcall target=\"activate-service\">\r\n" + "\t\t\t<param name=\"service.id\" value=\"" + serviceId + "\" />\r\n" + "\t\t</antcall>\r\n";
                        // add this to the deployElements tail
                        deployElements.addLast(xml);
                        xml = "\r\n\t\t<antcall target=\"deactivate-service\">\r\n" + "\t\t\t<param name=\"service.id\" value=\"" + serviceId + "\" />\r\n" + "\t\t</antcall>\r\n";
                        // add this to the undeployElements head
                        undeployElements.addFirst(xml);
                    }
                } catch (Exception e) {
                    throw new MojoExecutionException("failed to parse service descriptor " + fileName, e);
                }
            }
        }
        // now lets glue everything and write the build.xml script
        String xml = header + "\r\n\t<property name=\"du.filename\" value=\"" + project.getBuild().getFinalName() + ".jar\" />\r\n" + "\r\n\t<target name=\"deploy-jmx\">\r\n" + "\r\n\t\t<antcall target=\"install-DU\" />\r\n";
        for (String s : deployElements) {
            xml += s;
        }
        xml += "\r\n\t</target>\r\n" + "\r\n\t<target name=\"undeploy-jmx\">\r\n";
        for (String s : undeployElements) {
            xml += s;
        }
        xml += footer;
        printWriter = new PrintWriter(new FileWriter(buildFile));
        printWriter.write(xml);
        getLog().info("build.xml generated in target dir");
    } catch (IOException e) {
        throw new MojoExecutionException("Error preparing the build.xml: " + e.getMessage(), e);
    } finally {
        IOUtil.close(printWriter);
    }
}
Example 95
Project: Mav-master  File: MavenProject.java View source code
public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException {
    List<String> list = new ArrayList<>(getArtifacts().size() + 1);
    String d = getBuild().getOutputDirectory();
    if (d != null) {
        list.add(d);
    }
    for (Artifact a : getArtifacts()) {
        if (a.getArtifactHandler().isAddedToClasspath()) {
            // TODO let the scope handler deal with this
            if (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_PROVIDED.equals(a.getScope()) || Artifact.SCOPE_SYSTEM.equals(a.getScope())) {
                addArtifactPath(a, list);
            }
        }
    }
    return list;
}
Example 96
Project: maven-master  File: MavenProject.java View source code
public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException {
    List<String> list = new ArrayList<>(getArtifacts().size() + 1);
    String d = getBuild().getOutputDirectory();
    if (d != null) {
        list.add(d);
    }
    for (Artifact a : getArtifacts()) {
        if (a.getArtifactHandler().isAddedToClasspath()) {
            // TODO let the scope handler deal with this
            if (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_PROVIDED.equals(a.getScope()) || Artifact.SCOPE_SYSTEM.equals(a.getScope())) {
                addArtifactPath(a, list);
            }
        }
    }
    return list;
}
Example 97
Project: oceano-master  File: MavenProject.java View source code
public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException {
    List<String> list = new ArrayList<String>(getArtifacts().size() + 1);
    String d = getBuild().getOutputDirectory();
    if (d != null) {
        list.add(d);
    }
    for (Artifact a : getArtifacts()) {
        if (a.getArtifactHandler().isAddedToClasspath()) {
            if (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_PROVIDED.equals(a.getScope()) || Artifact.SCOPE_SYSTEM.equals(a.getScope())) {
                addArtifactPath(a, list);
            }
        }
    }
    return list;
}
Example 98
Project: cloudtm-data-platform-master  File: DmlPostProcessorMojo.java View source code
@Override
protected List<String> getClasspathElements() {
    try {
        return getMavenProject().getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        getLog().error(e);
    }
    return null;
}
Example 99
Project: cxf-xjc-utils-master  File: TestXSDToJavaMojo.java View source code
protected List<String> getClasspathElements() throws DependencyResolutionRequiredException {
    return project.getTestClasspathElements();
}
Example 100
Project: werval-master  File: AbstractRunGoal.java View source code
protected final URL[] runtimeClassPath() throws DependencyResolutionRequiredException, MalformedURLException {
    Set<URL> classPathSet = new LinkedHashSet<>();
    for (String runtimeClassPathElement : project.getRuntimeClasspathElements()) {
        classPathSet.add(new File(runtimeClassPathElement).toURI().toURL());
    }
    return classPathSet.toArray(new URL[classPathSet.size()]);
}
Example 101
Project: grains-master  File: GenerateMojo.java View source code
@Override
List<String> getGeneratorClasspath() throws DependencyResolutionRequiredException {
    return getProject().getRuntimeClasspathElements();
}

Java Examples for org.joda.time.format.PeriodFormatter

The following java examples will help you to understand the usage of org.joda.time.format.PeriodFormatter. These source code samples are taken from different open source projects.

Example 1
Project: humanize-master  File: TestJodaTime.java View source code
@Test
public void periodFormat() {
    PeriodFormatter fmt = PeriodFormat.getDefault();
    Assert.assertEquals(new Period(0, 100000000).toString(fmt), "1 day, 3 hours, 46 minutes and 40 seconds");
    fmt = PeriodFormat.wordBased(new Locale("es"));
    Assert.assertEquals(new Period(0, 100000000).toString(fmt), "1 día, 3 horas, 46 minutos y 40 segundos");
    fmt = ISOPeriodFormat.standard();
    Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P1DT3H46M40S");
    fmt = ISOPeriodFormat.alternate();
    Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P00000001T034640");
    fmt = ISOPeriodFormat.alternateWithWeeks();
    Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P0000W0001T034640");
}
Example 2
Project: gobblin-master  File: TimeBasedSubDirDatasetsFinder.java View source code
/**
   * Return true iff input folder time is between compaction.timebased.min.time.ago and
   * compaction.timebased.max.time.ago.
   */
protected boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) {
    DateTime currentTime = new DateTime(this.timeZone);
    PeriodFormatter periodFormatter = getPeriodFormatter();
    DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter);
    DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter);
    if (folderTime.isBefore(earliestAllowedFolderTime)) {
        log.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping", inputFolder, folderTime, earliestAllowedFolderTime));
        return false;
    } else if (folderTime.isAfter(latestAllowedFolderTime)) {
        log.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping", inputFolder, folderTime, latestAllowedFolderTime));
        return false;
    } else {
        return true;
    }
}
Example 3
Project: jerseyoauth2-master  File: WebAppConfiguration.java View source code
private Duration parseDuration(String initParameter, Duration defaultDuration) {
    if (initParameter != null) {
        PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendHours().appendSuffix("h ").appendMinutes().appendSuffix("min").toFormatter();
        Period p = formatter.parsePeriod(initParameter);
        return p.toDurationFrom(DateTime.now());
    } else
        return defaultDuration;
}
Example 4
Project: solarnetwork-common-master  File: JodaPeriodFormatEditor.java View source code
@Override
public String getAsText() {
    Object val = getValue();
    if (val == null) {
        return null;
    }
    PeriodFormatter format = this.periodFormatters[0];
    if (val instanceof ReadablePeriod) {
        return format.print((ReadablePeriod) val);
    }
    throw new IllegalArgumentException("Unsupported period object [" + val.getClass() + "]: " + val);
}
Example 5
Project: cloudhopper-commons-master  File: UptimeMain.java View source code
public static void main(String[] args) {
    //Period period = new Period(uptime, PeriodType.standard().withYearsRemoved().withWeeksRemoved().withMonthsRemoved().withMillisRemoved());
    //MutablePeriod period = new Duration(uptime).toPeriod().toMutablePeriod();
    long uptime = UPTIME_56_SECS;
    // ah, ha -- this is super important -- need to normalize the period!
    PeriodType periodType = PeriodType.standard().withYearsRemoved().withMonthsRemoved().withWeeksRemoved().withMillisRemoved();
    Period period = new Period(uptime).normalizedStandard(periodType);
    System.out.println("Uptime: " + uptime + " ms");
    System.out.println("Weeks: " + period.getWeeks());
    System.out.println("Days: " + period.getDays());
    System.out.println("Millis: " + period.getMillis() + " ms");
    // print out the uptime
    String uptimeStyleString = PeriodFormatterUtil.getStandardUptimeStyle().print(period);
    String linuxStyleString = PeriodFormatterUtil.getLinuxUptimeStyle().print(period);
    System.out.println(uptimeStyleString);
    System.out.println(linuxStyleString);
    PeriodFormatter fmt = new PeriodFormatterBuilder().printZeroNever().appendDays().appendSuffix(" day ", " days ").appendHours().appendSuffix(" hours ").appendMinutes().appendSuffix(" mins ").printZeroAlways().appendSeconds().appendSuffix(" secs ").toFormatter();
    String str0 = fmt.print(period);
    System.out.println(str0);
    String str1 = PeriodFormat.getDefault().print(period);
    System.out.println(str1);
}
Example 6
Project: epicsarchiverap-master  File: InstanceReport.java View source code
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService) throws IOException {
    logger.info("Generating Instance report");
    resp.setContentType(MimeTypeConstants.APPLICATION_JSON);
    try (PrintWriter out = resp.getWriter()) {
        LinkedList<Map<String, String>> result = new LinkedList<Map<String, String>>();
        for (ApplianceInfo info : configService.getAppliancesInCluster()) {
            HashMap<String, String> applianceInfo = new HashMap<String, String>();
            result.add(applianceInfo);
            applianceInfo.put("instance", info.getIdentity());
            int pvCount = 0;
            for (@SuppressWarnings("unused") String pvName : configService.getPVsForThisAppliance()) {
                pvCount++;
            }
            applianceInfo.put("pvCount", Integer.toString(pvCount));
            // The getApplianceMetrics here is not a typo. We redisplay some of the appliance metrics in this page.
            JSONObject engineMetrics = GetUrlContent.getURLContentAsJSONObject(info.getEngineURL() + "/getApplianceMetrics");
            JSONObject etlMetrics = GetUrlContent.getURLContentAsJSONObject(info.getEtlURL() + "/getApplianceMetrics");
            JSONObject retrievalMetrics = GetUrlContent.getURLContentAsJSONObject(info.getRetrievalURL() + "/getApplianceMetrics");
            if (engineMetrics != null && etlMetrics != null && retrievalMetrics != null) {
                logger.debug("All of the components are working for " + info.getIdentity());
                applianceInfo.put("status", "Working");
            } else {
                logger.debug("At least one of the components is not working for " + info.getIdentity());
                StringWriter buf = new StringWriter();
                buf.append("Stopped - ");
                if (engineMetrics == null)
                    buf.append("engine ");
                if (etlMetrics == null)
                    buf.append("ETL ");
                if (retrievalMetrics == null)
                    buf.append("retrieval ");
                applianceInfo.put("status", buf.toString());
            }
            GetUrlContent.combineJSONObjects(applianceInfo, engineMetrics);
            GetUrlContent.combineJSONObjects(applianceInfo, etlMetrics);
            GetUrlContent.combineJSONObjects(applianceInfo, retrievalMetrics);
            long vmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
            Period vmInterval = new Period(vmStartTime, System.currentTimeMillis(), PeriodType.yearMonthDayTime());
            PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever().appendYears().appendSuffix(" year", " years").appendMonths().appendSuffix(" month", " months").appendDays().appendSuffix(" day", " days").appendSeparator(" ").printZeroAlways().appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
            applianceInfo.put("MGMT_uptime", formatter.print(new Period(vmInterval)));
            applianceInfo.put("errors", Integer.toString(0));
            applianceInfo.put("capacityUtilized", "N/A");
        }
        out.println(JSONValue.toJSONString(result));
    }
}
Example 7
Project: ho.la.urv-master  File: ReportActivity.java View source code
private void refresh(Evalos eva) {
    PeriodFormatter HHMMFormater = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendHours().appendSeparator(":").appendMinutes().toFormatter();
    long accumulatedBalance = 0;
    // Fill Monday
    mReportTableMondayTheoretical.setText(eva.getDay(Day.MONDAY).getShiftDisplay());
    if (Day.today() >= Day.MONDAY) {
        Period mondayReal = eva.getDay(Day.MONDAY).getAccumulate();
        if (mondayReal != null) {
            mReportTableMondayReal.setText(HHMMFormater.print(mondayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.MONDAY).getShiftDisplay(), HHMMFormater.print(mondayReal));
            mReportTableMondayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Tuesday
    mReportTableTuesdayTheoretical.setText(eva.getDay(Day.TUESDAY).getShiftDisplay());
    if (Day.today() >= Day.TUESDAY) {
        Period tuesdayReal = eva.getDay(Day.TUESDAY).getAccumulate();
        if (tuesdayReal != null) {
            mReportTableTuesdayReal.setText(HHMMFormater.print(tuesdayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.TUESDAY).getShiftDisplay(), HHMMFormater.print(tuesdayReal));
            mReportTableTuesdayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Wednesday
    mReportTableWednesdayTheoretical.setText(eva.getDay(Day.WEDNESDAY).getShiftDisplay());
    if (Day.today() >= Day.WEDNESDAY) {
        Period wednesdayReal = eva.getDay(Day.WEDNESDAY).getAccumulate();
        if (wednesdayReal != null) {
            mReportTableWednesdayReal.setText(HHMMFormater.print(wednesdayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.WEDNESDAY).getShiftDisplay(), HHMMFormater.print(wednesdayReal));
            mReportTableWednesdayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Thursday
    mReportTableThursdayTheoretical.setText(eva.getDay(Day.THURSDAY).getShiftDisplay());
    if (Day.today() >= Day.THURSDAY) {
        Period thursdayReal = eva.getDay(Day.THURSDAY).getAccumulate();
        if (thursdayReal != null) {
            mReportTableThursdayReal.setText(HHMMFormater.print(thursdayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.THURSDAY).getShiftDisplay(), HHMMFormater.print(thursdayReal));
            mReportTableThursdayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Friday
    mReportTableFridayTheoretical.setText(eva.getDay(Day.FRIDAY).getShiftDisplay());
    if (Day.today() >= Day.FRIDAY) {
        Period fridayReal = eva.getDay(Day.FRIDAY).getAccumulate();
        if (fridayReal != null) {
            mReportTableFridayReal.setText(HHMMFormater.print(fridayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.FRIDAY).getShiftDisplay(), HHMMFormater.print(fridayReal));
            mReportTableFridayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Saturday
    mReportTableSaturdayTheoretical.setText(eva.getDay(Day.SATURDAY).getShiftDisplay());
    if (Day.today() >= Day.SATURDAY) {
        Period saturdayReal = eva.getDay(Day.SATURDAY).getAccumulate();
        if (saturdayReal != null) {
            mReportTableSaturdayReal.setText(HHMMFormater.print(saturdayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.SATURDAY).getShiftDisplay(), HHMMFormater.print(saturdayReal));
            mReportTableSaturdayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
    // Fill Sunday
    mReportTableSundayTheoretical.setText(eva.getDay(Day.SUNDAY).getShiftDisplay());
    if (Day.today() >= Day.SUNDAY) {
        Period sundayReal = eva.getDay(Day.SUNDAY).getAccumulate();
        if (sundayReal != null) {
            mReportTableSundayReal.setText(HHMMFormater.print(sundayReal));
            accumulatedBalance += eva.computeBalance(eva.getDay(Day.SUNDAY).getShiftDisplay(), HHMMFormater.print(sundayReal));
            mReportTableSundayBalance.setText(milisToDisplayTime(accumulatedBalance));
        }
    }
}
Example 8
Project: molgenis-master  File: ProgressImpl.java View source code
@Override
public void success() {
    jobExecution.setEndDate(new Date());
    jobExecution.setStatus(SUCCESS);
    jobExecution.setProgressInt(jobExecution.getProgressMax());
    Duration yourDuration = Duration.millis(timeRunning());
    Period period = yourDuration.toPeriod();
    PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendMinutes().appendSuffix("m ").appendSeconds().appendSuffix("s ").appendMillis().appendSuffix("ms ").toFormatter();
    String timeSpent = periodFormatter.print(period);
    JOB_EXECUTION_LOG.info("Execution successful. Time spent: {}", timeSpent);
    sendEmail(jobExecution.getSuccessEmail(), jobExecution.getType() + " job succeeded.", jobExecution.getLog());
    update();
    JobExecutionContext.unset();
}
Example 9
Project: RedReader-master  File: RRTime.java View source code
public static String formatDurationFrom(final Context context, final long startTime) {
    final String space = " ";
    final String comma = ",";
    final String separator = comma + space;
    final long endTime = utcCurrentTimeMillis();
    final DateTime dateTime = new DateTime(endTime);
    final DateTime localDateTime = dateTime.withZone(DateTimeZone.getDefault());
    Period period = new Duration(startTime, endTime).toPeriodTo(localDateTime);
    PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendYears().appendSuffix(space).appendSuffix(context.getString(R.string.time_year), context.getString(R.string.time_years)).appendSeparator(separator).appendMonths().appendSuffix(space).appendSuffix(context.getString(R.string.time_month), context.getString(R.string.time_months)).appendSeparator(separator).appendDays().appendSuffix(space).appendSuffix(context.getString(R.string.time_day), context.getString(R.string.time_days)).appendSeparator(separator).appendHours().appendSuffix(space).appendSuffix(context.getString(R.string.time_hour), context.getString(R.string.time_hours)).appendSeparator(separator).appendMinutes().appendSuffix(space).appendSuffix(context.getString(R.string.time_min), context.getString(R.string.time_mins)).appendSeparator(separator).appendSeconds().appendSuffix(space).appendSuffix(context.getString(R.string.time_sec), context.getString(R.string.time_secs)).appendSeparator(separator).appendMillis().appendSuffix(space).appendSuffix(context.getString(R.string.time_ms)).toFormatter();
    String duration = periodFormatter.print(period.normalizedStandard(PeriodType.yearMonthDayTime()));
    List<String> parts = Arrays.asList(duration.split(comma));
    if (parts.size() >= 2) {
        duration = parts.get(0) + comma + parts.get(1);
    }
    return String.format(context.getString(R.string.time_ago), duration);
}
Example 10
Project: spring-rest-server-master  File: HeaderUtil.java View source code
private Period getSessionMaxAge() {
    String maxAge = environment.getRequiredProperty("auth.session.maxAge");
    PeriodFormatter format = new PeriodFormatterBuilder().appendDays().appendSuffix("d", "d").printZeroRarelyFirst().appendHours().appendSuffix("h", "h").printZeroRarelyFirst().appendMinutes().appendSuffix("m", "m").toFormatter();
    Period sessionMaxAge = format.parsePeriod(maxAge);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Session maxAge is: " + formatIfNotZero(sessionMaxAge.getDays(), "days", "day") + formatIfNotZero(sessionMaxAge.getHours(), "hours", "hour") + formatIfNotZero(sessionMaxAge.getMinutes(), "minutes", "minute"));
    }
    return sessionMaxAge;
}
Example 11
Project: bennu-vaadin-master  File: VaadinProxiesCodeGeneratorTask.java View source code
@Override
public void execute() throws BuildException {
    super.execute();
    DateTime start = new DateTime();
    final Properties properties = new MultiProperty();
    try {
        properties.load(new FileInputStream(buildDir.getAbsolutePath() + "/WEB-INF/classes/configuration.properties"));
        File timestampFile = new File(srcBaseDir, "vaadin-timestamp");
        long latestBuildTime = srcBaseDir != null ? srcBaseDir.lastModified() : 0;
        boolean shouldCompile = false;
        // final String preInitClassnames =
        // properties.getProperty("pre.init.classnames");
        // System.out.println("Pre-init class names: " + preInitClassnames);
        // if (preInitClassnames != null) {
        // final String[] classnames = preInitClassnames.split(",");
        // for (final String classname : classnames) {
        // if (classname != null && !classname.isEmpty()) {
        // try {
        // Class.forName(classname.trim());
        // } catch (final ClassNotFoundException e) {
        // throw new Error(e);
        // }
        // }
        // }
        // }
        List<URL> domainModelURLs = new ArrayList<URL>();
        for (FileSet fileset : filesets) {
            if (fileset.getDir().exists()) {
                DirectoryScanner scanner = fileset.getDirectoryScanner(getProject());
                String[] includedFiles = scanner.getIncludedFiles();
                for (String includedFile : includedFiles) {
                    String filePath = fileset.getDir().getAbsolutePath() + "/" + includedFile;
                    File file = new File(filePath);
                    boolean isModified = file.lastModified() > latestBuildTime;
                    // System.out.println(includedFile + " : " + (isModified
                    // ? "not up to date" : "up to date"));
                    domainModelURLs.add(new File(filePath).toURI().toURL());
                    shouldCompile = shouldCompile || isModified;
                }
            }
        }
        // first, get the domain model
        DomainModel model = DomainModelParser.getDomainModel(domainModelURLs, false);
        VaadinProxiesCodeGenerator generator = new VaadinProxiesCodeGenerator(model, srcBaseDir, vaadinSrcDir, packageSourceLocations);
        generator.generate();
        timestampFile.delete();
        timestampFile.createNewFile();
    // } else {
    // System.out.println("All dml files are up to date, skipping generation");
    // }
    } catch (IOException e) {
        throw new BuildException(e);
    } catch (JClassAlreadyExistsException e) {
        throw new BuildException(e);
    }
    Duration processingTime = new Duration(start, new DateTime());
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix("m").appendSeconds().appendSuffix("s").toFormatter();
    System.out.println("Vaadin Generation Took: " + formatter.print(processingTime.toPeriod()));
}
Example 12
Project: my-ministry-assistant-master  File: Helper.java View source code
public static String getMinuteDuration(Cursor cursor) {
    SimpleDateFormat saveDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    Calendar start = Calendar.getInstance(Locale.getDefault());
    Calendar end = Calendar.getInstance(Locale.getDefault());
    Duration dur = new Duration(new DateTime(start), new DateTime(start));
    Duration durchange = new Duration(new DateTime(start), new DateTime(start));
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        try {
            start.setTime(saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_START))));
        } catch (Exception e) {
            start = Calendar.getInstance(Locale.getDefault());
        }
        try {
            end.setTime(saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_END))));
        } catch (Exception e) {
            end = Calendar.getInstance(Locale.getDefault());
        }
        durchange = new Duration(new DateTime(start), new DateTime(end));
        dur = dur.withDurationAdded(durchange, 1);
    }
    cursor.close();
    PeriodFormatter retVal = new PeriodFormatterBuilder().printZeroAlways().appendMinutes().toFormatter();
    return retVal.print(dur.toPeriod());
}
Example 13
Project: prissma-master  File: ContextUnit.java View source code
/**
	 * Retrieves the specified property value from the context unit.
	 * Used by GEO and TIME context units.
	 * @param prop
	 * @return
	 * @throws ContextUnitException
	 */
public double getComplexCtxUnitProp(Property prop) throws ContextUnitException {
    if (!instance.isResource())
        throw new ContextUnitException();
    if (this.type != CtxUnitType.GEO && this.type != CtxUnitType.TIME && instance.isResource())
        throw new ContextUnitException();
    else {
        Statement stat = ((Resource) instance).getProperty(prop);
        if (stat == null)
            throw new ContextUnitException();
        // TIME conversions
        if (prop.equals(PrissmaProperties.pStart)) {
            String timeStr = stat.getLiteral().getString();
            DateTimeFormatter dtf = ISODateTimeFormat.timeParser();
            // UTC by default
            DateTime startTime = dtf.withZone(DateTimeZone.UTC).parseDateTime(timeStr);
            long millis = startTime.getMillis();
            long seconds = millis / 1000;
            return seconds;
        } else if (prop.equals(PrissmaProperties.pDuration)) {
            String durationStr = stat.getLiteral().getString();
            PeriodFormatter pf = ISOPeriodFormat.standard();
            Period period = pf.parsePeriod(durationStr);
            int seconds = period.toStandardSeconds().getSeconds();
            return seconds;
        }
        return stat.getLiteral().getDouble();
    }
}
Example 14
Project: BudgetForce2-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 15
Project: csv2rdf4lod-automation-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 16
Project: D-MARLA-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 17
Project: fenixedu-ist-teacher-service-master  File: DistributionTeacherServicesByCourseDTO.java View source code
public String getDescription() {
    StringBuilder finalString = new StringBuilder(teacherUsername);
    finalString.append(" - ");
    finalString.append(teacherName);
    finalString.append(" - ");
    PeriodFormatter periodFormatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendHours().appendSuffix(":").appendMinutes().toFormatter();
    finalString.append(periodFormatter.print(getTimeSpentByTeacher().toPeriod()));
    return finalString.toString();
}
Example 18
Project: Ginkou-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 19
Project: h2o-3-master  File: PrettyPrint.java View source code
public static String toAge(Date from, Date to) {
    if (from == null || to == null)
        return "N/A";
    final Period period = new Period(from.getTime(), to.getTime());
    DurationFieldType[] dtf = new ArrayList<DurationFieldType>() {

        {
            add(DurationFieldType.years());
            add(DurationFieldType.months());
            add(DurationFieldType.days());
            if (period.getYears() == 0 && period.getMonths() == 0 && period.getDays() == 0) {
                add(DurationFieldType.hours());
                add(DurationFieldType.minutes());
            }
        }
    }.toArray(new DurationFieldType[0]);
    PeriodFormatter pf = PeriodFormat.getDefault();
    return pf.print(period.normalizedStandard(PeriodType.forFields(dtf)));
}
Example 20
Project: jacclog-master  File: AnalyzeLogEntriesShellCommand.java View source code
private void analyzeEntries() {
    if (service != null) {
        final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");
        final DateTime from = format.parseDateTime(this.from);
        final DateTime to = (this.to != null) ? format.parseDateTime(this.to) : from.plusDays(1);
        final Interval interval = new Interval(from, to);
        final Period period = interval.toPeriod();
        final StringBuffer buffer = new StringBuffer();
        buffer.append("Analyse the log entries from '");
        buffer.append(from.toString()).append('\'');
        buffer.append(" to '").append(to);
        // print the period
        final String space = " ";
        buffer.append("'. The period includes ");
        final PeriodFormatter dateFormat = new PeriodFormatterBuilder().appendYears().appendSuffix(" year", " years").appendSeparator(space).appendMonths().appendSuffix(" month", " months").appendSeparator(space).appendWeeks().appendSuffix(" week", " weeks").appendSeparator(space).appendDays().appendSuffix(" day", " days").appendSeparator(space).appendHours().appendSuffix(" hour", " hours").appendSeparator(space).appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(space).toFormatter();
        dateFormat.printTo(buffer, period);
        buffer.append('.');
        System.out.println(buffer.toString());
        final long maxResults = service.count(interval);
        if (maxResults > 0) {
            int maxCount = 0;
            if (proceed(maxResults)) {
                final long startTime = System.currentTimeMillis();
                final LogEntryAnalysisResult result = analyzerService.analyze(interval).toResult();
                final Map<UserAgentInfo, AtomicInteger> stats = result.getUserAgentInfos();
                System.out.println("User agent information count: " + stats.size());
                String name;
                String osName;
                int count;
                for (final Entry<UserAgentInfo, AtomicInteger> entry : stats.entrySet()) {
                    name = entry.getKey().getName();
                    osName = entry.getKey().getOsName();
                    count = entry.getValue().get();
                    maxCount += count;
                    System.out.println(name + " (" + osName + ") \t" + count);
                }
                System.out.println("Sum: " + maxCount);
                final long elapsedTime = System.currentTimeMillis() - startTime;
                final Period p = new Period(elapsedTime);
                System.out.println("Total processing time: " + p.toString(FORMATTER));
            }
        } else {
            System.out.println("There is nothing to analyze.");
        }
    }
}
Example 21
Project: joda-time-master  File: Interval.java View source code
/**
     * Parses a [email protected] Interval} from the specified string, using any offset it contains.
     * <p>
     * The String formats are described by
     * [email protected] ISODateTimeFormat#dateTimeParser()[email protected] .withOffsetParsed()}
     * and [email protected] ISOPeriodFormat#standard()}, and may be 'datetime/datetime',
     * 'datetime/period' or 'period/datetime'.
     * <p>
     * Sometimes this method and [email protected] new Interval(str)} return different results.
     * This can be confusing as the difference is not visible in [email protected] #toString()}.
     * <p>
     * When passed a string without an offset, such as '2010-06-30T01:20/P1D',
     * both the constructor and this method use the default time-zone.
     * As such, [email protected] Interval.parseWithOffset("2010-06-30T01:20/P1D")} and
     * [email protected] new Interval("2010-06-30T01:20/P1D"))} are equal.
     * <p>
     * However, when this method is passed a string with an offset,
     * the offset is directly parsed and stored.
     * As such, [email protected] Interval.parseWithOffset("2010-06-30T01:20+02:00/P1D")} and
     * [email protected] new Interval("2010-06-30T01:20+02:00/P1D"))} are NOT equal.
     * The object produced via this method has a zone of [email protected] DateTimeZone.forOffsetHours(2)}.
     * The object produced via the constructor has a zone of [email protected] DateTimeZone.getDefault()}.
     * 
     * @param str  the string to parse, not null
     * @since 2.9
     */
public static Interval parseWithOffset(String str) {
    int separator = str.indexOf('/');
    if (separator < 0) {
        throw new IllegalArgumentException("Format requires a '/' separator: " + str);
    }
    String leftStr = str.substring(0, separator);
    if (leftStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }
    String rightStr = str.substring(separator + 1);
    if (rightStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }
    DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
    PeriodFormatter periodParser = ISOPeriodFormat.standard();
    DateTime start = null;
    Period period = null;
    // before slash
    char c = leftStr.charAt(0);
    if (c == 'P' || c == 'p') {
        period = periodParser.withParseType(PeriodType.standard()).parsePeriod(leftStr);
    } else {
        start = dateTimeParser.parseDateTime(leftStr);
    }
    // after slash
    c = rightStr.charAt(0);
    if (c == 'P' || c == 'p') {
        if (period != null) {
            throw new IllegalArgumentException("Interval composed of two durations: " + str);
        }
        period = periodParser.withParseType(PeriodType.standard()).parsePeriod(rightStr);
        return new Interval(start, period);
    } else {
        DateTime end = dateTimeParser.parseDateTime(rightStr);
        if (period != null) {
            return new Interval(period, end);
        } else {
            return new Interval(start, end);
        }
    }
}
Example 22
Project: Moola-master  File: TempTest.java View source code
public static void main(String[] args) {
    DateTime todayDateObj = new DateTime(2014, 8, 9, 0, 0, 0);
    DateTime backDaysObj = todayDateObj.minusDays(9);
    DateTime backMonthObj = backDaysObj.minusMonths(10);
    DateTime backYearObj = backMonthObj.minusYears(10);
    System.out.println(todayDateObj);
    System.out.println(backDaysObj);
    System.out.println(backMonthObj);
    System.out.println(backYearObj);
    System.out.println(backYearObj.plusYears(10).plusMonths(10).plusDays(9));
//        DateTimeZone zone = DateTimeZone.forID("America/Argentina/San_Luis");
//        System.out.println(zone.getShortName(System.currentTimeMillis()));
//        System.out.println(LONDON.getShortName(System.currentTimeMillis()));
//        System.out.println(PARIS.getShortName(System.currentTimeMillis()));
//        System.out.println(NEWYORK.getShortName(System.currentTimeMillis()));
//          
//        for (String id : DateTimeZone.getAvailableIDs()) {
//            DateTimeZone z = DateTimeZone.forID(id);
//            String str = z.getShortName(System.currentTimeMillis());
//            String str2 = z.getName(System.currentTimeMillis());
//            if (str.startsWith("+") || str.startsWith("-")) {
//                System.out.println(z + " " + str + " " + str2 + " " + z.getNameKey(System.currentTimeMillis()));
//                System.out.println(DateTimeFormat.forPattern("z Z").withZone(z).print(System.currentTimeMillis()));
//            }
//        }
//        Locale.setDefault(Locale.FRENCH);
//        
//        PeriodFormatter f1 = PeriodFormat.getDefault();
//        PeriodFormatter f2 = PeriodFormat.wordBased();
//        PeriodFormatter f3 = PeriodFormat.wordBased(Locale.GERMAN);
//        String str1 = f1.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3));
//        String str2 = f2.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3));
//        String str3 = f3.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3));
//        System.out.println(str1);
//        System.out.println(str2);
//        System.out.println(str3);
////        DateTimeFormatter formatter = DateTimeFormat.forPattern("'added' MMMM dd yyyy 'at' HH:mm").withZoneUTC();
//        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
//            .appendLiteral("added ")
//            .appendMonthOfYearText()
//            .appendLiteral(' ')
//            .appendDayOfMonth(2)
//            .appendLiteral(' ')
//            .appendYear(4, 4)
//            .appendLiteral(" at ")
////            .append(DateTimeFormat.forPattern("HH:mm"))
//            .appendHourOfDay(2)
//            .appendLiteral(":")
//            .appendMinuteOfDay(2)
//            .toFormatter()
//            .withZoneUTC();
//
//        String s1 = "added December 11 2014 at 05:45";
//        String s2 = "added December 11 2014 at 14:45";
//    
//        DateTime date1 = DateTime.parse(s1, formatter);
//        DateTime date2 = DateTime.parse(s2, formatter);
//    
//        System.out.println(date1);
//        System.out.println(date2);
//        DateTimeZone MST = DateTimeZone.forID("MST");
//        DateTime start = new DateTime(2014, 8, 12, 9, 0, MST);
//        DateTime past1 = new DateTime(MST).minusDays(2);
//        DateTime later1 = past1.plusSeconds((int) new Duration(past1, start).getStandardSeconds());
//        System.out.println(past1);
//        System.out.println(start);
//        System.out.println(new Period(past1, start));
//        System.out.println(later1);
//        DateTime past2 = past1.withMillisOfSecond(0);
//        DateTime later2 = past2.plusSeconds((int) new Duration(past2, start).getStandardSeconds());
//        System.out.println(later2);
//        Locale poland = new Locale("pl", "PL");
//        DateTimeFormatter a = DateTimeFormat.forStyle("S-").withLocale(poland);
//        DateTimeFormatter b = DateTimeFormat.forStyle("M-").withLocale(poland);
//        System.out.println(a.print(0));
//        System.out.println(b.print(0));
//        
//        DateFormat e = DateFormat.getDateInstance(DateFormat.SHORT, poland);
//        System.out.println(e.format(new Date()));
//        DateFormat f = DateFormat.getDateInstance(DateFormat.MEDIUM, poland);
//        System.out.println(f.format(new Date()));
//        LocalDate start = new LocalDate(2014, 7, 31);
//        LocalDate end = new LocalDate(2014, 9, 17);
//        Period p = Period.fieldDifference(start, end);
//        LocalDate recalculatedEnd = start.plus(p);
//        System.out.println(p);
//        System.out.println(end);
//        System.out.println(recalculatedEnd);
//        DateTime tomorrow = new DateTime().plusDays(1);
//
//        Interval i1 = new Interval(today, today);
//        Interval i2 = new Interval(today, tomorrow);
//        Interval i3 = new Interval(tomorrow, tomorrow);
//        
//        System.out.println(i1);
//        System.out.println(i2);
//        System.out.println(i3);
//
//        if (i1.isBefore(i2)) System.out.println("i1 before i2"); // "i1 before i2"
//        if (i2.isBefore(i1)) System.out.println("i2 before i1"); // ""
//        if (i2.isBefore(i3)) System.out.println("i2 before i3"); // "i2 before i3"
//        TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
//        DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles"));
//        Calendar cLocal = Calendar.getInstance();
//        cLocal.set(2014, 0, 31, 16, 0, 0);
//        cLocal.set(Calendar.MILLISECOND, 0);
//        System.out.format("Local.instant=%d\n", cLocal.getTimeInMillis()); //output: 1391212800000
//
//        Calendar cUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
//        cUTC.set(2014, 1, 1, 0, 0, 0);
//        cUTC.set(Calendar.MILLISECOND, 0);
//        System.out.format("UTC.instant=%d\n", cUTC.getTimeInMillis()); //output: 1391212800000
//
//        LocalDate local = new LocalDate(cLocal.getTimeInMillis());
//        System.out.println(local + " " + local.getLocalMillis());
//        System.out.format("local=%s .instant=%d\n", local.toString(), local.toDate().getTime()); //output: local=2014-01-31 .instant=1391155200000
//        LocalDate utc = new LocalDate(cUTC.getTimeInMillis(), DateTimeZone.UTC);
//        System.out.println(utc + " " + utc.getLocalMillis());
//        System.out.format("utc=%s .instant=%d\n", utc.toString(), utc.toDate().getTime());//output: utc=2014-02-01 .instant=1391241600000
//
//        Period p1 = Period.fieldDifference(utc,local);
//        Period p = p1.normalizedStandard(PeriodType.millis()); //java.lang.ArithmeticException: Value cannot fit in an int: 2592000000
//        DateTimeZone zone = DateTimeZone.forOffsetMillis(p.getMillis());
//        Assert.assertEquals(DateTimeZone.forOffsetHours(-8), zone);        
//        
//        DateTime dtLocal = new DateTime(2014, 1, 31, 16, 00); //server time
//        DateTime dtUTC = new DateTime(2014, 2, 1, 0, 0, DateTimeZone.UTC); //Assume UTC = server+8 hours (actual code uses DateTime.now(DateTimeZone.UTC))
//        LocalDate local = dtLocal.toLocalDate();
//        LocalDate utc = dtUTC.toLocalDate();
//        System.out.println(local);
//        System.out.println(utc);
//
//        Period p = Period.fieldDifference(utc,local).normalizedStandard(PeriodType.millis()); //Throws a java.lang.ArithmeticException: Value cannot fit in an int: xx        
//        System.out.println(p);
//        DateTime dtLocal = new DateTime(2014, 1, 31, 15, 59); //Server time
//        DateTime dtUTC = new DateTime(2014, 1, 31, 12, 59, DateTimeZone.UTC); //Assume UTC = server+8 hours (actual code uses DateTime.now(DateTimeZone.UTC))
//
//        LocalDate local = dtLocal.toLocalDate();
//        LocalDate utc = dtUTC.toLocalDate();
//
//        Period p = Period.fieldDifference(utc,local).normalizedStandard(PeriodType.millis());        
//        
//        DateTimeZone timeZone = DateTimeZone.forID("America/Havana");
//        long milli = 1352005199998L;
//        MutableDateTime dt = new MutableDateTime(milli, timeZone);
//        // now dt is 2012-11-04T00:59:59.998-04:00
//
//        int year = dt.getYear(); // 2012
//        int month = dt.getMonthOfYear(); // 11
//        int day = dt.getDayOfMonth(); // 4
//
//        Interval theDay = new LocalDate(year, month, day).toInterval(timeZone);
//        // theDay is 2012-11-04T00:00:00.000-05:00/2012-11-05T00:00:00.000-05:00,
//        // which does not include dt.
//        System.out.println(theDay);
//
//        Interval lastDay = new LocalDate(year, month, day-1).toInterval(timeZone);
//        // lastDay is 2012-11-03T00:00:00.000-04:00/2012-11-04T00:00:00.000-05:00
//        // i.e. joda thinks that 2012-11-04T00:59:59.998-04:00 is an instance of 2012-11-3
//        // instead of 2012-11-04
//        System.out.println(lastDay);
//        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
//        DateTimeZone.setDefault(DateTimeZone.forOffsetHoursMinutes(5, 30));
//        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy").withZoneUTC();
//        DateTime dateTime = DateTime.parse("10/06/2014", dateTimeFormatter).toDateTime(DateTimeZone.UTC);
//        System.out.println(dateTime.getZone());
//        long value = dateTime.getMillis()/1000;
//        System.out.println(dateTime);
//        System.out.println(value);
//        System.out.println(new Date(value * 1000));
//        parseDate("dd/MM/yyyy", "10/06/2014") giving me 1402338600
//        which is
//        GMT: Mon, 09 Jun 2014 18:30:00 GMT
//        Your time zone: 6/10/2014 12:00:00 AM GMT+5.5        
//        System.out.println(new LocalDate(ISOChronology.getInstanceUTC()));
//        System.out.println(new LocalDate(CopticChronology.getInstanceUTC()));
//        System.out.println(new LocalDate(EthiopicChronology.getInstanceUTC()));
//        
//        LocalDate coptic = new LocalDate(1, 1, 1, CopticChronology.getInstanceUTC());
//        System.out.println(coptic);
//        System.out.println(coptic.toDateTimeAtStartOfDay(DateTimeZone.UTC).withChronology(ISOChronology.getInstanceUTC()).toLocalDate());
//        
//        LocalDate ethiopic = new LocalDate(1, 1, 1, EthiopicChronology.getInstanceUTC());
//        System.out.println(ethiopic);
//        System.out.println(ethiopic.toDateTimeAtStartOfDay(DateTimeZone.UTC).withChronology(ISOChronology.getInstanceUTC()).toLocalDate());
//        DateTimeZone tz = DateTimeZone.forID("America/Argentina/Buenos_Aires");
//        DateTimeZone.setDefault(tz);
//        DateTimeFormatter df = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss zzz");
//
//        df.parseMillis(df.print(System.currentTimeMillis()));
//        DateTimeZone branco = DateTimeZone.forID("America/Rio_Branco");
//        System.out.println(branco);
//        Instant old = new Instant(0L);
//        Instant i = new Instant(branco.nextTransition(old.getMillis()));
//        while (old.equals(i) == false) {
//            System.out.println(i);
//            old = i;
//            i = new Instant(branco.nextTransition(old.getMillis()));
//        }
//        
//        DateTime dt = new DateTime(2008, 6, 23, 23, 0, branco);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        dt = dt.plusMinutes(30);
//        System.out.println(dt);
//        DateTimeZone HONG_KONG_TZ = DateTimeZone.forID("Asia/Hong_Kong");
//        DateTime date1 = new DateTime(2013, 10, 2, 11, 30, 53, 512, HONG_KONG_TZ);
//        DateTime date2 = date1.toDateTime(DateTimeZone.UTC);
//        System.out.println(date1);
//        System.out.println(date2);
//
//        System.out.println(date1.compareTo(date2));
//        System.out.println(date1.toLocalDate().compareTo(date2.toLocalDate()));
//        System.out.println(DateTimeComparator.getInstance().compare(date1, date2));
//        System.out.println(DateTimeComparator.getDateOnlyInstance().compare(date1, date2));
//        System.out.println(DateTimeComparator.getDateOnlyInstance().compare(date1, date1.plusMinutes(1)));
//        TimeZone jdkMST = TimeZone.getTimeZone("MST");
//        TimeZone jdkDenver = TimeZone.getTimeZone("America/Denver");
//        DateTimeZone mst = DateTimeZone.forTimeZone(jdkMST);
//        DateTimeZone mst2 = DateTimeZone.forID(jdkMST.getID());
//        System.out.println(jdkMST);
//        jdkMST.setID("America/Denver");
//        System.out.println(jdkMST);
//        System.out.println(jdkDenver);
//        System.out.println(jdkDenver.equals(jdkMST));
//        System.out.println(jdkMST.getID());
//        System.out.println(mst.getID() + (mst.isFixed() ? " Fixed" : " DST"));
//        System.out.println(mst2.getID() + (mst2.isFixed() ? " Fixed" : " DST"));
//        DateTimeZone m = DateTimeZone.forID("MST7MDT");
//        System.out.println(m + (m.isFixed() ? " Fixed" : " DST"));
//        System.out.println(DateTimeFormat.forPattern("s").print(321234));
//        System.out.println(DateTimeFormat.forPattern("ss").print(321234));
//        System.out.println(DateTimeFormat.forPattern("sss").print(321234));
//        System.out.println(DateTimeFormat.forPattern("S").print(321234));
//        System.out.println(DateTimeFormat.forPattern("SS").print(321234));
//        System.out.println(DateTimeFormat.forPattern("SSS").print(321234));
//        System.out.println(DateTimeFormat.forPattern("SSSS").print(321234));
//        
//        DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK);
//        MutableDateTime result = new MutableDateTime(2000, 1, 1, 0, 0, 0, 0, NEWYORK);
//        System.out.println("4 = " + f.parseInto(result, "2 29", 0));
//        System.out.println("" + new MutableDateTime(2000, 2, 29, 0, 0, 0, 0, NEWYORK) + " = " + result);        
//        Chronology chronology = GJChronology.getInstance();
//
//        LocalDate start = new LocalDate(2013, 5, 31, chronology);
//        LocalDate expectedEnd = new LocalDate(-1, 5, 31, chronology); // 1 BC
////        System.out.println(expectedEnd.plusYears(2013).equals(start));
//        System.out.println(start.minusYears(2013).equals(expectedEnd));
////        System.out.println(start.plus(Period.years(-2013)).equals(expectedEnd));
//        Period p1 = new Period(5L, PeriodType.hours());
//        System.out.println(p1);
//        String string = p1.toString();
//        System.out.println(string);
//        Period p2 = Period.parse(string);
//        System.out.println(p2);
//        Locale.setDefault(Locale.CHINA);
//        TimeZone sTimeZone = java.util.TimeZone.getTimeZone("GMT-01:00");
//        System.out.println(Locale.getDefault());
//        System.out.println(sTimeZone.getDisplayName());
//        DateTimeZone dtz = DateTimeZone.forTimeZone(sTimeZone);
//        System.out.println(dtz.getID());        
//        DateTime n = DateTime.now();
//        final DateTime now = n.toDateTimeISO();
//        final DateTime parsed = DateTime.parse(now.toString()).withZone(null);
//        final DateTime parsed2 = new DateTime(now.toString());
//        System.out.println(now.getZone() + " " +  parsed.getZone());
//        System.out.println(now + " " +  parsed);
//        System.out.println(now.getZone() + " " +  parsed2.getZone());
//        System.out.println(now + " " +  parsed2);
//        
//        MutableDateTime time = new MutableDateTime(DateTimeZone.forOffsetHours(1));
////        time.setZone(DateTimeZone.forOffsetHours(1));
//        time.setRounding(time.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR);
//
//        MutableDateTime utcTime = new MutableDateTime(DateTimeZone.UTC);
//        utcTime.setRounding(utcTime.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR);
//
//        time.setMillis(90000);
//        utcTime.setMillis(90000);
//        System.out.println("time: " + time + ", utc " + utcTime);
//        System.out.println("time_millis: " + time.getMillis() + ", utc_millis " + utcTime.getMillis());
//        
////        MutableDateTime time = new MutableDateTime(DateTimeZone.forOffsetHours(1));
//////        time.setZone(DateTimeZone.forOffsetHours(1));
////        time.setRounding(time.getChronology().minuteOfHour(), MutableDateTime.ROUND_FLOOR);
////
////        MutableDateTime utcTime = new MutableDateTime(DateTimeZone.UTC);
////        utcTime.setRounding(utcTime.getChronology().minuteOfHour(), MutableDateTime.ROUND_FLOOR);
////
////        time.setMillis(90000);
////        utcTime.setMillis(90000);
////        System.out.println("time: " + time + ", utc " + utcTime);
////        System.out.println("time_millis: " + time.getMillis() + ", utc_millis " + utcTime.getMillis());
}
Example 23
Project: TCSlackNotifierPlugin-master  File: SlackServerAdapter.java View source code
private void postFailureBuild(SRunningBuild build) {
    String message = "";
    PeriodFormatter durationFormatter = new PeriodFormatterBuilder().printZeroRarelyFirst().appendHours().appendSuffix(" hour", " hours").appendSeparator(" ").printZeroRarelyLast().appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(" and ").appendSeconds().appendSuffix(" second", " seconds").toFormatter();
    Duration buildDuration = new Duration(1000 * build.getDuration());
    message = String.format("Project '%s' build failed! ( %s )", build.getFullName(), durationFormatter.print(buildDuration.toPeriod()));
    postToSlack(build, message, false);
}
Example 24
Project: TinyTravelTracker-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 25
Project: VarexJ-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 26
Project: way-master  File: StringConverter.java View source code
//-----------------------------------------------------------------------
/**
     * Extracts duration values from an object of this converter's type, and
     * sets them into the given ReadWritableDuration.
     *
     * @param period  period to get modified
     * @param object  the String to convert, must not be null
     * @param chrono  the chronology to use
     * @return the millisecond duration
     * @throws ClassCastException if the object is invalid
     */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
Example 27
Project: cms-ce-master  File: ExpressionFunctions.java View source code
public String currentDatePlusOffset(String format, String periodStr) {
    DateTime nowDateTime = timeService.getNowAsDateTime();
    PeriodFormatter periodFormatter = ISOPeriodFormat.standard();
    Period period = periodFormatter.parsePeriod(periodStr);
    DateTime offsetDateTime = nowDateTime.plus(period);
    SimpleDateFormat fmt = new SimpleDateFormat(format);
    return fmt.format(offsetDateTime.toDate());
}
Example 28
Project: elw-master  File: FormatTool.java View source code
private PeriodFormatter lookupPeriodFormatter(String pattern) {
    synchronized (dtfCache) {
        final PeriodFormatter cached = pfCache.get(pattern);
        if (cached != null) {
            return cached;
        }
        final PeriodFormatter created = createDefaultPeriodFormatted(pattern).withLocale(locale);
        pfCache.put(pattern, created);
        return created;
    }
}
Example 29
Project: jresponder-master  File: MessageRefImpl.java View source code
/**
	 * Gets the JR_WAIT_AFTER_LAST_MESSAGE property and parses it as an
	 * ISO8601 duration and returns the number of milliseconds it represents.
	 * Returns null if not set.
	 * @throws IllegalArgumentException if the value is in an invalid format
	 * @return
	 */
@Override
public Long getWaitAfterLastMessage() {
    // try to parse time from message
    String myWaitAfterLastMessageString = this.getProp(MessageRefProp.JR_WAIT_AFTER_LAST_MESSAGE);
    if (myWaitAfterLastMessageString == null) {
        logger().debug("No JR_WAIT_AFTER_LAST_MESSAGE property found on message (message={})", getName());
        return null;
    }
    PeriodFormatter myPeriodFormatter = ISOPeriodFormat.standard();
    try {
        long myDuration = myPeriodFormatter.parsePeriod(myWaitAfterLastMessageString).toStandardDuration().getMillis();
        return myDuration;
    } catch (IllegalArgumentException e) {
        logger().error("Unable to parse JR_WAIT_AFTER_LAST_MESSAGE value for (message={}), value was: \"{}\"  (this is a problem you need to fix!!! e.g. for one day, use \"P1D\")", new Object[] { getName(), myWaitAfterLastMessageString });
        throw new IllegalArgumentException("Error parsing JR_WAIT_AFTER_LAST_MESSAGE value: " + myWaitAfterLastMessageString, e);
    }
}
Example 30
Project: BlackboardVCPortlet-master  File: SessionImpl.java View source code
@Override
public String getTimeFancyText(DateTime from, DateTime to) {
    final String prefix = "Join in ";
    if (to != null) {
        Duration d = new Duration(to, from);
        Period timeUntil = new Period(to.toInstant(), from.toInstant(), PeriodType.dayTime());
        long standardDays = d.getStandardDays();
        if (standardDays > 0) {
            PeriodFormatter daysHours = new PeriodFormatterBuilder().appendDays().appendSuffix(" day", " days").appendSeparator(", and ").appendHours().appendSuffix(" hour", " hours").toFormatter();
            return prefix + daysHours.print(timeUntil.normalizedStandard(PeriodType.dayTime()));
        } else {
            PeriodFormatter dafaultFormatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" hour", " hours").appendSeparator(", and ").appendMinutes().appendSuffix(" minute", " minutes").toFormatter();
            return prefix + dafaultFormatter.print(timeUntil.normalizedStandard(PeriodType.dayTime()));
        }
    } else {
        return null;
    }
}
Example 31
Project: constellio-master  File: LDAPConfigurationManager.java View source code
private Duration newDuration(Map<String, String> configs, String key) {
    String durationString = getString(configs, key, null);
    if (durationString != null) {
        //format (\\d*d)(\\d*h)(\\d*mn) (d == day)
        PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendLiteral("d").appendHours().appendLiteral("h").appendMinutes().appendLiteral("mn").toFormatter();
        Duration duration = formatter.parsePeriod(durationString).toStandardDuration();
        return duration;
    }
    return null;
}
Example 32
Project: gina-puffinfeeder-android-viewer-master  File: ImageViewFrameActivty.java View source code
/**
     * Calculates how long it has been since the time stored in the parameters.
     * @param pic Date and time to compare with.
     * @return String describing how long it has been since the time described in the parameters.
     */
private String findTimeDifference(DateTime pic) {
    DateTime now = new DateTime(System.currentTimeMillis());
    Period diff = new Period(pic, now);
    PeriodFormatter toastFormatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" year, ", " years, ").appendMonths().appendSuffix(" month, ", " months, ").appendWeeks().appendSuffix(" week, ", " weeks, ").appendDays().appendSuffix(" day,", " days,").appendSeparator(" and ").printZeroAlways().appendHours().appendSuffix(" hour", " hours").appendLiteral(" ago.").toFormatter();
    return toastFormatter.print(diff);
}
Example 33
Project: lasso-master  File: MainActivity.java View source code
private void setTimeAgoPill(DateTime start) {
    if (start == null) {
        return;
    }
    Minutes minutes = Minutes.minutesBetween(start, Instant.now());
    PeriodFormatterBuilder periodFormatterBuilder = new PeriodFormatterBuilder();
    if (minutes.toStandardWeeks().getWeeks() > 1) {
        periodFormatterBuilder.appendWeeks().appendSuffix(getApplicationContext().getString(R.string.week), getApplicationContext().getString(R.string.weeks));
    } else if (minutes.toStandardDays().getDays() > 1) {
        periodFormatterBuilder.appendDays().appendSuffix(getApplicationContext().getString(R.string.day), getApplicationContext().getString(R.string.days));
    } else if (minutes.toStandardHours().getHours() > 1) {
        periodFormatterBuilder.appendHours().appendSuffix(getApplicationContext().getString(R.string.hour), getApplicationContext().getString(R.string.hours));
    } else {
        periodFormatterBuilder.appendMinutes().appendSuffix(getApplicationContext().getString(R.string.minute), getApplicationContext().getString(R.string.minutes));
    }
    periodFormatterBuilder.appendLiteral(" ago");
    PeriodFormatter formatter = periodFormatterBuilder.toFormatter();
    String pattern = "(\\d+)(.*)";
    Pattern r = Pattern.compile(pattern);
    Log.d("minutes", "Minutes: " + formatter.print(minutes));
    Matcher m = r.matcher(formatter.print(minutes));
    if (m.find()) {
        String number = m.group(1);
        String ago = m.group(2);
        minago.update(ago, number);
    }
}
Example 34
Project: w3act-master  File: User.java View source code
/**
     * This method calculates memership period for the user.
     * @return
     */
public String calculate_membership() {
    String res = "";
    Logger.debug("createdAt: " + createdAt + ", last_access: " + last_access + ", last_login: " + last_login);
    try {
        long timestampCreated = createdAt.getTime();
        Date dateCreated = new Date(timestampCreated * 1000);
        long timestampLastAccess = Long.valueOf(last_access);
        Date dateLastAccess = new Date(timestampLastAccess * 1000);
        Logger.debug("date created: " + dateCreated);
        Logger.debug("date last access: " + dateLastAccess);
        DateTime dt1 = new DateTime(dateCreated);
        DateTime dt2 = new DateTime(dateLastAccess);
        Period period = new Period(dt1, dt2);
        PeriodFormatterBuilder formaterBuilder = new PeriodFormatterBuilder().appendMonths().appendSuffix(" months ").appendWeeks().appendSuffix(" weeks");
        PeriodFormatter pf = formaterBuilder.toFormatter();
        //	        Logger.debug(pf.print(period));
        res = pf.print(period);
    } catch (Exception e) {
        Logger.debug("date difference calculation error: " + e);
    }
    return res;
}
Example 35
Project: OpenClinica-master  File: RuleController.java View source code
@RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
@ResponseBody
public org.openclinica.ns.rules_test.v31.RulesTest create(@RequestBody org.openclinica.ns.rules_test.v31.RulesTest ruleTest, Model model, HttpSession session, @PathVariable("study") String studyOid) throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(ruleTest.getRules());
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);
    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);
    getRulePostImportContainerService(currentStudy, userAccount);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
    Response response = new Response();
    response.setValid(Boolean.TRUE);
    if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
        response.setValid(Boolean.FALSE);
        for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
            for (String error : beanWrapper.getImportErrors()) {
                org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
                messageType.setMessage(error);
                response.getMessages().add(messageType);
            }
        }
        for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
            for (String error : beanWrapper.getImportErrors()) {
                org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
                messageType.setMessage(error);
                response.getMessages().add(messageType);
            }
        }
    }
    HashMap<String, String> p = new HashMap<String, String>();
    for (ParameterType parameterType : ruleTest.getParameters()) {
        p.put(parameterType.getKey(), parameterType.getValue());
    }
    ExpressionObjectWrapper eow = new ExpressionObjectWrapper(dataSource, currentStudy, rpic.getRuleDefs().get(0).getExpression(), rpic.getRuleSets().get(0));
    ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);
    // Run expression with populated HashMap
    DateTime start = new DateTime();
    HashMap<String, String> result = ep.testEvaluateExpression(p);
    DateTime end = new DateTime();
    Duration dur = new Duration(start, end);
    PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder().printZeroAlways().appendSecondsWithMillis().appendSuffix(" second", " seconds").toFormatter();
    yearsAndMonths.print(dur.toPeriod());
    // Run expression with empty HashMap to check rule validity, because
    // using illegal test values will cause invalidity
    HashMap<String, String> k = new HashMap<String, String>();
    HashMap<String, String> theResult = ep.testEvaluateExpression(k);
    ruleTest.getParameters().clear();
    for (Map.Entry<String, String> entry : result.entrySet()) {
        ParameterType parameterType = new ParameterType();
        parameterType.setKey(entry.getKey());
        parameterType.setValue(entry.getValue());
        ruleTest.getParameters().add(parameterType);
    }
    // if (theResult.get("ruleValidation").equals("rule_valid") && result.get("ruleValidation").equals("rule_invalid")) {
    // result.put("ruleValidation", "rule_valid");
    // result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " +
    // result.get("ruleValidationFailMessage"));
    // result.remove("ruleValidationFailMessage");
    // }
    // Put on screen
    // request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
    RulesTestMessagesType messageType = new RulesTestMessagesType();
    messageType.setKey("duration");
    messageType.setValue(yearsAndMonths.print(dur.toPeriod()));
    ruleTest.getRulesTestMessages().add(messageType);
    return ruleTest;
}
Example 36
Project: presto-master  File: DateTimeUtils.java View source code
public static long parsePeriodMillis(PeriodFormatter periodFormatter, String value, IntervalField startField, IntervalField endField) {
    try {
        Period period = parsePeriod(periodFormatter, value);
        return IntervalDayTime.toMillis(period.getValue(DAY_FIELD), period.getValue(HOUR_FIELD), period.getValue(MINUTE_FIELD), period.getValue(SECOND_FIELD), period.getValue(MILLIS_FIELD));
    } catch (IllegalArgumentException e) {
        throw invalidInterval(e, value, startField, endField);
    }
}
Example 37
Project: SAX-master  File: SAXProcessor.java View source code
/**
   * Generic method to convert the milliseconds into the elapsed time string.
   * 
   * @param start Start timestamp.
   * @param finish End timestamp.
   * @return String representation of the elapsed time.
   */
public static String timeToString(long start, long finish) {
    // in milliseconds
    Duration duration = new Duration(finish - start);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds().appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter();
    return formatter.print(duration.toPeriod());
}
Example 38
Project: whole-master  File: SchemaDataTypeParsers.java View source code
public static PeriodFormatter durationFormatter() {
    if (duration == null) {
        duration = new PeriodFormatterBuilder().rejectSignedValues(true).appendLiteral("P").appendYears().appendSuffix("Y").appendMonths().appendSuffix("M").appendWeeks().appendSuffix("W").appendDays().appendSuffix("D").appendSeparatorIfFieldsAfter("T").appendHours().appendSuffix("H").appendMinutes().appendSuffix("M").appendSecondsWithOptionalMillis().appendSuffix("S").toFormatter();
    }
    return duration;
}
Example 39
Project: eMonocot-master  File: Functions.java View source code
/**
	  *
	  * @param start
	  *            Set the start date
	  * @param end
	  *            Set the end date
	  * @return a formatted period
	  */
public static String formatPeriod(Date start, Date end) {
    DateTime startDate = new DateTime(start);
    DateTime endDate = new DateTime(end);
    Period period = new Interval(startDate, endDate).toPeriod();
    PeriodFormatter formatter = new PeriodFormatterBuilder().minimumPrintedDigits(2).appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
    return formatter.print(period);
}
Example 40
Project: knox-master  File: GatewayConfigImpl.java View source code
@Override
public long getGatewayDeploymentsBackupAgeLimit() {
    PeriodFormatter f = new PeriodFormatterBuilder().appendDays().toFormatter();
    String s = get(DEPLOYMENTS_BACKUP_AGE_LIMIT, "-1");
    long d;
    try {
        Period p = Period.parse(s, f);
        d = p.toStandardDuration().getMillis();
        if (d < 0) {
            d = -1;
        }
    } catch (Exception e) {
        d = -1;
    }
    return d;
}
Example 41
Project: openhab1-addons-master  File: SonosZonePlayer.java View source code
public boolean updateAlarm(SonosAlarm alarm) {
    if (alarm != null && isConfigured()) {
        Service service = device.findService(new UDAServiceId("AlarmClock"));
        Action action = service.getAction("ListAlarms");
        ActionInvocation invocation = new ActionInvocation(action);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
        PeriodFormatter pFormatter = new PeriodFormatterBuilder().printZeroAlways().appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
        try {
            invocation.setInput("ID", Integer.toString(alarm.getID()));
            invocation.setInput("StartLocalTime", formatter.print(alarm.getStartTime()));
            invocation.setInput("Duration", pFormatter.print(alarm.getDuration()));
            invocation.setInput("Recurrence", alarm.getRecurrence());
            invocation.setInput("RoomUUID", alarm.getRoomUUID());
            invocation.setInput("ProgramURI", alarm.getProgramURI());
            invocation.setInput("ProgramMetaData", alarm.getProgramMetaData());
            invocation.setInput("PlayMode", alarm.getPlayMode());
            invocation.setInput("Volume", Integer.toString(alarm.getVolume()));
            if (alarm.getIncludeLinkedZones()) {
                invocation.setInput("IncludeLinkedZones", "1");
            } else {
                invocation.setInput("IncludeLinkedZones", "0");
            }
            if (alarm.getEnabled()) {
                invocation.setInput("Enabled", "1");
            } else {
                invocation.setInput("Enabled", "0");
            }
        } catch (InvalidValueException ex) {
            logger.error("Action Invalid Value Exception {}", ex.getMessage());
        } catch (NumberFormatException ex) {
            logger.error("Action Invalid Value Format Exception {}", ex.getMessage());
        }
        executeActionInvocation(invocation);
        return true;
    } else {
        return false;
    }
}
Example 42
Project: java-saml-master  File: Util.java View source code
/**
	 * Interprets a ISO8601 duration value relative to a given timestamp.
	 *
	 * @param durationString
	 * 				 The duration, as a string.
	 * @param timestamp 
	 *               The unix timestamp we should apply the duration to.
	 *
	 * @return the new timestamp, after the duration is applied In Seconds.
	 *
	 * @throws IllegalArgumentException
	 */
public static long parseDuration(String durationString, long timestamp) throws IllegalArgumentException {
    boolean haveMinus = false;
    if (durationString.startsWith("-")) {
        durationString = durationString.substring(1);
        haveMinus = true;
    }
    PeriodFormatter periodFormatter = ISOPeriodFormat.standard().withLocale(new Locale("UTC"));
    Period period = periodFormatter.parsePeriod(durationString);
    DateTime dt = new DateTime(timestamp * 1000, DateTimeZone.UTC);
    DateTime result = null;
    if (haveMinus) {
        result = dt.minus(period);
    } else {
        result = dt.plus(period);
    }
    return result.getMillis() / 1000;
}
Example 43
Project: Traktoid-master  File: DateHelper.java View source code
public static String getRuntime(int runtime) {
    PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever().appendHours().appendSeparatorIfFieldsBefore("h").minimumPrintedDigits(2).appendMinutes().appendSeparatorIfFieldsBefore("m").toFormatter();
    return formatter.print(new Period(runtime * 60 * 1000));
}
Example 44
Project: gocd-master  File: RunDuration.java View source code
public String duration(PeriodFormatter formatter) {
    return "In Progress";
}
Example 45
Project: kickmaterial-master  File: PeriodToStringConverter.java View source code
/**
     * Shorter syntax for creating [email protected] PeriodFormatterAndValue}
     *
     * @param formatter
     * @param value
     * @return
     */
private static PeriodFormatterAndValue pav(@Nonnull PeriodFormatter formatter, int value) {
    return new PeriodFormatterAndValue(formatter, value);
}
Example 46
Project: lightblue-migrator-master  File: NMPMonitor.java View source code
/**
     * Returns the period in msecs
     */
private static long parsePeriod(String periodStr) {
    PeriodFormatter fmt = PeriodFormat.getDefault();
    Period p = fmt.parsePeriod(periodStr);
    return p.toStandardDuration().getMillis();
}
Example 47
Project: gson-jodatime-serialisers-master  File: PeriodConverter.java View source code
/**
   * Gson invokes this call-back method during serialization when it encounters a field of the
   * specified type. <p>
   *
   * In the implementation of this call-back method, you should consider invoking
   * [email protected] JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
   * non-trivial field of the [email protected] src} object. However, you should never invoke it on the
   * [email protected] src} object itself since that will cause an infinite loop (Gson will call your
   * call-back method again).
   * @param src the object that needs to be converted to Json.
   * @param typeOfSrc the actual type (fully genericized version) of the source object.
   * @return a JsonElement corresponding to the specified object.
   */
@Override
public JsonElement serialize(Period src, Type typeOfSrc, JsonSerializationContext context) {
    final PeriodFormatter fmt = ISOPeriodFormat.standard();
    return new JsonPrimitive(fmt.print(src));
}
Example 48
Project: substeps-core-master  File: DetailedJsonBuilder.java View source code
private String convert(long runningDurationMillis) {
    Duration duration = new Duration(runningDurationMillis);
    PeriodFormatter formatter = PeriodFormat.getDefault();
    return formatter.print(duration.toPeriod());
}