gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.beans.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import javax.swing.Timer;
public final class MainPanel extends JPanel {
private final JTextArea area = new JTextArea();
private final JProgressBar bar = new JProgressBar();
private final JPanel statusPanel = new JPanel(new BorderLayout());
private final JButton runButton = new JButton(new RunAction());
private final JButton canButton = new JButton(new CancelAction());
private final AnimatedLabel anil = new AnimatedLabel();
private transient Task worker;
public MainPanel() {
super(new BorderLayout());
area.setEditable(false);
area.setLineWrap(true);
Box box = Box.createHorizontalBox();
box.add(anil);
box.add(Box.createHorizontalGlue());
box.add(runButton);
box.add(canButton);
add(box, BorderLayout.NORTH);
add(statusPanel, BorderLayout.SOUTH);
add(new JScrollPane(area));
setPreferredSize(new Dimension(320, 240));
}
class RunAction extends AbstractAction {
public RunAction() {
super("run");
}
@Override public void actionPerformed(ActionEvent evt) {
runButton.setEnabled(false);
canButton.setEnabled(true);
anil.startAnimation();
statusPanel.removeAll();
statusPanel.add(bar);
statusPanel.revalidate();
bar.setIndeterminate(true);
worker = new Task() {
@Override protected void process(List<String> chunks) {
//System.out.println("process() is EDT?: " + EventQueue.isDispatchThread());
if (isCancelled()) {
return;
}
if (!isDisplayable()) {
cancel(true);
return;
}
for (String message: chunks) {
appendLine(message);
}
}
@Override public void done() {
//System.out.println("done() is EDT?: " + EventQueue.isDispatchThread());
if (!isDisplayable()) {
cancel(true);
return;
}
anil.stopAnimation();
runButton.setEnabled(true);
canButton.setEnabled(false);
statusPanel.remove(bar);
statusPanel.revalidate();
appendLine("\n");
try {
if (isCancelled()) {
appendLine("Cancelled");
} else {
appendLine(get());
}
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
appendLine("Exception");
}
appendLine("\n\n");
}
};
worker.addPropertyChangeListener(new ProgressListener(bar));
worker.execute();
}
}
class CancelAction extends AbstractAction {
public CancelAction() {
super("cancel");
}
@Override public void actionPerformed(ActionEvent evt) {
if (Objects.nonNull(worker) && !worker.isDone()) {
worker.cancel(true);
}
worker = null;
}
}
// private boolean isCancelled() {
// return Objects.nonNull(worker) ? worker.isCancelled() : true;
// }
private void appendLine(String str) {
area.append(str);
area.setCaretPosition(area.getDocument().getLength());
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
//frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Task extends SwingWorker<String, String> {
@Override public String doInBackground() {
//System.out.println("doInBackground() is EDT?: " + EventQueue.isDispatchThread());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
if (isCancelled()) {
cancel(true);
}
return "Interrupted";
}
int current = 0;
int lengthOfTask = 120; //list.size();
publish("Length Of Task: " + lengthOfTask);
publish("\n------------------------------\n");
while (current < lengthOfTask && !isCancelled()) {
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
return "Interrupted";
}
publish(".");
setProgress(100 * current / lengthOfTask);
current++;
}
return "Done";
}
}
class ProgressListener implements PropertyChangeListener {
private final JProgressBar progressBar;
ProgressListener(JProgressBar progressBar) {
this.progressBar = progressBar;
this.progressBar.setValue(0);
}
@Override public void propertyChange(PropertyChangeEvent e) {
String strPropertyName = e.getPropertyName();
if ("progress".equals(strPropertyName)) {
progressBar.setIndeterminate(false);
int progress = (Integer) e.getNewValue();
progressBar.setValue(progress);
}
}
}
class AnimatedLabel extends JLabel implements ActionListener {
private final Timer animator;
private final transient AnimeIcon icon = new AnimeIcon();
public AnimatedLabel() {
super();
animator = new Timer(100, this);
setIcon(icon);
addHierarchyListener(new HierarchyListener() {
@Override public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0 && !e.getComponent().isDisplayable()) {
stopAnimation();
}
}
});
}
@Override public void actionPerformed(ActionEvent e) {
icon.next();
repaint();
}
public void startAnimation() {
icon.setRunning(true);
animator.start();
}
public void stopAnimation() {
icon.setRunning(false);
animator.stop();
}
}
// //TEST: 1
// class AnimeIcon implements Icon {
// private static final Color ELLIPSE_COLOR = new Color(.5f, .5f, .5f);
// private static final double R = 2d;
// private static final double SX = 1d;
// private static final double SY = 1d;
// private static final int WIDTH = (int) (R * 8 + SX * 2);
// private static final int HEIGHT = (int) (R * 8 + SY * 2);
// private final List<Shape> list = new ArrayList<Shape>(Arrays.asList(
// new Ellipse2D.Double(SX + 3 * R, SY + 0 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 5 * R, SY + 1 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 6 * R, SY + 3 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 5 * R, SY + 5 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 3 * R, SY + 6 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 1 * R, SY + 5 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 0 * R, SY + 3 * R, 2 * R, 2 * R),
// new Ellipse2D.Double(SX + 1 * R, SY + 1 * R, 2 * R, 2 * R)));
//
// private boolean isRunning;
// public void next() {
// if (isRunning) {
// list.add(list.remove(0));
// }
// }
// public void setRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
// @Override public void paintIcon(Component c, Graphics g, int x, int y) {
// Graphics2D g2 = (Graphics2D) g.create();
// g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
// g2.fillRect(x, y, getIconWidth(), getIconHeight());
// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// g2.setColor(ELLIPSE_COLOR);
// g2.translate(x, y);
// int size = list.size();
// for (int i = 0; i < size; i++) {
// float alpha = isRunning ? (i + 1) / (float) size : .5f;
// g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
// g2.fill(list.get(i));
// }
// g2.dispose();
// }
// @Override public int getIconWidth() {
// return WIDTH;
// }
// @Override public int getIconHeight() {
// return HEIGHT;
// }
// }
// //TEST: 2
// class AnimeIcon implements Icon {
// private static final Color ELLIPSE_COLOR = new Color(.5f, .8f, .5f);
// private final List<Shape> list = new ArrayList<>();
// private final Dimension dim;
// private boolean isRunning;
// public AnimeIcon() {
// super();
// int r = 4;
// Shape s = new Ellipse2D.Float(0, 0, 2 * r, 2 * r);
// for (int i = 0; i < 8; i++) {
// AffineTransform at = AffineTransform.getRotateInstance(i * 2 * Math.PI / 8);
// at.concatenate(AffineTransform.getTranslateInstance(r, r));
// list.add(at.createTransformedShape(s));
// }
// //int d = (int) (r * 2 * (1 + 2 * Math.sqrt(2)));
// int d = (int) r * 2 * (1 + 3); // 2 * Math.sqrt(2) is nearly equal to 3.
// dim = new Dimension(d, d);
// }
// @Override public int getIconWidth() {
// return dim.width;
// }
// @Override public int getIconHeight() {
// return dim.height;
// }
// @Override public void paintIcon(Component c, Graphics g, int x, int y) {
// Graphics2D g2 = (Graphics2D) g.create();
// g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
// g2.fillRect(x, y, getIconWidth(), getIconHeight());
// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// g2.setColor(ELLIPSE_COLOR);
// int xx = x + dim.width / 2;
// int yy = y + dim.height / 2;
// g2.translate(xx, yy);
// int size = list.size();
// for (int i = 0; i < size; i++) {
// float alpha = isRunning ? (i + 1) / (float) size : .5f;
// g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
// g2.fill(list.get(i));
// }
// g2.dispose();
// }
// public void next() {
// if (isRunning) {
// list.add(list.remove(0));
// }
// }
// public void setRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
// }
//TEST: 3
class AnimeIcon implements Icon {
private static final Color ELLIPSE_COLOR = new Color(.9f, .7f, .7f);
private final List<Shape> list = new ArrayList<>();
private final Dimension dim;
private boolean isRunning;
private int rotate = 45;
public AnimeIcon() {
super();
int r = 4;
Shape s = new Ellipse2D.Float(0, 0, 2 * r, 2 * r);
for (int i = 0; i < 8; i++) {
AffineTransform at = AffineTransform.getRotateInstance(i * 2 * Math.PI / 8);
at.concatenate(AffineTransform.getTranslateInstance(r, r));
list.add(at.createTransformedShape(s));
}
int d = (int) r * 2 * (1 + 3);
dim = new Dimension(d, d);
}
@Override public int getIconWidth() {
return dim.width;
}
@Override public int getIconHeight() {
return dim.height;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
g2.fillRect(x, y, getIconWidth(), getIconHeight());
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(ELLIPSE_COLOR);
int xx = x + dim.width / 2;
int yy = y + dim.height / 2;
AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(rotate), xx, yy);
at.concatenate(AffineTransform.getTranslateInstance(xx, yy));
int size = list.size();
for (int i = 0; i < size; i++) {
float alpha = isRunning ? (i + 1) / (float) size : .5f;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2.fill(at.createTransformedShape(list.get(i)));
}
g2.dispose();
}
public void next() {
if (isRunning) {
rotate = (rotate + 45) % 360; //45 = 360 / 8
}
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
}
// //TEST: 4
// class AnimeIcon implements Icon {
// private static final int R = 4;
// private static final Color ELLIPSE_COLOR = new Color(.5f, .8f, .5f);
// private final Dimension dim;
// private boolean isRunning;
// private final List<Shape> list = new ArrayList<>();
// public AnimeIcon() {
// super();
// int d = (int) R * 2 * (1 + 3);
// dim = new Dimension(d, d);
//
// Ellipse2D.Float cricle = new Ellipse2D.Float(R, R, d - 2 * R, d - 2 * R);
// PathIterator i = new FlatteningPathIterator(cricle.getPathIterator(null), R);
// float[] coords = new float[6];
// int idx = 0;
// while (!i.isDone()) {
// i.currentSegment(coords);
// if (idx < 8) { // XXX
// list.add(new Ellipse2D.Float(coords[0] - R, coords[1] - R, 2 * R, 2 * R));
// idx++;
// }
// i.next();
// }
// }
// @Override public int getIconWidth() {
// return dim.width;
// }
// @Override public int getIconHeight() {
// return dim.height;
// }
// @Override public void paintIcon(Component c, Graphics g, int x, int y) {
// Graphics2D g2 = (Graphics2D) g.create();
// g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
// g2.fillRect(x, y, getIconWidth(), getIconHeight());
// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// g2.setColor(ELLIPSE_COLOR);
// int size = list.size();
// for (int i = 0; i < size; i++) {
// float alpha = isRunning ? (i + 1) / (float) size : .5f;
// g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
// g2.fill(list.get(i));
// }
// g2.dispose();
// }
// public void next() {
// if (isRunning) {
// list.add(list.remove(0));
// }
// }
// public void setRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
// }
| |
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =================================================================================================
/** ************************************************************************
** Summize
** This work protected by US Copyright Law and contains proprietary and
** confidential trade secrets.
** (c) Copyright 2007 Summize, ALL RIGHTS RESERVED.
** ************************************************************************/
package com.twitter.common.util;
//***************************************************************
//
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.NumberFormat;
/**
* This class is designed to provide basic statistics collection.
* For each instance of this object statistics and be added to it
* then the sum, mean, std dev, min and max can be gathered at the
* end. To reuse this object, a clear method can be called to reset
* the statistics.
*
* @author Abdur Chowdhury
*/
public class Stat implements Serializable {
/**
* Add a number to the statistics collector.
* doubles are used for all collections.
*
* @param int - number added to the statistics.
* @return void
*/
public void addNumber(int x) {
addNumber((double) x);
}
/**
* Add a number to the statistics collector.
* doubles are used for all collections.
*
* @param float - number added to the statistics.
* @return void
*/
public void addNumber(float x) {
addNumber((double) x);
}
/**
* Add a number to the statistics collector.
* doubles are used for all collections.
*
* @param double - number added to the statistics.
* @return void
*/
public synchronized void addNumber(double x) {
if (_max < x) {
_max = x;
}
if (_min > x) {
_min = x;
}
_sum += x;
_sumOfSq += (x * x);
_number++;
return;
}
/**
* Clear the statistics counters...
*
* @param void
* @return void
*/
public void clear() {
_max = 0;
_min = Double.MAX_VALUE;
_number = 0;
_mean = 0;
_stdDev = 0;
_sum = 0;
_sumOfSq = 0;
}
/**
* Create a string representation of the
* statistics collected so far. NOTE this
* is formated and may not suit all needs
* and thus the user should just call the
* needed methods to get mean, std dev, etc.
* and format the data as needed.
*
* @param void
* @return String - Java string formated out put
* of results.
*/
public String toString() {
return toString(false);
}
/**
* Create a string representation of the
* statistics collected so far. The results
* are formated in percentage format if
* passed in true, otherwise the results
* are the same as the toString call. NOTE this
* is formated and may not suit all needs
* and thus the user should just call the
* needed methods to get mean, std dev, etc.
* and format the data as needed.
*
* @param boolean - Format as percentages if set to true.
* @return String - Java string formated out put
* of results.
*/
public String toString(boolean percent) {
calculate();
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
if (_number > 1) {
StringBuffer results = new StringBuffer();
if (percent) {
results.append("Number:" + nf.format(_number * 100) + "%");
} else {
results.append("Number:" + nf.format(_number));
}
if (percent) {
results.append(" Max:" + nf.format(_max * 100) + "%");
} else {
results.append(" Max:" + nf.format(_max));
}
if (percent) {
results.append(" Min:" + nf.format(_min * 100) + "%");
} else {
results.append(" Min:" + nf.format(_min));
}
if (percent) {
results.append(" Mean:" + nf.format(_mean * 100) + "%");
} else {
results.append(" Mean:" + nf.format(_mean));
}
results.append(" Sum:" + nf.format(_sum));
results.append(" STD:" + nf.format(_stdDev));
return results.toString();
} else if (_number == 1) {
if (percent) {
return ("Number:" + nf.format(_sum * 100) + "%");
} else {
return ("Number:" + nf.format(_sum));
}
} else {
return ("Number: N/A");
}
}
private void calculate() {
getMean();
getStandardDev();
}
/**
* Get the max data element added to the statistics
* object so far.
*
* @param void
* @return double - Maximum entry added so far.
*/
public double getMax() {
return _max;
}
/**
* Get the min data element added to the statistics
* object so far.
*
* @param void
* @return double - Min entry added so far.
*/
public double getMin() {
return _min;
}
/**
* Get the number of data elements added to the statistics
* object so far.
*
* @param void
* @return double - Number of entries added so far.
*/
public long getNumberOfElements() {
return _number;
}
/**
* Get the average or mean of data elements added to the
* statistics object so far.
*
* @param void
* @return double - Mean of entries added so far.
*/
public double getMean() {
if (_number > 0) {
_mean = _sum / _number;
}
return _mean;
}
/**
* Get the ratio of the sum of elements divided by the number
* of elements added * 100
*
* @param void
* @return double - Percent of entries added so far.
*/
public double getPercent() {
if (_number > 0) {
_mean = _sum / _number;
}
_mean = _mean * 100;
return _mean;
}
/**
* Get the sum or mean of data elements added to the
* statistics object so far.
*
* @param void
* @return double - Sum of entries added so far.
*/
public double getSum() {
return _sum;
}
/**
* Get the sum of the squares of the data elements added
* to the statistics object so far.
*
* @param void
* @return double - Sum of the squares of the entries added so far.
*/
public double getSumOfSq() {
return _sumOfSq;
}
/**
* Get the standard deviation of the data elements added
* to the statistics object so far.
*
* @param void
* @return double - Sum of the standard deviation of the entries added so far.
*/
public double getStandardDev() {
if (_number > 1) {
_stdDev = Math.sqrt((_sumOfSq - ((_sum * _sum) / _number)) / (_number - 1));
}
return _stdDev;
}
/**
* Read the data from the inputstream so it can be used to populate
* the current objects state.
*
* @param InputStream - java.io.InputStream to write to.
* @return void
* @throws IOException
*/
public void readFromDataInput(InputStream in) throws IOException {
DataInput di = new DataInputStream(in);
readFromDataInput(di);
return;
}
/**
* Read the data from the datainput so it can be used to populate
* the current objects state.
*
* @param InputStream - java.io.InputStream to write to.
* @return void
* @throws IOException
*/
public void readFromDataInput(DataInput in) throws IOException {
_max = in.readDouble();
_min = in.readDouble();
_number = in.readLong();
_mean = in.readDouble();
_stdDev = in.readDouble();
_sum = in.readDouble();
_sumOfSq = in.readDouble();
return;
}
/**
* Write the data to the output steam so it can be streamed to an
* other process, wire or storage median in a format that another Stats
* object can read.
*
* @param OutputStream - java.io.OutputStream to write to.
* @return void
* @throws IOException
*/
public void writeToDataOutput(OutputStream out) throws IOException {
DataOutput dout = new DataOutputStream(out);
writeToDataOutput(dout);
return;
}
/**
* Write the data to the data output object so it can be written to an
* other process, wire or storage median in a format that another Stats
* object can read.
*
* @param InputStream - java.io.InputStream to write to.
* @return void
* @throws IOException
*/
public void writeToDataOutput(DataOutput out) throws IOException {
out.writeDouble(_max);
out.writeDouble(_min);
out.writeLong(_number);
out.writeDouble(_mean);
out.writeDouble(_stdDev);
out.writeDouble(_sum);
out.writeDouble(_sumOfSq);
return;
}
// ************************************
private static final long serialVersionUID = 1L;
private double _max = 0 ;
private double _min = Double.MAX_VALUE ;
private long _number = 0 ;
private double _mean = 0 ;
private double _stdDev = 0 ;
private double _sum = 0 ;
private double _sumOfSq ;
}
| |
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Eric Rizzo - Externalize Strings wizard always defaults to the "legacy" mechanism - http://bugs.eclipse.org/271375
*******************************************************************************/
package org.eclipse.jdt.internal.ui.refactoring.nls;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.refactoring.nls.KeyValuePair;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
import org.eclipse.jdt.internal.ui.propertiesfileeditor.PropertiesFileEscapes;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
class ExternalizeWizardPage extends UserInputWizardPage {
private static final String[] PROPERTIES;
private static final String[] fgTitles;
private static final int STATE_PROP= 0;
private static final int VAL_PROP= 1;
private static final int KEY_PROP= 2;
private static final int SIZE= 3; //column counter
private static final int ROW_COUNT= 5;
public static final String PAGE_NAME= "NLSWizardPage1"; //$NON-NLS-1$
static {
PROPERTIES= new String[SIZE];
PROPERTIES[STATE_PROP]= "task"; //$NON-NLS-1$
PROPERTIES[KEY_PROP]= "key"; //$NON-NLS-1$
PROPERTIES[VAL_PROP]= "value"; //$NON-NLS-1$
fgTitles= new String[SIZE];
fgTitles[STATE_PROP]= ""; //$NON-NLS-1$
fgTitles[KEY_PROP]= NLSUIMessages.ExternalizeWizardPage_key;
fgTitles[VAL_PROP]= NLSUIMessages.ExternalizeWizardPage_value;
}
private class CellModifier implements ICellModifier {
/**
* @see ICellModifier#canModify(Object, String)
*/
public boolean canModify(Object element, String property) {
if (property == null)
return false;
if (!(element instanceof NLSSubstitution))
return false;
NLSSubstitution subst= (NLSSubstitution) element;
if (PROPERTIES[KEY_PROP].equals(property) && subst.getState() != NLSSubstitution.EXTERNALIZED) {
return false;
}
return true;
}
/**
* @see ICellModifier#getValue(Object, String)
*/
public Object getValue(Object element, String property) {
if (element instanceof NLSSubstitution) {
NLSSubstitution substitution= (NLSSubstitution) element;
String res= null;
if (PROPERTIES[KEY_PROP].equals(property)) {
res= substitution.getKeyWithoutPrefix();
} else if (PROPERTIES[VAL_PROP].equals(property)) {
res= substitution.getValue();
} else if (PROPERTIES[STATE_PROP].equals(property)) {
return new Integer(substitution.getState());
}
if (res != null) {
return getEscapedAsciiString(res);
}
return ""; //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
/**
* @see ICellModifier#modify(Object, String, Object)
*/
public void modify(Object element, String property, Object value) {
if (element instanceof TableItem) {
Object data= ((TableItem) element).getData();
if (data instanceof NLSSubstitution) {
NLSSubstitution substitution= (NLSSubstitution) data;
if (PROPERTIES[KEY_PROP].equals(property)) {
String string = (String)value;
try {
string= PropertiesFileEscapes.unescape(string);
} catch (CoreException e) {
setPageComplete(RefactoringStatus.create(e.getStatus()));
return;
}
substitution.setKey(string);
}
if (PROPERTIES[VAL_PROP].equals(property)) {
String string = (String)value;
try {
string= PropertiesFileEscapes.unescape(string);
} catch (CoreException e) {
setPageComplete(RefactoringStatus.create(e.getStatus()));
return;
}
substitution.setValue(string);
}
if (PROPERTIES[STATE_PROP].equals(property)) {
substitution.setState(((Integer) value).intValue());
if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
substitution.generateKey(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()));
}
}
}
validateKeys(false);
fTableViewer.update(data, null);
}
}
}
private class NLSSubstitutionLabelProvider extends LabelProvider implements ITableLabelProvider, IFontProvider {
private FontRegistry fFontRegistry;
public NLSSubstitutionLabelProvider() {
fFontRegistry= JFaceResources.getFontRegistry();
}
public String getColumnText(Object element, int columnIndex) {
String columnText= ""; //$NON-NLS-1$
if (element instanceof NLSSubstitution) {
NLSSubstitution substitution= (NLSSubstitution) element;
if (columnIndex == KEY_PROP) {
if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
columnText= BasicElementLabels.getJavaElementName(substitution.getKey());
}
} else
if ((columnIndex == VAL_PROP) && (substitution.getValue() != null)) {
columnText= substitution.getValue();
}
}
return getEscapedAsciiString(columnText);
}
public Image getColumnImage(Object element, int columnIndex) {
if ((columnIndex == STATE_PROP) && (element instanceof NLSSubstitution)) {
return getNLSImage((NLSSubstitution) element);
}
return null;
}
public Font getFont(Object element) {
if (element instanceof NLSSubstitution) {
NLSSubstitution substitution= (NLSSubstitution) element;
if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
return fFontRegistry.getBold(JFaceResources.DIALOG_FONT);
}
}
return null;
}
private Image getNLSImage(NLSSubstitution sub) {
if ((sub.getValue() == null) && (sub.getKey() != null)) {
// Missing keys
JavaElementImageDescriptor imageDescriptor= new JavaElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(imageDescriptor);
} else
if (sub.isConflicting(fSubstitutions) || !isKeyValid(sub, null)) {
JavaElementImageDescriptor imageDescriptor= new JavaElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaElementImageDescriptor.ERROR, JavaElementImageProvider.SMALL_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(imageDescriptor);
} else {
return getNLSImage(sub.getState());
}
}
private Image getNLSImage(int task) {
switch (task) {
case NLSSubstitution.EXTERNALIZED :
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_TRANSLATE);
case NLSSubstitution.IGNORED :
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
case NLSSubstitution.INTERNALIZED :
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_SKIP);
default :
Assert.isTrue(false);
return null;
}
}
private ImageDescriptor getNLSImageDescriptor(int task) {
switch (task) {
case NLSSubstitution.EXTERNALIZED :
return JavaPluginImages.DESC_OBJS_NLS_TRANSLATE;
case NLSSubstitution.IGNORED :
return JavaPluginImages.DESC_OBJS_NLS_NEVER_TRANSLATE;
case NLSSubstitution.INTERNALIZED :
return JavaPluginImages.DESC_OBJS_NLS_SKIP;
default :
Assert.isTrue(false);
return null;
}
}
}
private static String getEscapedAsciiString(String s) {
if (s != null) {
StringBuffer sb= new StringBuffer(s.length());
int length= s.length();
for (int i= 0; i < length; i++) {
char c= s.charAt(i);
sb.append(getEscapedAsciiString(c));
}
return sb.toString();
}
return null;
}
private static String getEscapedAsciiString(char c) {
switch (c) {
case '\b':
return "\\b";//$NON-NLS-1$
case '\t':
return "\\t";//$NON-NLS-1$
case '\n':
return "\\n";//$NON-NLS-1$
case '\f':
return "\\f";//$NON-NLS-1$
case '\r':
return "\\r";//$NON-NLS-1$
case '\\':
return "\\\\";//$NON-NLS-1$
}
return String.valueOf(c);
}
private class NLSInputDialog extends StatusDialog implements IDialogFieldListener {
private StringDialogField fKeyField;
private StringDialogField fValueField;
private DialogField fMessageField;
private NLSSubstitution fSubstitution;
public NLSInputDialog(Shell parent, NLSSubstitution substitution) {
super(parent);
setTitle(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Title);
fSubstitution= substitution;
fMessageField= new DialogField();
if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_ext_Label);
} else {
fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Label);
}
fKeyField= new StringDialogField();
fKeyField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_key);
fKeyField.setDialogFieldListener(this);
fValueField= new StringDialogField();
fValueField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_value);
fValueField.setDialogFieldListener(this);
if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
fKeyField.setText(substitution.getKeyWithoutPrefix());
} else {
fKeyField.setText(""); //$NON-NLS-1$
}
fValueField.setText(substitution.getValueNonEmpty());
}
public KeyValuePair getResult() {
KeyValuePair res= new KeyValuePair(fKeyField.getText(), fValueField.getText());
return res;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
inner.setFont(composite.getFont());
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
inner.setLayout(layout);
fMessageField.doFillIntoGrid(inner, 2);
if (fSubstitution.getState() == NLSSubstitution.EXTERNALIZED) {
fKeyField.doFillIntoGrid(inner, 2);
LayoutUtil.setWidthHint(fKeyField.getTextControl(null), convertWidthInCharsToPixels(45));
}
fValueField.doFillIntoGrid(inner, 2);
LayoutUtil.setWidthHint(fValueField.getTextControl(null), convertWidthInCharsToPixels(45));
LayoutUtil.setHorizontalGrabbing(fValueField.getTextControl(null));
fValueField.postSetFocusOnDialogField(parent.getDisplay());
applyDialogFont(composite);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
*/
public void dialogFieldChanged(DialogField field) {
IStatus keyStatus= validateKey(fKeyField.getText());
//IStatus valueStatus= StatusInfo.OK_STATUS; // no validation yet
//updateStatus(StatusUtil.getMoreSevere(valueStatus, keyStatus));
updateStatus(keyStatus);
}
private IStatus validateKey(String val) {
if (fSubstitution.getState() != NLSSubstitution.EXTERNALIZED) {
return StatusInfo.OK_STATUS;
}
if (val == null || val.length() == 0) {
return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_empty_key);
}
if (fNLSRefactoring.isEclipseNLS()) {
if (!Character.isJavaIdentifierStart(val.charAt(0)))
return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
for (int i= 1, length= val.length(); i < length; i++) {
if (!Character.isJavaIdentifierPart(val.charAt(i)))
return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
}
} else {
// validation so keys don't contain spaces
for (int i= 0; i < val.length(); i++) {
if (Character.isWhitespace(val.charAt(i))) {
return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_key);
}
}
}
return StatusInfo.OK_STATUS;
}
}
private static final String SETTINGS_NLS_ACCESSORS= "nls_accessor_history"; //$NON-NLS-1$
private static final int SETTINGS_MAX_ENTRIES= 5;
private Text fPrefixField;
private Button fIsEclipseNLS;
private Table fTable;
private TableViewer fTableViewer;
private SourceViewer fSourceViewer;
private final ICompilationUnit fCu;
private NLSSubstitution[] fSubstitutions;
private Button fExternalizeButton;
private Button fIgnoreButton;
private Button fInternalizeButton;
private Button fRevertButton;
private Button fEditButton;
private NLSRefactoring fNLSRefactoring;
private Button fRenameButton;
private Combo fAccessorClassField;
private AccessorDescription[] fAccessorChoices;
private Button fFilterCheckBox;
public ExternalizeWizardPage(NLSRefactoring nlsRefactoring) {
super(PAGE_NAME);
fCu= nlsRefactoring.getCu();
fSubstitutions= nlsRefactoring.getSubstitutions();
fNLSRefactoring= nlsRefactoring;
fAccessorChoices= null;
setDescription(NLSUIMessages.ExternalizeWizardPage_description);
createDefaultExternalization(fSubstitutions);
}
/*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite supercomposite= new Composite(parent, SWT.NONE);
supercomposite.setFont(parent.getFont());
supercomposite.setLayout(new GridLayout());
createIsEclipseNLSCheckbox(supercomposite);
createKeyPrefixField(supercomposite);
SashForm composite= new SashForm(supercomposite, SWT.VERTICAL);
composite.setFont(supercomposite.getFont());
GridData data= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(data);
createTableViewer(composite);
createSourceViewer(composite);
createAccessorInfoComposite(supercomposite);
composite.setWeights(new int[]{65, 45});
validateKeys(false);
updateButtonStates(StructuredSelection.EMPTY);
// promote control
setControl(supercomposite);
Dialog.applyDialogFont(supercomposite);
PlatformUI.getWorkbench().getHelpSystem().setHelp(supercomposite, IJavaHelpContextIds.EXTERNALIZE_WIZARD_KEYVALUE_PAGE);
}
private void createAccessorInfoComposite(Composite supercomposite) {
Composite accessorComposite= new Composite(supercomposite, SWT.NONE);
accessorComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout layout= new GridLayout(2, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
accessorComposite.setLayout(layout);
Composite composite= new Composite(accessorComposite, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
layout= new GridLayout(1, true);
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
Label accessorClassLabel= new Label(composite, SWT.NONE);
accessorClassLabel.setText(NLSUIMessages.ExternalizeWizardPage_accessorclass_label);
accessorClassLabel.setLayoutData(new GridData());
SelectionListener listener= new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (e.widget instanceof Button) {
doConfigureButtonPressed();
} else {
doAccessorSelectionChanged();
}
}
};
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(30);
fAccessorClassField= new Combo(composite, SWT.READ_ONLY);
SWTUtil.setDefaultVisibleItemCount(fAccessorClassField);
fAccessorClassField.setLayoutData(data);
fAccessorClassField.addSelectionListener(listener);
//new Label(composite, SWT.NONE); // placeholder
Button configure= new Button(accessorComposite, SWT.PUSH);
configure.setText(NLSUIMessages.ExternalizeWizardPage_configure_button);
data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_END);
data.widthHint= SWTUtil.getButtonWidthHint(configure);
configure.setLayoutData(data);
configure.addSelectionListener(listener);
updateAccessorChoices();
}
protected void doAccessorSelectionChanged() {
int selectionIndex= fAccessorClassField.getSelectionIndex();
if (fAccessorChoices != null && selectionIndex < fAccessorChoices.length) {
AccessorDescription selected= fAccessorChoices[selectionIndex];
fNLSRefactoring.setAccessorClassName(selected.getAccessorClassName());
fNLSRefactoring.setAccessorClassPackage(selected.getAccessorClassPackage());
fNLSRefactoring.setResourceBundleName(selected.getResourceBundleName());
fNLSRefactoring.setResourceBundlePackage(selected.getResourceBundlePackage());
fNLSRefactoring.setIsEclipseNLS(fNLSRefactoring.detectIsEclipseNLS());
NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
if (fIsEclipseNLS != null) {
fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
fIsEclipseNLS.setEnabled(willCreateAccessorClass());
updatePrefix();
}
validateKeys(true);
}
}
private boolean willCreateAccessorClass() {
try {
return fNLSRefactoring.willCreateAccessorClass();
} catch (JavaModelException e) {
return false;
}
}
private void updateAccessorChoices() {
AccessorDescription configured= new AccessorDescription(
fNLSRefactoring.getAccessorClassName(),
fNLSRefactoring.getAccessorClassPackage(),
fNLSRefactoring.getResourceBundleName(),
fNLSRefactoring.getResourceBundlePackage());
ArrayList<AccessorDescription> currChoices= new ArrayList<AccessorDescription>();
ArrayList<String> currLabels= new ArrayList<String>();
currChoices.add(configured);
currLabels.add(configured.getLabel());
AccessorDescription[] choices= fAccessorChoices;
if (choices == null) {
choices= loadAccessorDescriptions();
}
for (int i= 0; i < choices.length; i++) {
AccessorDescription curr= choices[i];
if (!curr.equals(configured)) {
currChoices.add(curr);
currLabels.add(curr.getLabel());
}
}
String[] labels= currLabels.toArray(new String[currLabels.size()]);
fAccessorChoices= currChoices.toArray(new AccessorDescription[currChoices.size()]);
fAccessorClassField.setItems(labels);
fAccessorClassField.select(0);
}
private AccessorDescription[] loadAccessorDescriptions() {
IDialogSettings section= JavaPlugin.getDefault().getDialogSettings().getSection(SETTINGS_NLS_ACCESSORS);
if (section == null) {
return new AccessorDescription[0];
}
ArrayList<AccessorDescription> res= new ArrayList<AccessorDescription>();
for (int i= 0; i < SETTINGS_MAX_ENTRIES; i++) {
IDialogSettings serializedDesc= section.getSection(String.valueOf(i));
if (serializedDesc != null) {
AccessorDescription accessor= AccessorDescription.deserialize(serializedDesc);
if (accessor != null) {
res.add(accessor);
}
}
}
return res.toArray(new AccessorDescription[res.size()]);
}
private void storeAccessorDescriptions() {
if (fAccessorChoices == null) {
return;
}
IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
IDialogSettings nlsSection= dialogSettings.getSection(SETTINGS_NLS_ACCESSORS);
if (nlsSection == null) {
nlsSection= dialogSettings.addNewSection(SETTINGS_NLS_ACCESSORS);
}
int nEntries= Math.min(SETTINGS_MAX_ENTRIES, fAccessorChoices.length);
for (int i= 0; i < nEntries; i++) {
IDialogSettings serializedDesc= nlsSection.addNewSection(String.valueOf(i));
fAccessorChoices[i].serialize(serializedDesc);
}
}
private void doConfigureButtonPressed() {
NLSAccessorConfigurationDialog dialog= new NLSAccessorConfigurationDialog(getShell(), fNLSRefactoring);
if (dialog.open() == Window.OK) {
NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
if (fIsEclipseNLS != null) {
fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
fIsEclipseNLS.setEnabled(willCreateAccessorClass());
}
validateKeys(true);
updateAccessorChoices();
}
}
private Properties getProperties(IFile propertyFile) {
Properties props= new Properties();
try {
if (propertyFile.exists()) {
InputStream is= propertyFile.getContents();
props.load(is);
is.close();
}
} catch (Exception e) {
// sorry no property
}
return props;
}
private void createTableViewer(Composite composite) {
createTableComposite(composite);
/*
* Feature of CellEditors - double click is ignored.
* The workaround is to register my own listener and force the desired
* behavior.
*/
fTableViewer= new TableViewer(fTable) {
@Override
protected void hookControl(Control control) {
super.hookControl(control);
((Table) control).addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
if (getTable().getSelection().length == 0)
return;
TableItem item= getTable().getSelection()[0];
if (item.getBounds(STATE_PROP).contains(e.x, e.y)) {
List<?> widgetSel= getSelectionFromWidget();
if (widgetSel == null || widgetSel.size() != 1)
return;
NLSSubstitution substitution= (NLSSubstitution) widgetSel.get(0);
Integer value= (Integer) getCellModifier().getValue(substitution, PROPERTIES[STATE_PROP]);
int newValue= MultiStateCellEditor.getNextValue(NLSSubstitution.STATE_COUNT, value.intValue());
getCellModifier().modify(item, PROPERTIES[STATE_PROP], new Integer(newValue));
}
}
});
}
};
fTableViewer.setUseHashlookup(true);
final CellEditor[] editors= createCellEditors();
fTableViewer.setCellEditors(editors);
fTableViewer.setColumnProperties(PROPERTIES);
fTableViewer.setCellModifier(new CellModifier());
fTableViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
return fSubstitutions;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
});
fTableViewer.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (!fFilterCheckBox.getSelection()) {
return true;
}
NLSSubstitution curr= (NLSSubstitution) element;
return (curr.getInitialState() == NLSSubstitution.INTERNALIZED) || (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null);
}
});
fTableViewer.setLabelProvider(new NLSSubstitutionLabelProvider());
fTableViewer.setInput(new Object());
fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ExternalizeWizardPage.this.selectionChanged(event);
}
});
}
private void createDefaultExternalization(NLSSubstitution[] substitutions) {
for (int i= 0; i < substitutions.length; i++) {
NLSSubstitution substitution= substitutions[i];
if (substitution.getState() == NLSSubstitution.INTERNALIZED) {
substitution.setState(NLSSubstitution.EXTERNALIZED);
substitution.generateKey(substitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()));
}
}
}
private CellEditor[] createCellEditors() {
final CellEditor editors[]= new CellEditor[SIZE];
editors[STATE_PROP]= new MultiStateCellEditor(fTable, NLSSubstitution.STATE_COUNT, NLSSubstitution.DEFAULT);
editors[KEY_PROP]= new TextCellEditor(fTable);
editors[VAL_PROP]= new TextCellEditor(fTable);
return editors;
}
private void createSourceViewer(Composite parent) {
Composite c= new Composite(parent, SWT.NONE);
c.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout gl= new GridLayout();
gl.marginHeight= 0;
gl.marginWidth= 0;
c.setLayout(gl);
Label l= new Label(c, SWT.NONE);
l.setText(NLSUIMessages.ExternalizeWizardPage_context);
l.setLayoutData(new GridData());
// source viewer
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
fSourceViewer= new JavaSourceViewer(c, null, null, false, styles, store);
fSourceViewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, null));
fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
try {
String contents= fCu.getBuffer().getContents();
IDocument document= new Document(contents);
tools.setupJavaDocumentPartitioner(document);
fSourceViewer.setDocument(document);
fSourceViewer.setEditable(false);
GridData gd= new GridData(GridData.FILL_BOTH);
gd.heightHint= convertHeightInCharsToPixels(10);
gd.widthHint= convertWidthInCharsToPixels(40);
fSourceViewer.getControl().setLayoutData(gd);
} catch (JavaModelException e) {
ExceptionHandler.handle(e, NLSUIMessages.ExternalizeWizardPage_exception_title, NLSUIMessages.ExternalizeWizardPage_exception_message);
}
}
private void createKeyPrefixField(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout gl= new GridLayout();
gl.numColumns= 2;
gl.marginWidth= 0;
composite.setLayout(gl);
Label l= new Label(composite, SWT.NONE);
l.setText(NLSUIMessages.ExternalizeWizardPage_common_prefix);
l.setLayoutData(new GridData());
fPrefixField= new Text(composite, SWT.SINGLE | SWT.BORDER);
fPrefixField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fPrefixField.setText(fNLSRefactoring.getPrefix());
fPrefixField.selectAll();
fPrefixField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
fNLSRefactoring.setPrefix(fPrefixField.getText());
validateKeys(true);
}
});
}
private void createIsEclipseNLSCheckbox(Composite parent) {
if (fNLSRefactoring.isEclipseNLS() || fNLSRefactoring.isEclipseNLSAvailable()) {
fIsEclipseNLS= new Button(parent, SWT.CHECK);
fIsEclipseNLS.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fIsEclipseNLS.setText(NLSUIMessages.ExternalizeWizardPage_isEclipseNLSCheckbox);
fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
fIsEclipseNLS.setEnabled(willCreateAccessorClass());
fIsEclipseNLS.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
super.widgetDefaultSelected(e);
boolean isEclipseNLS= fIsEclipseNLS.getSelection();
fNLSRefactoring.setIsEclipseNLS(isEclipseNLS);
updatePrefix();
}
});
}
}
private void validateKeys(boolean refreshTable) {
RefactoringStatus status= new RefactoringStatus();
checkInvalidKeys(status);
checkDuplicateKeys(status);
checkMissingKeys(status);
setPageComplete(status);
if (refreshTable)
fTableViewer.refresh(true);
}
private void checkInvalidKeys(RefactoringStatus status) {
for (int i= 0; i < fSubstitutions.length; i++) {
if (!isKeyValid(fSubstitutions[i], status))
return;
}
}
private boolean isKeyValid(NLSSubstitution substitution, RefactoringStatus status) {
if (substitution == null)
return false;
if (substitution.getState() != NLSSubstitution.EXTERNALIZED)
return true;
String key= substitution.getKey();
if (fNLSRefactoring.isEclipseNLS()) {
if (key == null || key.length() == 0 || !Character.isJavaIdentifierStart(key.charAt(0))) {
if (status != null)
status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
return false;
}
for (int i= 1, length= key.length(); i < length; i++) {
if (!Character.isJavaIdentifierPart(key.charAt(i))) {
if (status != null)
status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
return false;
}
}
} else {
if (key == null || key.length() == 0) {
if (status != null)
status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
return false;
}
// validation so keys don't contain spaces
for (int i= 0; i < key.length(); i++) {
if (Character.isWhitespace(key.charAt(i))) {
if (status != null)
status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
return false;
}
}
}
return true;
}
private void checkDuplicateKeys(RefactoringStatus status) {
for (int i= 0; i < fSubstitutions.length; i++) {
NLSSubstitution substitution= fSubstitutions[i];
if (conflictingKeys(substitution)) {
status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_conflicting);
return;
}
}
}
private void checkMissingKeys(RefactoringStatus status) {
for (int i= 0; i < fSubstitutions.length; i++) {
NLSSubstitution substitution= fSubstitutions[i];
if ((substitution.getValue() == null) && (substitution.getKey() != null)) {
status.addWarning(NLSUIMessages.ExternalizeWizardPage_warning_keymissing);
return;
}
}
}
private boolean conflictingKeys(NLSSubstitution substitution) {
if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
return substitution.isConflicting(fSubstitutions);
}
return false;
}
private void createTableComposite(Composite parent) {
Composite comp= new Composite(parent, SWT.NONE);
comp.setFont(parent.getFont());
comp.setLayoutData(new GridData(GridData.FILL_BOTH));
FormLayout fl= new FormLayout();
fl.marginWidth= 0;
fl.marginHeight= 0;
comp.setLayout(fl);
Label l= new Label(comp, SWT.NONE);
l.setText(NLSUIMessages.ExternalizeWizardPage_strings_to_externalize);
FormData formData = new FormData();
formData.left = new FormAttachment(0, 0);
l.setLayoutData(formData);
Control tableControl= createTable(comp);
formData = new FormData();
formData.top = new FormAttachment(l, 5);
formData.left = new FormAttachment(0, 0);
formData.right = new FormAttachment(100,0);
formData.bottom = new FormAttachment(100,0);
tableControl.setLayoutData(formData);
fFilterCheckBox= new Button(comp, SWT.CHECK);
fFilterCheckBox.setText(NLSUIMessages.ExternalizeWizardPage_filter_label);
formData = new FormData();
formData.right = new FormAttachment(100,0);
fFilterCheckBox.setLayoutData(formData);
fFilterCheckBox.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
doFilterCheckBoxPressed();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fFilterCheckBox.setSelection(hasNewOrMissingSubstitutions());
}
private boolean hasNewOrMissingSubstitutions() {
for (int i= 0; i < fSubstitutions.length; i++) {
NLSSubstitution curr= fSubstitutions[i];
if (curr.getInitialState() == NLSSubstitution.INTERNALIZED) {
return true;
}
if (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null) {
return true;
}
}
return false;
}
/**
*
*/
protected void doFilterCheckBoxPressed() {
fTableViewer.refresh();
}
private Control createTable(Composite parent) {
Composite c= new Composite(parent, SWT.NONE);
GridLayout gl= new GridLayout();
gl.numColumns= 2;
gl.marginWidth= 0;
gl.marginHeight= 0;
c.setLayout(gl);
fTable= new Table(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.BORDER);
fTable.setFont(parent.getFont());
GridData tableGD= new GridData(GridData.FILL_BOTH);
tableGD.heightHint= SWTUtil.getTableHeightHint(fTable, ROW_COUNT);
//tableGD.widthHint= 40;
fTable.setLayoutData(tableGD);
fTable.setLinesVisible(true);
TableLayout layout= new TableLayout();
fTable.setLayout(layout);
fTable.setHeaderVisible(true);
ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[SIZE];
columnLayoutData[STATE_PROP]= new ColumnPixelData(18, false, true);
columnLayoutData[KEY_PROP]= new ColumnWeightData(40, true);
columnLayoutData[VAL_PROP]= new ColumnWeightData(40, true);
for (int i= 0; i < fgTitles.length; i++) {
TableColumn tc= new TableColumn(fTable, SWT.NONE, i);
tc.setText(fgTitles[i]);
layout.addColumnData(columnLayoutData[i]);
tc.setResizable(columnLayoutData[i].resizable);
}
createButtonComposite(c);
return c;
}
private void createButtonComposite(Composite parent) {
Composite buttonComp= new Composite(parent, SWT.NONE);
GridLayout gl= new GridLayout();
gl.marginHeight= 0;
gl.marginWidth= 0;
buttonComp.setLayout(gl);
buttonComp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
SelectionAdapter adapter= new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleButtonPressed(e.widget);
}
};
fExternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Externalize_Selected, adapter);
fIgnoreButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Ignore_Selected, adapter);
fInternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Internalize_Selected, adapter);
new Label(buttonComp, SWT.NONE); // separator
fEditButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Edit_key_and_value, adapter);
fRevertButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Revert_Selected, adapter);
fRenameButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Rename_Keys, adapter);
fEditButton.setEnabled(false);
fRenameButton.setEnabled(false);
buttonComp.pack();
}
protected void handleButtonPressed(Widget widget) {
fTableViewer.getTable().forceFocus(); // make sure cell editor is applied on all platforms, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=269611
if (widget == fExternalizeButton) {
setSelectedTasks(NLSSubstitution.EXTERNALIZED);
} else if (widget == fIgnoreButton) {
setSelectedTasks(NLSSubstitution.IGNORED);
} else if (widget == fInternalizeButton) {
setSelectedTasks(NLSSubstitution.INTERNALIZED);
} else if (widget == fEditButton) {
openEditButton(fTableViewer.getSelection());
} else if (widget == fRevertButton) {
revertStateOfSelection();
} else if (widget == fRenameButton) {
openRenameDialog();
}
}
/**
*
*/
private void openRenameDialog() {
IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
List<NLSSubstitution> elementsToRename= getExternalizedElements(sel);
RenameKeysDialog dialog= new RenameKeysDialog(getShell(), elementsToRename);
if (dialog.open() == Window.OK) {
fTableViewer.refresh();
updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
}
}
private void revertStateOfSelection() {
List<?> selection= getSelectedTableEntries();
for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
NLSSubstitution substitution= (NLSSubstitution) iter.next();
substitution.revert();
}
fTableViewer.refresh();
updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
}
private Button createTaskButton(Composite parent, String label, SelectionAdapter adapter) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
SWTUtil.setButtonDimensionHint(button);
button.addSelectionListener(adapter);
return button;
}
private void openEditButton(ISelection selection) {
try {
IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
NLSSubstitution substitution= (NLSSubstitution) sel.getFirstElement();
if (substitution == null) {
return;
}
NLSInputDialog dialog= new NLSInputDialog(getShell(), substitution);
if (dialog.open() == Window.CANCEL)
return;
KeyValuePair kvPair= dialog.getResult();
if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
substitution.setKey(kvPair.getKey());
}
substitution.setValue(kvPair.getValue());
validateKeys(false);
} finally {
fTableViewer.refresh();
fTableViewer.getControl().setFocus();
fTableViewer.setSelection(selection);
}
}
private List<?> getSelectedTableEntries() {
ISelection sel= fTableViewer.getSelection();
if (sel instanceof IStructuredSelection)
return((IStructuredSelection) sel).toList();
else
return Collections.EMPTY_LIST;
}
private void setSelectedTasks(int state) {
Assert.isTrue(state == NLSSubstitution.EXTERNALIZED || state == NLSSubstitution.IGNORED || state == NLSSubstitution.INTERNALIZED);
List<?> selected= getSelectedTableEntries();
String[] props= new String[]{PROPERTIES[STATE_PROP]};
for (Iterator<?> iter= selected.iterator(); iter.hasNext();) {
NLSSubstitution substitution= (NLSSubstitution) iter.next();
substitution.setState(state);
if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
substitution.generateKey(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()));
}
}
fTableViewer.update(selected.toArray(), props);
fTableViewer.getControl().setFocus();
updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
}
private void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
updateButtonStates(selection);
updateSourceView(selection);
}
private void updateSourceView(IStructuredSelection selection) {
NLSSubstitution first= (NLSSubstitution) selection.getFirstElement();
if (first != null) {
Region region= first.getNLSElement().getPosition();
fSourceViewer.setSelectedRange(region.getOffset(), region.getLength());
fSourceViewer.revealRange(region.getOffset(), region.getLength());
}
}
private void updateButtonStates(IStructuredSelection selection) {
fExternalizeButton.setEnabled(true);
fIgnoreButton.setEnabled(true);
fInternalizeButton.setEnabled(true);
fRevertButton.setEnabled(true);
if (containsOnlyElementsOfSameState(NLSSubstitution.EXTERNALIZED, selection)) {
fExternalizeButton.setEnabled(false);
}
if (containsOnlyElementsOfSameState(NLSSubstitution.IGNORED, selection)) {
fIgnoreButton.setEnabled(false);
}
if (containsOnlyElementsOfSameState(NLSSubstitution.INTERNALIZED, selection)) {
fInternalizeButton.setEnabled(false);
}
if (!containsElementsWithChange(selection)) {
fRevertButton.setEnabled(false);
}
fRenameButton.setEnabled(getExternalizedElements(selection).size() > 1);
fEditButton.setEnabled(selection.size() == 1);
}
private boolean containsElementsWithChange(IStructuredSelection selection) {
for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
NLSSubstitution substitution= (NLSSubstitution) iter.next();
if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
return true;
}
}
return false;
}
private List<NLSSubstitution> getExternalizedElements(IStructuredSelection selection) {
ArrayList<NLSSubstitution> res= new ArrayList<NLSSubstitution>();
for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
NLSSubstitution substitution= (NLSSubstitution) iter.next();
if (substitution.getState() == NLSSubstitution.EXTERNALIZED && !substitution.hasStateChanged()) {
res.add(substitution);
}
}
return res;
}
private boolean containsOnlyElementsOfSameState(int state, IStructuredSelection selection) {
for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
NLSSubstitution substitution= (NLSSubstitution) iter.next();
if (substitution.getState() != state) {
return false;
}
}
return true;
}
@Override
public boolean performFinish() {
return super.performFinish();
}
@Override
public IWizardPage getNextPage() {
return super.getNextPage();
}
@Override
public void dispose() {
storeAccessorDescriptions();
//widgets will be disposed. only need to null'em
fPrefixField= null;
fSourceViewer= null;
fTable= null;
fTableViewer= null;
fEditButton= null;
super.dispose();
}
/**
* Updates the prefix.
*
* @since 3.4
*/
private void updatePrefix() {
if (fNLSRefactoring.isEclipseNLS()) {
fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('.', '_'));
} else {
fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('_', '.'));
}
fPrefixField.setText(fNLSRefactoring.getPrefix());
validateKeys(true);
}
}
| |
import java.net.* ;
import java.util.* ;
import java.io.* ;
import org.json.* ;
import org.restlet.resource.*;
import org.restlet.representation.* ;
import org.restlet.ext.json.* ;
import org.restlet.data.* ;
/**
Defines a single test case running in its own thread.
Each test case connects to a URL (via HTTP GET) and
grabs the number of bytes or error condition.
**/
public class RunLoadTest {
/** URL to run the test */
private String myURL ;
/** Request Counter to track number of repeated requests */
private int reqCount ;
/** Group of Threads Running HTTP GETS on List of URLs */
private ThreadGroup myGroup ;
/** Used to Signal a Stop Request to all running threads */
private static boolean out_of_time = false ;
/**
Constructor which assigns the thread to a group and its source URL.
@param grp Thread Group
@param srcURL URL specification
*/
RunLoadTest( ThreadGroup grp, String srcURL )
{
this.myURL = srcURL ;
this.reqCount = 0 ;
this.myGroup = grp ;
}
/**
Signal the all threads to stop processing
*/
public static void setOutOfTime()
{
out_of_time = true ;
}
/**
Test for threads to check for stop processing signal
@return true, if out of time; otherwise, false.
*/
public static boolean isOutOfTime()
{
return out_of_time ;
}
/**
Creates a thread and runs a test case
*/
public void runTest()
{
// anonymous inner class for thread target
Thread myThread = new Thread (
this.myGroup,
new Runnable()
{
public void run()
{
while( !RunLoadTest.isOutOfTime() )
{
doTest() ;
try { Thread.sleep( 500 ) ; }
catch ( InterruptedException e ) {
System.out.println( e.getMessage() ) ;
}
}
System.out.println( "Test " + myGroup + " Stopped! ==> " + reqCount + " Runs.") ;
}
}
) ;
myThread.start() ;
}
/**
Performs a test by sending HTTP Gets to the URL,
and records the number of bytes returned. Each
test results are documented and displayed in
standard out with the following information:
URL - The source URL of the test
REQ CNT - How many times this test has run
START - The start time of the last test run
STOP - The stop time of the last test run
THREAD - The thread id handling this test case
RESULT - The result of the test. Either the number of bytes returned or an error message.
*/
private void doTest()
{
String result = "" ;
this.reqCount++ ;
// Connect and run test steps
Date startTime = new Date() ;
try {
ClientResource client = new ClientResource( this.myURL );
// place order
JSONObject json = new JSONObject();
json.put("payment", "quarter");
json.put("action", "place-order");
client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON);
// Get Gumball Count
Representation result_string = client.get() ;
JSONObject json_count = new JSONObject( result_string.getText() ) ;
result = Integer.toString( (int)json_count.get("count") ) ;
}
catch ( Exception e ) {
result = e.toString() ;
}
finally {
Date stopTime = new Date() ;
// Print Report of Result:
System.out.println( "======================================\n" +
"URL => " + this.myURL + "\n" +
"REQ CNT => " + this.reqCount + "\n" +
"START => " + startTime + "\n" +
"STOP => " + stopTime + "\n" +
"THREAD => " + Thread.currentThread().getName() + "\n" +
"RESULT => " + result + "\n" ) ;
}
}
/**
Main Class Routine that reads in URL specs from a file and a duration (in miliseconds)
of how long to run the test.
USAGE: java RunLoadTest [Duration in seconds]</b>
*/
public static void main( String[] args )
{
if ( args.length == 1 )
{
// Record Start of Test Run
Date testStart = new Date() ;
// Load and run tests
loadThread( "Test Group #1") ;
loadThread( "Test Group #2") ;
loadThread( "Test Group #3") ;
loadThread( "Test Group #4") ;
loadThread( "Test Group #5") ;
loadThread( "Test Group #6") ;
loadThread( "Test Group #7") ;
loadThread( "Test Group #8") ;
loadThread( "Test Group #9") ;
loadThread( "Test Group #10") ;
// Set Timer to stop testing
Timer timer = new Timer() ;
TimerTask task = new TimerTask()
{
public void run()
{
Date testStop = new Date() ;
RunLoadTest.setOutOfTime() ;
try { Thread.sleep(5000); } catch ( Exception e ) {}
// Pause to allow all threads to stop.
System.out.println( "Start Test Run: " + testStart.toString() ) ;
System.out.println( "Stop Test Run: " + testStop.toString() ) ;
long secondsBetween = (testStop.getTime() - testStart.getTime()) / 1000 ;
System.out.println( "Total Seconds: " + secondsBetween ) ;
}
} ;
// Schedule Test Run according to the duration given
long curDate = new Date().getTime() ;
long milis = Long.parseLong( args[0] ) * 1000 ;
timer.schedule( task, new Date( curDate + milis) );
}
else {
System.out.println( "USAGE: java RunLoadTest [Duration in seconds]" ) ;
}
}
/**
Helper method for main to load tests into a thread group and start each test case.
*/
private static void loadThread( String name ) {
try {
ThreadGroup myThreadGroup = new ThreadGroup( name ) ;
String urlSpec = "http://54.201.122.231:8181/v3/gumball" ;
//String urlSpec = "http://localhost:8080/v3/gumball" ;
RunLoadTest test = new RunLoadTest( myThreadGroup, urlSpec ) ;
test.runTest() ; // Run The Test in its own thread
myThreadGroup.list() ;
} catch ( Exception e ) {
System.out.println( "ERROR: " + e.getMessage() );
}
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.contentviewers;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.openide.nodes.Node;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeNormalizationException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationDataSource;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamArtifactUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContentViewer;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.Tag;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Annotations view of file contents.
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
@ServiceProvider(service = DataContentViewer.class, position = 8)
@NbBundle.Messages({
"AnnotationsContentViewer.title=Annotations",
"AnnotationsContentViewer.toolTip=Displays tags and comments associated with the selected content."
})
public class AnnotationsContentViewer extends javax.swing.JPanel implements DataContentViewer {
private static final Logger logger = Logger.getLogger(AnnotationsContentViewer.class.getName());
/**
* Creates an instance of AnnotationsContentViewer.
*/
public AnnotationsContentViewer() {
initComponents();
Utilities.configureTextPaneAsHtml(jTextPane1);
}
@Override
public void setNode(Node node) {
if ((node == null) || (!isSupported(node))) {
resetComponent();
return;
}
StringBuilder html = new StringBuilder();
BlackboardArtifact artifact = node.getLookup().lookup(BlackboardArtifact.class);
Content sourceFile = null;
try {
if (artifact != null) {
/*
* Get the source content based on the artifact to ensure we
* display the correct data instead of whatever was in the node.
*/
sourceFile = artifact.getSleuthkitCase().getAbstractFileById(artifact.getObjectID());
} else {
/*
* No artifact is present, so get the content based on what's
* present in the node. In this case, the selected item IS the
* source file.
*/
sourceFile = node.getLookup().lookup(AbstractFile.class);
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format(
"Exception while trying to retrieve a Content instance from the BlackboardArtifact '%s' (id=%d).",
artifact.getDisplayName(), artifact.getArtifactID()), ex);
}
if (artifact != null) {
populateTagData(html, artifact, sourceFile);
} else {
populateTagData(html, sourceFile);
}
if (sourceFile instanceof AbstractFile) {
populateCentralRepositoryData(html, artifact, (AbstractFile) sourceFile);
}
setText(html.toString());
jTextPane1.setCaretPosition(0);
}
/**
* Populate the "Selected Item" sections with tag data for the supplied
* content.
*
* @param html The HTML text to update.
* @param content Selected content.
*/
private void populateTagData(StringBuilder html, Content content) {
try {
SleuthkitCase tskCase = Case.getCurrentCaseThrows().getSleuthkitCase();
startSection(html, "Selected Item");
List<ContentTag> fileTagsList = tskCase.getContentTagsByContent(content);
if (fileTagsList.isEmpty()) {
addMessage(html, "There are no tags for the selected content.");
} else {
for (ContentTag tag : fileTagsList) {
addTagEntry(html, tag);
}
}
endSection(html);
} catch (NoCurrentCaseException ex) {
logger.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Exception while getting tags from the case database.", ex); //NON-NLS
}
}
/**
* Populate the "Selected Item" and "Source File" sections with tag data for
* a supplied artifact.
*
* @param html The HTML text to update.
* @param artifact A selected artifact.
* @param sourceFile The source content of the selected artifact.
*/
private void populateTagData(StringBuilder html, BlackboardArtifact artifact, Content sourceFile) {
try {
SleuthkitCase tskCase = Case.getCurrentCaseThrows().getSleuthkitCase();
startSection(html, "Selected Item");
List<BlackboardArtifactTag> artifactTagsList = tskCase.getBlackboardArtifactTagsByArtifact(artifact);
if (artifactTagsList.isEmpty()) {
addMessage(html, "There are no tags for the selected artifact.");
} else {
for (BlackboardArtifactTag tag : artifactTagsList) {
addTagEntry(html, tag);
}
}
endSection(html);
if (sourceFile != null) {
startSection(html, "Source File");
List<ContentTag> fileTagsList = tskCase.getContentTagsByContent(sourceFile);
if (fileTagsList.isEmpty()) {
addMessage(html, "There are no tags for the source content.");
} else {
for (ContentTag tag : fileTagsList) {
addTagEntry(html, tag);
}
}
endSection(html);
}
} catch (NoCurrentCaseException ex) {
logger.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Exception while getting tags from the case database.", ex); //NON-NLS
}
}
/**
* Populate the "Central Repository Comments" section with data.
*
* @param html The HTML text to update.
* @param artifact A selected artifact (can be null).
* @param sourceFile A selected file, or a source file of the selected
* artifact.
*/
private void populateCentralRepositoryData(StringBuilder html, BlackboardArtifact artifact, AbstractFile sourceFile) {
if (EamDb.isEnabled()) {
startSection(html, "Central Repository Comments");
List<CorrelationAttributeInstance> instancesList = new ArrayList<>();
if (artifact != null) {
instancesList.addAll(EamArtifactUtil.makeInstancesFromBlackboardArtifact(artifact, false));
}
try {
List<CorrelationAttributeInstance.Type> artifactTypes = EamDb.getInstance().getDefinedCorrelationTypes();
String md5 = sourceFile.getMd5Hash();
if (md5 != null && !md5.isEmpty() && null != artifactTypes && !artifactTypes.isEmpty()) {
for (CorrelationAttributeInstance.Type attributeType : artifactTypes) {
if (attributeType.getId() == CorrelationAttributeInstance.FILES_TYPE_ID) {
CorrelationCase correlationCase = EamDb.getInstance().getCase(Case.getCurrentCase());
instancesList.add(new CorrelationAttributeInstance(
md5,
attributeType,
correlationCase,
CorrelationDataSource.fromTSKDataSource(correlationCase, sourceFile.getDataSource()),
sourceFile.getParentPath() + sourceFile.getName(),
"",
sourceFile.getKnown()));
break;
}
}
}
boolean commentDataFound = false;
for (CorrelationAttributeInstance instance : instancesList) {
List<CorrelationAttributeInstance> correlatedInstancesList =
EamDb.getInstance().getArtifactInstancesByTypeValue(instance.getCorrelationType(), instance.getCorrelationValue());
for (CorrelationAttributeInstance correlatedInstance : correlatedInstancesList) {
if (correlatedInstance.getComment() != null && correlatedInstance.getComment().isEmpty() == false) {
commentDataFound = true;
addCentralRepositoryEntry(html, correlatedInstance);
}
}
}
if (commentDataFound == false) {
addMessage(html, "There is no comment data for the selected content in the Central Repository.");
}
} catch (EamDbException | TskCoreException ex) {
logger.log(Level.SEVERE, "Error connecting to the Central Repository database.", ex); // NON-NLS
} catch (CorrelationAttributeNormalizationException ex) {
logger.log(Level.SEVERE, "Error normalizing instance from Central Repository database.", ex); // NON-NLS
}
endSection(html);
}
}
/**
* Set the text of the text panel.
*
* @param text The text to set to the text panel.
*/
private void setText(String text) {
jTextPane1.setText("<html><body>" + text + "</body></html>"); //NON-NLS
}
/**
* Start a new data section.
*
* @param html The HTML text to add the section to.
* @param sectionName The name of the section.
*/
private void startSection(StringBuilder html, String sectionName) {
html.append("<p style=\"font-size:14px;font-weight:bold;\">")
.append(sectionName)
.append("</p><br>"); //NON-NLS
}
/**
* Add a message.
*
* @param html The HTML text to add the message to.
* @param message The message text.
*/
private void addMessage(StringBuilder html, String message) {
html.append("<p style=\"font-size:11px;font-style:italic;\">")
.append(message)
.append("</p><br>"); //NON-NLS
}
/**
* Add a data table containing information about a tag.
*
* @param html The HTML text to add the table to.
* @param tag The tag whose information will be used to populate the table.
*/
@NbBundle.Messages({
"AnnotationsContentViewer.tagEntryDataLabel.tag=Tag:",
"AnnotationsContentViewer.tagEntryDataLabel.tagUser=Tag User:",
"AnnotationsContentViewer.tagEntryDataLabel.comment=Comment:"
})
private void addTagEntry(StringBuilder html, Tag tag) {
startTable(html);
addRow(html, Bundle.AnnotationsContentViewer_tagEntryDataLabel_tag(), tag.getName().getDisplayName());
addRow(html, Bundle.AnnotationsContentViewer_tagEntryDataLabel_tagUser(), tag.getUserName());
addRow(html, Bundle.AnnotationsContentViewer_tagEntryDataLabel_comment(), formatHtmlString(tag.getComment()));
endTable(html);
}
/**
* Add a data table containing information about a correlation attribute
* instance in the Central Repository.
*
* @param html The HTML text to add the table to.
* @param attributeInstance The attribute instance whose information will be
* used to populate the table.
*/
@NbBundle.Messages({
"AnnotationsContentViewer.centralRepositoryEntryDataLabel.case=Case:",
"AnnotationsContentViewer.centralRepositoryEntryDataLabel.type=Type:",
"AnnotationsContentViewer.centralRepositoryEntryDataLabel.comment=Comment:",
"AnnotationsContentViewer.centralRepositoryEntryDataLabel.path=Path:"
})
private void addCentralRepositoryEntry(StringBuilder html, CorrelationAttributeInstance attributeInstance) {
startTable(html);
addRow(html, Bundle.AnnotationsContentViewer_centralRepositoryEntryDataLabel_case(), attributeInstance.getCorrelationCase().getDisplayName());
addRow(html, Bundle.AnnotationsContentViewer_centralRepositoryEntryDataLabel_type(), attributeInstance.getCorrelationType().getDisplayName());
addRow(html, Bundle.AnnotationsContentViewer_centralRepositoryEntryDataLabel_comment(), formatHtmlString(attributeInstance.getComment()));
addRow(html, Bundle.AnnotationsContentViewer_centralRepositoryEntryDataLabel_path(), attributeInstance.getFilePath());
endTable(html);
}
/**
* Start a data table.
*
* @param html The HTML text to add the table to.
*/
private void startTable(StringBuilder html) {
html.append("<table>"); //NON-NLS
}
/**
* Add a data row to a table.
*
* @param html The HTML text to add the row to.
* @param key The key for the left column of the data row.
* @param value The value for the right column of the data row.
*/
private void addRow(StringBuilder html, String key, String value) {
html.append("<tr><td valign=\"top\">"); //NON-NLS
html.append(key);
html.append("</td><td>"); //NON-NLS
html.append(value);
html.append("</td></tr>"); //NON-NLS
}
/**
* End a data table.
*
* @param html The HTML text on which to end a table.
*/
private void endTable(StringBuilder html) {
html.append("</table><br><br>"); //NON-NLS
}
/**
* End a data section.
*
* @param html The HTML text on which to end a section.
*/
private void endSection(StringBuilder html) {
html.append("<br>"); //NON-NLS
}
/**
* Apply escape sequence to special characters. Line feed and carriage
* return character combinations will be converted to HTML line breaks.
*
* @param text The text to format.
* @return The formatted text.
*/
private String formatHtmlString(String text) {
String formattedString = StringEscapeUtils.escapeHtml4(text);
return formattedString.replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane5 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setPreferredSize(new java.awt.Dimension(100, 58));
jTextPane1.setEditable(false);
jTextPane1.setName(""); // NOI18N
jTextPane1.setPreferredSize(new java.awt.Dimension(600, 52));
jScrollPane5.setViewportView(jTextPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 907, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
@Override
public String getTitle() {
return Bundle.AnnotationsContentViewer_title();
}
@Override
public String getToolTip() {
return Bundle.AnnotationsContentViewer_toolTip();
}
@Override
public DataContentViewer createInstance() {
return new AnnotationsContentViewer();
}
@Override
public boolean isSupported(Node node) {
BlackboardArtifact artifact = node.getLookup().lookup(BlackboardArtifact.class);
try {
if (artifact != null) {
if (artifact.getSleuthkitCase().getAbstractFileById(artifact.getObjectID()) != null) {
return true;
}
} else {
if (node.getLookup().lookup(AbstractFile.class) != null) {
return true;
}
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format(
"Exception while trying to retrieve a Content instance from the BlackboardArtifact '%s' (id=%d).",
artifact.getDisplayName(), artifact.getArtifactID()), ex);
}
return false;
}
@Override
public int isPreferred(Node node) {
return 1;
}
@Override
public Component getComponent() {
return this;
}
@Override
public void resetComponent() {
setText("");
}
}
| |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.install;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import org.hyperic.tools.ant.installer.InstallerConfigSchemaProvider;
import org.hyperic.util.JDK;
import org.hyperic.util.StringUtil;
import org.hyperic.util.config.ConfigResponse;
import org.hyperic.util.config.ConfigSchema;
import org.hyperic.util.config.DirConfigOption;
import org.hyperic.util.config.EarlyExitException;
import org.hyperic.util.config.InvalidOptionValueException;
import org.hyperic.util.file.FileUtil;
public abstract class BaseConfig implements InstallerConfigSchemaProvider {
public static final String PRODUCT = "HQ";
public static final String INSTALLMODE_UPGRADE = "upgrade";
public static final String INSTALLMODE_QUICK = "quick";
public static final String INSTALLMODE_ORACLE = "oracle";
public static final String INSTALLMODE_POSTGRESQL = "postgresql";
public static final String INSTALLMODE_MYSQL = "mysql";
public static final String INSTALLMODE_FULL = "full";
private final String baseName;
private Hashtable projectProps;
private String installDir;
public BaseConfig (String baseName) {
this.baseName = baseName;
}
public void setInstallDir(String instDir) {
installDir = instDir;
}
public String getInstallDir () { return installDir; }
public void setProjectProperties(Hashtable props) {
this.projectProps = props;
}
public Hashtable getProjectProperties () { return projectProps; }
public String getProjectProperty (String key) {
Object o = projectProps.get(key);
if (o == null) return "null";
return o.toString();
}
public void setProjectProperty (String key, String value) {
projectProps.put(key, value);
}
public String getCompletionText (ConfigResponse config) {
return null;
}
public String getBaseName() {
return baseName;
}
public abstract String getName();
public boolean isUpgrade () {
String installMode = getProjectProperty("install.mode");
return installMode.equals(INSTALLMODE_UPGRADE);
}
/**
* Return the directory where the product will be installed.
* This is the value the end-user entered during the installation, for
* example, /usr/local/HQ or "C:\Program Files\Hyperic HQ"
* @return the install dir. The return value will always end with a
* File.separator
*/
public String getInstallDir (ConfigResponse config) {
String dir
= StringUtil.normalizePath(config.getValue(getBaseName()
+ ".installdir"));
if (!dir.endsWith(File.separator)) dir += File.separator;
return dir;
}
/**
* The product installation directory. This includes the product name
* and version, for example /usr/local/HQ/server-1.2.9 on unix or
* "C:\Program Files\Hyperic HQ\server-1.2.9" on windows
* @return the product install dir. This value will always end
* in a File.separator
*/
public String getProductInstallDir (ConfigResponse config) {
String installDir = getInstallDir(config);
return installDir
+ getBaseName() + "-" + getProjectProperty("version")
+ File.separator;
}
public ConfigSchema getSchema (ConfigResponse previous,
int iterationCount)
throws EarlyExitException {
if (iterationCount == 2) {
// Sanity check
String installDir = getInstallDir(previous);
File dir = new File(installDir);
try {
if (!FileUtil.canWrite(dir)) {
throw new EarlyExitException("Can't write to installation "
+ "directory: " + installDir);
}
} catch (IOException e) {
throw new EarlyExitException("Can't write to installation " +
"directory: " + e.getMessage());
}
}
if (isUpgrade()) return getUpgradeSchema(previous, iterationCount);
return getInstallSchema(previous, iterationCount);
}
protected ConfigSchema getUpgradeSchema (ConfigResponse previous,
int iterationCount)
throws EarlyExitException {
ConfigSchema schema = new ConfigSchema();
if (iterationCount == 0) {
schema.addOption(new UpgradeDirConfigOption(baseName+".upgradedir",
"Enter current installation path of "
+ getName()
+ " to upgrade: ",
"", this));
return schema;
} else if (iterationCount == 1) {
String upgradeDir = previous.getValue(baseName+".upgradedir");
String installDir = new File(upgradeDir).getParent();
if (installDir == null || installDir.startsWith("${")) {
installDir = getDefaultInstallPath();
}
schema.addOption(new DirConfigOption(baseName + ".installdir",
"Enter new " + getName() + " directory",
installDir));
return schema;
}
return null;
}
/**
* A callback used by UpgradeDirConfigOption. The UpgradeDirConfigOption's
* checkOptionIsValid method ensures that the directory the user specifies
* for upgrade exists and that it contains an appropriate marker file as
* returned by the BaseConfig.getMarkerFiles method. Then it calls into
* this method. This method lets each product implement further checks
* to ensure that the directory is suitable for upgrade. In particular, the
* HQ server checks to see if a pointbase-backed server is going to be
* upgraded, and throws an error if it is because we don't upgrade pointbase
*/
public void canUpgrade (String dir) throws InvalidOptionValueException {}
/**
* @return An array of Strings, each representing a marker file that would
* indicate the presence of the product. These files should be relative,
* and should not begin with a slash. They should use UNIX-style slashes
* for directories. Look at ShellConfig.getMarkerFiles for an example.
*/
protected abstract String[] getMarkerFiles ();
protected ConfigSchema getInstallSchema (ConfigResponse previous,
int iterationCount)
throws EarlyExitException {
ConfigSchema schema = new ConfigSchema();
if ( iterationCount == 0 ) {
// populate schema...
if (installDir == null || installDir.startsWith("${")) {
installDir = getDefaultInstallPath();
}
schema.addOption(new DirConfigOption(baseName + ".installdir",
getName() + " installation " +
"path",
installDir));
}
return schema;
}
private static String getDefaultInstallPath() {
if (JDK.IS_WIN32) {
return "C:\\Program Files";
}
return "/home/hyperic";
}
protected String getExtension() {
if (JDK.IS_WIN32) {
return ".bat";
}
else {
return ".sh";
}
}
protected String getScriptExtension() {
if (JDK.IS_WIN32) {
return ".bat";
}
else {
return ".sh";
}
}
}
| |
/*
* Copyright 2013 Gunnar Kappei.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.opengis.gml.impl;
/**
* An XML MultiCurveType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public class MultiCurveTypeImpl extends net.opengis.gml.impl.AbstractGeometricAggregateTypeImpl implements net.opengis.gml.MultiCurveType
{
private static final long serialVersionUID = 1L;
public MultiCurveTypeImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName CURVEMEMBER$0 =
new javax.xml.namespace.QName("http://www.opengis.net/gml", "curveMember");
private static final javax.xml.namespace.QName CURVEMEMBERS$2 =
new javax.xml.namespace.QName("http://www.opengis.net/gml", "curveMembers");
/**
* Gets a List of "curveMember" elements
*/
public java.util.List<net.opengis.gml.CurvePropertyType> getCurveMemberList()
{
final class CurveMemberList extends java.util.AbstractList<net.opengis.gml.CurvePropertyType>
{
@Override
public net.opengis.gml.CurvePropertyType get(int i)
{ return MultiCurveTypeImpl.this.getCurveMemberArray(i); }
@Override
public net.opengis.gml.CurvePropertyType set(int i, net.opengis.gml.CurvePropertyType o)
{
net.opengis.gml.CurvePropertyType old = MultiCurveTypeImpl.this.getCurveMemberArray(i);
MultiCurveTypeImpl.this.setCurveMemberArray(i, o);
return old;
}
@Override
public void add(int i, net.opengis.gml.CurvePropertyType o)
{ MultiCurveTypeImpl.this.insertNewCurveMember(i).set(o); }
@Override
public net.opengis.gml.CurvePropertyType remove(int i)
{
net.opengis.gml.CurvePropertyType old = MultiCurveTypeImpl.this.getCurveMemberArray(i);
MultiCurveTypeImpl.this.removeCurveMember(i);
return old;
}
@Override
public int size()
{ return MultiCurveTypeImpl.this.sizeOfCurveMemberArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new CurveMemberList();
}
}
/**
* Gets array of all "curveMember" elements
* @deprecated
*/
@Deprecated
public net.opengis.gml.CurvePropertyType[] getCurveMemberArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<net.opengis.gml.CurvePropertyType> targetList = new java.util.ArrayList<net.opengis.gml.CurvePropertyType>();
get_store().find_all_element_users(CURVEMEMBER$0, targetList);
net.opengis.gml.CurvePropertyType[] result = new net.opengis.gml.CurvePropertyType[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "curveMember" element
*/
public net.opengis.gml.CurvePropertyType getCurveMemberArray(int i)
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CurvePropertyType target = null;
target = (net.opengis.gml.CurvePropertyType)get_store().find_element_user(CURVEMEMBER$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "curveMember" element
*/
public int sizeOfCurveMemberArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(CURVEMEMBER$0);
}
}
/**
* Sets array of all "curveMember" element WARNING: This method is not atomicaly synchronized.
*/
public void setCurveMemberArray(net.opengis.gml.CurvePropertyType[] curveMemberArray)
{
check_orphaned();
arraySetterHelper(curveMemberArray, CURVEMEMBER$0);
}
/**
* Sets ith "curveMember" element
*/
public void setCurveMemberArray(int i, net.opengis.gml.CurvePropertyType curveMember)
{
generatedSetterHelperImpl(curveMember, CURVEMEMBER$0, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "curveMember" element
*/
public net.opengis.gml.CurvePropertyType insertNewCurveMember(int i)
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CurvePropertyType target = null;
target = (net.opengis.gml.CurvePropertyType)get_store().insert_element_user(CURVEMEMBER$0, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "curveMember" element
*/
public net.opengis.gml.CurvePropertyType addNewCurveMember()
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CurvePropertyType target = null;
target = (net.opengis.gml.CurvePropertyType)get_store().add_element_user(CURVEMEMBER$0);
return target;
}
}
/**
* Removes the ith "curveMember" element
*/
public void removeCurveMember(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(CURVEMEMBER$0, i);
}
}
/**
* Gets the "curveMembers" element
*/
public net.opengis.gml.CurveArrayPropertyType getCurveMembers()
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CurveArrayPropertyType target = null;
target = (net.opengis.gml.CurveArrayPropertyType)get_store().find_element_user(CURVEMEMBERS$2, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* True if has "curveMembers" element
*/
public boolean isSetCurveMembers()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(CURVEMEMBERS$2) != 0;
}
}
/**
* Sets the "curveMembers" element
*/
public void setCurveMembers(net.opengis.gml.CurveArrayPropertyType curveMembers)
{
generatedSetterHelperImpl(curveMembers, CURVEMEMBERS$2, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "curveMembers" element
*/
public net.opengis.gml.CurveArrayPropertyType addNewCurveMembers()
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CurveArrayPropertyType target = null;
target = (net.opengis.gml.CurveArrayPropertyType)get_store().add_element_user(CURVEMEMBERS$2);
return target;
}
}
/**
* Unsets the "curveMembers" element
*/
public void unsetCurveMembers()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(CURVEMEMBERS$2, 0);
}
}
}
| |
package org.dice.solrenhancements.spellchecker;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SH: This doesn't do anything different to solr src it's currently just for testing the suggester functionality, so see why it's failing for
* certain scenarios.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.HighFrequencyDictionary;
import org.apache.lucene.search.spell.SuggestMode;
import org.apache.lucene.search.suggest.FileDictionary;
import org.apache.lucene.search.suggest.Lookup;
import org.apache.lucene.search.suggest.Lookup.LookupResult;
import org.apache.lucene.search.suggest.analyzing.AnalyzingSuggester;
import org.apache.lucene.search.suggest.fst.WFSTCompletionLookup;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.spelling.SolrSpellChecker;
import org.apache.solr.spelling.SpellingOptions;
import org.apache.solr.spelling.SpellingResult;
import org.apache.solr.spelling.suggest.LookupFactory;
import org.apache.solr.spelling.suggest.fst.FSTLookupFactory;
import org.apache.solr.spelling.suggest.jaspell.JaspellLookupFactory;
import org.apache.solr.spelling.suggest.tst.TSTLookupFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
public class DiceSuggester extends SolrSpellChecker {
private static final Logger LOG = LoggerFactory.getLogger(DiceSuggester.class);
/** Location of the source data - either a path to a file, or null for the
* current IndexReader.
*/
public static final String LOCATION = "sourceLocation";
public static final String SUGGESTION_ANALYZER_FIELDTYPE = "suggestionAnalyzerFieldTypeName";
/** Fully-qualified class of the {@link Lookup} implementation. */
public static final String LOOKUP_IMPL = "lookupImpl";
/**
* Minimum frequency of terms to consider when building the dictionary.
*/
public static final String THRESHOLD_TOKEN_FREQUENCY = "threshold";
/**
* Name of the location where to persist the dictionary. If this location
* is relative then the data will be stored under the core's dataDir. If this
* is null the storing will be disabled.
*/
public static final String STORE_DIR = "storeDir";
protected String sourceLocation;
protected File storeDir;
protected float threshold;
protected Dictionary dictionary;
protected IndexReader reader;
protected Lookup lookup;
protected String lookupImpl;
protected SolrCore core;
private LookupFactory factory;
private Analyzer suggestionAnalyzer = null;
private String suggestionAnalyzerFieldTypeName = null;
@Override
public String init(NamedList config, SolrCore core) {
LOG.info("init: " + config);
String name = super.init(config, core);
threshold = config.get(THRESHOLD_TOKEN_FREQUENCY) == null ? 0.0f
: (Float)config.get(THRESHOLD_TOKEN_FREQUENCY);
sourceLocation = (String) config.get(LOCATION);
lookupImpl = (String)config.get(LOOKUP_IMPL);
IndexSchema schema = core.getLatestSchema();
suggestionAnalyzerFieldTypeName = (String)config.get(SUGGESTION_ANALYZER_FIELDTYPE);
if (schema.getFieldTypes().containsKey(suggestionAnalyzerFieldTypeName)) {
FieldType fieldType = schema.getFieldTypes().get(suggestionAnalyzerFieldTypeName);
suggestionAnalyzer = fieldType.getQueryAnalyzer();
}
// support the old classnames without -Factory for config file backwards compatibility.
if (lookupImpl == null || "org.apache.solr.spelling.suggest.jaspell.JaspellLookup".equals(lookupImpl)) {
lookupImpl = JaspellLookupFactory.class.getName();
} else if ("org.apache.solr.spelling.suggest.tst.TSTLookup".equals(lookupImpl)) {
lookupImpl = TSTLookupFactory.class.getName();
} else if ("org.apache.solr.spelling.suggest.fst.FSTLookup".equals(lookupImpl)) {
lookupImpl = FSTLookupFactory.class.getName();
}
factory = core.getResourceLoader().newInstance(lookupImpl, LookupFactory.class);
lookup = factory.create(config, core);
String store = (String)config.get(STORE_DIR);
if (store != null) {
storeDir = new File(store);
if (!storeDir.isAbsolute()) {
storeDir = new File(core.getDataDir() + File.separator + storeDir);
}
if (!storeDir.exists()) {
storeDir.mkdirs();
} else {
// attempt reload of the stored lookup
try {
lookup.load(new FileInputStream(new File(storeDir, factory.storeFileName())));
} catch (IOException e) {
LOG.warn("Loading stored lookup data failed", e);
}
}
}
return name;
}
@Override
public void build(SolrCore core, SolrIndexSearcher searcher) throws IOException {
LOG.info("build()");
if (sourceLocation == null) {
reader = searcher.getIndexReader();
dictionary = new HighFrequencyDictionary(reader, field, threshold);
} else {
try {
final String fileDelim = ",";
if(sourceLocation.contains(fileDelim)){
String[] files = sourceLocation.split(fileDelim);
Reader[] readers = new Reader[files.length];
for(int i = 0; i < files.length; i++){
Reader reader = new InputStreamReader(
core.getResourceLoader().openResource(files[i]),IOUtils.UTF_8);
readers[i] = reader;
}
dictionary = new MultipleFileDictionary(readers);
}
else{
dictionary = new FileDictionary(new InputStreamReader(
core.getResourceLoader().openResource(sourceLocation), IOUtils.UTF_8));
}
} catch (UnsupportedEncodingException e) {
// should not happen
LOG.error("should not happen", e);
}
}
lookup.build(dictionary);
if (storeDir != null) {
File target = new File(storeDir, factory.storeFileName());
if(!lookup.store(new FileOutputStream(target))) {
if (sourceLocation == null) {
assert reader != null && field != null;
LOG.error("Store Lookup build from index on field: " + field + " failed reader has: " + reader.maxDoc() + " docs");
} else {
LOG.error("Store Lookup build from sourceloaction: " + sourceLocation + " failed");
}
} else {
LOG.info("Stored suggest data to: " + target.getAbsolutePath());
}
}
}
@Override
public void reload(SolrCore core, SolrIndexSearcher searcher) throws IOException {
LOG.info("reload()");
if (dictionary == null && storeDir != null) {
// this may be a firstSearcher event, try loading it
FileInputStream is = new FileInputStream(new File(storeDir, factory.storeFileName()));
try {
if (lookup.load(is)) {
return; // loaded ok
}
} finally {
IOUtils.closeWhileHandlingException(is);
}
LOG.debug("load failed, need to build Lookup again");
}
// loading was unsuccessful - build it again
build(core, searcher);
}
static SpellingResult EMPTY_RESULT = new SpellingResult();
@Override
public SpellingResult getSuggestions(SpellingOptions options) throws IOException {
LOG.debug("getSuggestions: " + options.tokens);
if (lookup == null) {
LOG.info("Lookup is null - invoke spellchecker.build first");
return EMPTY_RESULT;
}
SpellingResult res = new SpellingResult();
CharsRef scratch = new CharsRef();
for (Token currentToken : options.tokens) {
scratch.chars = currentToken.buffer();
scratch.offset = 0;
scratch.length = currentToken.length();
boolean onlyMorePopular = (options.suggestMode == SuggestMode.SUGGEST_MORE_POPULAR) &&
!(lookup instanceof WFSTCompletionLookup) &&
!(lookup instanceof AnalyzingSuggester);
// get more than the requested suggestions as a lot get collapsed by the corrections
List<LookupResult> suggestions = lookup.lookup(scratch, onlyMorePopular, options.count * 10);
if (suggestions == null || suggestions.size() == 0) {
continue;
}
if (options.suggestMode != SuggestMode.SUGGEST_MORE_POPULAR) {
Collections.sort(suggestions);
}
final LinkedHashMap<String, Integer> lhm = new LinkedHashMap<String, Integer>();
for (LookupResult lr : suggestions) {
String suggestion = lr.key.toString();
if(this.suggestionAnalyzer != null) {
String correction = getAnalyzerResult(suggestion);
// multiple could map to the same, so don't repeat suggestions
if(!isStringNullOrEmpty(correction)){
if(lhm.containsKey(correction)){
lhm.put(correction, lhm.get(correction) + (int) lr.value);
}
else {
lhm.put(correction, (int) lr.value);
}
}
}
else {
lhm.put(suggestion, (int) lr.value);
}
if(lhm.size() >= options.count){
break;
}
}
// sort by new doc frequency
Map<String, Integer> orderedMap = null;
if (options.suggestMode != SuggestMode.SUGGEST_MORE_POPULAR){
// retain the sort order from above
orderedMap = lhm;
}
else {
orderedMap = new TreeMap<String, Integer>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return lhm.get(s2).compareTo(lhm.get(s1));
}
});
orderedMap.putAll(lhm);
}
for(Map.Entry<String, Integer> entry: orderedMap.entrySet()){
res.add(currentToken, entry.getKey(), entry.getValue());
}
}
return res;
}
private boolean isStringNullOrEmpty(String s){
return s == null || s.length() == 0;
}
private String getAnalyzerResult(String suggestion){
TokenStream ts = null;
try {
Reader reader = new StringReader(suggestion);
ts = this.suggestionAnalyzer.tokenStream("", reader);
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
ts.reset();
while (ts.incrementToken()) {
String word = termAtt.toString();
if(word != null && word.length() > 0) {
return word;
}
}
}
catch (Exception ex){
if(this.field != null)
{
LOG.error(String.format("Error executing analyzer for field: %s in DiceSuggester on suggestion: %s",
this.field, suggestion), ex);
}else if(this.fieldTypeName != null){
LOG.error(String.format("Error executing analyzer for field type: %s in DiceSuggester on suggestion: %s",
this.fieldTypeName, suggestion), ex);
}
}
finally {
if(ts != null)
{
IOUtils.closeWhileHandlingException(ts);
}
}
return null;
}
}
| |
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.orm.jpa;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Convenient builder for JPA EntityManagerFactory instances. Collects common
* configuration when constructed and then allows you to create one or more
* {@link LocalContainerEntityManagerFactoryBean} through a fluent builder pattern. The
* most common options are covered in the builder, but you can always manipulate the
* product of the builder if you need more control, before returning it from a
* {@code @Bean} definition.
*
* @author Dave Syer
* @author Phillip Webb
* @author Stephane Nicoll
* @since 1.3.0
*/
public class EntityManagerFactoryBuilder {
private final JpaVendorAdapter jpaVendorAdapter;
private final PersistenceUnitManager persistenceUnitManager;
private final Map<String, Object> jpaProperties;
private final URL persistenceUnitRootLocation;
private AsyncTaskExecutor bootstrapExecutor;
private PersistenceUnitPostProcessor[] persistenceUnitPostProcessors;
/**
* Create a new instance passing in the common pieces that will be shared if multiple
* EntityManagerFactory instances are created.
* @param jpaVendorAdapter a vendor adapter
* @param jpaProperties the JPA properties to be passed to the persistence provider
* @param persistenceUnitManager optional source of persistence unit information (can
* be null)
*/
public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map<String, ?> jpaProperties,
PersistenceUnitManager persistenceUnitManager) {
this(jpaVendorAdapter, jpaProperties, persistenceUnitManager, null);
}
/**
* Create a new instance passing in the common pieces that will be shared if multiple
* EntityManagerFactory instances are created.
* @param jpaVendorAdapter a vendor adapter
* @param jpaProperties the JPA properties to be passed to the persistence provider
* @param persistenceUnitManager optional source of persistence unit information (can
* be null)
* @param persistenceUnitRootLocation the persistence unit root location to use as a
* fallback (can be null)
* @since 1.4.1
*/
public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map<String, ?> jpaProperties,
PersistenceUnitManager persistenceUnitManager, URL persistenceUnitRootLocation) {
this.jpaVendorAdapter = jpaVendorAdapter;
this.persistenceUnitManager = persistenceUnitManager;
this.jpaProperties = new LinkedHashMap<>(jpaProperties);
this.persistenceUnitRootLocation = persistenceUnitRootLocation;
}
public Builder dataSource(DataSource dataSource) {
return new Builder(dataSource);
}
/**
* Configure the bootstrap executor to be used by the
* {@link LocalContainerEntityManagerFactoryBean}.
* @param bootstrapExecutor the executor
* @since 2.1.0
*/
public void setBootstrapExecutor(AsyncTaskExecutor bootstrapExecutor) {
this.bootstrapExecutor = bootstrapExecutor;
}
/**
* Set the {@linkplain PersistenceUnitPostProcessor persistence unit post processors}
* to be applied to the PersistenceUnitInfo used for creating the
* {@link LocalContainerEntityManagerFactoryBean}.
* @param persistenceUnitPostProcessors the persistence unit post processors to use
* @since 2.5.0
*/
public void setPersistenceUnitPostProcessors(PersistenceUnitPostProcessor... persistenceUnitPostProcessors) {
this.persistenceUnitPostProcessors = persistenceUnitPostProcessors;
}
/**
* A fluent builder for a LocalContainerEntityManagerFactoryBean.
*/
public final class Builder {
private DataSource dataSource;
private String[] packagesToScan;
private String persistenceUnit;
private Map<String, Object> properties = new HashMap<>();
private String[] mappingResources;
private boolean jta;
private Builder(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* The names of packages to scan for {@code @Entity} annotations.
* @param packagesToScan packages to scan
* @return the builder for fluent usage
*/
public Builder packages(String... packagesToScan) {
this.packagesToScan = packagesToScan;
return this;
}
/**
* The classes whose packages should be scanned for {@code @Entity} annotations.
* @param basePackageClasses the classes to use
* @return the builder for fluent usage
*/
public Builder packages(Class<?>... basePackageClasses) {
Set<String> packages = new HashSet<>();
for (Class<?> type : basePackageClasses) {
packages.add(ClassUtils.getPackageName(type));
}
this.packagesToScan = StringUtils.toStringArray(packages);
return this;
}
/**
* The name of the persistence unit. If only building one EntityManagerFactory you
* can omit this, but if there are more than one in the same application you
* should give them distinct names.
* @param persistenceUnit the name of the persistence unit
* @return the builder for fluent usage
*/
public Builder persistenceUnit(String persistenceUnit) {
this.persistenceUnit = persistenceUnit;
return this;
}
/**
* Generic properties for standard JPA or vendor-specific configuration. These
* properties override any values provided in the constructor.
* @param properties the properties to use
* @return the builder for fluent usage
*/
public Builder properties(Map<String, ?> properties) {
this.properties.putAll(properties);
return this;
}
/**
* The mapping resources (equivalent to {@code <mapping-file>} entries in
* {@code persistence.xml}) for the persistence unit.
* <p>
* Note that mapping resources must be relative to the classpath root, e.g.
* "META-INF/mappings.xml" or "com/mycompany/repository/mappings.xml", so that
* they can be loaded through {@code ClassLoader.getResource()}.
* @param mappingResources the mapping resources to use
* @return the builder for fluent usage
*/
public Builder mappingResources(String... mappingResources) {
this.mappingResources = mappingResources;
return this;
}
/**
* Configure if using a JTA {@link DataSource}, i.e. if
* {@link LocalContainerEntityManagerFactoryBean#setDataSource(DataSource)
* setDataSource} or
* {@link LocalContainerEntityManagerFactoryBean#setJtaDataSource(DataSource)
* setJtaDataSource} should be called on the
* {@link LocalContainerEntityManagerFactoryBean}.
* @param jta if the data source is JTA
* @return the builder for fluent usage
*/
public Builder jta(boolean jta) {
this.jta = jta;
return this;
}
public LocalContainerEntityManagerFactoryBean build() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
if (EntityManagerFactoryBuilder.this.persistenceUnitManager != null) {
entityManagerFactoryBean
.setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager);
}
if (this.persistenceUnit != null) {
entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit);
}
entityManagerFactoryBean.setJpaVendorAdapter(EntityManagerFactoryBuilder.this.jpaVendorAdapter);
if (this.jta) {
entityManagerFactoryBean.setJtaDataSource(this.dataSource);
}
else {
entityManagerFactoryBean.setDataSource(this.dataSource);
}
entityManagerFactoryBean.setPackagesToScan(this.packagesToScan);
entityManagerFactoryBean.getJpaPropertyMap().putAll(EntityManagerFactoryBuilder.this.jpaProperties);
entityManagerFactoryBean.getJpaPropertyMap().putAll(this.properties);
if (!ObjectUtils.isEmpty(this.mappingResources)) {
entityManagerFactoryBean.setMappingResources(this.mappingResources);
}
URL rootLocation = EntityManagerFactoryBuilder.this.persistenceUnitRootLocation;
if (rootLocation != null) {
entityManagerFactoryBean.setPersistenceUnitRootLocation(rootLocation.toString());
}
if (EntityManagerFactoryBuilder.this.bootstrapExecutor != null) {
entityManagerFactoryBean.setBootstrapExecutor(EntityManagerFactoryBuilder.this.bootstrapExecutor);
}
if (EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors != null) {
entityManagerFactoryBean.setPersistenceUnitPostProcessors(
EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors);
}
return entityManagerFactoryBean;
}
}
}
| |
package minefantasy.mf2.client.gui;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import minefantasy.mf2.MineFantasyII;
import minefantasy.mf2.api.helpers.GuiHelper;
import minefantasy.mf2.api.knowledge.InformationBase;
import minefantasy.mf2.api.knowledge.InformationList;
import minefantasy.mf2.api.knowledge.InformationPage;
import minefantasy.mf2.api.knowledge.ResearchLogic;
import minefantasy.mf2.api.rpg.RPGElements;
import minefantasy.mf2.api.rpg.Skill;
import minefantasy.mf2.api.rpg.SkillList;
import minefantasy.mf2.item.ItemResearchScroll;
import minefantasy.mf2.knowledge.KnowledgeListMF;
import minefantasy.mf2.network.packet.ResearchRequest;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiKnowledge extends GuiScreen
{
int offsetByX = 70;
int offsetByY = 0;
public int buyWidth = 225;
public int buyHeight = 72;
private RenderItem itemrender = new RenderItem();
private InformationBase selected = null;
private InformationBase highlighted = null;
private static final int field_146572_y = InformationList.minDisplayColumn * 24 - 112;
private static final int field_146571_z = InformationList.minDisplayRow * 24 - 112;
private static final int field_146559_A = InformationList.maxDisplayColumn * 24 - 77;
private static final int field_146560_B = InformationList.maxDisplayRow * 24 - 77;
private static final ResourceLocation screenTex = new ResourceLocation("minefantasy2:textures/gui/knowledge/knowledge.png");
private static final ResourceLocation buyTex = new ResourceLocation("minefantasy2:textures/gui/knowledge/purchase.png");
private static final ResourceLocation skillTex = new ResourceLocation("minefantasy2:textures/gui/knowledge/skilllist.png");
protected static int field_146555_f = 256;
protected static int field_146557_g = 202;
protected static int field_146563_h;
protected static int field_146564_i;
protected static float field_146570_r = 1.0F;
protected static double field_146569_s;
protected static double field_146568_t;
protected static double field_146567_u;
protected static double field_146566_v;
protected static double field_146565_w;
protected static double field_146573_x;
private static int field_146554_D;
private static boolean allDiscovered = true;
private static int currentPage = -1;
private GuiButton button;
private LinkedList<InformationBase> informationList = new LinkedList<InformationBase>();
private EntityPlayer player;
private boolean hasScroll = false;
private boolean canPurchase = false;
public GuiKnowledge(EntityPlayer user)
{
this.player = user;
short short1 = 141;
short short2 = 141;
GuiKnowledge.field_146569_s = GuiKnowledge.field_146567_u = GuiKnowledge.field_146565_w = KnowledgeListMF.gettingStarted.displayColumn * 24 - short1 / 2 - 12;
GuiKnowledge.field_146568_t = GuiKnowledge.field_146566_v = GuiKnowledge.field_146573_x = KnowledgeListMF.gettingStarted.displayRow * 24 - short2 / 2;
informationList.clear();
for (Object achievement : InformationList.knowledgeList)
{
if (!InformationPage.isInfoInPages((InformationBase)achievement))
{
informationList.add((InformationBase)achievement);
}
}
for(Object base: InformationList.knowledgeList.toArray())
{
if(!ResearchLogic.hasInfoUnlocked(user, (InformationBase)base))
{
allDiscovered = false;
break;
}
}
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui()
{
int i1 = (this.width - GuiKnowledge.field_146555_f) / 2 + offsetByX;
int j1 = (this.height - GuiKnowledge.field_146557_g) / 2 + offsetByY;
this.buttonList.clear();
this.buttonList.add(new GuiOptionButton(1, this.width / 2 + 24, this.height / 2 + 101, 80, 20, I18n.format("gui.done", new Object[0])));
this.buttonList.add(button = new GuiButton(2, (width - field_146555_f) / 2 + 24, height / 2 + 101, 125, 20, InformationPage.getTitle(currentPage)));
int purchasex = i1 + (field_146555_f - buyWidth)/2;
int purchasey =j1 + (field_146557_g - buyHeight)/2;
//PURCHASE SCREEN
this.buttonList.add(new GuiOptionButton(3, purchasex + 19, purchasey + 47, 80, 20, I18n.format("gui.purchase", new Object[0])));
this.buttonList.add(new GuiOptionButton(4, purchasex + 125, purchasey + 47, 80, 20, I18n.format("gui.cancel", new Object[0])));
}
@Override
protected void mouseClicked(int x, int y, int button)
{
if(selected == null && button == 0 && highlighted != null)
{
if(ResearchLogic.hasInfoUnlocked(player, highlighted) && !highlighted.getPages().isEmpty())
{
player.openGui(MineFantasyII.instance, 1, player.worldObj, 0, highlighted.ID, 0);
}
else if(ResearchLogic.canPurchase(player, highlighted))
{
selected = highlighted;
setPurchaseAvailable(player);
}
}
super.mouseClicked(x, y, button);
}
@Override
protected void actionPerformed(GuiButton p_146284_1_)
{
if (p_146284_1_.id == 1)
{
this.mc.displayGuiScreen((GuiScreen)null);
}
if (selected == null && p_146284_1_.id == 2)
{
boolean hasDwarvern = ResearchLogic.hasInfoUnlocked(mc.thePlayer, KnowledgeListMF.dwarvernKnowledge);
boolean hasGnomish = ResearchLogic.hasInfoUnlocked(mc.thePlayer, KnowledgeListMF.gnomishKnowledge);
currentPage++;
if(currentPage == 5 && !hasDwarvern){currentPage++;};
if(currentPage == 6 && !hasGnomish){currentPage++;};
if (currentPage >= InformationPage.getInfoPages().size())
{
currentPage = -1;
}
button.displayString = InformationPage.getTitle(currentPage);
}
if (p_146284_1_.id == 3 && selected != null)
{
((EntityClientPlayerMP)player).sendQueue.addToSendQueue(new ResearchRequest(player, selected.ID).generatePacket());
selected = null;
}
if (p_146284_1_.id == 4 && selected != null)
{
selected = null;
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
@Override
protected void keyTyped(char p_73869_1_, int p_73869_2_)
{
if (p_73869_2_ == this.mc.gameSettings.keyBindInventory.getKeyCode())
{
this.mc.displayGuiScreen((GuiScreen)null);
this.mc.setIngameFocus();
}
else
{
super.keyTyped(p_73869_1_, p_73869_2_);
}
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int mx, int my, float f)
{
{
int k;
if (selected == null && Mouse.isButtonDown(0))
{
k = (this.width - GuiKnowledge.field_146555_f) / 2 + offsetByX;
int l = (this.height - GuiKnowledge.field_146557_g) / 2 + offsetByY;
int i1 = k + 8;
int j1 = l + 17;
if ((GuiKnowledge.field_146554_D == 0 || GuiKnowledge.field_146554_D == 1) && mx >= i1 && mx < i1 + 224 && my >= j1 && my < j1 + 155)
{
if (GuiKnowledge.field_146554_D == 0)
{
GuiKnowledge.field_146554_D = 1;
}
else
{
GuiKnowledge.field_146567_u -= (mx - GuiKnowledge.field_146563_h) * GuiKnowledge.field_146570_r;
GuiKnowledge.field_146566_v -= (my - GuiKnowledge.field_146564_i) * GuiKnowledge.field_146570_r;
GuiKnowledge.field_146565_w = GuiKnowledge.field_146569_s = GuiKnowledge.field_146567_u;
GuiKnowledge.field_146573_x = GuiKnowledge.field_146568_t = GuiKnowledge.field_146566_v;
}
GuiKnowledge.field_146563_h = mx;
GuiKnowledge.field_146564_i = my;
}
}
else
{
GuiKnowledge.field_146554_D = 0;
}
k = Mouse.getDWheel();
float f4 = GuiKnowledge.field_146570_r;
if (k < 0)
{
GuiKnowledge.field_146570_r += 0.25F;
}
else if (k > 0)
{
GuiKnowledge.field_146570_r -= 0.25F;
}
GuiKnowledge.field_146570_r = MathHelper.clamp_float(GuiKnowledge.field_146570_r, 1.0F, 3.0F);
if (GuiKnowledge.field_146570_r != f4)
{
float f6 = f4 - GuiKnowledge.field_146570_r;
float f5 = f4 * GuiKnowledge.field_146555_f;
float f1 = f4 * GuiKnowledge.field_146557_g;
float f2 = GuiKnowledge.field_146570_r * GuiKnowledge.field_146555_f;
float f3 = GuiKnowledge.field_146570_r * GuiKnowledge.field_146557_g;
GuiKnowledge.field_146567_u -= (f2 - f5) * 0.5F;
GuiKnowledge.field_146566_v -= (f3 - f1) * 0.5F;
GuiKnowledge.field_146565_w = GuiKnowledge.field_146569_s = GuiKnowledge.field_146567_u;
GuiKnowledge.field_146573_x = GuiKnowledge.field_146568_t = GuiKnowledge.field_146566_v;
}
if (GuiKnowledge.field_146565_w < field_146572_y)
{
GuiKnowledge.field_146565_w = field_146572_y;
}
if (GuiKnowledge.field_146573_x < field_146571_z)
{
GuiKnowledge.field_146573_x = field_146571_z;
}
if (GuiKnowledge.field_146565_w >= field_146559_A)
{
GuiKnowledge.field_146565_w = field_146559_A - 1;
}
if (GuiKnowledge.field_146573_x >= field_146560_B)
{
GuiKnowledge.field_146573_x = field_146560_B - 1;
}
this.drawDefaultBackground();
this.renderMainPage(mx, my, f);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
this.drawOverlay();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
if(buttonList.get(2) != null)
{
((GuiButton)buttonList.get(2)).visible = selected != null;
((GuiButton)buttonList.get(2)).enabled = selected != null && canPurchase ;
((GuiButton)buttonList.get(3)).visible = selected != null;
}
}
/**
* Called from the main game loop to update the screen.
*/
@Override
public void updateScreen()
{
{
GuiKnowledge.field_146569_s = GuiKnowledge.field_146567_u;
GuiKnowledge.field_146568_t = GuiKnowledge.field_146566_v;
double d0 = GuiKnowledge.field_146565_w - GuiKnowledge.field_146567_u;
double d1 = GuiKnowledge.field_146573_x - GuiKnowledge.field_146566_v;
if (d0 * d0 + d1 * d1 < 4.0D)
{
GuiKnowledge.field_146567_u += d0;
GuiKnowledge.field_146566_v += d1;
}
else
{
GuiKnowledge.field_146567_u += d0 * 0.85D;
GuiKnowledge.field_146566_v += d1 * 0.85D;
}
}
}
protected void drawOverlay()
{
int i = (this.width - GuiKnowledge.field_146555_f) / 2 + offsetByX;
int j = (this.height - GuiKnowledge.field_146557_g) / 2 + offsetByY;
this.fontRendererObj.drawString(I18n.format("gui.information", new Object[0]), i + 15, j + 5, 4210752);
}
protected void renderMainPage(int mx, int my, float f)
{
int k = MathHelper.floor_double(GuiKnowledge.field_146569_s + (GuiKnowledge.field_146567_u - GuiKnowledge.field_146569_s) * f);
int l = MathHelper.floor_double(GuiKnowledge.field_146568_t + (GuiKnowledge.field_146566_v - GuiKnowledge.field_146568_t) * f);
if (k < field_146572_y)
{
k = field_146572_y;
}
if (l < field_146571_z)
{
l = field_146571_z;
}
if (k >= field_146559_A)
{
k = field_146559_A - 1;
}
if (l >= field_146560_B)
{
l = field_146560_B - 1;
}
int i1 = (this.width - GuiKnowledge.field_146555_f) / 2 + offsetByX;
int j1 = (this.height - GuiKnowledge.field_146557_g) / 2 + offsetByY;
int k1 = i1 + 16;
int l1 = j1 + 17;
this.zLevel = 0.0F;
GL11.glDepthFunc(GL11.GL_GEQUAL);
GL11.glPushMatrix();
GL11.glTranslatef(k1, l1, -200.0F);
GL11.glScalef(1.0F / GuiKnowledge.field_146570_r, 1.0F / GuiKnowledge.field_146570_r, 0.0F);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
int i2 = k + 288 >> 4;
int j2 = l + 288 >> 4;
int k2 = (k + 288) % 16;
int l2 = (l + 288) % 16;
boolean flag = true;
boolean flag1 = true;
boolean flag2 = true;
boolean flag3 = true;
boolean flag4 = true;
Random random = new Random();
float f1 = 16.0F / GuiKnowledge.field_146570_r;
float f2 = 16.0F / GuiKnowledge.field_146570_r;
int i3;
int j3;
int k3;
for (i3 = 0; i3 * f1 - l2 < 155.0F; ++i3)
{
float f3 = 0.6F - (j2 + i3) / 25.0F * 0.3F;
GL11.glColor4f(f3, f3, f3, 1.0F);
for (j3 = 0; j3 * f2 - k2 < 224.0F; ++j3)
{
IIcon iicon = Blocks.planks.getIcon(0, 0);
this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
this.drawTexturedModelRectFromIcon(j3 * 16 - k2, i3 * 16 - l2, iicon, 16, 16);
}
}
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
this.mc.getTextureManager().bindTexture(screenTex);
int researchVisibility;
int j4;
int l4;
List<InformationBase> achievementList = (currentPage == -1 ? informationList : InformationPage.getInfoPage(currentPage).getInfoList());
for (i3 = 0; i3 < achievementList.size(); ++i3)
{
InformationBase achievement1 = achievementList.get(i3);
if (achievement1.parentInfo != null && achievementList.contains(achievement1.parentInfo))
{
j3 = achievement1.displayColumn * 24 - k + 11;
k3 = achievement1.displayRow * 24 - l + 11;
l4 = achievement1.parentInfo.displayColumn * 24 - k + 11;
int l3 = achievement1.parentInfo.displayRow * 24 - l + 11;
boolean flag5 = ResearchLogic.hasInfoUnlocked(player, achievement1);
boolean flag6 = ResearchLogic.canUnlockInfo(player, achievement1);
researchVisibility = ResearchLogic.func_150874_c(player, achievement1);
if (researchVisibility <= getVisibleRange()[0])
{
j4 = -16777216;
if (flag5)
{
j4 = -6250336;
}
else if (flag6)
{
j4 = -16711936;
}
this.drawHorizontalLine(j3, l4, k3, j4);
this.drawVerticalLine(l4, k3, l3, j4);
if (j3 > l4)
{
this.drawTexturedModalRect(j3 - 11 - 7, k3 - 5, 114, 234, 7, 11);
}
else if (j3 < l4)
{
this.drawTexturedModalRect(j3 + 11, k3 - 5, 107, 234, 7, 11);
}
else if (k3 > l3)
{
this.drawTexturedModalRect(j3 - 5, k3 - 11 - 7, 96, 234, 11, 7);
}
else if (k3 < l3)
{
this.drawTexturedModalRect(j3 - 5, k3 + 11, 96, 241, 11, 7);
}
}
}
}
InformationBase achievement = null;
RenderItem renderitem = new RenderItem();
float f4 = (mx - k1) * GuiKnowledge.field_146570_r;
float f5 = (my - l1) * GuiKnowledge.field_146570_r;
RenderHelper.enableGUIStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
int i5;
int j5;
for (l4 = 0; l4 < achievementList.size(); ++l4)
{
InformationBase achievement2 = achievementList.get(l4);
i5 = achievement2.displayColumn * 24 - k;
j5 = achievement2.displayRow * 24 - l;
if (i5 >= -24 && j5 >= -24 && i5 <= 224.0F * GuiKnowledge.field_146570_r && j5 <= 155.0F * GuiKnowledge.field_146570_r)
{
researchVisibility = ResearchLogic.func_150874_c(player, achievement2);
float f6;
if (ResearchLogic.hasInfoUnlocked(player, achievement2))
{
f6 = 0.75F;
GL11.glColor4f(f6, f6, f6, 1.0F);
}
else if (ResearchLogic.canUnlockInfo(player, achievement2))
{
f6 = 1.0F;
GL11.glColor4f(0.5F, 1.0F, 0.5F, 1.0F);
}
else if (researchVisibility < getVisibleRange()[1])
{
f6 = 0.3F;
GL11.glColor4f(f6, f6, f6, 1.0F);
}
else if (researchVisibility == getVisibleRange()[1])
{
f6 = 0.2F;
GL11.glColor4f(f6, f6, f6, 1.0F);
}
else
{
if (researchVisibility != getVisibleRange()[2])
{
continue;
}
f6 = 0.1F;
GL11.glColor4f(f6, f6, f6, 1.0F);
}
this.mc.getTextureManager().bindTexture(screenTex);
GL11.glEnable(GL11.GL_BLEND);// Forge: Specifically enable blend because it is needed here. And we fix Generic RenderItem's leakage of it.
if (achievement2.getSpecial())
{
this.drawTexturedModalRect(i5 - 2, j5 - 2, 26, 202, 26, 26);
}
else if (achievement2.getPerk())
{
this.drawTexturedModalRect(i5 - 2, j5 - 2, 52, 202, 26, 26);
}
else
{
this.drawTexturedModalRect(i5 - 2, j5 - 2, 0, 202, 26, 26);
}
GL11.glDisable(GL11.GL_BLEND); //Forge: Cleanup states we set.
if (!ResearchLogic.canUnlockInfo(player, achievement2))
{
f6 = 0.1F;
GL11.glColor4f(f6, f6, f6, 1.0F);
renderitem.renderWithColor = false;
}
GL11.glDisable(GL11.GL_LIGHTING); //Forge: Make sure Lighting is disabled. Fixes MC-33065
GL11.glEnable(GL11.GL_CULL_FACE);
renderitem.renderItemAndEffectIntoGUI(this.mc.fontRenderer, this.mc.getTextureManager(), achievement2.theItemStack, i5 + 3, j5 + 3);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_LIGHTING);
if (!ResearchLogic.canUnlockInfo(player, achievement2))
{
renderitem.renderWithColor = true;
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (f4 >= i5 && f4 <= i5 + 22 && f5 >= j5 && f5 <= j5 + 22)
{
achievement = achievement2;
}
}
}
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(screenTex);
this.drawTexturedModalRect(i1, j1, 0, 0, GuiKnowledge.field_146555_f, GuiKnowledge.field_146557_g);
this.zLevel = 0.0F;
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
if(selected != null)
{
int purchasex = i1 + (field_146555_f - buyWidth)/2;
int purchasey =j1 + (field_146557_g - buyHeight)/2;
renderPurchaseScreen(purchasex, purchasey, mx, my);
}
drawSkillList();
super.drawScreen(mx, my, f);
highlighted = achievement;
if (selected == null && achievement != null)
{
String s1 = achievement.getName();
String s2 = achievement.getDescription();
i5 = mx + 12;
j5 = my - 4;
researchVisibility = ResearchLogic.func_150874_c(player, achievement);
if (!ResearchLogic.canUnlockInfo(player, achievement))
{
String s;
int k4;
if (researchVisibility == 3)
{
s1 = I18n.format("achievement.unknown", new Object[0]);
j4 = Math.max(this.fontRendererObj.getStringWidth(s1), 120);
s = (new ChatComponentTranslation("achievement.requires", new Object[] {achievement.parentInfo.getName()})).getUnformattedText();
k4 = this.fontRendererObj.splitStringWidth(s, j4);
this.drawGradientRect(i5 - 3, j5 - 3, i5 + j4 + 3, j5 + k4 + 12 + 3, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s, i5, j5 + 12, j4, -9416624);
}
else if (researchVisibility < 3)
{
j4 = Math.max(this.fontRendererObj.getStringWidth(s1), 120);
s = (new ChatComponentTranslation("achievement.requires", new Object[] {achievement.parentInfo.getName()})).getUnformattedText();
k4 = this.fontRendererObj.splitStringWidth(s, j4);
this.drawGradientRect(i5 - 3, j5 - 3, i5 + j4 + 3, j5 + k4 + 12 + 3, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s, i5, j5 + 12, j4, -9416624);
}
else
{
s1 = null;
}
}
else
{
j4 = Math.max(this.fontRendererObj.getStringWidth(s1), 120);
int k5 = this.fontRendererObj.splitStringWidth(s2, j4);
if (ResearchLogic.hasInfoUnlocked(player, achievement) || ResearchLogic.canUnlockInfo(player, achievement))
{
k5 += 12;
}
this.drawGradientRect(i5 - 3, j5 - 3, i5 + j4 + 3, j5 + k5 + 3 + 12, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s2, i5, j5 + 12, j4, -6250336);
if (ResearchLogic.hasInfoUnlocked(player, achievement))
{
this.fontRendererObj.drawStringWithShadow(I18n.format("information.discovered", new Object[0]), i5, j5 + k5 + 4, -7302913);
}
else if(ResearchLogic.canUnlockInfo(player, achievement))
{
this.fontRendererObj.drawStringWithShadow(StatCollector.translateToLocal("information.buy"), i5, j5 + k5 + 4, -7302913);
}
}
if (s1 != null)
{
this.fontRendererObj.drawStringWithShadow(s1, i5, j5, ResearchLogic.canUnlockInfo(player, achievement) ? (achievement.getSpecial() ? -128 : -1) : (achievement.getSpecial() ? -8355776 : -8355712));
}
}
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
RenderHelper.disableStandardItemLighting();
}
/**
* Returns true if this GUI should pause the game when it is displayed in single-player
*/
@Override
public boolean doesGuiPauseGame()
{
return false;
}
private int[] getVisibleRange()
{
return new int[]{1, 2, 3};
}
private void renderPurchaseScreen(int x, int y, int mx, int my)
{
if(selected != null)
{
String[] requirements = selected.getRequiredSkills();
int size = 0;
if(requirements != null)
{
size = requirements.length;
}
this.mc.getTextureManager().bindTexture(buyTex);
this.drawTexturedModalRect(x, y, 0, 0, buyWidth, 27);//Top
for(int a = 0; a < size; a++)
{
this.drawTexturedModalRect(x, y+27 + (a*19), 0, 27, buyWidth, 19);//Middle
}
this.drawTexturedModalRect(x, y+27 + (size*19), 0, 46, buyWidth, 26);//Bottom
if(buttonList.get(2) != null && buttonList.get(3) != null)
{
int j1 = (this.height - GuiKnowledge.field_146557_g) / 2;
int purchasey =j1 + (field_146557_g - buyHeight)/2;
int offset = -19;
if(requirements != null)
{
offset += (19*requirements.length);
}
((GuiButton)buttonList.get(2)).yPosition = purchasey + 47 + offset;
((GuiButton)buttonList.get(3)).yPosition = purchasey + 47 + offset;
}
int red = GuiHelper.getColourForRGB(220, 0, 0);
int white = 16777215;
mc.fontRenderer.drawString(selected.getName(), x+22, y+12, white, false);
if(hasScroll)
{
mc.fontRenderer.drawStringWithShadow(StatCollector.translateToLocal("knowledge.hasScroll"), x+20, y+32, red);
}
else
{
for(int a = 0; a < requirements.length; a ++)
{
boolean isUnlocked = selected.isUnlocked(a, mc.thePlayer);
String text = requirements[a];
mc.fontRenderer.drawStringWithShadow(text, x+20, y+32 + (a*19), isUnlocked ? white : red);
}
}
}
GL11.glColor3f(255, 255, 255);
}
private void setPurchaseAvailable(EntityPlayer user)
{
hasScroll = getHasScroll(user);
if(selected != null)
{
canPurchase = !hasScroll && selected.hasSkillsUnlocked(user);
}
else
{
canPurchase = false;
}
}
private boolean getHasScroll(EntityPlayer user)
{
if(selected == null || user == null)
{
return false;
}
int id = selected.ID;
for(int a = 0; a < user.inventory.getSizeInventory(); a++)
{
ItemStack slot = user.inventory.getStackInSlot(a);
if(slot != null && slot.getItem() instanceof ItemResearchScroll)
{
if(slot.getItemDamage() == id)
{
return true;
}
}
}
return false;
}
protected void drawSkillList()
{
GL11.glPushMatrix();
int skillWidth = 143;
int skillHeight = 156;
int x = (this.width - GuiKnowledge.field_146555_f) / 2 - skillWidth + offsetByX;
int y = (this.height - GuiKnowledge.field_146557_g) / 2 + offsetByY;
this.mc.getTextureManager().bindTexture(skillTex);
this.drawTexturedModalRect(x, y, 0, 0, skillWidth, skillHeight);
drawSkill(x+20, y+20, SkillList.artisanry);
drawSkill(x+20, y+44, SkillList.construction);
drawSkill(x+20, y+68, SkillList.provisioning);
drawSkill(x+20, y+92, SkillList.engineering);
drawSkill(x+20, y+116, SkillList.combat);
drawSkillName(x+20, y+20, SkillList.artisanry);
drawSkillName(x+20, y+44, SkillList.construction);
drawSkillName(x+20, y+68, SkillList.provisioning);
drawSkillName(x+20, y+92, SkillList.engineering);
drawSkillName(x+20, y+116, SkillList.combat);
GL11.glPopMatrix();
}
protected void drawSkill(int x, int y, Skill skill)
{
if(skill != null)
{
int level = RPGElements.getLevel(mc.thePlayer, skill);
int xp = skill.getXP(player)[0];
int max = skill.getXP(player)[1];
//this.mc.getTextureManager().bindTexture(skillTex);
float scale = (float)xp / (float)max;
this.drawTexturedModalRect(x+22, y+13, 0, 156, (int)(78F * scale), 5);
//mc.fontRenderer.drawString(skill.getDisplayName(), x+2, y+1, 0);
//mc.fontRenderer.drawString(""+level, x+1, y+10, 0);
}
}
protected void drawSkillName(int x, int y, Skill skill)
{
if(skill != null)
{
int level = RPGElements.getLevel(mc.thePlayer, skill);
mc.fontRenderer.drawString(skill.getDisplayName(), x+2, y+1, 0);
mc.fontRenderer.drawString(""+level, x+1, y+10, 0);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.tools;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.tools.util.DistCpUtils;
import org.apache.hadoop.security.Credentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.util.Set;
import com.google.common.collect.Sets;
/**
* The CopyListing abstraction is responsible for how the list of
* sources and targets is constructed, for DistCp's copy function.
* The copy-listing should be a
* SequenceFile<Text, CopyListingFileStatus>, located at the path
* specified to buildListing(), each entry being a pair of (Source relative
* path, source file status), all the paths being fully qualified.
*/
public abstract class CopyListing extends Configured {
private Credentials credentials;
static final Logger LOG = LoggerFactory.getLogger(DistCp.class);
/**
* Build listing function creates the input listing that distcp uses to
* perform the copy.
*
* The build listing is a sequence file that has relative path of a file in the key
* and the file status information of the source file in the value
*
* For instance if the source path is /tmp/data and the traversed path is
* /tmp/data/dir1/dir2/file1, then the sequence file would contain
*
* key: /dir1/dir2/file1 and value: FileStatus(/tmp/data/dir1/dir2/file1)
*
* File would also contain directory entries. Meaning, if /tmp/data/dir1/dir2/file1
* is the only file under /tmp/data, the resulting sequence file would contain the
* following entries
*
* key: /dir1 and value: FileStatus(/tmp/data/dir1)
* key: /dir1/dir2 and value: FileStatus(/tmp/data/dir1/dir2)
* key: /dir1/dir2/file1 and value: FileStatus(/tmp/data/dir1/dir2/file1)
*
* Cases requiring special handling:
* If source path is a file (/tmp/file1), contents of the file will be as follows
*
* TARGET DOES NOT EXIST: Key-"", Value-FileStatus(/tmp/file1)
* TARGET IS FILE : Key-"", Value-FileStatus(/tmp/file1)
* TARGET IS DIR : Key-"/file1", Value-FileStatus(/tmp/file1)
*
* @param pathToListFile - Output file where the listing would be stored
* @param distCpContext - distcp context associated with input options
* @throws IOException - Exception if any
*/
public final void buildListing(Path pathToListFile,
DistCpContext distCpContext) throws IOException {
validatePaths(distCpContext);
doBuildListing(pathToListFile, distCpContext);
Configuration config = getConf();
config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, pathToListFile.toString());
config.setLong(DistCpConstants.CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED, getBytesToCopy());
config.setLong(DistCpConstants.CONF_LABEL_TOTAL_NUMBER_OF_RECORDS, getNumberOfPaths());
validateFinalListing(pathToListFile, distCpContext);
LOG.info("Number of paths in the copy list: " + this.getNumberOfPaths());
}
/**
* Validate input and output paths
*
* @param distCpContext - Distcp context
* @throws InvalidInputException If inputs are invalid
* @throws IOException any Exception with FS
*/
protected abstract void validatePaths(DistCpContext distCpContext)
throws IOException, InvalidInputException;
/**
* The interface to be implemented by sub-classes, to create the source/target file listing.
* @param pathToListFile Path on HDFS where the listing file is written.
* @param distCpContext - Distcp context
* @throws IOException Thrown on failure to create the listing file.
*/
protected abstract void doBuildListing(Path pathToListFile,
DistCpContext distCpContext) throws IOException;
/**
* Return the total bytes that distCp should copy for the source paths
* This doesn't consider whether file is same should be skipped during copy
*
* @return total bytes to copy
*/
protected abstract long getBytesToCopy();
/**
* Return the total number of paths to distcp, includes directories as well
* This doesn't consider whether file/dir is already present and should be skipped during copy
*
* @return Total number of paths to distcp
*/
protected abstract long getNumberOfPaths();
/**
* Validate the final resulting path listing. Checks if there are duplicate
* entries. If preserving ACLs, checks that file system can support ACLs.
* If preserving XAttrs, checks that file system can support XAttrs.
*
* @param pathToListFile - path listing build by doBuildListing
* @param context - Distcp context with associated input options
* @throws IOException - Any issues while checking for duplicates and throws
* @throws DuplicateFileException - if there are duplicates
*/
private void validateFinalListing(Path pathToListFile, DistCpContext context)
throws DuplicateFileException, IOException {
Configuration config = getConf();
final boolean splitLargeFile = context.splitLargeFile();
// When splitLargeFile is enabled, we don't randomize the copylist
// earlier, so we don't do the sorting here. For a file that has
// multiple entries due to split, we check here that their
// <chunkOffset, chunkLength> is continuous.
//
Path checkPath = splitLargeFile?
pathToListFile : DistCpUtils.sortListing(config, pathToListFile);
SequenceFile.Reader reader = new SequenceFile.Reader(
config, SequenceFile.Reader.file(checkPath));
try {
Text lastKey = new Text("*"); //source relative path can never hold *
long lastChunkOffset = -1;
long lastChunkLength = -1;
CopyListingFileStatus lastFileStatus = new CopyListingFileStatus();
Text currentKey = new Text();
Set<URI> aclSupportCheckFsSet = Sets.newHashSet();
Set<URI> xAttrSupportCheckFsSet = Sets.newHashSet();
long idx = 0;
while (reader.next(currentKey)) {
if (currentKey.equals(lastKey)) {
CopyListingFileStatus currentFileStatus = new CopyListingFileStatus();
reader.getCurrentValue(currentFileStatus);
if (!splitLargeFile) {
throw new DuplicateFileException("File " + lastFileStatus.getPath()
+ " and " + currentFileStatus.getPath()
+ " would cause duplicates. Aborting");
} else {
if (lastChunkOffset + lastChunkLength !=
currentFileStatus.getChunkOffset()) {
throw new InvalidInputException("File " + lastFileStatus.getPath()
+ " " + lastChunkOffset + "," + lastChunkLength
+ " and " + currentFileStatus.getPath()
+ " " + currentFileStatus.getChunkOffset() + ","
+ currentFileStatus.getChunkLength()
+ " are not continuous. Aborting");
}
}
}
reader.getCurrentValue(lastFileStatus);
if (context.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config);
URI lastFsUri = lastFs.getUri();
if (!aclSupportCheckFsSet.contains(lastFsUri)) {
DistCpUtils.checkFileSystemAclSupport(lastFs);
aclSupportCheckFsSet.add(lastFsUri);
}
}
if (context.shouldPreserve(DistCpOptions.FileAttribute.XATTR)) {
FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config);
URI lastFsUri = lastFs.getUri();
if (!xAttrSupportCheckFsSet.contains(lastFsUri)) {
DistCpUtils.checkFileSystemXAttrSupport(lastFs);
xAttrSupportCheckFsSet.add(lastFsUri);
}
}
lastKey.set(currentKey);
if (splitLargeFile) {
lastChunkOffset = lastFileStatus.getChunkOffset();
lastChunkLength = lastFileStatus.getChunkLength();
}
if (context.shouldUseDiff() && LOG.isDebugEnabled()) {
LOG.debug("Copy list entry " + idx + ": " +
lastFileStatus.getPath().toUri().getPath());
idx++;
}
}
} finally {
IOUtils.closeStream(reader);
}
}
/**
* Protected constructor, to initialize configuration.
* @param configuration The input configuration,
* with which the source/target FileSystems may be accessed.
* @param credentials - Credentials object on which the FS delegation tokens are cached.If null
* delegation token caching is skipped
*/
protected CopyListing(Configuration configuration, Credentials credentials) {
setConf(configuration);
setCredentials(credentials);
}
/**
* set Credentials store, on which FS delegatin token will be cached
* @param credentials - Credentials object
*/
protected void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
/**
* get credentials to update the delegation tokens for accessed FS objects
* @return Credentials object
*/
protected Credentials getCredentials() {
return credentials;
}
/**
* Returns the key for an entry in the copy listing sequence file.
* @param sourcePathRoot the root source path for determining the relative
* target path
* @param fileStatus the copy listing file status
* @return the key for the sequence file entry
*/
protected Text getFileListingKey(Path sourcePathRoot,
CopyListingFileStatus fileStatus) {
return new Text(DistCpUtils.getRelativePath(sourcePathRoot,
fileStatus.getPath()));
}
/**
* Returns the value for an entry in the copy listing sequence file.
* @param fileStatus the copy listing file status
* @return the value for the sequence file entry
*/
protected CopyListingFileStatus getFileListingValue(
CopyListingFileStatus fileStatus) {
return fileStatus;
}
/**
* Public Factory method with which the appropriate CopyListing implementation may be retrieved.
* @param configuration The input configuration.
* @param credentials Credentials object on which the FS delegation tokens are cached
* @param context Distcp context with associated input options
* @return An instance of the appropriate CopyListing implementation.
* @throws java.io.IOException - Exception if any
*/
public static CopyListing getCopyListing(Configuration configuration,
Credentials credentials, DistCpContext context) throws IOException {
String copyListingClassName = configuration.get(DistCpConstants.
CONF_LABEL_COPY_LISTING_CLASS, "");
Class<? extends CopyListing> copyListingClass;
try {
if (! copyListingClassName.isEmpty()) {
copyListingClass = configuration.getClass(DistCpConstants.
CONF_LABEL_COPY_LISTING_CLASS, GlobbedCopyListing.class,
CopyListing.class);
} else {
if (context.getSourceFileListing() == null) {
copyListingClass = GlobbedCopyListing.class;
} else {
copyListingClass = FileBasedCopyListing.class;
}
}
copyListingClassName = copyListingClass.getName();
Constructor<? extends CopyListing> constructor = copyListingClass.
getDeclaredConstructor(Configuration.class, Credentials.class);
return constructor.newInstance(configuration, credentials);
} catch (Exception e) {
throw new IOException("Unable to instantiate " + copyListingClassName, e);
}
}
static class DuplicateFileException extends RuntimeException {
public DuplicateFileException(String message) {
super(message);
}
}
static class InvalidInputException extends RuntimeException {
public InvalidInputException(String message) {
super(message);
}
public InvalidInputException(String message, Throwable cause) {
super(message, cause);
}
}
public static class AclsNotSupportedException extends RuntimeException {
public AclsNotSupportedException(String message) {
super(message);
}
}
public static class XAttrsNotSupportedException extends RuntimeException {
public XAttrsNotSupportedException(String message) {
super(message);
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.mailvalidator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.mailvalidator.MailValidatorMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class MailValidatorDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = MailValidatorMeta.class; // for i18n purposes, needed by Translator2!!
private boolean gotPreviousFields = false;
private Label wlemailFieldName;
private CCombo wemailFieldName;
private FormData fdlemailFieldName, fdemailFieldName;
private Label wldefaultSMTPField;
private CCombo wdefaultSMTPField;
private FormData fdldefaultSMTPField, fddefaultSMTPField;
private Label wlResult;
private TextVar wResult;
private FormData fdlResult, fdResult;
private Label wleMailSender;
private TextVar weMailSender;
private FormData fdleMailSender, fdeMailSender;
private Label wlTimeOut;
private TextVar wTimeOut;
private FormData fdlTimeOut, fdTimeOut;
private Label wlDefaultSMTP;
private TextVar wDefaultSMTP;
private FormData fdlDefaultSMTP, fdDefaultSMTP;
private Label wldynamicDefaultSMTP;
private Button wdynamicDefaultSMTP;
private FormData fdldynamicDefaultSMTP;
private FormData fddynamicDefaultSMTP;
private Group wResultGroup;
private FormData fdResultGroup;
private Group wSettingsGroup;
private FormData fdSettingsGroup;
private Label wlResultAsString;
private FormData fdlResultAsString;
private Button wResultAsString;
private FormData fdResultAsString;
private Label wlSMTPCheck;
private FormData fdlSMTPCheck;
private Button wSMTPCheck;
private FormData fdSMTPCheck;
private Label wlResultStringFalse;
private FormData fdlResultStringFalse;
private Label wlResultStringTrue;
private FormData fdlResultStringTrue;
private FormData fdResultStringTrue;
private FormData fdResultStringFalse;
private TextVar wResultStringFalse;
private TextVar wResultStringTrue;
private TextVar wErrorMsg;
private Label wlErrorMsg;
private FormData fdlErrorMsg;
private FormData fdErrorMsg;
private MailValidatorMeta input;
public MailValidatorDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (MailValidatorMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "MailValidatorDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "MailValidatorDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// emailFieldName field
wlemailFieldName = new Label( shell, SWT.RIGHT );
wlemailFieldName.setText( BaseMessages.getString( PKG, "MailValidatorDialog.emailFieldName.Label" ) );
props.setLook( wlemailFieldName );
fdlemailFieldName = new FormData();
fdlemailFieldName.left = new FormAttachment( 0, 0 );
fdlemailFieldName.right = new FormAttachment( middle, -margin );
fdlemailFieldName.top = new FormAttachment( wStepname, margin );
wlemailFieldName.setLayoutData( fdlemailFieldName );
wemailFieldName = new CCombo( shell, SWT.BORDER | SWT.READ_ONLY );
props.setLook( wemailFieldName );
wemailFieldName.addModifyListener( lsMod );
fdemailFieldName = new FormData();
fdemailFieldName.left = new FormAttachment( middle, 0 );
fdemailFieldName.top = new FormAttachment( wStepname, margin );
fdemailFieldName.right = new FormAttachment( 100, -margin );
wemailFieldName.setLayoutData( fdemailFieldName );
wemailFieldName.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
get();
shell.setCursor( null );
busy.dispose();
}
} );
// ////////////////////////
// START OF Settings GROUP
//
wSettingsGroup = new Group( shell, SWT.SHADOW_NONE );
props.setLook( wSettingsGroup );
wSettingsGroup.setText( BaseMessages.getString( PKG, "MailValidatorDialog.SettingsGroup.Label" ) );
FormLayout groupSettings = new FormLayout();
groupSettings.marginWidth = 10;
groupSettings.marginHeight = 10;
wSettingsGroup.setLayout( groupSettings );
// perform SMTP check?
wlSMTPCheck = new Label( wSettingsGroup, SWT.RIGHT );
wlSMTPCheck.setText( BaseMessages.getString( PKG, "MailValidatorDialog.SMTPCheck.Label" ) );
props.setLook( wlSMTPCheck );
fdlSMTPCheck = new FormData();
fdlSMTPCheck.left = new FormAttachment( 0, 0 );
fdlSMTPCheck.top = new FormAttachment( wResult, margin );
fdlSMTPCheck.right = new FormAttachment( middle, -2 * margin );
wlSMTPCheck.setLayoutData( fdlSMTPCheck );
wSMTPCheck = new Button( wSettingsGroup, SWT.CHECK );
props.setLook( wSMTPCheck );
wSMTPCheck.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.SMTPCheck.Tooltip" ) );
fdSMTPCheck = new FormData();
fdSMTPCheck.left = new FormAttachment( middle, -margin );
fdSMTPCheck.top = new FormAttachment( wemailFieldName, margin );
wSMTPCheck.setLayoutData( fdSMTPCheck );
wSMTPCheck.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
activeSMTPCheck();
}
} );
// TimeOut fieldname ...
wlTimeOut = new Label( wSettingsGroup, SWT.RIGHT );
wlTimeOut.setText( BaseMessages.getString( PKG, "MailValidatorDialog.TimeOutField.Label" ) );
props.setLook( wlTimeOut );
fdlTimeOut = new FormData();
fdlTimeOut.left = new FormAttachment( 0, 0 );
fdlTimeOut.right = new FormAttachment( middle, -2 * margin );
fdlTimeOut.top = new FormAttachment( wSMTPCheck, margin );
wlTimeOut.setLayoutData( fdlTimeOut );
wTimeOut = new TextVar( transMeta, wSettingsGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wTimeOut.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.TimeOutField.Tooltip" ) );
props.setLook( wTimeOut );
wTimeOut.addModifyListener( lsMod );
fdTimeOut = new FormData();
fdTimeOut.left = new FormAttachment( middle, -margin );
fdTimeOut.top = new FormAttachment( wSMTPCheck, margin );
fdTimeOut.right = new FormAttachment( 100, 0 );
wTimeOut.setLayoutData( fdTimeOut );
// eMailSender fieldname ...
wleMailSender = new Label( wSettingsGroup, SWT.RIGHT );
wleMailSender.setText( BaseMessages.getString( PKG, "MailValidatorDialog.eMailSenderField.Label" ) );
props.setLook( wleMailSender );
fdleMailSender = new FormData();
fdleMailSender.left = new FormAttachment( 0, 0 );
fdleMailSender.right = new FormAttachment( middle, -2 * margin );
fdleMailSender.top = new FormAttachment( wTimeOut, margin );
wleMailSender.setLayoutData( fdleMailSender );
weMailSender = new TextVar( transMeta, wSettingsGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
weMailSender.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.eMailSenderField.Tooltip" ) );
props.setLook( weMailSender );
weMailSender.addModifyListener( lsMod );
fdeMailSender = new FormData();
fdeMailSender.left = new FormAttachment( middle, -margin );
fdeMailSender.top = new FormAttachment( wTimeOut, margin );
fdeMailSender.right = new FormAttachment( 100, 0 );
weMailSender.setLayoutData( fdeMailSender );
// DefaultSMTP fieldname ...
wlDefaultSMTP = new Label( wSettingsGroup, SWT.RIGHT );
wlDefaultSMTP.setText( BaseMessages.getString( PKG, "MailValidatorDialog.DefaultSMTPField.Label" ) );
props.setLook( wlDefaultSMTP );
fdlDefaultSMTP = new FormData();
fdlDefaultSMTP.left = new FormAttachment( 0, 0 );
fdlDefaultSMTP.right = new FormAttachment( middle, -2 * margin );
fdlDefaultSMTP.top = new FormAttachment( weMailSender, margin );
wlDefaultSMTP.setLayoutData( fdlDefaultSMTP );
wDefaultSMTP = new TextVar( transMeta, wSettingsGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wDefaultSMTP.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.DefaultSMTPField.Tooltip" ) );
props.setLook( wDefaultSMTP );
wDefaultSMTP.addModifyListener( lsMod );
fdDefaultSMTP = new FormData();
fdDefaultSMTP.left = new FormAttachment( middle, -margin );
fdDefaultSMTP.top = new FormAttachment( weMailSender, margin );
fdDefaultSMTP.right = new FormAttachment( 100, 0 );
wDefaultSMTP.setLayoutData( fdDefaultSMTP );
// dynamic SMTP server?
wldynamicDefaultSMTP = new Label( wSettingsGroup, SWT.RIGHT );
wldynamicDefaultSMTP.setText( BaseMessages.getString( PKG, "MailValidatorDialog.dynamicDefaultSMTP.Label" ) );
props.setLook( wldynamicDefaultSMTP );
fdldynamicDefaultSMTP = new FormData();
fdldynamicDefaultSMTP.left = new FormAttachment( 0, 0 );
fdldynamicDefaultSMTP.top = new FormAttachment( wDefaultSMTP, margin );
fdldynamicDefaultSMTP.right = new FormAttachment( middle, -2 * margin );
wldynamicDefaultSMTP.setLayoutData( fdldynamicDefaultSMTP );
wdynamicDefaultSMTP = new Button( wSettingsGroup, SWT.CHECK );
props.setLook( wdynamicDefaultSMTP );
wdynamicDefaultSMTP.setToolTipText( BaseMessages.getString(
PKG, "MailValidatorDialog.dynamicDefaultSMTP.Tooltip" ) );
fddynamicDefaultSMTP = new FormData();
fddynamicDefaultSMTP.left = new FormAttachment( middle, -margin );
fddynamicDefaultSMTP.top = new FormAttachment( wDefaultSMTP, margin );
wdynamicDefaultSMTP.setLayoutData( fddynamicDefaultSMTP );
wdynamicDefaultSMTP.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
activedynamicDefaultSMTP();
}
} );
// defaultSMTPField field
wldefaultSMTPField = new Label( wSettingsGroup, SWT.RIGHT );
wldefaultSMTPField.setText( BaseMessages.getString( PKG, "MailValidatorDialog.defaultSMTPField.Label" ) );
props.setLook( wldefaultSMTPField );
fdldefaultSMTPField = new FormData();
fdldefaultSMTPField.left = new FormAttachment( 0, 0 );
fdldefaultSMTPField.right = new FormAttachment( middle, -2 * margin );
fdldefaultSMTPField.top = new FormAttachment( wdynamicDefaultSMTP, margin );
wldefaultSMTPField.setLayoutData( fdldefaultSMTPField );
wdefaultSMTPField = new CCombo( wSettingsGroup, SWT.BORDER | SWT.READ_ONLY );
props.setLook( wdefaultSMTPField );
wdefaultSMTPField.addModifyListener( lsMod );
fddefaultSMTPField = new FormData();
fddefaultSMTPField.left = new FormAttachment( middle, -margin );
fddefaultSMTPField.top = new FormAttachment( wdynamicDefaultSMTP, margin );
fddefaultSMTPField.right = new FormAttachment( 100, -margin );
wdefaultSMTPField.setLayoutData( fddefaultSMTPField );
wdefaultSMTPField.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
get();
shell.setCursor( null );
busy.dispose();
}
} );
fdSettingsGroup = new FormData();
fdSettingsGroup.left = new FormAttachment( 0, margin );
fdSettingsGroup.top = new FormAttachment( wemailFieldName, margin );
fdSettingsGroup.right = new FormAttachment( 100, -margin );
wSettingsGroup.setLayoutData( fdSettingsGroup );
// ///////////////////////////////////////////////////////////
// / END OF Settings GROUP
// ///////////////////////////////////////////////////////////
// ////////////////////////
// START OF Result GROUP
//
wResultGroup = new Group( shell, SWT.SHADOW_NONE );
props.setLook( wResultGroup );
wResultGroup.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultGroup.label" ) );
FormLayout groupResult = new FormLayout();
groupResult.marginWidth = 10;
groupResult.marginHeight = 10;
wResultGroup.setLayout( groupResult );
// Result fieldname ...
wlResult = new Label( wResultGroup, SWT.RIGHT );
wlResult.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultField.Label" ) );
props.setLook( wlResult );
fdlResult = new FormData();
fdlResult.left = new FormAttachment( 0, 0 );
fdlResult.right = new FormAttachment( middle, -2 * margin );
fdlResult.top = new FormAttachment( wSettingsGroup, margin * 2 );
wlResult.setLayoutData( fdlResult );
wResult = new TextVar( transMeta, wResultGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wResult.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultField.Tooltip" ) );
props.setLook( wResult );
wResult.addModifyListener( lsMod );
fdResult = new FormData();
fdResult.left = new FormAttachment( middle, -margin );
fdResult.top = new FormAttachment( wSettingsGroup, margin * 2 );
fdResult.right = new FormAttachment( 100, 0 );
wResult.setLayoutData( fdResult );
// is Result as String
wlResultAsString = new Label( wResultGroup, SWT.RIGHT );
wlResultAsString.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultAsString.Label" ) );
props.setLook( wlResultAsString );
fdlResultAsString = new FormData();
fdlResultAsString.left = new FormAttachment( 0, 0 );
fdlResultAsString.top = new FormAttachment( wResult, margin );
fdlResultAsString.right = new FormAttachment( middle, -2 * margin );
wlResultAsString.setLayoutData( fdlResultAsString );
wResultAsString = new Button( wResultGroup, SWT.CHECK );
props.setLook( wResultAsString );
wResultAsString.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultAsString.Tooltip" ) );
fdResultAsString = new FormData();
fdResultAsString.left = new FormAttachment( middle, -margin );
fdResultAsString.top = new FormAttachment( wResult, margin );
wResultAsString.setLayoutData( fdResultAsString );
wResultAsString.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
activeResultAsString();
}
} );
// ResultStringTrue fieldname ...
wlResultStringTrue = new Label( wResultGroup, SWT.RIGHT );
wlResultStringTrue.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultStringTrueField.Label" ) );
props.setLook( wlResultStringTrue );
fdlResultStringTrue = new FormData();
fdlResultStringTrue.left = new FormAttachment( 0, 0 );
fdlResultStringTrue.right = new FormAttachment( middle, -2 * margin );
fdlResultStringTrue.top = new FormAttachment( wResultAsString, margin );
wlResultStringTrue.setLayoutData( fdlResultStringTrue );
wResultStringTrue = new TextVar( transMeta, wResultGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wResultStringTrue.setToolTipText( BaseMessages.getString(
PKG, "MailValidatorDialog.ResultStringTrueField.Tooltip" ) );
props.setLook( wResultStringTrue );
wResultStringTrue.addModifyListener( lsMod );
fdResultStringTrue = new FormData();
fdResultStringTrue.left = new FormAttachment( middle, -margin );
fdResultStringTrue.top = new FormAttachment( wResultAsString, margin );
fdResultStringTrue.right = new FormAttachment( 100, 0 );
wResultStringTrue.setLayoutData( fdResultStringTrue );
// ResultStringFalse fieldname ...
wlResultStringFalse = new Label( wResultGroup, SWT.RIGHT );
wlResultStringFalse
.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ResultStringFalseField.Label" ) );
props.setLook( wlResultStringFalse );
fdlResultStringFalse = new FormData();
fdlResultStringFalse.left = new FormAttachment( 0, 0 );
fdlResultStringFalse.right = new FormAttachment( middle, -2 * margin );
fdlResultStringFalse.top = new FormAttachment( wResultStringTrue, margin );
wlResultStringFalse.setLayoutData( fdlResultStringFalse );
wResultStringFalse = new TextVar( transMeta, wResultGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wResultStringFalse.setToolTipText( BaseMessages.getString(
PKG, "MailValidatorDialog.ResultStringFalseField.Tooltip" ) );
props.setLook( wResultStringFalse );
wResultStringFalse.addModifyListener( lsMod );
fdResultStringFalse = new FormData();
fdResultStringFalse.left = new FormAttachment( middle, -margin );
fdResultStringFalse.top = new FormAttachment( wResultStringTrue, margin );
fdResultStringFalse.right = new FormAttachment( 100, 0 );
wResultStringFalse.setLayoutData( fdResultStringFalse );
// ErrorMsg fieldname ...
wlErrorMsg = new Label( wResultGroup, SWT.RIGHT );
wlErrorMsg.setText( BaseMessages.getString( PKG, "MailValidatorDialog.ErrorMsgField.Label" ) );
props.setLook( wlErrorMsg );
fdlErrorMsg = new FormData();
fdlErrorMsg.left = new FormAttachment( 0, 0 );
fdlErrorMsg.right = new FormAttachment( middle, -2 * margin );
fdlErrorMsg.top = new FormAttachment( wResultStringFalse, margin );
wlErrorMsg.setLayoutData( fdlErrorMsg );
wErrorMsg = new TextVar( transMeta, wResultGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wErrorMsg.setToolTipText( BaseMessages.getString( PKG, "MailValidatorDialog.ErrorMsgField.Tooltip" ) );
props.setLook( wErrorMsg );
wErrorMsg.addModifyListener( lsMod );
fdErrorMsg = new FormData();
fdErrorMsg.left = new FormAttachment( middle, -margin );
fdErrorMsg.top = new FormAttachment( wResultStringFalse, margin );
fdErrorMsg.right = new FormAttachment( 100, 0 );
wErrorMsg.setLayoutData( fdErrorMsg );
fdResultGroup = new FormData();
fdResultGroup.left = new FormAttachment( 0, margin );
fdResultGroup.top = new FormAttachment( wSettingsGroup, 2 * margin );
fdResultGroup.right = new FormAttachment( 100, -margin );
wResultGroup.setLayoutData( fdResultGroup );
// ///////////////////////////////////////////////////////////
// / END OF Result GROUP
// ///////////////////////////////////////////////////////////
// THE BUTTONS
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wCancel }, margin, wResultGroup );
// Add listeners
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
wOK.addListener( SWT.Selection, lsOK );
wCancel.addListener( SWT.Selection, lsCancel );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
activeSMTPCheck();
activeResultAsString();
input.setChanged( changed );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
private void activedynamicDefaultSMTP() {
wldefaultSMTPField.setEnabled( wSMTPCheck.getSelection() && wdynamicDefaultSMTP.getSelection() );
wdefaultSMTPField.setEnabled( wSMTPCheck.getSelection() && wdynamicDefaultSMTP.getSelection() );
}
private void activeSMTPCheck() {
wlTimeOut.setEnabled( wSMTPCheck.getSelection() );
wTimeOut.setEnabled( wSMTPCheck.getSelection() );
wlDefaultSMTP.setEnabled( wSMTPCheck.getSelection() );
wDefaultSMTP.setEnabled( wSMTPCheck.getSelection() );
wleMailSender.setEnabled( wSMTPCheck.getSelection() );
weMailSender.setEnabled( wSMTPCheck.getSelection() );
wdynamicDefaultSMTP.setEnabled( wSMTPCheck.getSelection() );
wldynamicDefaultSMTP.setEnabled( wSMTPCheck.getSelection() );
activedynamicDefaultSMTP();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
if ( input.getEmailField() != null ) {
wemailFieldName.setText( input.getEmailField() );
}
if ( input.getResultFieldName() != null ) {
wResult.setText( input.getResultFieldName() );
}
wResultAsString.setSelection( input.isResultAsString() );
if ( input.getEMailValideMsg() != null ) {
wResultStringTrue.setText( input.getEMailValideMsg() );
}
if ( input.getEMailNotValideMsg() != null ) {
wResultStringFalse.setText( input.getEMailNotValideMsg() );
}
if ( input.getErrorsField() != null ) {
wErrorMsg.setText( input.getErrorsField() );
}
int timeout = Const.toInt( input.getTimeOut(), 0 );
wTimeOut.setText( String.valueOf( timeout ) );
wSMTPCheck.setSelection( input.isSMTPCheck() );
if ( input.getDefaultSMTP() != null ) {
wDefaultSMTP.setText( input.getDefaultSMTP() );
}
if ( input.geteMailSender() != null ) {
weMailSender.setText( input.geteMailSender() );
}
wdynamicDefaultSMTP.setSelection( input.isdynamicDefaultSMTP() );
if ( input.getDefaultSMTPField() != null ) {
wdefaultSMTPField.setText( input.getDefaultSMTPField() );
}
wStepname.selectAll();
wStepname.setFocus();
}
private void activeResultAsString() {
wlResultStringFalse.setEnabled( wResultAsString.getSelection() );
wResultStringFalse.setEnabled( wResultAsString.getSelection() );
wlResultStringTrue.setEnabled( wResultAsString.getSelection() );
wResultStringTrue.setEnabled( wResultAsString.getSelection() );
}
private void cancel() {
stepname = null;
input.setChanged( changed );
dispose();
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
input.setEmailfield( wemailFieldName.getText() );
input.setResultFieldName( wResult.getText() );
stepname = wStepname.getText(); // return value
input.setResultAsString( wResultAsString.getSelection() );
input.setEmailValideMsg( wResultStringTrue.getText() );
input.setEmailNotValideMsg( wResultStringFalse.getText() );
input.setErrorsField( wErrorMsg.getText() );
input.setTimeOut( wTimeOut.getText() );
input.setDefaultSMTP( wDefaultSMTP.getText() );
input.seteMailSender( weMailSender.getText() );
input.setSMTPCheck( wSMTPCheck.getSelection() );
input.setdynamicDefaultSMTP( wdynamicDefaultSMTP.getSelection() );
input.setDefaultSMTPField( wdefaultSMTPField.getText() );
dispose();
}
private void get() {
if ( !gotPreviousFields ) {
try {
String emailField = null;
String smtpdefaultField = null;
if ( wemailFieldName.getText() != null ) {
emailField = wemailFieldName.getText();
}
if ( wdefaultSMTPField.getText() != null ) {
smtpdefaultField = wdefaultSMTPField.getText();
}
wemailFieldName.removeAll();
wdefaultSMTPField.removeAll();
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null ) {
wemailFieldName.setItems( r.getFieldNames() );
wdefaultSMTPField.setItems( r.getFieldNames() );
}
if ( emailField != null ) {
wemailFieldName.setText( emailField );
}
if ( smtpdefaultField != null ) {
wdefaultSMTPField.setText( smtpdefaultField );
}
gotPreviousFields = true;
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "MailValidatorDialog.FailedToGetFields.DialogTitle" ),
BaseMessages.getString( PKG, "MailValidatorDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
}
}
| |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package db;
import java.io.IOException;
import db.buffers.DataBuffer;
import generic.util.UnsignedDataUtils;
import ghidra.util.BigEndianDataConverter;
/**
* <code>FixedField10</code> provide an unsigned 10-byte fixed-length field value.
* The most-significant byte corresponds to index-0 (i.e., data[0]).
*/
public class FixedField10 extends FixedField {
/**
* Zero fixed10 field value
*/
public static final FixedField10 ZERO_VALUE = new FixedField10(0L, (short) 0, true);
/**
* Minimum long field value
*/
public static FixedField10 MIN_VALUE = ZERO_VALUE;
/**
* Maximum long field value
*/
public static FixedField10 MAX_VALUE = new FixedField10(-1L, (short) -1, true);
/**
* Instance intended for defining a {@link Table} {@link Schema}
*/
@SuppressWarnings("hiding")
public static final FixedField10 INSTANCE = ZERO_VALUE;
// This implementation uses both a data byte array and short+long variables
// for data storage. While the short+long is always available, the data
// byte array is only set when needed or supplied during construction.
// The use of the short+long is done to speed-up comparison with other
// FixedField10 instances or directly from a DataBuffer.
private short lo2;
private long hi8;
/**
* Construct a 10-byte fixed-length field with an initial value of 0.
*/
public FixedField10() {
super(null, false);
}
/**
* Construct a 10-byte fixed-length field with an initial value of data.
* @param data initial 10-byte binary value. A null corresponds to zero value
* and does not affect the null-state (see {@link #setNull()} and {@link #isNull()}).
* @throws IllegalArgumentException thrown if data is not 10-bytes in length
*/
public FixedField10(byte[] data) {
this(data, false);
}
/**
* Construct a 10-byte fixed-length binary field with an initial value of data.
* @param data initial 10-byte binary value. A null corresponds to zero value
* and does not affect the null-state (see {@link #setNull()} and {@link #isNull()}).
* @param immutable true if field value is immutable
* @throws IllegalArgumentException thrown if data is not 10-bytes in length
*/
public FixedField10(byte[] data, boolean immutable) {
super(data, immutable);
if (data != null) {
if (data.length != 10) {
throw new IllegalArgumentException("Invalid FixedField10 data length");
}
updatePrimitiveValue(data);
}
}
FixedField10(long hi8, short lo2, boolean immutable) {
super(null, immutable);
this.hi8 = hi8;
this.lo2 = lo2;
}
@Override
public int compareTo(Field o) {
if (!(o instanceof FixedField10)) {
throw new UnsupportedOperationException("may only compare similar Field types");
}
FixedField10 f = (FixedField10) o;
if (hi8 != f.hi8) {
return UnsignedDataUtils.unsignedLessThan(hi8, f.hi8) ? -1 : 1;
}
if (lo2 != f.lo2) {
return UnsignedDataUtils.unsignedLessThan(lo2, f.lo2) ? -1 : 1;
}
return 0;
}
@Override
int compareTo(DataBuffer buffer, int offset) {
long otherHi8 = buffer.getLong(offset);
if (hi8 != otherHi8) {
return UnsignedDataUtils.unsignedLessThan(hi8, otherHi8) ? -1 : 1;
}
short otherLo2 = buffer.getShort(offset + 8);
if (lo2 != otherLo2) {
return UnsignedDataUtils.unsignedLessThan(lo2, otherLo2) ? -1 : 1;
}
return 0;
}
@Override
public FixedField copyField() {
if (isNull()) {
FixedField10 copy = new FixedField10();
copy.setNull();
return copy;
}
return new FixedField10(hi8, lo2, false);
}
@Override
public FixedField newField() {
return new FixedField10();
}
@Override
FixedField getMinValue() {
return MIN_VALUE;
}
@Override
FixedField getMaxValue() {
return MAX_VALUE;
}
@Override
public byte[] getBinaryData() {
if (data != null) {
return data;
}
data = new byte[10];
BigEndianDataConverter.INSTANCE.putLong(data, 0, hi8);
BigEndianDataConverter.INSTANCE.putShort(data, 8, lo2);
return data;
}
@Override
public void setBinaryData(byte[] d) {
if (d == null || d.length != 10) {
// null value not permitted although null state is (see setNull())
throw new IllegalArgumentException("Invalid FixedField10 data length");
}
updatingValue();
this.data = d;
updatePrimitiveValue(d);
}
void updatePrimitiveValue(byte[] d) {
hi8 = BigEndianDataConverter.INSTANCE.getLong(d, 0);
lo2 = BigEndianDataConverter.INSTANCE.getShort(d, 8);
}
@Override
void setNull() {
super.setNull();
data = null;
hi8 = 0;
lo2 = 0;
}
@Override
byte getFieldType() {
return FIXED_10_TYPE;
}
@Override
int write(Buffer buf, int offset) throws IOException {
if (data != null) {
return buf.put(offset, data);
}
offset = buf.putLong(offset, hi8);
return buf.putShort(offset, lo2);
}
@Override
int read(Buffer buf, int offset) throws IOException {
updatingValue();
data = null; // be lazy
hi8 = buf.getLong(offset);
lo2 = buf.getShort(offset + 8);
return offset + 10;
}
@Override
int readLength(Buffer buf, int offset) throws IOException {
return 10;
}
@Override
int length() {
return 10;
}
@Override
public int hashCode() {
final int prime = 31;
int result = (int) (hi8 ^ (hi8 >>> 32));
result = prime * result + lo2;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof FixedField10)) {
return false;
}
FixedField10 other = (FixedField10) obj;
if (hi8 != other.hi8) {
return false;
}
if (lo2 != other.lo2) {
return false;
}
return true;
}
@Override
public String getValueAsString() {
return "{" + BinaryField.getValueAsString(getBinaryData()) + "}";
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.jstorm.schedule.default_assign;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.Config;
import com.alibaba.jstorm.client.ConfigExtension;
import com.alibaba.jstorm.client.WorkerAssignment;
import com.alibaba.jstorm.daemon.supervisor.SupervisorInfo;
import com.alibaba.jstorm.schedule.TopologyAssignContext;
import com.alibaba.jstorm.utils.FailedAssignTopologyException;
import com.alibaba.jstorm.utils.NetWorkUtils;
public class WorkerScheduler {
public static Logger LOG = LoggerFactory.getLogger(WorkerScheduler.class);
private static WorkerScheduler instance;
private WorkerScheduler() {
}
public static WorkerScheduler getInstance() {
if (instance == null) {
instance = new WorkerScheduler();
}
return instance;
}
public List<ResourceWorkerSlot> getAvailableWorkers(
DefaultTopologyAssignContext context, Set<Integer> needAssign,
int num) {
int workersNum = getWorkersNum(context, num);
if (workersNum == 0) {
throw new FailedAssignTopologyException("there's no enough worker");
}
List<ResourceWorkerSlot> assignedWorkers =
new ArrayList<ResourceWorkerSlot>();
// userdefine assignments
getRightWorkers(
context,
needAssign,
assignedWorkers,
workersNum,
getUserDefineWorkers(context, ConfigExtension
.getUserDefineAssignment(context.getStormConf())));
// old assignments
if (ConfigExtension.isUseOldAssignment(context.getStormConf())) {
getRightWorkers(context, needAssign, assignedWorkers, workersNum,
context.getOldWorkers());
} else if (context.getAssignType() == TopologyAssignContext.ASSIGN_TYPE_REBALANCE
&& context.isReassign() == false) {
int cnt = 0;
for (ResourceWorkerSlot worker : context.getOldWorkers()) {
if (cnt < workersNum) {
ResourceWorkerSlot resFreeWorker = new ResourceWorkerSlot();
resFreeWorker.setPort(worker.getPort());
resFreeWorker.setHostname(worker.getHostname());
resFreeWorker.setNodeId(worker.getNodeId());
assignedWorkers.add(resFreeWorker);
cnt++;
} else {
break;
}
}
}
int defaultWorkerNum =
Math.min(workersNum - assignedWorkers.size(), needAssign.size());
LOG.info("Get workers from user define and old assignments: "
+ assignedWorkers);
for (int i = 0; i < defaultWorkerNum; i++) {
assignedWorkers.add(new ResourceWorkerSlot());
}
List<SupervisorInfo> isolationSupervisors =
this.getIsolationSupervisors(context);
if (isolationSupervisors.size() != 0) {
putAllWorkerToSupervisor(assignedWorkers,
getResAvailSupervisors(isolationSupervisors));
} else {
putAllWorkerToSupervisor(assignedWorkers,
getResAvailSupervisors(context.getCluster()));
}
this.setAllWorkerMemAndCpu(context.getStormConf(), assignedWorkers);
LOG.info("Assigned workers=" + assignedWorkers);
return assignedWorkers;
}
private void setAllWorkerMemAndCpu(Map conf,
List<ResourceWorkerSlot> assignedWorkers) {
long defaultSize = ConfigExtension.getMemSizePerWorker(conf);
int defaultCpu = ConfigExtension.getCpuSlotPerWorker(conf);
for (ResourceWorkerSlot worker : assignedWorkers) {
if (worker.getMemSize() <= 0)
worker.setMemSize(defaultSize);
if (worker.getCpu() <= 0)
worker.setCpu(defaultCpu);
}
}
private void putAllWorkerToSupervisor(
List<ResourceWorkerSlot> assignedWorkers,
List<SupervisorInfo> supervisors) {
for (ResourceWorkerSlot worker : assignedWorkers) {
if (worker.getHostname() != null) {
for (SupervisorInfo supervisor : supervisors) {
if (NetWorkUtils.equals(supervisor.getHostName(),
worker.getHostname())
&& supervisor.getAvailableWorkerPorts().size() > 0) {
putWorkerToSupervisor(supervisor, worker);
break;
}
}
}
}
supervisors = getResAvailSupervisors(supervisors);
Collections.sort(supervisors, new Comparator<SupervisorInfo>() {
@Override
public int compare(SupervisorInfo o1, SupervisorInfo o2) {
// TODO Auto-generated method stub
return -NumberUtils.compare(o1.getAvailableWorkerPorts().size(), o2
.getAvailableWorkerPorts().size());
}
});
putWorkerToSupervisor(assignedWorkers, supervisors);
}
private void putWorkerToSupervisor(SupervisorInfo supervisor,
ResourceWorkerSlot worker) {
int port = worker.getPort();
if (!supervisor.getAvailableWorkerPorts().contains(worker.getPort())) {
port = supervisor.getAvailableWorkerPorts().iterator().next();
}
worker.setPort(port);
supervisor.getAvailableWorkerPorts().remove(port);
worker.setNodeId(supervisor.getSupervisorId());
}
private void putWorkerToSupervisor(
List<ResourceWorkerSlot> assignedWorkers,
List<SupervisorInfo> supervisors) {
int allUsedPorts = 0;
for (SupervisorInfo supervisor : supervisors) {
int supervisorUsedPorts = supervisor.getWorkerPorts().size()
- supervisor.getAvailableWorkerPorts().size();
allUsedPorts = allUsedPorts + supervisorUsedPorts;
}
// per supervisor should be allocated ports in theory
int theoryAveragePorts =
(allUsedPorts + assignedWorkers.size()) / supervisors.size()
+ 1;
// supervisor which use more than theoryAveragePorts ports will be
// pushed overLoadSupervisors
List<SupervisorInfo> overLoadSupervisors =
new ArrayList<SupervisorInfo>();
int key = 0;
Iterator<ResourceWorkerSlot> iterator = assignedWorkers.iterator();
while (iterator.hasNext()) {
if (supervisors.size() == 0)
break;
if (key >= supervisors.size())
key = 0;
SupervisorInfo supervisor = supervisors.get(key);
int supervisorUsedPorts = supervisor.getWorkerPorts().size()
- supervisor.getAvailableWorkerPorts().size();
if (supervisorUsedPorts < theoryAveragePorts) {
ResourceWorkerSlot worker = iterator.next();
if (worker.getNodeId() != null)
continue;
worker.setHostname(supervisor.getHostName());
worker.setNodeId(supervisor.getSupervisorId());
worker.setPort(
supervisor.getAvailableWorkerPorts().iterator().next());
supervisor.getAvailableWorkerPorts().remove(worker.getPort());
if (supervisor.getAvailableWorkerPorts().size() == 0)
supervisors.remove(supervisor);
key++;
} else {
overLoadSupervisors.add(supervisor);
supervisors.remove(supervisor);
}
}
// rest assignedWorkers will be allocate supervisor by deal
Collections.sort(overLoadSupervisors, new Comparator<SupervisorInfo>() {
@Override
public int compare(SupervisorInfo o1, SupervisorInfo o2) {
// TODO Auto-generated method stub
return -NumberUtils.compare(o1.getAvailableWorkerPorts().size(),
o2.getAvailableWorkerPorts().size());
}
});
key = 0;
while (iterator.hasNext()) {
if (overLoadSupervisors.size() == 0)
break;
if (key >= overLoadSupervisors.size())
key = 0;
ResourceWorkerSlot worker = iterator.next();
if (worker.getNodeId() != null)
continue;
SupervisorInfo supervisor = overLoadSupervisors.get(key);
worker.setHostname(supervisor.getHostName());
worker.setNodeId(supervisor.getSupervisorId());
worker.setPort(
supervisor.getAvailableWorkerPorts().iterator().next());
supervisor.getAvailableWorkerPorts().remove(worker.getPort());
if (supervisor.getAvailableWorkerPorts().size() == 0)
overLoadSupervisors.remove(supervisor);
key++;
}
}
private void getRightWorkers(DefaultTopologyAssignContext context,
Set<Integer> needAssign, List<ResourceWorkerSlot> assignedWorkers,
int workersNum, Collection<ResourceWorkerSlot> workers) {
Set<Integer> assigned = new HashSet<Integer>();
List<ResourceWorkerSlot> users = new ArrayList<ResourceWorkerSlot>();
if (workers == null)
return;
for (ResourceWorkerSlot worker : workers) {
boolean right = true;
Set<Integer> tasks = worker.getTasks();
if (tasks == null)
continue;
for (Integer task : tasks) {
if (!needAssign.contains(task) || assigned.contains(task)) {
right = false;
break;
}
}
if (right) {
assigned.addAll(tasks);
users.add(worker);
}
}
if (users.size() + assignedWorkers.size() > workersNum) {
return;
}
if (users.size() + assignedWorkers.size() == workersNum
&& assigned.size() != needAssign.size()) {
return;
}
assignedWorkers.addAll(users);
needAssign.removeAll(assigned);
}
private int getWorkersNum(DefaultTopologyAssignContext context,
int workersNum) {
Map<String, SupervisorInfo> supervisors = context.getCluster();
List<SupervisorInfo> isolationSupervisors =
this.getIsolationSupervisors(context);
int slotNum = 0;
if (isolationSupervisors.size() != 0) {
for (SupervisorInfo superivsor : isolationSupervisors) {
slotNum = slotNum + superivsor.getAvailableWorkerPorts().size();
}
return Math.min(slotNum, workersNum);
}
for (Entry<String, SupervisorInfo> entry : supervisors.entrySet()) {
slotNum = slotNum + entry.getValue().getAvailableWorkerPorts().size();
}
return Math.min(slotNum, workersNum);
}
/**
* @param context
* @param workers
* @return
*/
private List<ResourceWorkerSlot> getUserDefineWorkers(
DefaultTopologyAssignContext context, List<WorkerAssignment> workers) {
List<ResourceWorkerSlot> ret = new ArrayList<ResourceWorkerSlot>();
if (workers == null)
return ret;
Map<String, List<Integer>> componentToTask =
(HashMap<String, List<Integer>>) ((HashMap<String, List<Integer>>) context
.getComponentTasks()).clone();
if (context.getAssignType() != context.ASSIGN_TYPE_NEW) {
checkUserDefineWorkers(context, workers,
context.getTaskToComponent());
}
for (WorkerAssignment worker : workers) {
ResourceWorkerSlot workerSlot =
new ResourceWorkerSlot(worker, componentToTask);
if (workerSlot.getTasks().size() != 0) {
ret.add(workerSlot);
}
}
return ret;
}
private void checkUserDefineWorkers(DefaultTopologyAssignContext context,
List<WorkerAssignment> workers, Map<Integer, String> taskToComponent) {
Set<ResourceWorkerSlot> unstoppedWorkers =
context.getUnstoppedWorkers();
List<WorkerAssignment> re = new ArrayList<WorkerAssignment>();
for (WorkerAssignment worker : workers) {
for (ResourceWorkerSlot unstopped : unstoppedWorkers) {
if (unstopped
.compareToUserDefineWorker(worker, taskToComponent))
re.add(worker);
}
}
workers.removeAll(re);
}
private List<SupervisorInfo> getResAvailSupervisors(
Map<String, SupervisorInfo> supervisors) {
List<SupervisorInfo> availableSupervisors =
new ArrayList<SupervisorInfo>();
for (Entry<String, SupervisorInfo> entry : supervisors.entrySet()) {
SupervisorInfo supervisor = entry.getValue();
if (supervisor.getAvailableWorkerPorts().size() > 0)
availableSupervisors.add(entry.getValue());
}
return availableSupervisors;
}
private List<SupervisorInfo> getResAvailSupervisors(
List<SupervisorInfo> supervisors) {
List<SupervisorInfo> availableSupervisors =
new ArrayList<SupervisorInfo>();
for (SupervisorInfo supervisor : supervisors) {
if (supervisor.getAvailableWorkerPorts().size() > 0)
availableSupervisors.add(supervisor);
}
return availableSupervisors;
}
private List<SupervisorInfo> getIsolationSupervisors(
DefaultTopologyAssignContext context) {
List<String> isolationHosts =
(List<String>) context.getStormConf().get(
Config.ISOLATION_SCHEDULER_MACHINES);
LOG.info("Isolation machines: " + isolationHosts);
if (isolationHosts == null)
return new ArrayList<SupervisorInfo>();
List<SupervisorInfo> isolationSupervisors =
new ArrayList<SupervisorInfo>();
for (Entry<String, SupervisorInfo> entry : context.getCluster()
.entrySet()) {
if (containTargetHost(isolationHosts, entry.getValue()
.getHostName())) {
isolationSupervisors.add(entry.getValue());
}
}
return isolationSupervisors;
}
private boolean containTargetHost(Collection<String> hosts, String target) {
for (String host : hosts) {
if (NetWorkUtils.equals(host, target) == true) {
return true;
}
}
return false;
}
}
| |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.gwt.client.sectioning;
import java.util.ArrayList;
import java.util.Collection;
import org.unitime.timetable.gwt.client.aria.AriaStatus;
import org.unitime.timetable.gwt.client.aria.AriaTextBox;
import org.unitime.timetable.gwt.client.widgets.HorizontalPanelWithHint;
import org.unitime.timetable.gwt.client.widgets.LoadingWidget;
import org.unitime.timetable.gwt.client.widgets.UniTimeDialogBox;
import org.unitime.timetable.gwt.client.widgets.WebTable;
import org.unitime.timetable.gwt.client.widgets.WebTable.RowClickEvent;
import org.unitime.timetable.gwt.resources.GwtAriaMessages;
import org.unitime.timetable.gwt.resources.StudentSectioningConstants;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.resources.StudentSectioningResources;
import org.unitime.timetable.gwt.services.SectioningService;
import org.unitime.timetable.gwt.services.SectioningServiceAsync;
import org.unitime.timetable.gwt.shared.ClassAssignmentInterface;
import org.unitime.timetable.gwt.shared.CourseRequestInterface;
import com.google.gwt.aria.client.Id;
import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* @author Tomas Muller
*/
public class SuggestionsBox extends UniTimeDialogBox {
public static final StudentSectioningResources RESOURCES = GWT.create(StudentSectioningResources.class);
public static final StudentSectioningMessages MESSAGES = GWT.create(StudentSectioningMessages.class);
public static final StudentSectioningConstants CONSTANTS = GWT.create(StudentSectioningConstants.class);
public static final GwtAriaMessages ARIA = GWT.create(GwtAriaMessages.class);
private final SectioningServiceAsync iSectioningService = GWT.create(SectioningService.class);
private ClassAssignmentInterface.ClassAssignment iAssignment;
private AsyncCallback<Collection<ClassAssignmentInterface>> iCallback = null;
private ArrayList<ClassAssignmentInterface.ClassAssignment> iCurrent = null;
private ArrayList<ClassAssignmentInterface> iResult = null;
private ArrayList<SuggestionSelectedHandler> iSuggestionSelectedHandlers = new ArrayList<SuggestionSelectedHandler>();
private WebTable iSuggestions;
private HTML iMessages;
private HTML iLegend;
private ScrollPanel iSuggestionsScroll;
private String iSource;
private AriaTextBox iFilter;
private int iIndex;
private CourseRequestInterface iRequest;
private HorizontalPanelWithHint iFilterPanel;
private Button iSearch;
private boolean iOnline;
private TimeGrid iGrid;
private PopupPanel iHint;
private String iHintId = null;
private Timer iHideHint;
public SuggestionsBox(TimeGrid.ColorProvider color, boolean online) {
super(true, false);
iOnline = online;
setText("Alternatives");
setAnimationEnabled(true);
setAutoHideEnabled(true);
setGlassEnabled(true);
setModal(false);
VerticalPanel suggestionPanel = new VerticalPanel();
suggestionPanel.setSpacing(5);
iFilterPanel = new HorizontalPanelWithHint(new HTML(MESSAGES.suggestionsFilterHint(), false));
iFilterPanel.setSpacing(3);
Label filterLabel = new Label("Filter:");
iFilterPanel.add(filterLabel);
iFilterPanel.setCellVerticalAlignment(filterLabel, HasVerticalAlignment.ALIGN_MIDDLE);
iFilter = new AriaTextBox();
iFilter.setStyleName("gwt-SuggestBox");
iFilter.getElement().getStyle().setWidth(600, Unit.PX);
iFilter.getElement().getStyle().setHeight(26, Unit.PX);
iFilterPanel.add(iFilter);
HTML ariaDescription = new HTML(MESSAGES.suggestionsFilterHint(), false);
ariaDescription.setStyleName("unitime-AriaHiddenLabel");
ariaDescription.getElement().setId(DOM.createUniqueId());
iFilterPanel.add(ariaDescription);
Roles.getTextboxRole().setAriaDescribedbyProperty(iFilter.getElement(), Id.of(ariaDescription.getElement()));
iSearch = new Button(MESSAGES.buttonSearch());
iSearch.setAccessKey('s');
iSearch.addStyleName("unitime-NoPrint");
iFilterPanel.add(iSearch);
iFilterPanel.setCellVerticalAlignment(iSearch, HasVerticalAlignment.ALIGN_MIDDLE);
suggestionPanel.add(iFilterPanel);
suggestionPanel.setCellHorizontalAlignment(iFilter, HasHorizontalAlignment.ALIGN_CENTER);
iSuggestions = new WebTable();
iSuggestions.setHeader(new WebTable.Row(
new WebTable.Cell("", 1, "10px"),
new WebTable.Cell(MESSAGES.colSubject(), 1, "50px"),
new WebTable.Cell(MESSAGES.colCourse(), 1, "50px"),
new WebTable.Cell(MESSAGES.colSubpart(), 1, "40px"),
new WebTable.Cell(MESSAGES.colClass(), 1, "40px"),
new WebTable.Cell(MESSAGES.colTime(), 1, "75px").aria(ARIA.colTimeCurrent()),
new WebTable.Cell("", 1, "1px").aria(ARIA.colTimeNew()),
new WebTable.Cell(MESSAGES.colDate(), 1, "50px").aria(ARIA.colDateCurrent()),
new WebTable.Cell("", 1, "1px").aria(ARIA.colDateNew()),
new WebTable.Cell(MESSAGES.colRoom(), 1, "50px").aria(ARIA.colRoomCurrent()),
new WebTable.Cell("", 1, "1px").aria(ARIA.colRoomNew()),
new WebTable.Cell(MESSAGES.colInstructor(), 1, "100px"),
new WebTable.Cell(MESSAGES.colParent(), 1, "50px"),
new WebTable.Cell(MESSAGES.colIcons(), 1, "10px")
));
iSuggestions.setSelectSameIdRows(true);
iSuggestions.setEmptyMessage(MESSAGES.suggestionsLoading());
iSuggestionsScroll = new ScrollPanel(iSuggestions);
iSuggestionsScroll.getElement().getStyle().setHeight(400, Unit.PX);
iSuggestionsScroll.setStyleName("unitime-ScrollPanel");
suggestionPanel.add(iSuggestionsScroll);
iLegend = new HTML();
iLegend.setStyleName("unitime-SuggestionsLegend");
suggestionPanel.add(iLegend);
iMessages = new HTML();
iMessages.setStyleName("unitime-SuggestionsMessage");
suggestionPanel.add(iMessages);
iCallback = new AsyncCallback<Collection<ClassAssignmentInterface>>() {
public void onFailure(Throwable caught) {
iSuggestions.clearData(true);
iSuggestions.setEmptyMessage("<font color='red'>" + caught.getMessage() + "</font>");
iMessages.setHTML("");
LoadingWidget.getInstance().hide();
center();
AriaStatus.getInstance().setHTML(caught.getMessage());
}
public void onSuccess(Collection<ClassAssignmentInterface> result) {
iResult = (ArrayList<ClassAssignmentInterface>)result;
iMessages.setHTML("");
String ariaStatus = null;
if (result.isEmpty()) {
iSuggestions.clearData(true);
if (iFilter.getText().isEmpty()) {
iSuggestions.setEmptyMessage(MESSAGES.suggestionsNoAlternative(iSource));
ariaStatus = ARIA.suggestionsNoAlternative(iSource);
} else {
iSuggestions.setEmptyMessage(MESSAGES.suggestionsNoAlternativeWithFilter(iSource, iFilter.getText()));
ariaStatus = ARIA.suggestionsNoAlternativeWithFilter(iSource, iFilter.getText());
}
LoadingWidget.getInstance().hide();
center();
} else {
ArrayList<WebTable.Row> rows = new ArrayList<WebTable.Row>();
int lastSize = 0;
int suggestionId = 0;
for (ClassAssignmentInterface suggestion: result) {
if (suggestion.hasMessages()) iMessages.setHTML(suggestion.getMessages("<br>"));
if (suggestion.getCourseAssignments().isEmpty()) {
suggestionId++; continue;
}
for (ClassAssignmentInterface.CourseAssignment course: suggestion.getCourseAssignments()) {
ArrayList<ClassAssignmentInterface.ClassAssignment> sameCourse = new ArrayList<ClassAssignmentInterface.ClassAssignment>();
if (!course.isFreeTime()) {
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (course.getCourseId().equals(x.getCourseId())) sameCourse.add(x);
}
} else {
ClassAssignmentInterface.ClassAssignment clazz = course.getClassAssignments().get(0);
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (x.isFreeTime() && x.getDaysString(CONSTANTS.shortDays()).equals(clazz.getDaysString(CONSTANTS.shortDays())) && x.getStart() == clazz.getStart() && x.getLength() == clazz.getLength()) sameCourse.add(x);
}
}
boolean selected = false;
if (iAssignment.isFreeTime() && course.isFreeTime() &&
course.getClassAssignments().get(0).getDaysString(CONSTANTS.shortDays()).equals(iAssignment.getDaysString(CONSTANTS.shortDays())) &&
course.getClassAssignments().get(0).getStart() == iAssignment.getStart() &&
course.getClassAssignments().get(0).getLength() == iAssignment.getLength()) selected = true;
if (!iAssignment.isFreeTime() && !iAssignment.isAssigned() && iAssignment.getCourseId().equals(course.getCourseId())) selected = true;
if (course.isAssigned()) {
int clazzIdx = 0;
Long selectClassId = null;
String selectSubpart = null;
if (iAssignment.getSubpartId() != null && iAssignment.getCourseId().equals(course.getCourseId())) {
for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) {
if (iAssignment.getSubpartId().equals(clazz.getSubpartId()))
selectClassId = clazz.getClassId();
}
if (selectClassId == null)
for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) {
if (iAssignment.getSubpart().equals(clazz.getSubpart()))
selectSubpart = clazz.getSubpart();
}
if (selectClassId == null && selectSubpart == null) selected = true;
}
clazz: for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) {
if (selectClassId != null) selected = selectClassId.equals(clazz.getClassId());
if (selectSubpart != null) selected = selectSubpart.equals(clazz.getSubpart());
ClassAssignmentInterface.ClassAssignment old = null;
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (course.isFreeTime()) {
if (x.isFreeTime() && x.isCourseAssigned() && x.getDaysString(CONSTANTS.shortDays()).equals(clazz.getDaysString(CONSTANTS.shortDays())) &&
x.getStart() == clazz.getStart() && x.getLength() == clazz.getLength()) continue clazz;
} else {
if (clazz.getCourseId().equals(x.getCourseId()) && clazz.getClassId().equals(x.getClassId())) continue clazz; // the exact same assignment
if (clazz.getCourseId().equals(x.getCourseId()) && clazz.getSubpartId().equals(x.getSubpartId())) { old = x; break; }
}
}
if (old == null && clazzIdx < sameCourse.size()) old = sameCourse.get(clazzIdx);
if (old == null && sameCourse.size() == 1 && !sameCourse.get(0).isAssigned()) old = sameCourse.get(0);
WebTable.IconsCell icons = new WebTable.IconsCell();
if (clazz != null && clazz.isSaved())
icons.add(RESOURCES.saved(), MESSAGES.saved(MESSAGES.clazz(clazz.getSubject(), clazz.getCourseNbr(), clazz.getSubpart(), clazz.getSection())));
if (course.isLocked())
icons.add(RESOURCES.courseLocked(), MESSAGES.courseLocked(course.getSubject() + " " + course.getCourseNbr()));
if (clazz != null && clazz.isOfHighDemand())
icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(clazz.getExpected(), clazz.getAvailableLimit()));
if (clazz != null && clazz.hasNote())
icons.add(RESOURCES.note(), clazz.getNote());
if (clazz != null && clazz.hasOverlapNote())
icons.add(RESOURCES.overlap(), clazz.getOverlapNote());
final WebTable.Row row = new WebTable.Row(
new WebTable.Cell(rows.size() == lastSize ? suggestionId + "." : ""),
new WebTable.Cell(clazzIdx > 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()).aria(clazzIdx == 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()),
new WebTable.Cell(clazzIdx > 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())).aria(clazzIdx == 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())),
new WebTable.Cell(compare(old == null ? null : old.getSubpart(), clazz == null ? null : clazz.getSubpart(), CmpMode.SINGLE, selected, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getSection(), clazz == null ? null : clazz.getSection(), CmpMode.SINGLE, selected, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_OLD, selected, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_NEW, selected, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_OLD, selected, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_NEW, selected, clazz == null)),
(clazz != null && clazz.hasDistanceConflict() ?
new WebTable.IconCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()),
compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, selected, clazz == null)) :
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, selected, clazz == null))),
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_NEW, selected, clazz == null)),
new WebTable.InstructorCell(clazz == null ? null : clazz.getInstructors(), clazz == null ? null : clazz.getInstructorEmails(), ", "),
new WebTable.Cell(compare(old == null ? null : old.getParentSection(), clazz == null ? null : clazz.getParentSection(), CmpMode.SINGLE, selected, clazz == null)),
icons);
String style = (selected?"text-blue":"") + (lastSize > 0 && rows.size() == lastSize ? " top-border-solid" : clazzIdx == 0 && !rows.isEmpty() ? " top-border-dashed": "");
row.setId(String.valueOf(suggestionId));
for (WebTable.Cell cell: row.getCells())
cell.setStyleName(style.trim());
row.getCell(0).setStyleName((lastSize > 0 && rows.size() == lastSize ? "top-border-solid" : ""));
rows.add(row);
row.setAriaLabel(ARIA.assigned(
(course.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(clazz.getSubject(), clazz.getCourseNbr(), clazz.getSubpart(), clazz.getSection())) + " " +
clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(", ")));
clazzIdx++;
}
} else {
if (sameCourse.isEmpty() || !sameCourse.get(0).isCourseAssigned()) continue;
for (int idx = 0; idx < sameCourse.size(); idx++) {
ClassAssignmentInterface.ClassAssignment old = sameCourse.get(idx);
ClassAssignmentInterface.ClassAssignment clazz = null;
WebTable.IconsCell icons = new WebTable.IconsCell();
if (old != null && old.isSaved())
icons.add(RESOURCES.saved(), MESSAGES.saved(MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())));
if (course.isLocked())
icons.add(RESOURCES.courseLocked(), MESSAGES.courseLocked(course.getSubject() + " " + course.getCourseNbr()));
if (old != null && old.isOfHighDemand())
icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(old.getExpected(), old.getAvailableLimit()));
if (old != null && old.hasNote())
icons.add(RESOURCES.note(), old.getNote());
WebTable.Row row = new WebTable.Row(
new WebTable.Cell(rows.size() == lastSize ? suggestionId + "." : ""),
new WebTable.Cell(idx > 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()).aria(idx == 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()),
new WebTable.Cell(idx > 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())).aria(idx == 0 ? "" : course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())),
new WebTable.Cell(compare(old == null ? null : old.getSubpart(), clazz == null ? null : clazz.getSubpart(), CmpMode.SINGLE, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getSection(), clazz == null ? null : clazz.getSection(), CmpMode.SINGLE, false, clazz == null)),
//new WebTable.Cell(compare(old == null ? null : old.getLimitString(), clazz == null ? null : clazz.getLimitString(), false)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_OLD, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_NEW, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_OLD, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_NEW, false, clazz == null)),
(old != null && old.hasDistanceConflict() ?
new WebTable.IconCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(old.getBackToBackRooms(), old.getBackToBackDistance()),
compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, false, clazz == null)) :
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, false, clazz == null))),
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_NEW, false, clazz == null)),
//new WebTable.Cell(compare(old == null ? null : old.getInstructors(", "), clazz == null ? null : clazz.getInstructors(", "), true)),
new WebTable.InstructorCell(old == null ? null : old.getInstructors(), old == null ? null : old.getInstructorEmails(), ", "),
new WebTable.Cell(compare(old == null ? null : old.getParentSection(), clazz == null ? null : clazz.getParentSection(), CmpMode.SINGLE, false, clazz == null)),
icons);
row.setId(String.valueOf(suggestionId));
String style = "text-red" + (lastSize > 0 && rows.size() == lastSize ? " top-border-solid" : idx == 0 && !rows.isEmpty() ? " top-border-dashed": "");
for (WebTable.Cell cell: row.getCells())
cell.setStyleName(style);
row.getCell(0).setStyleName((lastSize > 0 && rows.size() == lastSize ? "top-border-solid" : ""));
row.setAriaLabel(ARIA.unassigned(
(course.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())) + " " +
old.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + old.getRooms(", ")));
rows.add(row);
}
}
}
Long lastCourseId = null;
current: for (ClassAssignmentInterface.ClassAssignment old: iCurrent) {
if (old == null || old.isFreeTime()) continue;
for (ClassAssignmentInterface.CourseAssignment course: suggestion.getCourseAssignments()) {
if (old.getCourseId().equals(course.getCourseId())) continue current;
}
ClassAssignmentInterface.ClassAssignment clazz = null;
WebTable.IconsCell icons = new WebTable.IconsCell();
if (old != null && old.isSaved())
icons.add(RESOURCES.saved(), MESSAGES.saved(MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())));
if (old != null && old.isOfHighDemand())
icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(old.getExpected(), old.getAvailableLimit()));
if (old != null && old.hasNote())
icons.add(RESOURCES.note(), old.getNote());
WebTable.Row row = new WebTable.Row(
new WebTable.Cell(rows.size() == lastSize ? suggestionId + "." : ""),
new WebTable.Cell(old.getCourseId().equals(lastCourseId) ? "" : old.isFreeTime() ? MESSAGES.freeTimeSubject() : old.getSubject()).aria(!old.getCourseId().equals(lastCourseId) ? "" : old.isFreeTime() ? MESSAGES.freeTimeSubject() : old.getSubject()),
new WebTable.Cell(old.getCourseId().equals(lastCourseId) ? "" : old.isFreeTime() ? MESSAGES.freeTimeCourse() : old.getCourseNbr(CONSTANTS.showCourseTitle())).aria(!old.getCourseId().equals(lastCourseId) ? "" : old.isFreeTime() ? MESSAGES.freeTimeCourse() : old.getCourseNbr(CONSTANTS.showCourseTitle())),
new WebTable.Cell(compare(old == null ? null : old.getSubpart(), clazz == null ? null : clazz.getSubpart(), CmpMode.SINGLE, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getSection(), clazz == null ? null : clazz.getSection(), CmpMode.SINGLE, false, clazz == null)),
//new WebTable.Cell(compare(old == null ? null : old.getLimitString(), clazz == null ? null : clazz.getLimitString(), false)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_OLD, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), clazz == null ? null : clazz.getTimeString(CONSTANTS.shortDays(), CONSTANTS.useAmPm(), MESSAGES.arrangeHours()), CmpMode.BOTH_NEW, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_OLD, false, clazz == null)),
new WebTable.Cell(compare(old == null ? null : old.getDatePattern(), clazz == null ? null : clazz.getDatePattern(), CmpMode.BOTH_NEW, false, clazz == null)),
(old != null && old.hasDistanceConflict() ?
new WebTable.IconCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(old.getBackToBackRooms(), old.getBackToBackDistance()),
compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, false, clazz == null)) :
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_OLD, false, clazz == null))),
new WebTable.Cell(compare(old == null ? null : old.getRooms(", "), clazz == null ? null : clazz.getRooms(", "), CmpMode.BOTH_NEW, false, clazz == null)),
//new WebTable.Cell(compare(old == null ? null : old.getInstructors(", "), clazz == null ? null : clazz.getInstructors(", "), true)),
new WebTable.InstructorCell(old == null ? null : old.getInstructors(), old == null ? null : old.getInstructorEmails(), ", "),
new WebTable.Cell(compare(old == null ? null : old.getParentSection(), clazz == null ? null : clazz.getParentSection(), CmpMode.SINGLE, false, clazz == null)),
icons);
row.setId(String.valueOf(suggestionId));
String style = "text-red" + (lastSize > 0 && rows.size() == lastSize ? " top-border-solid" : !old.getCourseId().equals(lastCourseId) && !rows.isEmpty() ? " top-border-dashed": "");
for (WebTable.Cell cell: row.getCells())
cell.setStyleName(style);
row.getCell(0).setStyleName((lastSize > 0 && rows.size() == lastSize ? " top-border-solid" : ""));
row.setAriaLabel(ARIA.unassigned(
(old.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())) + " " +
old.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + old.getRooms(", ")));
rows.add(row);
lastCourseId = old.getCourseId();
}
lastSize = rows.size();
suggestionId++;
}
WebTable.Row[] rowArray = new WebTable.Row[rows.size()];
int idx = 0;
for (WebTable.Row row: rows) rowArray[idx++] = row;
iSuggestions.setData(rowArray);
if (rows.isEmpty()) {
if (iFilter.getText().isEmpty()) {
iSuggestions.setEmptyMessage(MESSAGES.suggestionsNoAlternative(iSource));
ariaStatus = ARIA.suggestionsNoAlternative(iSource);
} else {
iSuggestions.setEmptyMessage(MESSAGES.suggestionsNoAlternativeWithFilter(iSource, iFilter.getText()));
ariaStatus = ARIA.suggestionsNoAlternativeWithFilter(iSource, iFilter.getText());
}
} else {
ariaStatus = ARIA.showingAlternatives(Integer.valueOf(rows.get(rows.size() - 1).getId()), iSource);
}
LoadingWidget.getInstance().hide();
center();
if (ariaStatus != null)
AriaStatus.getInstance().setHTML(ariaStatus);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
iFilter.setFocus(true);
}
});
}
}
};
iSuggestions.addRowClickHandler(new WebTable.RowClickHandler() {
public void onRowClick(RowClickEvent event) {
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(event.getRow().getId()));
SuggestionSelectedEvent e = new SuggestionSelectedEvent(suggestion);
for (SuggestionSelectedHandler h: iSuggestionSelectedHandlers)
h.onSuggestionSelected(e);
hide();
}
});
iFilter.addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
if (iSuggestions.getSelectedRow() >= 0) {
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()));
SuggestionSelectedEvent e = new SuggestionSelectedEvent(suggestion);
for (SuggestionSelectedHandler h: iSuggestionSelectedHandlers)
h.onSuggestionSelected(e);
hide();
} else {
LoadingWidget.getInstance().show(MESSAGES.suggestionsLoading());
iSectioningService.computeSuggestions(iOnline, iRequest, iCurrent, iIndex, iFilter.getText(), iCallback);
}
}
}
});
iSearch.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
LoadingWidget.getInstance().show(MESSAGES.suggestionsLoading());
iSectioningService.computeSuggestions(iOnline, iRequest, iCurrent, iIndex, iFilter.getText(), iCallback);
}
});
iGrid = new TimeGrid(color);
iHint = new PopupPanel();
iHint.setStyleName("unitime-SuggestionsHint");
iHideHint = new Timer() {
@Override
public void run() {
if (iHint.isShowing()) iHint.hide();
}
};
iSuggestions.addRowOverHandler(new WebTable.RowOverHandler() {
@Override
public void onRowOver(final WebTable.RowOverEvent event) {
iHideHint.cancel();
if (iHint.isShowing() && event.getRow().getId().equals(iHintId)) return;
if (!event.getRow().getId().equals(iHintId)) {
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(event.getRow().getId()));
int index = 0;
iGrid.clear(false);
for (ClassAssignmentInterface.CourseAssignment course: suggestion.getCourseAssignments()) {
for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) {
if (clazz.isFreeTime()) {
CourseRequestInterface.FreeTime ft = new CourseRequestInterface.FreeTime();
ft.setLength(clazz.getLength());
ft.setStart(clazz.getStart());
for (int d: clazz.getDays()) ft.addDay(d);
iGrid.addFreeTime(ft);
} else if (clazz.isAssigned()) {
iGrid.addClass(clazz, index++);
}
}
}
TimeGrid w = (TimeGrid)iGrid.getPrintWidget();
w.addStyleName("unitime-SuggestionsHintWidget");
iHint.setWidget(new SimplePanel(w));
iHint.setSize((w.getWidth() / 2) + "px", (w.getHeight() / 2) + "px");
iHintId = event.getRow().getId();
}
iHint.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
Element tr = iSuggestions.getTable().getRowFormatter().getElement(event.getRowIdx());
boolean top = (tr.getAbsoluteBottom() - Window.getScrollTop() + 30 + offsetHeight > Window.getClientHeight());
iHint.setPopupPosition(
Math.max(Math.min(event.getEvent().getClientX() + 15, tr.getAbsoluteRight() - offsetWidth - 15), tr.getAbsoluteLeft() + 15),
top ? tr.getAbsoluteTop() - offsetHeight - 30 : tr.getAbsoluteBottom() + 30);
}
});
}
});
iSuggestions.addRowOutHandler(new WebTable.RowOutHandler() {
@Override
public void onRowOut(WebTable.RowOutEvent event) {
if (iHint.isShowing()) iHideHint.schedule(500);
}
});
iSuggestions.addRowMoveHandler(new WebTable.RowMoveHandler() {
@Override
public void onRowMove(WebTable.RowMoveEvent event) {
if (iHint.isShowing()) {
if (event.getRowIdx() < 0) { iHint.hide(); return; }
Element tr = iSuggestions.getTable().getRowFormatter().getElement(event.getRowIdx());
boolean top = (tr.getAbsoluteBottom() - Window.getScrollTop() + 30 + iHint.getOffsetHeight() > Window.getClientHeight());
iHint.setPopupPosition(
Math.max(Math.min(event.getEvent().getClientX() + 15, tr.getAbsoluteRight() - iHint.getOffsetWidth() - 15), tr.getAbsoluteLeft() + 15),
top ? tr.getAbsoluteTop() - iHint.getOffsetHeight() - 30 : tr.getAbsoluteBottom() + 30);
}
}
});
addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
if (iHint.isShowing()) iHint.hide();
iHideHint.cancel();
RootPanel.getBodyElement().getStyle().setOverflow(Overflow.AUTO);
iFilterPanel.hideHint();
}
});
setWidget(suggestionPanel);
}
@Override
public void center() {
super.center();
RootPanel.getBodyElement().getStyle().setOverflow(Overflow.HIDDEN);
}
private static enum CmpMode {
SINGLE,
BOTH_OLD,
BOTH_NEW,
ARIA
};
private String compare(String oldVal, String newVal, CmpMode mode, boolean selected, boolean conflict) {
switch (mode) {
case ARIA:
return (newVal != null && !newVal.isEmpty() ? newVal : oldVal != null ? oldVal : "");
case SINGLE:
return (newVal != null && !newVal.isEmpty() ? newVal : oldVal != null ? "<font color='"+ (conflict ? "red" : selected ? "#9999FF" : "#999999") +"'>" + oldVal + "</font>" : null);
case BOTH_OLD:
return (oldVal == null || oldVal.isEmpty() ? newVal : newVal == null || newVal.isEmpty() ? "<font color='" + (conflict ? "red" : selected ? "#9999FF" : "#999999") + "'>" + oldVal + "</font>" : oldVal.equals(newVal) ? oldVal : "<font color='" + ( selected ? "#9999FF" : "#999999" ) + "'>" + oldVal + "</font>");
case BOTH_NEW:
return (oldVal != null && !oldVal.isEmpty() && newVal != null && !newVal.isEmpty() && !newVal.equals(oldVal) ? "<font color='#" + ( selected ? "#9999FF" : "#999999" ) + "'>→</font> " + newVal : null);
default:
return newVal;
}
}
public void open(CourseRequestInterface request, ArrayList<ClassAssignmentInterface.ClassAssignment> rows, int index) {
LoadingWidget.getInstance().show(MESSAGES.suggestionsLoading());
ClassAssignmentInterface.ClassAssignment row = rows.get(index);
iAssignment = row;
iCurrent = rows;
iSource = null;
iRequest = request;
iIndex = index;
iHintId = null;
if (row.isFreeTime()) {
iSource = MESSAGES.freeTime(row.getDaysString(CONSTANTS.shortDays()), row.getStartString(CONSTANTS.useAmPm()), row.getEndString(CONSTANTS.useAmPm()));
} else {
if (row.getSubpart() == null)
iSource = MESSAGES.course(row.getSubject(), row.getCourseNbr());
else
iSource = MESSAGES.clazz(row.getSubject(), row.getCourseNbr(), row.getSubpart(), row.getSection());
}
setText(MESSAGES.suggestionsAlternatives(iSource));
iSuggestions.setSelectedRow(-1);
iSuggestions.clearData(true);
iSuggestions.setEmptyMessage(MESSAGES.suggestionsLoading());
iLegend.setHTML(
row.isFreeTime() ? MESSAGES.suggestionsLegendOnFreeTime(row.getDaysString(CONSTANTS.shortDays()) + " " + row.getStartString(CONSTANTS.useAmPm()) + " - " + row.getEndString(CONSTANTS.useAmPm())) :
row.isAssigned() ? MESSAGES.suggestionsLegendOnClass(MESSAGES.clazz(row.getSubject(), row.getCourseNbr(), row.getSubpart(), row.getSection()))
: MESSAGES.suggestionsLegendOnCourse(MESSAGES.course(row.getSubject(), row.getCourseNbr())));
iMessages.setHTML("");
iFilter.setText("");
iSectioningService.computeSuggestions(iOnline, request, rows, index, iFilter.getText(), iCallback);
}
protected void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
switch (DOM.eventGetType((Event) event.getNativeEvent())) {
case Event.ONKEYUP:
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) {
hide();
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_DOWN) {
if (iSuggestions.getRowsCount() > 0) {
String id = (iSuggestions.getSelectedRow() < 0 ? null : iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId());
int row = iSuggestions.getSelectedRow() + 1;
while (id != null && id.equals(iSuggestions.getRows()[row % iSuggestions.getRowsCount()].getId())) row++;
iSuggestions.setSelectedRow(row % iSuggestions.getRowsCount());
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()));
AriaStatus.getInstance().setText(ARIA.showingAlternative(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()), Integer.parseInt(iSuggestions.getRows()[iSuggestions.getRows().length - 1].getId()), toString(suggestion)));
}
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_UP) {
if (iSuggestions.getRowsCount() > 0) {
int row = iSuggestions.getSelectedRow() <= 0 ? iSuggestions.getRowsCount() - 1 : iSuggestions.getSelectedRow() - 1;
String id = iSuggestions.getRows()[row % iSuggestions.getRowsCount()].getId();
while (id.equals(iSuggestions.getRows()[(iSuggestions.getRowsCount() + row - 1) % iSuggestions.getRowsCount()].getId())) row--;
iSuggestions.setSelectedRow((iSuggestions.getRowsCount() + row) % iSuggestions.getRowsCount());
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()));
AriaStatus.getInstance().setText(ARIA.showingAlternative(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()), Integer.parseInt(iSuggestions.getRows()[iSuggestions.getRows().length - 1].getId()), toString(suggestion)));
}
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
if (iSuggestions.getSelectedRow() >= 0) {
ClassAssignmentInterface suggestion = iResult.get(Integer.parseInt(iSuggestions.getRows()[iSuggestions.getSelectedRow()].getId()));
AriaStatus.getInstance().setText(ARIA.selectedAlternative(toString(suggestion)));
SuggestionSelectedEvent e = new SuggestionSelectedEvent(suggestion);
for (SuggestionSelectedHandler h: iSuggestionSelectedHandlers)
h.onSuggestionSelected(e);
hide();
}
}
break;
}
}
private String toString(ClassAssignmentInterface suggestion) {
String ret = "";
for (ClassAssignmentInterface.CourseAssignment course: suggestion.getCourseAssignments()) {
ArrayList<ClassAssignmentInterface.ClassAssignment> sameCourse = new ArrayList<ClassAssignmentInterface.ClassAssignment>();
if (!course.isFreeTime()) {
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (course.getCourseId().equals(x.getCourseId())) sameCourse.add(x);
}
} else {
ClassAssignmentInterface.ClassAssignment clazz = course.getClassAssignments().get(0);
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (x.isFreeTime() && x.getDaysString(CONSTANTS.shortDays()).equals(clazz.getDaysString(CONSTANTS.shortDays())) && x.getStart() == clazz.getStart() && x.getLength() == clazz.getLength()) sameCourse.add(x);
}
}
if (course.isAssigned()) {
clazz: for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) {
for (ClassAssignmentInterface.ClassAssignment x: iCurrent) {
if (x == null) continue;
if (course.isFreeTime()) {
if (x.isFreeTime() && x.isCourseAssigned() && x.getDaysString(CONSTANTS.shortDays()).equals(clazz.getDaysString(CONSTANTS.shortDays())) &&
x.getStart() == clazz.getStart() && x.getLength() == clazz.getLength()) continue clazz;
} else {
if (clazz.getCourseId().equals(x.getCourseId()) && clazz.getClassId().equals(x.getClassId())) continue clazz; // the exact same assignment
if (clazz.getCourseId().equals(x.getCourseId()) && clazz.getSubpartId().equals(x.getSubpartId())) { break; }
}
}
ret += ARIA.assigned(
(course.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(clazz.getSubject(), clazz.getCourseNbr(), clazz.getSubpart(), clazz.getSection())) + " " +
clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(", "));
}
} else {
if (sameCourse.isEmpty() || !sameCourse.get(0).isCourseAssigned()) continue;
for (int idx = 0; idx < sameCourse.size(); idx++) {
ClassAssignmentInterface.ClassAssignment old = sameCourse.get(idx);
ret += ARIA.unassigned(
(course.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())) + " " +
old.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + old.getRooms(", "));
}
}
}
current: for (ClassAssignmentInterface.ClassAssignment old: iCurrent) {
if (old == null || old.isFreeTime()) continue;
for (ClassAssignmentInterface.CourseAssignment course: suggestion.getCourseAssignments()) {
if (old.getCourseId().equals(course.getCourseId())) continue current;
}
ret += ARIA.unassigned(
(old.isFreeTime() ? MESSAGES.course(MESSAGES.freeTimeSubject(), MESSAGES.freeTimeCourse()) : MESSAGES.clazz(old.getSubject(), old.getCourseNbr(), old.getSubpart(), old.getSection())) + " " +
old.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + old.getRooms(", "));
}
return ret;
}
public interface SuggestionSelectedHandler {
public void onSuggestionSelected(SuggestionSelectedEvent event);
}
public class SuggestionSelectedEvent {
private ClassAssignmentInterface iSuggestion;
private SuggestionSelectedEvent(ClassAssignmentInterface suggestion) {
iSuggestion = suggestion;
}
public ClassAssignmentInterface getSuggestion() { return iSuggestion; }
}
public void addSuggestionSelectedHandler(SuggestionSelectedHandler h) {
iSuggestionSelectedHandlers.add(h);
}
}
| |
package org.wso2.developerstudio.datamapper.diagram.part;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler;
import org.eclipse.gmf.runtime.common.ui.services.action.contributionitem.ContributionItemService;
import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.providers.DiagramContextMenuProvider;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IWorkbenchPart;
import org.wso2.developerstudio.datamapper.diagram.custom.action.AddNewFieldAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.AddNewTypeAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.AddNewRecordsListAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.AddNewRootRecordAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.ConcatManyAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.ExportSchemaAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.LoadInputSchemaAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.LoadOutputSchemaAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.RenameFieldAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.RenameNodeAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.SchemaFromJsonAction;
import org.wso2.developerstudio.datamapper.diagram.custom.action.SplitManyAction;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.ConcatEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.ElementEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.InputEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.OutputEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.SplitEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.TreeNode2EditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.TreeNode3EditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.TreeNodeEditPart;
/**
* @generated
*/
public class DiagramEditorContextMenuProvider extends DiagramContextMenuProvider {
private static final String EDIT_GROUP_ID = "editGroup"; //$NON-NLS-1$
private static final String NAVIGATE_GROUP_ID = "navigateGroup";
private static final String PROPERTIES_GROUP_ID = "propertiesGroup";
private static final String MENU_ADDITIONS = "additions";
private static final String MENU_PROPERTIES = "properties";
private static final String ERROR_BUILDING_CONTEXT_MENU = Messages.DiagramEditorContextMenuProvider_errorContextMenu;
/**
* @generated
*/
private IWorkbenchPart part;
/**
* @generated
*/
private DeleteElementAction deleteAction;
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> contextActions;
// Actions for adding a new root record
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> addNewRootRecordContextActions;
// Actions for adding a new record
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> addNewRecordContextActions;
// Actions for adding a new records list
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> addNewRecordsListContextActions;
// Actions for adding a new field
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> addNewFieldContextActions;
// Actions for Renaming a new field
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> addRenamingNodedActions;
// Actions for Renaming a new field
Map<Class<? extends AbstractBorderedShapeEditPart>, AbstractActionHandler> addRenamingFieldActions;
// Actions for getting schema from data-set
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> schemaFromDatasetActions;
// Actions for exporting schema
Map<Class<? extends ShapeNodeEditPart>, AbstractActionHandler> exportSchemaActions;
/**
* @generated NOT
*/
public DiagramEditorContextMenuProvider(IWorkbenchPart part, EditPartViewer viewer) {
super(part, viewer);
this.part = part;
deleteAction = new org.wso2.developerstudio.datamapper.diagram.part.DeleteElementAction(
part);
deleteAction.init();
contextActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
contextActions.put(InputEditPart.class, new LoadInputSchemaAction(part));
contextActions.put(OutputEditPart.class, new LoadOutputSchemaAction(part));
contextActions.put(ConcatEditPart.class, new ConcatManyAction(part));
contextActions.put(SplitEditPart.class, new SplitManyAction(part));
// Initialize new root record context sensitive actions.
addNewRootRecordContextActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
// New root record actions are added only to input and output editparts
addNewRootRecordContextActions.put(InputEditPart.class, new AddNewRootRecordAction(part));
addNewRootRecordContextActions.put(OutputEditPart.class, new AddNewRootRecordAction(part));
// Initialize new record context sensitive actions.
addNewRecordContextActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
// New record actions are added to treenode editparts
addNewRecordContextActions.put(TreeNodeEditPart.class, new AddNewTypeAction(part));
addNewRecordContextActions.put(TreeNode2EditPart.class, new AddNewTypeAction(part));
addNewRecordContextActions.put(TreeNode3EditPart.class, new AddNewTypeAction(part));
// Initialize new records list context sensitive actions.
addNewRecordsListContextActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
// New records list actions are added to treenode editparts
addNewRecordsListContextActions.put(TreeNodeEditPart.class, new AddNewRecordsListAction(
part));
addNewRecordsListContextActions.put(TreeNode2EditPart.class, new AddNewRecordsListAction(
part));
addNewRecordsListContextActions.put(TreeNode3EditPart.class, new AddNewRecordsListAction(
part));
addNewRecordsListContextActions.put(ElementEditPart.class, new AddNewRecordsListAction(
part));
// Initialize new field context sensitive actions.
addNewFieldContextActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
// New field actions are added to treenode editparts
addNewFieldContextActions.put(TreeNodeEditPart.class, new AddNewFieldAction(part));
addNewFieldContextActions.put(TreeNode2EditPart.class, new AddNewFieldAction(part));
addNewFieldContextActions.put(TreeNode3EditPart.class, new AddNewFieldAction(part));
//Initialize renaming action
// Initialize new field context sensitive actions.
addRenamingNodedActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
// New field actions are added to treenode editparts
addRenamingNodedActions.put(TreeNodeEditPart.class, new RenameNodeAction(part));
addRenamingNodedActions.put(TreeNode2EditPart.class, new RenameNodeAction(part));
addRenamingNodedActions.put(TreeNode3EditPart.class, new RenameNodeAction(part));
//Initialize renaming field action
// Initialize new field context sensitive actions.
addRenamingFieldActions = new HashMap<Class<? extends AbstractBorderedShapeEditPart>, AbstractActionHandler>();
// New field actions are added to treenode editparts
addRenamingFieldActions.put(ElementEditPart.class, new RenameFieldAction(part));
// Initialize schema from dataset actions.
schemaFromDatasetActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
schemaFromDatasetActions.put(InputEditPart.class, new SchemaFromJsonAction(part));
schemaFromDatasetActions.put(OutputEditPart.class, new SchemaFromJsonAction(part));
// Initialize export schema actions.
exportSchemaActions = new HashMap<Class<? extends ShapeNodeEditPart>, AbstractActionHandler>();
exportSchemaActions.put(InputEditPart.class, new ExportSchemaAction(part));
exportSchemaActions.put(OutputEditPart.class, new ExportSchemaAction(part));
}
/**
* @generated
*/
public void dispose() {
if (deleteAction != null) {
deleteAction.dispose();
deleteAction = null;
}
super.dispose();
}
/**
* @generated NOT
*/
public void buildContextMenu(final IMenuManager menu) {
getViewer().flush();
try {
TransactionUtil.getEditingDomain((EObject) getViewer().getContents().getModel())
.runExclusive(new Runnable() {
public void run() {
ContributionItemService.getInstance().contributeToPopupMenu(
DiagramEditorContextMenuProvider.this, part);
menu.remove(ActionIds.ACTION_DELETE_FROM_MODEL);
// Fixing TOOLS-2425
menu.remove(ActionIds.MENU_NAVIGATE);
menu.remove(ActionIds.MENU_EDIT);
menu.remove(ActionIds.MENU_FORMAT);
menu.remove(ActionIds.MENU_FILTERS);
menu.remove(ActionIds.MENU_FILE);
menu.remove(MENU_PROPERTIES);
menu.remove(MENU_ADDITIONS);
List<?> selectedEPs = getViewer().getSelectedEditParts();
if (selectedEPs.size() == 1) {
EditPart selectedEditorPart = (IGraphicalEditPart) selectedEPs
.get(0);
EObject contextObj = ((View) selectedEditorPart.getModel())
.getElement();
if (contextObj instanceof EObject) {
// Append new root item to menu
AbstractActionHandler addNewRootRecordContextAction = addNewRootRecordContextActions
.get(selectedEditorPart.getClass());
if (null != addNewRootRecordContextAction) {
menu.appendToGroup(EDIT_GROUP_ID,
addNewRootRecordContextAction);
}
// Append new record item to menu
AbstractActionHandler addNewRecordContextAction = addNewRecordContextActions
.get(selectedEditorPart.getClass());
if (null != addNewRecordContextAction) {
menu.appendToGroup(EDIT_GROUP_ID, addNewRecordContextAction);
}
// Append new records list item to menu
AbstractActionHandler addNewRecordsListContextAction = addNewRecordsListContextActions
.get(selectedEditorPart.getClass());
if (null != addNewRecordsListContextAction) {
menu.appendToGroup(EDIT_GROUP_ID,
addNewRecordsListContextAction);
}
// Append new field item to menu
AbstractActionHandler addNewFieldContextAction = addNewFieldContextActions
.get(selectedEditorPart.getClass());
if (null != addNewFieldContextAction) {
menu.appendToGroup(EDIT_GROUP_ID, addNewFieldContextAction);
}
// Append new field item to menu
AbstractActionHandler addRenameNodedAction = addRenamingNodedActions
.get(selectedEditorPart.getClass());
if (null != addRenameNodedAction) {
menu.appendToGroup(EDIT_GROUP_ID, addRenameNodedAction);
}
// Append new field item to menu
AbstractActionHandler addRenameFieldAction = addRenamingFieldActions
.get(selectedEditorPart.getClass());
if (null != addRenameFieldAction) {
menu.appendToGroup(EDIT_GROUP_ID, addRenameFieldAction);
}
// Append Schema from dataset item to menu
AbstractActionHandler schemaFromDatasetAction = schemaFromDatasetActions
.get(selectedEditorPart.getClass());
if (null != schemaFromDatasetAction) {
menu.appendToGroup(NAVIGATE_GROUP_ID,
schemaFromDatasetAction);
}
// Append load from file item to menu
AbstractActionHandler contextAction = contextActions
.get(selectedEditorPart.getClass());
if (null != contextAction) {
menu.appendToGroup(NAVIGATE_GROUP_ID, contextAction);
}
// Append export schema item to menu
AbstractActionHandler exportSchemaAction = exportSchemaActions
.get(selectedEditorPart.getClass());
if (null != exportSchemaAction) {
menu.appendToGroup(NAVIGATE_GROUP_ID, exportSchemaAction);
}
}
}
menu.prependToGroup(PROPERTIES_GROUP_ID, deleteAction);
}
});
} catch (Exception e) {
org.wso2.developerstudio.datamapper.diagram.part.DataMapperDiagramEditorPlugin
.getInstance().logError(ERROR_BUILDING_CONTEXT_MENU, e);
}
}
}
| |
/*---------------------------------------------------------------
* Copyright 2005 by the Radiological Society of North America
*
* This source software is released under the terms of the
* RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/
package org.rsna.server;
import org.apache.log4j.Logger;
import org.rsna.util.FileUtil;
import org.rsna.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.TimeZone;
/**
* A simple HTTP text response in UTF-8.
*/
public class HttpResponse {
static final Logger logger = Logger.getLogger(HttpResponse.class);
static Hashtable<String,String> contentTypes = new ContentTypes();
public static final int ok = 200;
public static final int found = 302;
public static final int notmodified = 304;
public static final int unauthorized = 401;
public static final int forbidden = 403;
public static final int notfound = 404;
public static final int servererror = 500;
public static final int notimplemented = 501;
protected static SimpleDateFormat dateFormat = null;
final Socket socket;
final OutputStream outputStream;
final Hashtable<String,String> headers;
final List<ResponseItem> responseContent;
long responseLength = 0;
int responseCode = 200;
/**
* Create an HttpResponse, connecting it to an OutputStream and
* setting a default response code of 200.
* @param socket the socket on which to construct the response.
*/
public HttpResponse(Socket socket) throws Exception {
this.socket = socket;
outputStream = socket.getOutputStream();
headers = new Hashtable<String,String> ();
responseContent = new LinkedList<ResponseItem>();
responseLength = 0;
String date = getHttpDate(-1);
if (date != null) setHeader( "Date", date );
}
/**
* Get the OutputStream associated with this response.
* @return the OutputStream.
*/
public OutputStream getOutputStream() {
return outputStream;
}
/**
* Flush and close the OutputStream associated with this response.
*/
public synchronized void close() {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
catch (Exception ignore) { logger.warn("Unable to close the output stream"); }
}
/**
* Set a response code for the HttpResponse.
* @param responseCode the integer response code to be sent with the response, e.g., 404
*/
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
/**
* Insert a header.
* @param name the header name, e.g. "Content-Type".
* @param value the header text value, e.g., "application/zip".
*/
public void setHeader(String name, String value) {
headers.put(name,value);
}
/**
* Set headers that disable caching.
*/
public void disableCaching() {
String date = getHttpDate(-1);
if (date != null) headers.put("Expires", date);
headers.put("Pragma","no-cache");
headers.put("Cache-Control","no-cache");
}
/**
* Set the Content-Type header that corresponds to the
* extension of a file. This method calls setContentType(String),
* supplying the extension of the file.
* @param file the file whose extension is to be used to determine
* the Content-Type.
* @return the Content-Type.
*/
public String setContentType(File file) {
String name = file.getName();
String ext = name.substring(name.lastIndexOf(".")+1);
return setContentType(ext);
}
/**
* Set the Content-Type header that corresponds to a String.
* If the string doesn't correspond to a known Content-Type,
* the header is not set.
* <br><br>
* <table border="1">
* <tr><td>application</td><td>application/x-ms-application</td></tr>
* <tr><td>avi</td><td>video/x-msvideo</td></tr>
* <tr><td>css</td><td>text/css;charset=UTF-8</td></tr>
* <tr><td>csv</td><td>text/csv;charset=UTF-8</td></tr>
* <tr><td>dcm</td><td>application/dicom</td></tr>
* <tr><td>deploy</td><td>application/octet-stream</td></tr>
* <tr><td>docx</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr>
* <tr><td>dotx</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.template</td></tr>
* <tr><td>gif</td><td>image/gif</td></tr>
* <tr><td>htm</td><td>text/html;charset=UTF-8</td></tr>
* <tr><td>html</td><td>text/html;charset=UTF-8</td></tr>
* <tr><td>jar</td><td>application/java-archive</td></tr>
* <tr><td>jnlp</td><td>application/x-java-jnlp-file;charset=UTF-8</td></tr>
* <tr><td>jpeg</td><td>image/jpeg</td></tr>
* <tr><td>jpg</td><td>image/jpeg</td></tr>
* <tr><td>js</td><td>text/javascript;charset=UTF-8</td></tr>
* <tr><td>manifest</td><td>application/x-ms-manifest</td></tr>
* <tr><td>md</td><td>application/unknown</td></tr>
* <tr><td>mp4</td><td>video/mp4</td></tr>
* <tr><td>mpeg</td><td>video/mpeg</td></tr>
* <tr><td>mpg</td><td>video/mpg</td></tr>
* <tr><td>oga</td><td>audio/oga</td></tr>
* <tr><td>ogg</td><td>video/ogg</td></tr>
* <tr><td>ogv</td><td>video/ogg</td></tr>
* <tr><td>pdf</td><td>application/pdf</td></tr>
* <tr><td>png</td><td>image/png</td></tr>
* <tr><td>pot</td><td>application/vnd.ms-powerpoint</td></tr>
* <tr><td>potx</td><td>application/vnd.openxmlformats-officedocument.presentationml.template</td></tr>
* <tr><td>pps</td><td>application/vnd.ms-powerpoint</td></tr>
* <tr><td>ppsx</td><td>application/vnd.openxmlformats-officedocument.presentationml.slideshow</td></tr>
* <tr><td>ppt</td><td>application/vnd.ms-powerpoint</td></tr>
* <tr><td>pptx</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr>
* <tr><td>svg</td><td>image/xvg+xml</td></tr>
* <tr><td>swf</td><td>application/x-shockwave-flash</td></tr>
* <tr><td>txt</td><td>text/plain;charset=UTF-8</td></tr>
* <tr><td>wav</td><td>audio/wav</td></tr>
* <tr><td>webm</td><td>video/webm</td></tr>
* <tr><td>wmv</td><td>video/x-ms-wmv</td></tr>
* <tr><td>xlsx</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr>
* <tr><td>xltx</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.template</td></tr>
* <tr><td>xml</td><td>text/xml;charset=UTF-8</td></tr>
* <tr><td>zip</td><td>application/zip</td></tr>
* </table>
* @param ext the name of a Content-Type (e.g. "html", "xml", etc.).
* @return the Content-Type.
*/
public String setContentType(String ext) {
String contentType = contentTypes.get(ext);
if (contentType != null) setHeader("Content-Type", contentType);
return contentType;
}
/**
* Set the Disposition header for a file.
* @param file the file whose name is to be inserted into
* the Disposition header.
*/
public String setContentDisposition(File file) {
String disposition = "attachment; filename=\"" + file.getName() + "\"";
setHeader("Content-Disposition", disposition);
return disposition;
}
/**
* Set the Last-Modified header for a file.
* @param time the last modified date in milliseconds.
*/
public void setLastModified(long time) {
String date = getHttpDate(time);
if (date != null) setHeader("Last-Modified", date);
}
/**
* Set the ETag header using the value of a long integer.
* @param value the value to be used as the ETag.
*/
public void setETag(long value) {
setHeader("ETag", "\""+value+"\"");
}
/**
* Convert a millisecond time to the Http date format for use in headers.
* The format returned is: "Thu, 16 Mar 2000 11:00:00 GMT"
* @param time Date value, or -1 to use the current datetime.
*/
public synchronized String getHttpDate(long time) {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
dateFormat.setTimeZone( TimeZone.getTimeZone("GMT") );
}
Date date = (time == -1) ? new Date() : new Date(time);
try { return dateFormat.format(date); }
catch (Exception ex) { return null; }
}
/**
* Add a text string content item to the response.
* @param string the string to be added to the response.
*/
public void write(String string) {
try {
ResponseItem item = new ResponseItem(string);
responseContent.add(item);
responseLength += item.length;
}
catch (Exception ignore) {
logger.warn("Could not add \""+string+"\" to the response.");
}
}
/**
* Add a file content item to the response.
* @param file the file whose contents are to be added to the response.
*/
public void write(File file) {
try {
ResponseItem item = new ResponseItem(file);
responseContent.add(item);
responseLength += item.length;
}
catch (Exception ignore) {
logger.warn("Unable to add file "+file+" to the response.");
}
}
/**
* Add a byte array content item to the response.
* @param bytes to be added to the response.
*/
public void write(byte[] bytes) {
try {
ResponseItem item = new ResponseItem(bytes);
responseContent.add(item);
responseLength += item.length;
}
catch (Exception ignore) {
logger.warn("Unable to add the byte array to the response.");
}
}
/**
* Add a resource content item to the response.
* @param url the URL of the resource to be added to the response.
*/
public void write(URL url) {
try {
byte[] bytes = FileUtil.getBytes( url.openStream() );
ResponseItem item = new ResponseItem(bytes);
responseContent.add(item);
responseLength += item.length;
}
catch (Exception ignore) {
logger.warn("Unable to add the resource "+url+" to the response.");
}
}
/**
* Set the HttpResponse to trigger a redirect. This method sets
* the HTTP response code to 302, adds the Location header,
* <b>and</b> calls the send() method.
* @param url the destination
*/
public void redirect(String url) {
setResponseCode(found);
setHeader("Location", url);
send();
}
/**
* Send the response, setting the Content-Length header
* and including all the content items.
*/
public boolean send() {
try {
String preamble =
"HTTP/1.1 " + responseCode + "\r\n" +
getHeadersString() +
"Content-Length: " + responseLength + "\r\n\r\n";
byte[] preambleBytes = preamble.getBytes("UTF-8");
outputStream.write(preambleBytes);
ListIterator<ResponseItem> it = responseContent.listIterator();
while (it.hasNext()) it.next().write();
outputStream.flush();
return true;
}
catch (Exception ex) {
//logger.error("Unable to send the response.", ex);
return false;
}
}
//Get all the headers as a string.
String getHeadersString() {
StringBuffer sb = new StringBuffer();
Enumeration<String> keys = headers.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String value = headers.get(key);
sb.append(key + ": " + value + "\r\n");
}
return sb.toString();
}
/**
* List the headers for this HttpResponse
*/
public String listHeaders(String margin) {
StringBuffer sb = new StringBuffer();
for (String key : headers.keySet()) {
sb.append(margin + key + ": " + headers.get(key) + "\n");
}
if (sb.length() == 0) sb.append(margin + "none\n");
return sb.toString();
}
//A class to encapsulate one part of the content of a response.
class ResponseItem {
byte[] bytes = null;
File file = null;
long length = 0;
public ResponseItem(byte[] bytes) throws Exception {
this.bytes = bytes;
length = bytes.length;
}
public ResponseItem(String string) throws Exception {
bytes = string.getBytes("UTF-8");
length = bytes.length;
}
public ResponseItem(File file) throws Exception {
this.file = file;
length = file.length();
}
public void write() {
try {
if (bytes != null) outputStream.write(bytes);
else if (file != null) {
FileInputStream inputStream = new FileInputStream(file);
int nbytes;
byte[] buffer = new byte[2048];
while ((nbytes = inputStream.read(buffer)) != -1) {
outputStream.write(buffer,0,nbytes);
}
inputStream.close();
}
}
catch (Exception ignore) {
logger.debug("Unable to write to the output stream.", ignore);
}
}
}
//A static class to provide a mapping from file extension to Content-Type.
static class ContentTypes extends Hashtable<String,String> {
public ContentTypes() {
super();
put("application", "application/x-ms-application");
put("avi","video/x-msvideo");
put("css","text/css;charset=UTF-8");
put("csv","text/csv;charset=UTF-8");
put("dcm","application/dicom");
put("deploy","application/octet-stream");
put("docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document");
put("dotx","application/vnd.openxmlformats-officedocument.wordprocessingml.template");
put("gif","image/gif");
put("htm","text/html;charset=UTF-8");
put("html","text/html;charset=UTF-8");
put("jar","application/java-archive");
put("jnlp","application/x-java-jnlp-file;charset=UTF-8");
put("jpeg","image/jpeg");
put("jpg","image/jpeg");
put("js","text/javascript;charset=UTF-8");
put("manifest", "application/x-ms-manifest");
put("md","application/unknown");
put("mp4","video/mp4");
put("mpeg","video/mpg");
put("mpg","video/mpg");
put("oga","audio/oga");
put("ogg","video/ogg");
put("ogv","video/ogg");
put("pdf","application/pdf");
put("png","image/png");
put("pot","application/vnd.ms-powerpoint");
put("potx","application/vnd.openxmlformats-officedocument.presentationml.template");
put("pps","application/vnd.ms-powerpoint");
put("ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow");
put("ppt","application/vnd.ms-powerpoint");
put("pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation");
put("svg","image/svg+xml");
put("swf","application/x-shockwave-flash");
put("txt","text/plain;charset=UTF-8");
put("wav","audio/wav");
put("webm","video/webm");
put("wmv","video/x-ms-wmv");
put("xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
put("xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template");
put("xml","text/xml;charset=UTF-8");
put("zip","application/zip");
File file = new File("ContentTypes.xml");
if (file.exists()) {
try {
Document doc = XmlUtil.getDocument(file);
Element root = doc.getDocumentElement();
Node child = root.getFirstChild();
while (child != null) {
if ((child instanceof Element) && child.getNodeName().toLowerCase().equals("file")) {
Element filetype = (Element)child;
String ext = filetype.getAttribute("ext").toLowerCase();
if (ext.startsWith(".")) ext = ext.substring(1);
String type = filetype.getAttribute("type");
put(ext, type);
}
child = child.getNextSibling();
}
}
catch (Exception skip) {
logger.warn("Unable to load ContentType extensions ("+file+")");
}
}
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.percolator;
import org.elasticsearch.action.percolate.PercolateRequestBuilder;
import org.elasticsearch.action.percolate.PercolateResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.InternalBucketMetricValue;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.action.percolate.PercolateSourceBuilder.docBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertMatchCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
*
*/
public class PercolatorFacetsAndAggregationsIT extends ESIntegTestCase {
@Test
// Just test the integration with facets and aggregations, not the facet and aggregation functionality!
public void testFacetsAndAggregations() throws Exception {
assertAcked(prepareCreate("test").addMapping("type", "field1", "type=string", "field2", "type=string"));
ensureGreen();
int numQueries = scaledRandomIntBetween(250, 500);
int numUniqueQueries = between(1, numQueries / 2);
String[] values = new String[numUniqueQueries];
for (int i = 0; i < values.length; i++) {
values[i] = "value" + i;
}
int[] expectedCount = new int[numUniqueQueries];
logger.info("--> registering {} queries", numQueries);
for (int i = 0; i < numQueries; i++) {
String value = values[i % numUniqueQueries];
expectedCount[i % numUniqueQueries]++;
QueryBuilder queryBuilder = matchQuery("field1", value);
client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", queryBuilder).field("field2", "b").endObject()).execute()
.actionGet();
}
client().admin().indices().prepareRefresh("test").execute().actionGet();
for (int i = 0; i < numQueries; i++) {
String value = values[i % numUniqueQueries];
PercolateRequestBuilder percolateRequestBuilder = client().preparePercolate().setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", value).endObject()));
SubAggCollectionMode aggCollectionMode = randomFrom(SubAggCollectionMode.values());
percolateRequestBuilder.addAggregation(AggregationBuilders.terms("a").field("field2").collectMode(aggCollectionMode));
if (randomBoolean()) {
percolateRequestBuilder.setPercolateQuery(matchAllQuery());
}
if (randomBoolean()) {
percolateRequestBuilder.setScore(true);
} else {
percolateRequestBuilder.setSortByScore(true).setSize(numQueries);
}
boolean countOnly = randomBoolean();
if (countOnly) {
percolateRequestBuilder.setOnlyCount(countOnly);
}
PercolateResponse response = percolateRequestBuilder.execute().actionGet();
assertMatchCount(response, expectedCount[i % numUniqueQueries]);
if (!countOnly) {
assertThat(response.getMatches(), arrayWithSize(expectedCount[i % numUniqueQueries]));
}
List<Aggregation> aggregations = response.getAggregations().asList();
assertThat(aggregations.size(), equalTo(1));
assertThat(aggregations.get(0).getName(), equalTo("a"));
List<Terms.Bucket> buckets = new ArrayList<>(((Terms) aggregations.get(0)).getBuckets());
assertThat(buckets.size(), equalTo(1));
assertThat(buckets.get(0).getKeyAsString(), equalTo("b"));
assertThat(buckets.get(0).getDocCount(), equalTo((long) expectedCount[i % values.length]));
}
}
@Test
// Just test the integration with facets and aggregations, not the facet and aggregation functionality!
public void testAggregationsAndPipelineAggregations() throws Exception {
assertAcked(prepareCreate("test").addMapping("type", "field1", "type=string", "field2", "type=string"));
ensureGreen();
int numQueries = scaledRandomIntBetween(250, 500);
int numUniqueQueries = between(1, numQueries / 2);
String[] values = new String[numUniqueQueries];
for (int i = 0; i < values.length; i++) {
values[i] = "value" + i;
}
int[] expectedCount = new int[numUniqueQueries];
logger.info("--> registering {} queries", numQueries);
for (int i = 0; i < numQueries; i++) {
String value = values[i % numUniqueQueries];
expectedCount[i % numUniqueQueries]++;
QueryBuilder queryBuilder = matchQuery("field1", value);
client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", queryBuilder).field("field2", "b").endObject()).execute()
.actionGet();
}
client().admin().indices().prepareRefresh("test").execute().actionGet();
for (int i = 0; i < numQueries; i++) {
String value = values[i % numUniqueQueries];
PercolateRequestBuilder percolateRequestBuilder = client().preparePercolate().setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", value).endObject()));
SubAggCollectionMode aggCollectionMode = randomFrom(SubAggCollectionMode.values());
percolateRequestBuilder.addAggregation(AggregationBuilders.terms("a").field("field2").collectMode(aggCollectionMode));
if (randomBoolean()) {
percolateRequestBuilder.setPercolateQuery(matchAllQuery());
}
if (randomBoolean()) {
percolateRequestBuilder.setScore(true);
} else {
percolateRequestBuilder.setSortByScore(true).setSize(numQueries);
}
boolean countOnly = randomBoolean();
if (countOnly) {
percolateRequestBuilder.setOnlyCount(countOnly);
}
percolateRequestBuilder.addAggregation(PipelineAggregatorBuilders.maxBucket("max_a").setBucketsPaths("a>_count"));
PercolateResponse response = percolateRequestBuilder.execute().actionGet();
assertMatchCount(response, expectedCount[i % numUniqueQueries]);
if (!countOnly) {
assertThat(response.getMatches(), arrayWithSize(expectedCount[i % numUniqueQueries]));
}
Aggregations aggregations = response.getAggregations();
assertThat(aggregations.asList().size(), equalTo(2));
Terms terms = aggregations.get("a");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("a"));
List<Terms.Bucket> buckets = new ArrayList<>(terms.getBuckets());
assertThat(buckets.size(), equalTo(1));
assertThat(buckets.get(0).getKeyAsString(), equalTo("b"));
assertThat(buckets.get(0).getDocCount(), equalTo((long) expectedCount[i % values.length]));
InternalBucketMetricValue maxA = aggregations.get("max_a");
assertThat(maxA, notNullValue());
assertThat(maxA.getName(), equalTo("max_a"));
assertThat(maxA.value(), equalTo((double) expectedCount[i % values.length]));
assertThat(maxA.keys(), equalTo(new String[] { "b" }));
}
}
@Test
public void testSignificantAggs() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
PercolateRequestBuilder percolateRequestBuilder = client().preparePercolate().setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "value").endObject()))
.addAggregation(AggregationBuilders.significantTerms("a").field("field2"));
PercolateResponse response = percolateRequestBuilder.get();
assertNoFailures(response);
}
@Test
public void testSingleShardAggregations() throws Exception {
assertAcked(prepareCreate("test").setSettings(Settings.builder().put(indexSettings()).put("SETTING_NUMBER_OF_SHARDS", 1))
.addMapping("type", "field1", "type=string", "field2", "type=string"));
ensureGreen();
int numQueries = scaledRandomIntBetween(250, 500);
logger.info("--> registering {} queries", numQueries);
for (int i = 0; i < numQueries; i++) {
String value = "value0";
QueryBuilder queryBuilder = matchQuery("field1", value);
client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", queryBuilder).field("field2", i % 3 == 0 ? "b" : "a").endObject())
.execute()
.actionGet();
}
client().admin().indices().prepareRefresh("test").execute().actionGet();
for (int i = 0; i < numQueries; i++) {
String value = "value0";
PercolateRequestBuilder percolateRequestBuilder = client().preparePercolate().setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", value).endObject()));
SubAggCollectionMode aggCollectionMode = randomFrom(SubAggCollectionMode.values());
percolateRequestBuilder.addAggregation(AggregationBuilders.terms("terms").field("field2").collectMode(aggCollectionMode)
.order(Order.term(true)).shardSize(2).size(1));
if (randomBoolean()) {
percolateRequestBuilder.setPercolateQuery(matchAllQuery());
}
if (randomBoolean()) {
percolateRequestBuilder.setScore(true);
} else {
percolateRequestBuilder.setSortByScore(true).setSize(numQueries);
}
boolean countOnly = randomBoolean();
if (countOnly) {
percolateRequestBuilder.setOnlyCount(countOnly);
}
percolateRequestBuilder.addAggregation(PipelineAggregatorBuilders.maxBucket("max_terms").setBucketsPaths("terms>_count"));
PercolateResponse response = percolateRequestBuilder.execute().actionGet();
assertMatchCount(response, numQueries);
if (!countOnly) {
assertThat(response.getMatches(), arrayWithSize(numQueries));
}
Aggregations aggregations = response.getAggregations();
assertThat(aggregations.asList().size(), equalTo(2));
Terms terms = aggregations.get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<Terms.Bucket> buckets = new ArrayList<>(terms.getBuckets());
assertThat(buckets.size(), equalTo(1));
assertThat(buckets.get(0).getKeyAsString(), equalTo("a"));
InternalBucketMetricValue maxA = aggregations.get("max_terms");
assertThat(maxA, notNullValue());
assertThat(maxA.getName(), equalTo("max_terms"));
assertThat(maxA.keys(), equalTo(new String[] { "a" }));
}
}
}
| |
/*
* Copyright (c) 2000-2005 Regents of the University of California.
* All rights reserved.
*
* This software was developed at the University of California, Irvine.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Irvine. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
package edu.uci.isr.xarch.instance;
import org.w3c.dom.*;
import edu.uci.isr.xarch.*;
import java.util.*;
/**
* DOM-Based implementation of the IPoint interface.
*
* @author Automatically generated by xArch apigen.
*/
public class PointImpl implements IPoint, DOMBased{
public static final String XSD_TYPE_NSURI = InstanceConstants.NS_URI;
public static final String XSD_TYPE_NAME = "Point";
protected IXArch xArch;
/** Tag name for anchorOnInterfaces in this object. */
public static final String ANCHOR_ON_INTERFACE_ELT_NAME = "anchorOnInterface";
protected Element elt;
private static SequenceOrder seqOrd = new SequenceOrder(
new QName[]{
new QName(InstanceConstants.NS_URI, ANCHOR_ON_INTERFACE_ELT_NAME)
}
);
public PointImpl(Element elt){
if(elt == null){
throw new IllegalArgumentException("Element cannot be null.");
}
this.elt = elt;
}
public Node getDOMNode(){
return elt;
}
public void setDOMNode(Node node){
if(node.getNodeType() != Node.ELEMENT_NODE){
throw new IllegalArgumentException("Base DOM node of this type must be an Element.");
}
elt = (Element)node;
}
protected static SequenceOrder getSequenceOrder(){
return seqOrd;
}
public void setXArch(IXArch xArch){
this.xArch = xArch;
}
public IXArch getXArch(){
return this.xArch;
}
public IXArchElement cloneElement(int depth){
synchronized(DOMUtils.getDOMLock(elt)){
Document doc = elt.getOwnerDocument();
if(depth == 0){
Element cloneElt = (Element)elt.cloneNode(false);
cloneElt = (Element)doc.importNode(cloneElt, true);
PointImpl cloneImpl = new PointImpl(cloneElt);
cloneImpl.setXArch(getXArch());
return cloneImpl;
}
else if(depth == 1){
Element cloneElt = (Element)elt.cloneNode(false);
cloneElt = (Element)doc.importNode(cloneElt, true);
PointImpl cloneImpl = new PointImpl(cloneElt);
cloneImpl.setXArch(getXArch());
NodeList nl = elt.getChildNodes();
int size = nl.getLength();
for(int i = 0; i < size; i++){
Node n = nl.item(i);
Node cloneNode = (Node)n.cloneNode(false);
cloneNode = doc.importNode(cloneNode, true);
cloneElt.appendChild(cloneNode);
}
return cloneImpl;
}
else /* depth = infinity */{
Element cloneElt = (Element)elt.cloneNode(true);
cloneElt = (Element)doc.importNode(cloneElt, true);
PointImpl cloneImpl = new PointImpl(cloneElt);
cloneImpl.setXArch(getXArch());
return cloneImpl;
}
}
}
//Override 'equals' to be DOM-based...
public boolean equals(Object o){
if(o == null){
return false;
}
if(!(o instanceof DOMBased)){
return super.equals(o);
}
DOMBased db = (DOMBased)o;
Node dbNode = db.getDOMNode();
return dbNode.equals(getDOMNode());
}
//Override 'hashCode' to be based on the underlying node
public int hashCode(){
return getDOMNode().hashCode();
}
/**
* For internal use only.
*/
private static Object makeDerivedWrapper(Element elt, String baseTypeName){
synchronized(DOMUtils.getDOMLock(elt)){
QName typeName = XArchUtils.getXSIType(elt);
if(typeName == null){
return null;
}
else{
if(!DOMUtils.hasXSIType(elt, "http://www.ics.uci.edu/pub/arch/xArch/instance.xsd", baseTypeName)){
try{
String packageTitle = XArchUtils.getPackageTitle(typeName.getNamespaceURI());
String packageName = XArchUtils.getPackageName(packageTitle);
String implName = XArchUtils.getImplName(packageName, typeName.getName());
Class c = Class.forName(implName);
java.lang.reflect.Constructor con = c.getConstructor(new Class[]{Element.class});
Object o = con.newInstance(new Object[]{elt});
return o;
}
catch(Exception e){
//Lots of bad things could happen, but this
//is OK, because this is best-effort anyway.
}
}
return null;
}
}
}
public XArchTypeMetadata getTypeMetadata(){
return IPoint.TYPE_METADATA;
}
public XArchInstanceMetadata getInstanceMetadata(){
return new XArchInstanceMetadata(XArchUtils.getPackageTitle(elt.getNamespaceURI()));
}
public void setAnchorOnInterface(IXMLLink value){
if(!(value instanceof DOMBased)){
throw new IllegalArgumentException("Cannot handle non-DOM-based xArch entities.");
}
{
IXMLLink oldElt = getAnchorOnInterface();
DOMUtils.removeChildren(elt, InstanceConstants.NS_URI, ANCHOR_ON_INTERFACE_ELT_NAME);
IXArch context = getXArch();
if(context != null){
context.fireXArchEvent(
new XArchEvent(this,
XArchEvent.CLEAR_EVENT,
XArchEvent.ELEMENT_CHANGED,
"anchorOnInterface", oldElt,
XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this), true)
);
}
}
Element newChildElt = (Element)(((DOMBased)value).getDOMNode());
newChildElt = DOMUtils.cloneAndRename(newChildElt, InstanceConstants.NS_URI, ANCHOR_ON_INTERFACE_ELT_NAME);
((DOMBased)value).setDOMNode(newChildElt);
synchronized(DOMUtils.getDOMLock(elt)){
elt.appendChild(newChildElt);
DOMUtils.order(elt, getSequenceOrder());
}
IXArch context = getXArch();
if(context != null){
context.fireXArchEvent(
new XArchEvent(this,
XArchEvent.SET_EVENT,
XArchEvent.ELEMENT_CHANGED,
"anchorOnInterface", value,
XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))
);
}
}
public void clearAnchorOnInterface(){
IXMLLink oldElt = getAnchorOnInterface();
DOMUtils.removeChildren(elt, InstanceConstants.NS_URI, ANCHOR_ON_INTERFACE_ELT_NAME);
IXArch context = getXArch();
if(context != null){
context.fireXArchEvent(
new XArchEvent(this,
XArchEvent.CLEAR_EVENT,
XArchEvent.ELEMENT_CHANGED,
"anchorOnInterface", oldElt,
XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))
);
}
}
public IXMLLink getAnchorOnInterface(){
NodeList nl = DOMUtils.getChildren(elt, InstanceConstants.NS_URI, ANCHOR_ON_INTERFACE_ELT_NAME);
if(nl.getLength() == 0){
return null;
}
else{
Element el = (Element)nl.item(0);
IXArch de = getXArch();
if(de != null){
IXArchElement cachedXArchElt = de.getWrapper(el);
if(cachedXArchElt != null){
return (IXMLLink)cachedXArchElt;
}
}
Object o = makeDerivedWrapper(el, "XMLLink");
if(o != null){
try{
((edu.uci.isr.xarch.IXArchElement)o).setXArch(getXArch());
if(de != null){
de.cacheWrapper(el, ((edu.uci.isr.xarch.IXArchElement)o));
}
return (IXMLLink)o;
}
catch(Exception e){}
}
XMLLinkImpl eltImpl = new XMLLinkImpl(el);
eltImpl.setXArch(getXArch());
if(de != null){
de.cacheWrapper(el, ((edu.uci.isr.xarch.IXArchElement)eltImpl));
}
return eltImpl;
}
}
public boolean hasAnchorOnInterface(IXMLLink value){
IXMLLink thisValue = getAnchorOnInterface();
IXMLLink thatValue = value;
if((thisValue == null) && (thatValue == null)){
return true;
}
else if((thisValue == null) && (thatValue != null)){
return false;
}
else if((thisValue != null) && (thatValue == null)){
return false;
}
return thisValue.isEquivalent(thatValue);
}
public boolean isEquivalent(IPoint c){
return (getClass().equals(c.getClass())) &&
hasAnchorOnInterface(c.getAnchorOnInterface()) ;
}
}
| |
/**
Copyright (c) 2010, Cisco Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Cisco Systems, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.cisco.qte.jdtn.tcpcl;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.cisco.qte.jdtn.bp.BPException;
import com.cisco.qte.jdtn.bp.EndPointId;
import com.cisco.qte.jdtn.general.GeneralManagement;
import com.cisco.qte.jdtn.general.JDtnException;
import com.cisco.qte.jdtn.general.Link;
import com.cisco.qte.jdtn.general.LinkAddress;
import com.cisco.qte.jdtn.general.Neighbor;
import com.cisco.qte.jdtn.general.NeighborsList;
import com.cisco.qte.jdtn.general.Utils;
import com.cisco.qte.jdtn.ltp.IPAddress;
import com.cisco.qte.jdtn.general.XmlRDParser;
import com.cisco.qte.jdtn.general.XmlRdParserException;
/**
* TCP Convergence Layer Link
* NOTE: We do not support reactive fragmentation
*/
public class TcpClLink extends Link {
private static final Logger _logger =
Logger.getLogger(TcpClLink.class.getCanonicalName());
public static final boolean IPV6_DEFAULT = false;
// TCPCL spec says max segment should be 2-3 times the Link MTU.
public static final int MAX_SEG_SIZE_DEFAULT = 4500;
public static final int MAX_SEG_SIZE_MIN = 32;
public static final int MAX_SEG_SIZE_MAX = 32 * 1024 * 1024;
public static final int TCPCL_PORT_DEFAULT = 4556;
public static final int TCPCL_PORT_MIN = 1000;
public static final int TCPCL_PORT_MAX = 65535;
/** IP Address of this Link */
private IPAddress _ipAddress;
/** Network Interface name this Link represents */
private String _ifName = null;
/** True => IPV6 version of the interface wanted; false => IPV4 version */
private boolean _ipv6 = IPV6_DEFAULT;
/** Max number of bytes in a TCPCL Data Segment */
private int _maxSegmentSize = MAX_SEG_SIZE_DEFAULT;
/** The TCP Port number upon which we will accept TcpCl connections */
private int _tcpPort = TCPCL_PORT_DEFAULT;
/** The system network interface of the Link */
protected NetworkInterface _networkInterface = null;
private boolean _connectionAcceptorStarted = false;
private Thread _connectionAcceptorThread = null;
private ServerSocket _serverSocket = null;
/**
* Constructor
* @param name Link Name
*/
public TcpClLink(String name) {
super(name);
}
/**
* Parse attributes of the < Link > element specific to TcpClLink.
* Advances the parse past the < /Link > tag.
* @param parser
* @param name
* @param linkType
* @return The TcpClLink created
* @throws JDtnException on TcpClLink specific errors
* @throws IOException on I/O errors
* @throws XMLStreamException on XML parsing errors
* @throws InterruptedException
*/
public static TcpClLink parseLink(
XmlRDParser parser,
String name,
Link.LinkType linkType)
throws JDtnException, XmlRdParserException, IOException, InterruptedException {
// Parse Attributes beyond those parsed by super
// ifName="ifname" - REQUIRED
String ifName = parser.getAttributeValue("ifName");
if (ifName == null || ifName.length() == 0) {
throw new JDtnException("Required attribute 'ifName' missing");
}
// ipv6="boolean" - Needed to createTcpClLink()
Boolean ipv6 = Utils.getBooleanAttribute(parser, "ipv6");
if (ipv6 == null) {
ipv6 = IPV6_DEFAULT;
}
// Create the Link
TcpClLink link = createTcpClLink(name, ifName, ipv6);
// Parse optional attributes
// maxSegmentSize='n'
Integer intVal = Utils.getIntegerAttribute(
parser,
"maxSegmentSize",
MAX_SEG_SIZE_MIN,
MAX_SEG_SIZE_MAX);
if (intVal != null) {
link.setMaxSegmentSize(intVal);
}
// tcpPort='n'
intVal = Utils.getIntegerAttribute(
parser,
"tcpPort",
TCPCL_PORT_MIN,
TCPCL_PORT_MAX);
if (intVal != null) {
link.setTcpPort(intVal);
}
// Parse </Link>
XmlRDParser.EventType event = Utils.nextNonTextEvent(parser);
if (event != XmlRDParser.EventType.END_ELEMENT ||
!parser.getElementTag().equals("Link")) {
throw new JDtnException("Missing /Link");
}
return link;
}
/*
* Output TcpClLink specific attributes to the configuration file
* @see com.cisco.qte.jdtn.general.Link#writeConfigImpl(java.io.PrintWriter)
*/
@Override
protected void writeConfigImpl(PrintWriter pw) {
pw.println(" ifName='" + getIfName() + "'");
pw.println(" ipv6='" + isIpv6() + "'");
if (getMaxSegmentSize() != MAX_SEG_SIZE_DEFAULT) {
pw.println(" maxSegmentSize='" + getMaxSegmentSize() + "'");
}
if (getTcpPort() != TCPCL_PORT_DEFAULT) {
pw.println(" tcpPort='" + getTcpPort() + "'");
}
}
/**
* Create a TcpClLink satisfying the given criteria
* @param linkName Locally-unique name desired for the Link
* @param ifName Network Interface Name
* @param wantIPV6 Whether want IPV6 (true) or IPV4 (false)
* @return Link created
* @throws JDtnException if cannot satisfy given criteria
*/
public static TcpClLink createTcpClLink(
String linkName,
String ifName,
boolean wantIPV6) throws JDtnException {
// Try to find an address for the TcpClLink
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface intfc = interfaces.nextElement();
if (intfc.getName().equals(ifName)) {
Enumeration<InetAddress> addresses = intfc.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress inetAddress = addresses.nextElement();
if (!inetAddress.isMulticastAddress()) {
if (wantIPV6 && (inetAddress instanceof Inet6Address)) {
// IPV6 Link
IPAddress ipAddress = new IPAddress(inetAddress);
TcpClLink link = new TcpClLink(linkName);
link.setIfName(ifName);
link.setIpAddress(ipAddress);
link.setNetworkInterface(intfc);
link.setIpv6(wantIPV6);
return link;
} else if (!wantIPV6 && (inetAddress instanceof Inet4Address)) {
// IPV4 Link
IPAddress ipAddress = new IPAddress(inetAddress);
TcpClLink link = new TcpClLink(linkName);
link.setIfName(ifName);
link.setIpAddress(ipAddress);
link.setNetworkInterface(intfc);
link.setIpv6(wantIPV6);
return link;
}
}
}
}
}
} catch (Exception e) {
_logger.log(Level.SEVERE, "Searching for InetAddress for UDPLink " + linkName, e);
}
throw new JDtnException(
"createTcpClLink(linkName=" + linkName +
", ifName=" + ifName +
", wantIPVF=" + wantIPV6 +
") failed to find matching NetworkInterface");
}
/**
* Dump this object
*/
@Override
public String dump(String indent, boolean detailed) {
StringBuilder sb = new StringBuilder(indent + "TcpClLink\n");
sb.append(super.dump(indent + " ", detailed));
sb.append(indent + " ifName=" + getIfName() + "\n");
sb.append(indent + " ipv6=" + isIpv6() + "\n");
sb.append(indent + " ipAddress=" + getIpAddress() + "\n");
sb.append(indent + " MaxSegmentSize= " + getMaxSegmentSize() + "\n");
sb.append(indent + " TcpPort=" + getTcpPort() + "\n");
return sb.toString();
}
/**
* Start the Connection Acceptor Thread for this Link. This is called from
* a TcpClNeighbor when it wants to accept connects. We have a 'use count'
* mechanism to handle multiple requests from TcpClNeighbors to start the
* Connection Acceptor Thread.
* @param port TCP Port Number
*/
private void startConnectionAcceptor() {
if (!_connectionAcceptorStarted) {
_connectionAcceptorThread = new Thread(new ConnectionAcceptor(this));
_connectionAcceptorThread.setName("Acceptor-" + getName());
_connectionAcceptorThread.start();
_connectionAcceptorStarted = true;
}
}
/**
* Stop the Connection Acceptor Thread for this link (taking use count into
* account).
* @throws InterruptedException If interrupted waiting for thread to die
*/
private void stopConnectionAcceptor() throws InterruptedException {
if (_connectionAcceptorStarted) {
_connectionAcceptorThread.interrupt();
_connectionAcceptorThread.join(200L);
// Note: apparently you cannot interrupt a Thread that's blocked
// on a ServerSocket.accept(). The interrupt has not effect.
// So we have to use a larger hammer consisting of closing the
// ServerSocket out from under the thread. Also, since the the
// accept won't be interrupted, we use a relatively short timeout
// on the join(), since it will probably time out anyway.
if (_connectionAcceptorThread.isAlive()) {
if (_serverSocket != null) {
try {
_serverSocket.close();
} catch (IOException e) {
_logger.log(Level.SEVERE, "close ServerSocket", e);
}
}
}
_connectionAcceptorStarted = false;
}
}
/**
* Thread which accepts incoming TCP connections
*/
public class ConnectionAcceptor implements Runnable {
private TcpClLink _link = null;
public ConnectionAcceptor(TcpClLink link) {
_link = link;
}
public void run() {
_serverSocket = null;
try {
while (!Thread.interrupted()) {
InetAddress inetAddress = getIpAddress().getInetAddress();
if (_serverSocket == null) {
openServerSocket(inetAddress);
}
if (_serverSocket != null) {
acceptSocketConnection();
}
}
} catch (InterruptedException e) {
if (GeneralManagement.isDebugLogging()) {
_logger.fine("Acceptor Thread interrupted");
}
} finally {
if (_serverSocket != null) {
try {
_serverSocket.close();
} catch (IOException e) {
// Nothing
}
_serverSocket = null;
}
}
}
/**
* Open the ServerSocket so we can accept connections. Called from
* ConnectionAccepter Thread. Sets member _serverSocket.
* @param inetAddress Local IP Address of this Link
* @throws InterruptedException if interrupted during process
*/
private void openServerSocket(InetAddress inetAddress)
throws InterruptedException {
// Repeat until we've successfully opened the Server Socket
while (_serverSocket == null) {
if (Thread.interrupted()) {
return;
}
try {
// Open the Server Socket
_serverSocket = new ServerSocket(_tcpPort, 1, inetAddress);
_serverSocket.setReuseAddress(true);
} catch (SocketException e) {
if (e.getMessage().contains("Address already in use")) {
// This is most likely a temporary condition caused
// by a previous run. It will go away after a few
// seconds.
_logger.warning("Address in use, will delay and try again later");
Thread.sleep(4000L);
continue;
}
_logger.log(Level.SEVERE, "Trying to open Server Socket; will try again later: ", e);
Thread.sleep(4000L);
continue;
} catch (IOException e) {
_logger.log(Level.SEVERE, "Trying to open Server Socket; will try again later: ", e);
Thread.sleep(4000L);
continue;
}
}
}
/**
* Accept a connection on the ServerSocket and notify the associated
* Neighbor to start its state machine to bring up the connection and
* start receiving Bundles. Uses member _serverSocket.
* @throws InterruptedException if interrupted during process
*/
private void acceptSocketConnection() throws InterruptedException {
Socket socket = null;
TcpClNeighbor tcpClNeighbor = null;
// Accept a TCP connection
try {
socket = _serverSocket.accept();
} catch (IOException e) {
if (e instanceof SocketException) {
if (e.getMessage().equals("Socket closed")) {
if (GeneralManagement.isDebugLogging()) {
_logger.fine("Socket closed out from under me; bailing");
}
} else if (e.getMessage().equals("Interrupted system call")) {
if (GeneralManagement.isDebugLogging()) {
_logger.fine("Socket accept interrupted; bailing");
}
} else {
_logger.log(Level.SEVERE, "ServerSocket.accept(); will try again later", e);
}
} else {
_logger.log(Level.SEVERE, "ServerSocket.accept(); will try again later", e);
}
try {
_serverSocket.close();
} catch (IOException e1) {
// Nothing
}
_serverSocket = null;
Thread.sleep(4000L);
return;
}
InetAddress remoteAddress = socket.getInetAddress();
IPAddress ipAddress = new IPAddress(remoteAddress);
Neighbor neighbor = NeighborsList.getInstance()
.findNeighborByAddress(ipAddress);
if (neighbor == null) {
// Got a Connection from unknown Neighbor; check policy
// for what to do
if (TcpClManagement.getInstance().isAcceptUnconfiguredNeighbors()) {
// Create a temporary Neighbor. This is most likely
// a "Router Hello" message coming in. The connection
// will be completed, the Router Hello will be processed
// and will result in deletion of the temporary Neighbor.
try {
EndPointId eid = EndPointId.createEndPointId("dtn://" + ipAddress);
tcpClNeighbor = TcpClManagement.getInstance().addNeighbor("Temporary-Neighbor-" + UUID.randomUUID().toString(), eid);
LinkAddress linkAddress = new LinkAddress(_link, ipAddress);
tcpClNeighbor.addLinkAddress(linkAddress);
tcpClNeighbor.setTemporary(true);
neighbor = tcpClNeighbor;
} catch (BPException e) {
_logger.log(Level.SEVERE, "Adding New Neighbor", e);
try {
socket.close();
} catch (IOException e1) {
// Nothing
}
return;
} catch (JDtnException e) {
_logger.log(Level.SEVERE, "Adding New Neighbor", e);
try {
socket.close();
} catch (IOException e1) {
// Nothing
}
return;
}
} else {
// Policy says don't accept the Connection
_logger.severe("Connection from unknown Neighbor " +
ipAddress + ": connection ignored");
try {
socket.close();
} catch (IOException e) {
// Nothing
}
Thread.sleep(4000L);
return;
}
}
if (!(neighbor instanceof TcpClNeighbor)) {
_logger.severe("Neighbor not TcpClNeighbor: "
+ ipAddress);
try {
socket.close();
} catch (IOException e) {
// Nothing
}
return;
}
// Notify the Neighbor that the connection has been accepted,
// starting up its state machine to bring up the connection
// and accepting Bundles.
tcpClNeighbor = (TcpClNeighbor) neighbor;
try {
tcpClNeighbor.notifyConnectionAccepted(socket);
} catch (JDtnException e) {
_logger.log(Level.SEVERE, "notifyConnectionAccepted", e);
try {
socket.close();
} catch (IOException e1) {
// Nothing
}
return;
} catch (IOException e) {
_logger.log(Level.SEVERE, "notifyConnectionAccepted", e);
try {
socket.close();
} catch (IOException e1) {
// Nothing
}
return;
}
}
}
/**
* Called on Management Start Event
* @see com.cisco.qte.jdtn.general.Link#linkStartImpl()
*/
@Override
protected void linkStartImpl() throws Exception {
startConnectionAcceptor();
}
/**
* Called on Management Stop Event
* @see com.cisco.qte.jdtn.general.Link#linkStopImpl()
*/
@Override
protected void linkStopImpl() throws InterruptedException {
stopConnectionAcceptor();
}
/**
* Called when Link is removed.
* @see com.cisco.qte.jdtn.general.Link#linkRemovedImpl()
*/
@Override
protected void linkRemovedImpl() {
try {
stopConnectionAcceptor();
} catch (InterruptedException e) {
// Nothing
}
}
/**
* Get the convergence layer type of Link.
* @see com.cisco.qte.jdtn.general.Link#getLinkTypeImpl()
*/
@Override
protected LinkType getLinkTypeImpl() {
return Link.LinkType.LINK_TYPE_TCPCL;
}
/** Network Interface name this Link represents */
public String getIfName() {
return _ifName;
}
/** Network Interface name this Link represents */
public void setIfName(String ifName) {
this._ifName = new String(ifName);
}
/** True => IPV6 version of the interface wanted; false => IPV4 version */
public boolean isIpv6() {
return _ipv6;
}
/** True => IPV6 version of the interface wanted; false => IPV4 version */
public void setIpv6(boolean ipv6) {
this._ipv6 = ipv6;
}
/** Max number of bytes in a TCPCL Data Segment */
public int getMaxSegmentSize() {
return _maxSegmentSize;
}
/** Max number of bytes in a TCPCL Data Segment */
public void setMaxSegmentSize(int maxSegmentSize) throws IllegalArgumentException {
if (maxSegmentSize < MAX_SEG_SIZE_MIN ||
maxSegmentSize > MAX_SEG_SIZE_MAX) {
throw new IllegalArgumentException(
"MaxSegmentSize must be in the range [" +
MAX_SEG_SIZE_MIN + ", " + MAX_SEG_SIZE_MAX + "]");
}
this._maxSegmentSize = maxSegmentSize;
}
/** IP Address of this Link */
public IPAddress getIpAddress() {
return _ipAddress;
}
/** IP Address of this Link */
public void setIpAddress(IPAddress ipAddress) {
this._ipAddress = ipAddress;
}
/** The system network interface of the Link */
public NetworkInterface getNetworkInterface() {
return _networkInterface;
}
/** The system network interface of the Link */
public void setNetworkInterface(NetworkInterface networkInterface) {
_networkInterface = networkInterface;
}
/** The TCP Port number upon which we will accept TcpCl connections */
public int getTcpPort() {
return _tcpPort;
}
/** The TCP Port number upon which we will accept TcpCl connections */
public void setTcpPort(int tcpPort) throws InterruptedException {
boolean previouslyStarted = _connectionAcceptorThread != null;
if (previouslyStarted) {
stopConnectionAcceptor();
}
this._tcpPort = tcpPort;
if (previouslyStarted) {
startConnectionAcceptor();
}
}
}
| |
package org.nodes.draw;
import static java.lang.Math.abs;
import static java.lang.Math.floor;
import static nl.peterbloem.kit.Series.series;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.nodes.DGraph;
import org.nodes.DLink;
import org.nodes.DegreeIndexComparator;
import org.nodes.Graph;
import org.nodes.Link;
import org.nodes.Node;
import org.nodes.util.BufferedImageTranscoder;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.gvt.GraphicsNode;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;
import nl.peterbloem.kit.Series;
public class Draw
{
private static final String ns = SVGDOMImplementation.SVG_NAMESPACE_URI;
public static <L> BufferedImage draw(Graph<L> graph, int width)
{
return draw(graph, new CircleLayout<L>(graph), width);
}
public static <L> BufferedImage draw(Graph<L> graph, Layout<L> layout, int width)
{
SVGDocument svg = svg(graph, layout);
return draw(svg, width);
}
public static <L> BufferedImage draw(SVGDocument svg, int width)
{
BufferedImageTranscoder t = new BufferedImageTranscoder();
t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) width);
// t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) height);
// t.addTranscodingHint(PNGTranscoder.KEY_, (float) width);
TranscoderInput input = new TranscoderInput(svg);
try
{
t.transcode(input, null);
} catch (TranscoderException e)
{
throw new RuntimeException(e);
}
return t.getBufferedImage();
}
public static <L> Document svg(Graph<L> graph)
{
return svg(graph, new CircleLayout<L>(graph));
}
public static <L> void write(Document svg, File file)
throws IOException
{
try
{
// Use a Transformer for output
TransformerFactory tFactory =
TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(svg);
StreamResult result = new StreamResult(new FileOutputStream(file));
transformer.transform(source, result);
} catch (TransformerException e)
{
throw new RuntimeException(e);
}
}
public static <L> SVGDocument svg(Graph<L> graph, Layout<L> layout)
{
// * Set up an SVG generator
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
SVGDocument doc = (SVGDocument) impl.createDocument(ns, "svg", null);
Element canvas = doc.getDocumentElement();
canvas.setAttributeNS(null, "width", "2.0");
canvas.setAttributeNS(null, "height", "2.0");
Element g = doc.createElementNS(ns, "g");
g.setAttributeNS(null, "transform", "translate(1,1)");
canvas.appendChild(g);
// * Draw the edges
for(Link<L> link : graph.links())
{
Point a = layout.point(link.first()),
b = layout.point(link.second());
Element line = doc.createElementNS(ns, "line");
line.setAttributeNS(null, "x1", "" + a.get(0));
line.setAttributeNS(null, "y1", "" + a.get(1));
line.setAttributeNS(null, "x2", "" + b.get(0));
line.setAttributeNS(null, "y2", "" + b.get(1));
line.setAttributeNS(null, "stroke", "black");
line.setAttributeNS(null, "stroke-opacity", "0.1");
line.setAttributeNS(null, "stroke-width", "0.005");
g.appendChild(line);
}
// * Draw the nodes
for(Node<L> node : graph.nodes())
{
Point p = layout.point(node);
Element circle = doc.createElementNS(ns, "circle");
circle.setAttributeNS(null, "cx", "" + p.get(0));
circle.setAttributeNS(null, "cy", "" + p.get(1));
circle.setAttributeNS(null, "r", "0.01");
circle.setAttributeNS(null, "fill", "red");
g.appendChild(circle);
}
return doc;
}
public static <L> void show(Graph<L> graph)
{
}
/**
* Draws a density plot of the adjacency matrix
*
* @param graph
* @param layout
* @param width
* @param height
* @return
*/
public static <L> BufferedImage matrix(
Graph<L> graph, int width, int height)
{
return matrix(graph, width, height, null);
}
public static <L> BufferedImage matrix(
Graph<L> graph, int width, int height, List<Integer> order)
{
boolean log = true;
boolean directed = graph instanceof DGraph<?>;
float max = Float.NEGATIVE_INFINITY;
float[][] matrix = new float[width][];
for(int x = 0; x < width; x++)
{
matrix[x] = new float[height];
for(int y = 0; y < height; y++)
matrix[x][y] = 0.0f;
}
int xp, yp;
for(Link<L> link : graph.links())
{
int i = link.first().index(), j = link.second().index();
int ii = order == null ? i : order.get(i);
int jj = order == null ? j : order.get(j);
xp = toPixel(ii, width, 0, graph.size());
yp = toPixel(jj, height, 0, graph.size());
if(xp >= 0 && xp < width && yp >= 0 && yp < height)
{
matrix[xp][yp] ++;
max = Math.max(matrix[xp][yp], max);
}
if(! directed)
{
// * Swap
int t = ii;
ii = jj;
jj = t;
xp = toPixel(ii, width, 0, graph.size());
yp = toPixel(jj, height, 0, graph.size());
if(xp >= 0 && xp < width && yp >= 0 && yp < height)
{
matrix[xp][yp] ++;
max = Math.max(matrix[xp][yp], max);
}
}
}
BufferedImage image =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Color color;
if(log)
max = (float)Math.log(max + 1.0f);
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
{
//float value = matrix[x][yRes - y - 1];
float value = matrix[x][y];
if(log)
value = (float)Math.log(value + 1.0f);
float gray = value / max;
if(gray < 0.0)
color = Color.BLUE;
else if(gray > 1.0)
color = Color.RED;
else
color = new Color(gray, gray, gray, 1.0f);
image.setRGB(x, y, color.getRGB());
}
return image;
}
/**
* REMINDER:
*
* - The order has order.get(indexInOriginalGraph) = indexInOrderedGraph
* - The inverseOrder has inverseOrder.get(indexInOrderedGraph) = indexInOriginalGraph
*
* in the order the elements represent the indices of the ordered graph
* in the inverseOrder the elements represent the indices of the original graph
*
* @param graph
* @return
*/
public static <L> List<Integer> degreeOrdering(Graph<L> graph)
{
List<Integer> inv = new ArrayList<Integer>(Series.series(graph.size()));
Comparator<Integer> comp =
Collections.reverseOrder(new DegreeIndexComparator(graph));
Collections.sort(inv, comp);
return inverse(inv);
}
public static List<Integer> inverse(List<Integer> order)
{
List<Integer> inv = new ArrayList<Integer>(order.size());
for(int i : series(order.size()))
inv.add(null);
for(int index : series(order.size()))
inv.set(order.get(index), index);
return inv;
}
/**
* Converts a double value to its index in a given range when that range
* is discretized to a given number of bins. Useful for finding pixel values
* when creating images.
*
* @param coord
* @param res
* @param rangeStart
* @param rangeEnd
* @return The pixel index. Can be out of range (negative of too large).
*/
public static int toPixel(double coord, int res, double rangeStart, double rangeEnd)
{
double pixSize = abs(rangeStart - rangeEnd) / (double) res;
return (int)floor((coord - rangeStart)/pixSize);
}
/**
*
* @param pixel
* @param res
* @param rangeStart
* @param rangeEnd
* @return
*/
public static double toCoord(int pixel, int res, double rangeStart, double rangeEnd){
double pixSize = abs(rangeStart - rangeEnd) / (double) res;
return pixSize * ((double) pixel) + pixSize * 0.5 + rangeStart;
}
}
| |
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.instrument.payment;
import java.util.Arrays;
import org.apache.commons.lang.ObjectUtils;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinitionVisitor;
import com.opengamma.analytics.financial.instrument.InstrumentDefinitionWithData;
import com.opengamma.analytics.financial.instrument.annuity.DateRelativeTo;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.interestrate.payments.derivative.Coupon;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponFixed;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIborCompoundingFlatSpread;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIborCompoundingSpread;
import com.opengamma.analytics.financial.interestrate.payments.derivative.Payment;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.financial.convention.StubType;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.rolldate.RollDateAdjuster;
import com.opengamma.timeseries.DoubleTimeSeries;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
/**
* Class describing a Ibor-like coupon with compounding and spread. There are three ISDA versions of compounding with spread. The one referred in this class is
* the "Flat Compounding" (not "Compounding" and not "Compounding treating spread as simple interest"). The Ibor fixing are compounded over several sub-periods.
* The amount paid is described in the reference below. The fixing have their own start dates, end dates and accrual factors. In general they are close to the
* accrual dates used to compute the coupon accrual factors.
* <p>
* Reference: Mengle, D. (2009). Alternative compounding methods for over-the-counter derivative transactions. ISDA.
*/
public class CouponIborCompoundingFlatSpreadDefinition extends CouponDefinition
implements InstrumentDefinitionWithData<Payment, DoubleTimeSeries<ZonedDateTime>> {
/**
* The Ibor-like index on which the coupon fixes. The index currency should be the same as the coupon currency. All the coupon sub-periods fix on the same
* index.
*/
private final IborIndex _index;
/**
* The start dates of the accrual sub-periods.
*/
private final ZonedDateTime[] _subperiodAccrualStartDates;
/**
* The end dates of the accrual sub-periods.
*/
private final ZonedDateTime[] _subperiodAccrualEndDates;
/**
* The accrual factors (or year fraction) associated to the sub-periods.
*/
private final double[] _subperiodAccrualFactors;
/**
* The coupon fixing dates.
*/
private final ZonedDateTime[] _fixingDates;
/**
* The start dates of the fixing periods.
*/
private final ZonedDateTime[] _fixingSubperiodStartDates;
/**
* The end dates of the fixing periods.
*/
private final ZonedDateTime[] _fixingSuberiodEndDates;
/**
* The accrual factors (or year fraction) associated with the fixing periods in the Index day count convention.
*/
private final double[] _fixingSubperiodAccrualFactors;
/**
* The spread paid above the Ibor rate.
*/
private final double _spread;
/**
* The rate of the first compounded rate. This is an optional field.
*/
private final double _initialRate;
/**
* Constructor.
*
* @param currency
* The coupon currency.
* @param paymentDate
* The coupon payment date.
* @param accrualStartDate
* The start date of the accrual period.
* @param accrualEndDate
* The end date of the accrual period.
* @param paymentAccrualFactor
* The accrual factor of the accrual period.
* @param notional
* The coupon notional.
* @param index
* The Ibor-like index on which the coupon fixes. The index currency should be the same as the coupon currency.
* @param accrualStartDates
* The start dates of the accrual sub-periods.
* @param accrualEndDates
* The end dates of the accrual sub-periods.
* @param paymentAccrualFactors
* The accrual factors (or year fraction) associated to the sub-periods.
* @param fixingDates
* The coupon fixing dates.
* @param fixingPeriodStartDates
* The start dates of the fixing periods.
* @param fixingPeriodEndDates
* The end dates of the fixing periods.
* @param fixingPeriodAccrualFactors
* The accrual factors (or year fraction) associated with the fixing periods in the Index day count convention.
* @param spread
* The spread paid above the Ibor rate.
* @param initialRate
* The rate of the first compound period.
*/
protected CouponIborCompoundingFlatSpreadDefinition(
final Currency currency,
final ZonedDateTime paymentDate,
final ZonedDateTime accrualStartDate,
final ZonedDateTime accrualEndDate,
final double paymentAccrualFactor,
final double notional,
final IborIndex index,
final ZonedDateTime[] accrualStartDates,
final ZonedDateTime[] accrualEndDates,
final double[] paymentAccrualFactors,
final ZonedDateTime[] fixingDates,
final ZonedDateTime[] fixingPeriodStartDates,
final ZonedDateTime[] fixingPeriodEndDates,
final double[] fixingPeriodAccrualFactors,
final double spread,
final double initialRate) {
super(currency, paymentDate, accrualStartDate, accrualEndDate, paymentAccrualFactor, notional);
ArgumentChecker.isTrue(accrualStartDates.length == accrualEndDates.length, "Accrual start and end dates should have same length");
ArgumentChecker.isTrue(accrualStartDates.length == fixingDates.length, "Same length");
ArgumentChecker.isTrue(accrualStartDates.length == fixingPeriodStartDates.length, "Same length");
ArgumentChecker.isTrue(accrualStartDates.length == fixingPeriodEndDates.length, "Same length");
ArgumentChecker.isTrue(accrualStartDates.length == fixingPeriodAccrualFactors.length, "Same length");
_index = index;
_subperiodAccrualStartDates = accrualStartDates;
_subperiodAccrualEndDates = accrualEndDates;
_subperiodAccrualFactors = paymentAccrualFactors;
_fixingDates = fixingDates;
_fixingSubperiodStartDates = fixingPeriodStartDates;
_fixingSuberiodEndDates = fixingPeriodEndDates;
_fixingSubperiodAccrualFactors = fixingPeriodAccrualFactors;
_spread = spread;
_initialRate = initialRate;
}
/**
* Builds a Ibor compounded coupon with a spread using the "Flat compounded" to calculate each compounded period rate.
*
* @param currency
* The coupon currency.
* @param paymentDate
* The coupon payment date.
* @param accrualStartDate
* The start date of the accrual period.
* @param accrualEndDate
* The end date of the accrual period.
* @param paymentAccrualFactor
* The accrual factor of the accrual period.
* @param notional
* The coupon notional.
* @param index
* The Ibor-like index on which the coupon fixes. The index currency should be the same as the coupon currency.
* @param accrualStartDates
* The start dates of the accrual sub-periods.
* @param accrualEndDates
* The end dates of the accrual sub-periods.
* @param paymentAccrualFactors
* The accrual factors (or year fraction) associated to the sub-periods.
* @param fixingDates
* The coupon fixing dates.
* @param fixingPeriodStartDates
* The start dates of the fixing periods.
* @param fixingPeriodEndDates
* The end dates of the fixing periods.
* @param fixingPeriodAccrualFactors
* The accrual factors (or year fraction) associated with the fixing periods in the Index day count convention.
* @param spread
* The spread paid above the Ibor rate.
* @param initialRate
* The rate of the first compounded period.
* @return The compounded coupon.
*/
public static CouponIborCompoundingFlatSpreadDefinition from(
final Currency currency,
final ZonedDateTime paymentDate,
final ZonedDateTime accrualStartDate,
final ZonedDateTime accrualEndDate,
final double paymentAccrualFactor,
final double notional,
final IborIndex index,
final ZonedDateTime[] accrualStartDates,
final ZonedDateTime[] accrualEndDates,
final double[] paymentAccrualFactors,
final ZonedDateTime[] fixingDates,
final ZonedDateTime[] fixingPeriodStartDates,
final ZonedDateTime[] fixingPeriodEndDates,
final double[] fixingPeriodAccrualFactors,
final double spread,
final double initialRate) {
return new CouponIborCompoundingFlatSpreadDefinition(
currency,
paymentDate,
accrualStartDate,
accrualEndDate,
paymentAccrualFactor,
notional,
index,
accrualStartDates,
accrualEndDates,
paymentAccrualFactors,
fixingDates,
fixingPeriodStartDates,
fixingPeriodEndDates,
fixingPeriodAccrualFactors,
spread,
initialRate);
}
/**
* Builds an Ibor compounded coupon from the accrual and payment details. The fixing dates and fixing accrual periods are computed from those dates using the
* index conventions.
*
* @param paymentDate
* The coupon payment date.
* @param notional
* The coupon notional.
* @param index
* The Ibor-like index on which the coupon fixes. The index currency should be the same as the coupon currency.
* @param accrualStartDates
* The start dates of the accrual sub-periods.
* @param accrualEndDates
* The end dates of the accrual sub-periods.
* @param paymentAccrualFactors
* The accrual factors (or year fraction) associated to the sub-periods.
* @param spread
* The spread paid above the Ibor rate.
* @param calendar
* The holiday calendar for the ibor index.
* @return The compounded coupon.
*/
public static CouponIborCompoundingFlatSpreadDefinition from(final ZonedDateTime paymentDate, final double notional, final IborIndex index,
final ZonedDateTime[] accrualStartDates, final ZonedDateTime[] accrualEndDates, final double[] paymentAccrualFactors, final double spread,
final Calendar calendar) {
final int nbSubPeriod = accrualEndDates.length;
final ZonedDateTime accrualStartDate = accrualStartDates[0];
final ZonedDateTime accrualEndDate = accrualEndDates[nbSubPeriod - 1];
double paymentAccrualFactor = 0.0;
final ZonedDateTime[] fixingDates = new ZonedDateTime[nbSubPeriod];
final ZonedDateTime[] fixingPeriodEndDates = new ZonedDateTime[nbSubPeriod];
final double[] fixingPeriodAccrualFactors = new double[nbSubPeriod];
for (int loopsub = 0; loopsub < nbSubPeriod; loopsub++) {
paymentAccrualFactor += paymentAccrualFactors[loopsub];
fixingDates[loopsub] = ScheduleCalculator.getAdjustedDate(accrualStartDates[loopsub], -index.getSpotLag(), calendar);
fixingPeriodEndDates[loopsub] = ScheduleCalculator.getAdjustedDate(accrualStartDates[loopsub], index, calendar);
fixingPeriodAccrualFactors[loopsub] = index.getDayCount().getDayCountFraction(accrualStartDates[loopsub], fixingPeriodEndDates[loopsub], calendar);
}
return new CouponIborCompoundingFlatSpreadDefinition(
index.getCurrency(),
paymentDate,
accrualStartDate,
accrualEndDate,
paymentAccrualFactor,
notional,
index,
accrualStartDates,
accrualEndDates,
paymentAccrualFactors,
fixingDates,
accrualStartDates,
fixingPeriodEndDates,
fixingPeriodAccrualFactors,
spread,
Double.NaN);
}
/**
* Builds an Ibor compounded coupon from a total period and the Ibor index. The Ibor day count is used to compute the accrual factors. If required the stub of
* the sub-periods will be short and last. The payment date is the adjusted end accrual date. The payment accrual factors are in the day count of the index.
*
* @param notional
* The coupon notional.
* @param accrualStartDate
* The first accrual date.
* @param accrualEndDate
* The end accrual date.
* @param index
* The underlying Ibor index.
* @param spread
* The spread paid above the Ibor rate.
* @param stub
* The stub type used for the compounding sub-periods. Not null.
* @param businessDayConvention
* The leg business day convention.
* @param endOfMonth
* The leg end-of-month convention.
* @param calendar
* The holiday calendar for the ibor leg.
* @return The compounded coupon.
*/
public static CouponIborCompoundingFlatSpreadDefinition from(final double notional, final ZonedDateTime accrualStartDate, final ZonedDateTime accrualEndDate,
final IborIndex index,
final double spread, final StubType stub, final BusinessDayConvention businessDayConvention, final boolean endOfMonth, final Calendar calendar) {
ArgumentChecker.notNull(accrualStartDate, "Accrual start date");
ArgumentChecker.notNull(accrualEndDate, "Accrual end date");
ArgumentChecker.notNull(index, "Index");
ArgumentChecker.notNull(stub, "Stub type");
ArgumentChecker.notNull(calendar, "Calendar");
final boolean isStubShort = stub.equals(StubType.SHORT_END) || stub.equals(StubType.SHORT_START);
final boolean isStubStart = stub.equals(StubType.LONG_START) || stub.equals(StubType.SHORT_START); // Implementation note: dates computed from the end.
final ZonedDateTime[] accrualEndDates = ScheduleCalculator.getAdjustedDateSchedule(accrualStartDate, accrualEndDate, index.getTenor(), isStubShort,
isStubStart,
businessDayConvention, calendar, endOfMonth);
final int nbSubPeriod = accrualEndDates.length;
final ZonedDateTime[] accrualStartDates = new ZonedDateTime[nbSubPeriod];
accrualStartDates[0] = accrualStartDate;
System.arraycopy(accrualEndDates, 0, accrualStartDates, 1, nbSubPeriod - 1);
final double[] paymentAccrualFactors = new double[nbSubPeriod];
for (int loopsub = 0; loopsub < nbSubPeriod; loopsub++) {
paymentAccrualFactors[loopsub] = index.getDayCount().getDayCountFraction(accrualStartDates[loopsub], accrualEndDates[loopsub], calendar);
}
return from(accrualEndDates[nbSubPeriod - 1], notional, index, accrualStartDates, accrualEndDates, paymentAccrualFactors, spread, calendar);
}
/**
* Builds an Ibor compounded coupon from a total period and the Ibor index. The Ibor day count is used to compute the accrual factors. If required the stub of
* the sub-periods will be short and last. The payment date is the adjusted end accrual date. The payment accrual factors are in the day count of the index.
*
* @param notional
* The coupon notional.
* @param accrualStartDate
* The first accrual date.
* @param accrualEndDate
* The end accrual date.
* @param index
* The underlying Ibor index.
* @param spread
* The spread paid above the Ibor rate.
* @param stub
* The stub type used for the compounding sub-periods. Not null.
* @param businessDayConvention
* The leg business day convention.
* @param endOfMonth
* The leg end-of-month convention.
* @param calendar
* The holiday calendar for the ibor leg.
* @param adjuster
* the rollr date adjuster, null for no adjustment.
* @return The compounded coupon.
*/
public static CouponIborCompoundingFlatSpreadDefinition from(final double notional, final ZonedDateTime accrualStartDate, final ZonedDateTime accrualEndDate,
final IborIndex index,
final double spread, final StubType stub, final BusinessDayConvention businessDayConvention, final boolean endOfMonth, final Calendar calendar,
final RollDateAdjuster adjuster) {
ArgumentChecker.notNull(accrualStartDate, "Accrual start date");
ArgumentChecker.notNull(accrualEndDate, "Accrual end date");
ArgumentChecker.notNull(index, "Index");
ArgumentChecker.notNull(stub, "Stub type");
ArgumentChecker.notNull(calendar, "Calendar");
final boolean isStubShort = stub.equals(StubType.SHORT_END) || stub.equals(StubType.SHORT_START);
final boolean isStubStart = stub.equals(StubType.LONG_START) || stub.equals(StubType.SHORT_START); // Implementation note: dates computed from the end.
final ZonedDateTime[] accrualEndDates = ScheduleCalculator.getAdjustedDateSchedule(accrualStartDate, accrualEndDate, index.getTenor(), isStubShort,
isStubStart,
businessDayConvention, calendar, endOfMonth, adjuster);
final int nbSubPeriod = accrualEndDates.length;
final ZonedDateTime[] accrualStartDates = new ZonedDateTime[nbSubPeriod];
accrualStartDates[0] = accrualStartDate;
System.arraycopy(accrualEndDates, 0, accrualStartDates, 1, nbSubPeriod - 1);
final double[] paymentAccrualFactors = new double[nbSubPeriod];
for (int loopsub = 0; loopsub < nbSubPeriod; loopsub++) {
paymentAccrualFactors[loopsub] = index.getDayCount().getDayCountFraction(accrualStartDates[loopsub], accrualEndDates[loopsub], calendar);
}
return from(accrualEndDates[nbSubPeriod - 1], notional, index, accrualStartDates, accrualEndDates, paymentAccrualFactors, spread, calendar);
}
public static CouponIborCompoundingFlatSpreadDefinition from(
final double notional,
final ZonedDateTime accrualStartDate, final ZonedDateTime accrualEndDate,
final IborIndex index, final double spread, final StubType stubType,
final Calendar accrualCalendar,
final BusinessDayConvention accrualBusinessDayConvention,
final Calendar fixingCalendar,
final BusinessDayConvention fixingBusinessDayConvention,
final Calendar resetCalendar,
final DateRelativeTo resetRelativeTo,
final DateRelativeTo paymentRelativeTo,
final RollDateAdjuster rollDateAdjuster) {
final boolean isEOM = true;
final ZonedDateTime paymentDate = DateRelativeTo.START == paymentRelativeTo ? accrualStartDate : accrualEndDate;
final double paymentAccrualFactor = index.getDayCount().getDayCountFraction(accrualStartDate, paymentDate, accrualCalendar);
final ZonedDateTime[] accrualEndDates = ScheduleCalculator.getAdjustedDateSchedule(
accrualStartDate,
accrualEndDate,
index.getTenor(),
stubType,
accrualBusinessDayConvention,
accrualCalendar,
isEOM,
rollDateAdjuster);
final ZonedDateTime[] accrualStartDates = new ZonedDateTime[accrualEndDates.length];
accrualStartDates[0] = accrualStartDate;
System.arraycopy(accrualEndDates, 0, accrualStartDates, 1, accrualEndDates.length - 1);
final double[] paymentAccrualFactors = new double[accrualEndDates.length];
for (int i = 0; i < paymentAccrualFactors.length; i++) {
paymentAccrualFactors[i] = index.getDayCount().getDayCountFraction(accrualStartDates[i], accrualEndDates[i], accrualCalendar);
}
final ZonedDateTime[] fixingStartDates = accrualStartDates;
final ZonedDateTime[] fixingEndDates = ScheduleCalculator.getAdjustedDateSchedule(
fixingStartDates,
index.getTenor(),
fixingBusinessDayConvention,
fixingCalendar,
null);
// ZonedDateTime[] fixingEndDates = ScheduleCalculator.getAdjustedDateSchedule(
// accrualStartDate,
// accrualEndDate,
// index.getTenor(),
// stubType,
// fixingBusinessDayConvention,
// fixingCalendar,
// isEOM,
// rollDateAdjuster);
// ZonedDateTime[] fixingStartDates = new ZonedDateTime[fixingEndDates.length];
// fixingStartDates[0] = accrualStartDate;
// System.arraycopy(fixingEndDates, 0, fixingStartDates, 1, fixingEndDates.length - 1);
final ZonedDateTime[] resetDates = ScheduleCalculator.getAdjustedDate(
DateRelativeTo.START == resetRelativeTo ? accrualStartDates : accrualEndDates, -index.getSpotLag(), resetCalendar);
final double[] fixingAccrualFactors = new double[accrualEndDates.length];
for (int i = 0; i < fixingAccrualFactors.length; i++) {
fixingAccrualFactors[i] = index.getDayCount().getDayCountFraction(fixingStartDates[i], fixingEndDates[i], fixingCalendar);
}
return new CouponIborCompoundingFlatSpreadDefinition(
index.getCurrency(),
paymentDate,
accrualStartDate,
accrualEndDate,
paymentAccrualFactor,
notional,
index,
accrualStartDates,
accrualEndDates,
paymentAccrualFactors,
resetDates,
fixingStartDates,
fixingEndDates,
fixingAccrualFactors,
spread,
Double.NaN);
}
/**
* Returns the Ibor index underlying the coupon.
*
* @return The index.
*/
public IborIndex getIndex() {
return _index;
}
/**
* Returns the accrual start dates of each sub-period.
*
* @return The dates.
*/
public ZonedDateTime[] getSubperiodsAccrualStartDates() {
return _subperiodAccrualStartDates;
}
/**
* Returns the accrual end dates of each sub-period.
*
* @return The dates.
*/
public ZonedDateTime[] getSubperiodsAccrualEndDates() {
return _subperiodAccrualEndDates;
}
/**
* Returns the payment accrual factors for each sub-period.
*
* @return The factors.
*/
public double[] getSubperiodsAccrualFactors() {
return _subperiodAccrualFactors;
}
/**
* Returns the fixing dates for each sub-period.
*
* @return The dates.
*/
public ZonedDateTime[] getFixingDates() {
return _fixingDates;
}
/**
* Returns the fixing period start dates for each sub-period.
*
* @return The dates.
*/
public ZonedDateTime[] getFixingSubperiodStartDates() {
return _fixingSubperiodStartDates;
}
/**
* Returns the fixing period end dates for each sub-period.
*
* @return The dates.
*/
public ZonedDateTime[] getFixingSubperiodEndDates() {
return _fixingSuberiodEndDates;
}
/**
* Returns the fixing period accrual factors for each sub-period.
*
* @return The factors.
*/
public double[] getFixingSubperiodAccrualFactors() {
return _fixingSubperiodAccrualFactors;
}
/**
* Returns the spread.
*
* @return the spread
*/
public double getSpread() {
return _spread;
}
/**
* Returns the rate of the first compounded period.
*
* @return the rate of the first compounded period.
*/
public double getInitialRate() {
return _initialRate;
}
/**
* {@inheritDoc}
*
* @deprecated Use the method that does not take yield curve names
*/
@Deprecated
@Override
public Coupon toDerivative(final ZonedDateTime dateTime, final DoubleTimeSeries<ZonedDateTime> indexFixingTimeSeries, final String... yieldCurveNames) {
throw new UnsupportedOperationException(
"CouponIborCompoundingFlatSpreadDefinition does not support toDerivative with yield curve name - deprecated method");
}
/**
* {@inheritDoc}
*
* @deprecated Use the method that does not take yield curve names
*/
@Deprecated
@Override
public CouponIborCompoundingSpread toDerivative(final ZonedDateTime dateTime, final String... yieldCurveNames) {
throw new UnsupportedOperationException(
"CouponIborCompoundingFlatSpreadDefinition does not support toDerivative with yield curve name - deprecated method");
}
@Override
public CouponIborCompoundingFlatSpread toDerivative(final ZonedDateTime dateTime) {
final LocalDate dateConversion = dateTime.toLocalDate();
ArgumentChecker.isTrue(!dateConversion.isAfter(_fixingDates[0].toLocalDate()),
"toDerivative without time series should have a date before the first fixing date.");
final double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate());
final double[] fixingTimes = TimeCalculator.getTimeBetween(dateTime, _fixingDates);
final double[] fixingPeriodStartTimes = TimeCalculator.getTimeBetween(dateTime, _fixingSubperiodStartDates);
final double[] fixingPeriodEndTimes = TimeCalculator.getTimeBetween(dateTime, _fixingSuberiodEndDates);
return new CouponIborCompoundingFlatSpread(getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), 0, _index, _subperiodAccrualFactors,
fixingTimes, fixingPeriodStartTimes, fixingPeriodEndTimes, _fixingSubperiodAccrualFactors, _spread);
}
@Override
public Coupon toDerivative(final ZonedDateTime dateTime, final DoubleTimeSeries<ZonedDateTime> indexFixingTimeSeries) {
final LocalDate dateConversion = dateTime.toLocalDate();
ArgumentChecker.notNull(indexFixingTimeSeries, "Index fixing time series");
ArgumentChecker.isTrue(!dateConversion.isAfter(getPaymentDate().toLocalDate()), "date is after payment date");
final double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate());
final int nbSubPeriods = _fixingDates.length;
int nbFixed = 0;
if (!Double.isNaN(_initialRate)) { // Force the initial rate to be used
nbFixed++;
}
while (nbFixed < nbSubPeriods && dateConversion.isAfter(_fixingDates[nbFixed].toLocalDate())) { // If fixing is strictly before today, period has fixed
nbFixed++;
}
if (nbFixed < nbSubPeriods && dateConversion.equals(_fixingDates[nbFixed].toLocalDate())) { // Not all periods already fixed, checking if todays fixing is
// available
final ZonedDateTime rezonedFixingDateNext = ZonedDateTime.of(LocalDateTime.of(_fixingDates[nbFixed].toLocalDate(), LocalTime.of(0, 0)), ZoneOffset.UTC);
final Double fixedRate = indexFixingTimeSeries.getValue(rezonedFixingDateNext);
if (fixedRate != null) {
nbFixed++;
}
}
final double[] rateFixed = new double[nbFixed];
double cpaAccumulated = 0;
for (int loopsub = 0; loopsub < nbFixed; loopsub++) {
// Finding the fixing
final ZonedDateTime rezonedFixingDate = ZonedDateTime.of(LocalDateTime.of(_fixingDates[loopsub].toLocalDate(), LocalTime.of(0, 0)), ZoneOffset.UTC);
final Double fixing;
if (!Double.isNaN(_initialRate) && loopsub == 0) {
// TODO validate the correct compounding behaviour
cpaAccumulated += getNotional() * (_initialRate + _spread) * _subperiodAccrualFactors[loopsub];
} else {
fixing = indexFixingTimeSeries.getValue(rezonedFixingDate);
if (fixing == null) {
throw new OpenGammaRuntimeException("Could not get fixing value for date " + rezonedFixingDate);
}
rateFixed[loopsub] = fixing;
cpaAccumulated += cpaAccumulated * fixing * _subperiodAccrualFactors[loopsub]; // Additional Compounding Period Amount
cpaAccumulated += getNotional() * (fixing + _spread) * _subperiodAccrualFactors[loopsub]; // Basic Compounding Period Amount
}
}
if (nbFixed == nbSubPeriods) {
// Implementation note: all dates already fixed: CouponFixed
final double rate = cpaAccumulated / (getNotional() * getPaymentYearFraction());
return new CouponFixed(getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), rate, getAccrualStartDate(), getAccrualEndDate());
}
// Implementation note: Copying the remaining periods
final int nbSubPeriodLeft = nbSubPeriods - nbFixed;
final double[] paymentAccrualFactorsLeft = new double[nbSubPeriodLeft];
System.arraycopy(_subperiodAccrualFactors, nbFixed, paymentAccrualFactorsLeft, 0, nbSubPeriodLeft);
final double[] fixingTimesLeft = new double[nbSubPeriodLeft];
System.arraycopy(TimeCalculator.getTimeBetween(dateTime, _fixingDates), nbFixed, fixingTimesLeft, 0, nbSubPeriodLeft);
final double[] fixingPeriodStartTimesLeft = new double[nbSubPeriodLeft];
System.arraycopy(TimeCalculator.getTimeBetween(dateTime, _fixingSubperiodStartDates), nbFixed, fixingPeriodStartTimesLeft, 0, nbSubPeriodLeft);
final double[] fixingPeriodEndTimesLeft = new double[nbSubPeriodLeft];
System.arraycopy(TimeCalculator.getTimeBetween(dateTime, _fixingSuberiodEndDates), nbFixed, fixingPeriodEndTimesLeft, 0, nbSubPeriodLeft);
final double[] fixingPeriodAccrualFactorsLeft = new double[nbSubPeriodLeft];
System.arraycopy(_fixingSubperiodAccrualFactors, nbFixed, fixingPeriodAccrualFactorsLeft, 0, nbSubPeriodLeft);
return new CouponIborCompoundingFlatSpread(getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), cpaAccumulated, _index,
paymentAccrualFactorsLeft,
fixingTimesLeft, fixingPeriodStartTimesLeft, fixingPeriodEndTimesLeft, fixingPeriodAccrualFactorsLeft, _spread);
}
@Override
public <U, V> V accept(final InstrumentDefinitionVisitor<U, V> visitor, final U data) {
ArgumentChecker.notNull(visitor, "visitor");
return visitor.visitCouponIborCompoundingFlatSpreadDefinition(this, data);
}
@Override
public <V> V accept(final InstrumentDefinitionVisitor<?, V> visitor) {
ArgumentChecker.notNull(visitor, "visitor");
return visitor.visitCouponIborCompoundingFlatSpreadDefinition(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Arrays.hashCode(_fixingDates);
result = prime * result + Arrays.hashCode(_fixingSubperiodAccrualFactors);
result = prime * result + Arrays.hashCode(_fixingSuberiodEndDates);
result = prime * result + Arrays.hashCode(_fixingSubperiodStartDates);
result = prime * result + (_index == null ? 0 : _index.hashCode());
long temp;
temp = Double.doubleToLongBits(_spread);
result = prime * result + (int) (temp ^ temp >>> 32);
result = prime * result + Arrays.hashCode(_subperiodAccrualEndDates);
result = prime * result + Arrays.hashCode(_subperiodAccrualFactors);
result = prime * result + Arrays.hashCode(_subperiodAccrualStartDates);
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CouponIborCompoundingFlatSpreadDefinition other = (CouponIborCompoundingFlatSpreadDefinition) obj;
if (!Arrays.equals(_fixingDates, other._fixingDates)) {
return false;
}
if (!Arrays.equals(_fixingSubperiodAccrualFactors, other._fixingSubperiodAccrualFactors)) {
return false;
}
if (!Arrays.equals(_fixingSuberiodEndDates, other._fixingSuberiodEndDates)) {
return false;
}
if (!Arrays.equals(_fixingSubperiodStartDates, other._fixingSubperiodStartDates)) {
return false;
}
if (!ObjectUtils.equals(_index, other._index)) {
return false;
}
if (Double.doubleToLongBits(_spread) != Double.doubleToLongBits(other._spread)) {
return false;
}
if (!Arrays.equals(_subperiodAccrualEndDates, other._subperiodAccrualEndDates)) {
return false;
}
if (!Arrays.equals(_subperiodAccrualFactors, other._subperiodAccrualFactors)) {
return false;
}
if (!Arrays.equals(_subperiodAccrualStartDates, other._subperiodAccrualStartDates)) {
return false;
}
return true;
}
}
| |
package org.apache.lucene.util;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Some of this code came from the excellent Unicode
* conversion examples from:
*
* http://www.unicode.org/Public/PROGRAMS/CVTUTF
*
* Full Copyright for that code follows:
*/
/*
* Copyright 2001-2004 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
/*
* Additional code came from the IBM ICU library.
*
* http://www.icu-project.org
*
* Full Copyright for that code follows.
*/
/*
* Copyright (C) 1999-2010, International Business Machines
* Corporation and others. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* provided that the above copyright notice(s) and this permission notice appear
* in all copies of the Software and that both the above copyright notice(s) and
* this permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
* LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization of the
* copyright holder.
*/
/**
* Class to encode java's UTF16 char[] into UTF8 byte[]
* without always allocating a new byte[] as
* String.getBytes("UTF-8") does.
*
* @lucene.internal
*/
public final class UnicodeUtil {
private UnicodeUtil() {} // no instance
public static final int UNI_SUR_HIGH_START = 0xD800;
public static final int UNI_SUR_HIGH_END = 0xDBFF;
public static final int UNI_SUR_LOW_START = 0xDC00;
public static final int UNI_SUR_LOW_END = 0xDFFF;
public static final int UNI_REPLACEMENT_CHAR = 0xFFFD;
private static final long UNI_MAX_BMP = 0x0000FFFF;
private static final int HALF_BASE = 0x0010000;
private static final long HALF_SHIFT = 10;
private static final long HALF_MASK = 0x3FFL;
private static final int SURROGATE_OFFSET =
Character.MIN_SUPPLEMENTARY_CODE_POINT -
(UNI_SUR_HIGH_START << HALF_SHIFT) - UNI_SUR_LOW_START;
/**
* @lucene.internal
*/
public static final class UTF8Result {
public byte[] result = new byte[10];
public int length;
public void setLength(int newLength) {
if (result.length < newLength) {
result = ArrayUtil.grow(result, newLength);
}
length = newLength;
}
}
/**
* @lucene.internal
*/
public static final class UTF16Result {
public char[] result = new char[10];
public int[] offsets = new int[10];
public int length;
public void setLength(int newLength) {
if (result.length < newLength) {
result = ArrayUtil.grow(result, newLength);
}
length = newLength;
}
public void copyText(UTF16Result other) {
setLength(other.length);
System.arraycopy(other.result, 0, result, 0, length);
}
}
/** Encode characters from a char[] source, starting at
* offset for length chars. Returns a hash of the resulting bytes. After encoding, result.offset will always be 0. */
public static int UTF16toUTF8WithHash(final char[] source, final int offset, final int length, BytesRef result) {
int hash = 0;
int upto = 0;
int i = offset;
final int end = offset + length;
byte[] out = result.bytes;
// Pre-allocate for worst case 4-for-1
final int maxLen = length * 4;
if (out.length < maxLen)
out = result.bytes = new byte[ArrayUtil.oversize(maxLen, 1)];
result.offset = 0;
while(i < end) {
final int code = (int) source[i++];
if (code < 0x80) {
hash = 31*hash + (out[upto++] = (byte) code);
} else if (code < 0x800) {
hash = 31*hash + (out[upto++] = (byte) (0xC0 | (code >> 6)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | (code & 0x3F)));
} else if (code < 0xD800 || code > 0xDFFF) {
hash = 31*hash + (out[upto++] = (byte)(0xE0 | (code >> 12)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | (code & 0x3F)));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && i < end) {
int utf32 = (int) source[i];
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = (code << 10) + utf32 + SURROGATE_OFFSET;
i++;
hash = 31*hash + (out[upto++] = (byte)(0xF0 | (utf32 >> 18)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)));
hash = 31*hash + (out[upto++] = (byte)(0x80 | (utf32 & 0x3F)));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
hash = 31*hash + (out[upto++] = (byte) 0xEF);
hash = 31*hash + (out[upto++] = (byte) 0xBF);
hash = 31*hash + (out[upto++] = (byte) 0xBD);
}
}
//assert matches(source, offset, length, out, upto);
result.length = upto;
return hash;
}
/** Encode characters from a char[] source, starting at
* offset and stopping when the character 0xffff is seen.
* Returns the number of bytes written to bytesOut. */
public static void UTF16toUTF8(final char[] source, final int offset, UTF8Result result) {
int upto = 0;
int i = offset;
byte[] out = result.result;
while(true) {
final int code = (int) source[i++];
if (upto+4 > out.length) {
out = result.result = ArrayUtil.grow(out, upto+4);
}
if (code < 0x80)
out[upto++] = (byte) code;
else if (code < 0x800) {
out[upto++] = (byte) (0xC0 | (code >> 6));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
if (code == 0xffff)
// END
break;
out[upto++] = (byte)(0xE0 | (code >> 12));
out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && source[i] != 0xffff) {
int utf32 = (int) source[i];
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
i++;
out[upto++] = (byte)(0xF0 | (utf32 >> 18));
out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F));
out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (utf32 & 0x3F));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
out[upto++] = (byte) 0xEF;
out[upto++] = (byte) 0xBF;
out[upto++] = (byte) 0xBD;
}
}
//assert matches(source, offset, i-offset-1, out, upto);
result.length = upto;
}
/** Encode characters from a char[] source, starting at
* offset for length chars. Returns the number of bytes
* written to bytesOut. */
public static void UTF16toUTF8(final char[] source, final int offset, final int length, UTF8Result result) {
int upto = 0;
int i = offset;
final int end = offset + length;
byte[] out = result.result;
while(i < end) {
final int code = (int) source[i++];
if (upto+4 > out.length) {
out = result.result = ArrayUtil.grow(out, upto+4);
}
if (code < 0x80)
out[upto++] = (byte) code;
else if (code < 0x800) {
out[upto++] = (byte) (0xC0 | (code >> 6));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
out[upto++] = (byte)(0xE0 | (code >> 12));
out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && i < end && source[i] != 0xffff) {
int utf32 = (int) source[i];
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
i++;
out[upto++] = (byte)(0xF0 | (utf32 >> 18));
out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F));
out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (utf32 & 0x3F));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
out[upto++] = (byte) 0xEF;
out[upto++] = (byte) 0xBF;
out[upto++] = (byte) 0xBD;
}
}
//assert matches(source, offset, length, out, upto);
result.length = upto;
}
/** Encode characters from this String, starting at offset
* for length characters. Returns the number of bytes
* written to bytesOut. */
public static void UTF16toUTF8(final String s, final int offset, final int length, UTF8Result result) {
final int end = offset + length;
byte[] out = result.result;
int upto = 0;
for(int i=offset;i<end;i++) {
final int code = (int) s.charAt(i);
if (upto+4 > out.length) {
out = result.result = ArrayUtil.grow(out, upto+4);
}
if (code < 0x80)
out[upto++] = (byte) code;
else if (code < 0x800) {
out[upto++] = (byte) (0xC0 | (code >> 6));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
out[upto++] = (byte)(0xE0 | (code >> 12));
out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && (i < end-1)) {
int utf32 = (int) s.charAt(i+1);
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
i++;
out[upto++] = (byte)(0xF0 | (utf32 >> 18));
out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F));
out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (utf32 & 0x3F));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
out[upto++] = (byte) 0xEF;
out[upto++] = (byte) 0xBF;
out[upto++] = (byte) 0xBD;
}
}
//assert matches(s, offset, length, out, upto);
result.length = upto;
}
/** Encode characters from this String, starting at offset
* for length characters. After encoding, result.offset will always be 0.
*/
public static void UTF16toUTF8(final CharSequence s, final int offset, final int length, BytesRef result) {
final int end = offset + length;
byte[] out = result.bytes;
result.offset = 0;
// Pre-allocate for worst case 4-for-1
final int maxLen = length * 4;
if (out.length < maxLen)
out = result.bytes = new byte[maxLen];
int upto = 0;
for(int i=offset;i<end;i++) {
final int code = (int) s.charAt(i);
if (code < 0x80)
out[upto++] = (byte) code;
else if (code < 0x800) {
out[upto++] = (byte) (0xC0 | (code >> 6));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
out[upto++] = (byte)(0xE0 | (code >> 12));
out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && (i < end-1)) {
int utf32 = (int) s.charAt(i+1);
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = (code << 10) + utf32 + SURROGATE_OFFSET;
i++;
out[upto++] = (byte)(0xF0 | (utf32 >> 18));
out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F));
out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (utf32 & 0x3F));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
out[upto++] = (byte) 0xEF;
out[upto++] = (byte) 0xBF;
out[upto++] = (byte) 0xBD;
}
}
//assert matches(s, offset, length, out, upto);
result.length = upto;
}
/** Encode characters from a char[] source, starting at
* offset for length chars. After encoding, result.offset will always be 0.
*/
public static void UTF16toUTF8(final char[] source, final int offset, final int length, BytesRef result) {
int upto = 0;
int i = offset;
final int end = offset + length;
byte[] out = result.bytes;
// Pre-allocate for worst case 4-for-1
final int maxLen = length * 4;
if (out.length < maxLen)
out = result.bytes = new byte[maxLen];
result.offset = 0;
while(i < end) {
final int code = (int) source[i++];
if (code < 0x80)
out[upto++] = (byte) code;
else if (code < 0x800) {
out[upto++] = (byte) (0xC0 | (code >> 6));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
out[upto++] = (byte)(0xE0 | (code >> 12));
out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (code & 0x3F));
} else {
// surrogate pair
// confirm valid high surrogate
if (code < 0xDC00 && i < end) {
int utf32 = (int) source[i];
// confirm valid low surrogate and write pair
if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
utf32 = (code << 10) + utf32 + SURROGATE_OFFSET;
i++;
out[upto++] = (byte)(0xF0 | (utf32 >> 18));
out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F));
out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F));
out[upto++] = (byte)(0x80 | (utf32 & 0x3F));
continue;
}
}
// replace unpaired surrogate or out-of-order low surrogate
// with substitution character
out[upto++] = (byte) 0xEF;
out[upto++] = (byte) 0xBF;
out[upto++] = (byte) 0xBD;
}
}
//assert matches(source, offset, length, out, upto);
result.length = upto;
}
/** Convert UTF8 bytes into UTF16 characters. If offset
* is non-zero, conversion starts at that starting point
* in utf8, re-using the results from the previous call
* up until offset. */
public static void UTF8toUTF16(final byte[] utf8, final int offset, final int length, final UTF16Result result) {
final int end = offset + length;
char[] out = result.result;
if (result.offsets.length <= end) {
result.offsets = ArrayUtil.grow(result.offsets, end+1);
}
final int[] offsets = result.offsets;
// If incremental decoding fell in the middle of a
// single unicode character, rollback to its start:
int upto = offset;
while(offsets[upto] == -1)
upto--;
int outUpto = offsets[upto];
// Pre-allocate for worst case 1-for-1
if (outUpto+length >= out.length) {
out = result.result = ArrayUtil.grow(out, outUpto+length+1);
}
while (upto < end) {
final int b = utf8[upto]&0xff;
final int ch;
offsets[upto++] = outUpto;
if (b < 0xc0) {
assert b < 0x80;
ch = b;
} else if (b < 0xe0) {
ch = ((b&0x1f)<<6) + (utf8[upto]&0x3f);
offsets[upto++] = -1;
} else if (b < 0xf0) {
ch = ((b&0xf)<<12) + ((utf8[upto]&0x3f)<<6) + (utf8[upto+1]&0x3f);
offsets[upto++] = -1;
offsets[upto++] = -1;
} else {
assert b < 0xf8;
ch = ((b&0x7)<<18) + ((utf8[upto]&0x3f)<<12) + ((utf8[upto+1]&0x3f)<<6) + (utf8[upto+2]&0x3f);
offsets[upto++] = -1;
offsets[upto++] = -1;
offsets[upto++] = -1;
}
if (ch <= UNI_MAX_BMP) {
// target is a character <= 0xFFFF
out[outUpto++] = (char) ch;
} else {
// target is a character in range 0xFFFF - 0x10FFFF
final int chHalf = ch - HALF_BASE;
out[outUpto++] = (char) ((chHalf >> HALF_SHIFT) + UNI_SUR_HIGH_START);
out[outUpto++] = (char) ((chHalf & HALF_MASK) + UNI_SUR_LOW_START);
}
}
offsets[upto] = outUpto;
result.length = outUpto;
}
// Only called from assert
/*
private static boolean matches(char[] source, int offset, int length, byte[] result, int upto) {
try {
String s1 = new String(source, offset, length);
String s2 = new String(result, 0, upto, "UTF-8");
if (!s1.equals(s2)) {
//System.out.println("DIFF: s1 len=" + s1.length());
//for(int i=0;i<s1.length();i++)
// System.out.println(" " + i + ": " + (int) s1.charAt(i));
//System.out.println("s2 len=" + s2.length());
//for(int i=0;i<s2.length();i++)
// System.out.println(" " + i + ": " + (int) s2.charAt(i));
// If the input string was invalid, then the
// difference is OK
if (!validUTF16String(s1))
return true;
return false;
}
return s1.equals(s2);
} catch (UnsupportedEncodingException uee) {
return false;
}
}
// Only called from assert
private static boolean matches(String source, int offset, int length, byte[] result, int upto) {
try {
String s1 = source.substring(offset, offset+length);
String s2 = new String(result, 0, upto, "UTF-8");
if (!s1.equals(s2)) {
// Allow a difference if s1 is not valid UTF-16
//System.out.println("DIFF: s1 len=" + s1.length());
//for(int i=0;i<s1.length();i++)
// System.out.println(" " + i + ": " + (int) s1.charAt(i));
//System.out.println(" s2 len=" + s2.length());
//for(int i=0;i<s2.length();i++)
// System.out.println(" " + i + ": " + (int) s2.charAt(i));
// If the input string was invalid, then the
// difference is OK
if (!validUTF16String(s1))
return true;
return false;
}
return s1.equals(s2);
} catch (UnsupportedEncodingException uee) {
return false;
}
}
public static final boolean validUTF16String(String s) {
final int size = s.length();
for(int i=0;i<size;i++) {
char ch = s.charAt(i);
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
if (i < size-1) {
i++;
char nextCH = s.charAt(i);
if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) {
// Valid surrogate pair
} else
// Unmatched high surrogate
return false;
} else
// Unmatched high surrogate
return false;
} else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END)
// Unmatched low surrogate
return false;
}
return true;
}
public static final boolean validUTF16String(char[] s, int size) {
for(int i=0;i<size;i++) {
char ch = s[i];
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
if (i < size-1) {
i++;
char nextCH = s[i];
if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) {
// Valid surrogate pair
} else
return false;
} else
return false;
} else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END)
// Unmatched low surrogate
return false;
}
return true;
}
*/
/** Shift value for lead surrogate to form a supplementary character. */
private static final int LEAD_SURROGATE_SHIFT_ = 10;
/** Mask to retrieve the significant value from a trail surrogate.*/
private static final int TRAIL_SURROGATE_MASK_ = 0x3FF;
/** Trail surrogate minimum value */
private static final int TRAIL_SURROGATE_MIN_VALUE = 0xDC00;
/** Lead surrogate minimum value */
private static final int LEAD_SURROGATE_MIN_VALUE = 0xD800;
/** The minimum value for Supplementary code points */
private static final int SUPPLEMENTARY_MIN_VALUE = 0x10000;
/** Value that all lead surrogate starts with */
private static final int LEAD_SURROGATE_OFFSET_ = LEAD_SURROGATE_MIN_VALUE
- (SUPPLEMENTARY_MIN_VALUE >> LEAD_SURROGATE_SHIFT_);
/**
* Cover JDK 1.5 API. Create a String from an array of codePoints.
*
* @param codePoints The code array
* @param offset The start of the text in the code point array
* @param count The number of code points
* @return a String representing the code points between offset and count
* @throws IllegalArgumentException If an invalid code point is encountered
* @throws IndexOutOfBoundsException If the offset or count are out of bounds.
*/
public static String newString(int[] codePoints, int offset, int count) {
if (count < 0) {
throw new IllegalArgumentException();
}
char[] chars = new char[count];
int w = 0;
for (int r = offset, e = offset + count; r < e; ++r) {
int cp = codePoints[r];
if (cp < 0 || cp > 0x10ffff) {
throw new IllegalArgumentException();
}
while (true) {
try {
if (cp < 0x010000) {
chars[w] = (char) cp;
w++;
} else {
chars[w] = (char) (LEAD_SURROGATE_OFFSET_ + (cp >> LEAD_SURROGATE_SHIFT_));
chars[w + 1] = (char) (TRAIL_SURROGATE_MIN_VALUE + (cp & TRAIL_SURROGATE_MASK_));
w += 2;
}
break;
} catch (IndexOutOfBoundsException ex) {
int newlen = (int) (Math.ceil((double) codePoints.length * (w + 2)
/ (r - offset + 1)));
char[] temp = new char[newlen];
System.arraycopy(chars, 0, temp, 0, w);
chars = temp;
}
}
}
return new String(chars, 0, w);
}
/**
* Interprets the given byte array as UTF-8 and converts to UTF-16. The {@link CharsRef} will be extended if
* it doesn't provide enough space to hold the worst case of each byte becoming a UTF-16 codepoint.
* <p>
* NOTE: Full characters are read, even if this reads past the length passed (and
* can result in an ArrayOutOfBoundsException if invalid UTF-8 is passed).
* Explicit checks for valid UTF-8 are not performed.
*/
public static void UTF8toUTF16(byte[] utf8, int offset, int length, CharsRef chars) {
int out_offset = chars.offset = 0;
final char[] out = chars.chars = ArrayUtil.grow(chars.chars, length);
final int limit = offset + length;
while (offset < limit) {
int b = utf8[offset++]&0xff;
if (b < 0xc0) {
assert b < 0x80;
out[out_offset++] = (char)b;
} else if (b < 0xe0) {
out[out_offset++] = (char)(((b&0x1f)<<6) + (utf8[offset++]&0x3f));
} else if (b < 0xf0) {
out[out_offset++] = (char)(((b&0xf)<<12) + ((utf8[offset]&0x3f)<<6) + (utf8[offset+1]&0x3f));
offset += 2;
} else {
assert b < 0xf8;
int ch = ((b&0x7)<<18) + ((utf8[offset]&0x3f)<<12) + ((utf8[offset+1]&0x3f)<<6) + (utf8[offset+2]&0x3f);
offset += 3;
if (ch < UNI_MAX_BMP) {
out[out_offset++] = (char)ch;
} else {
int chHalf = ch - 0x0010000;
out[out_offset++] = (char) ((chHalf >> 10) + 0xD800);
out[out_offset++] = (char) ((chHalf & HALF_MASK) + 0xDC00);
}
}
}
chars.length = out_offset - chars.offset;
}
/**
* Utility method for {@link #UTF8toUTF16(byte[], int, int, CharsRef)}
* @see #UTF8toUTF16(byte[], int, int, CharsRef)
*/
public static void UTF8toUTF16(BytesRef bytesRef, CharsRef chars) {
UTF8toUTF16(bytesRef.bytes, bytesRef.offset, bytesRef.length, chars);
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.path;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBuiltinTypeClassExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper;
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrExpressionImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
import static com.intellij.psi.util.PsiUtil.substituteTypeParameter;
/**
* @author ilyas
*/
public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProperty {
private static final Function<GrIndexPropertyImpl, PsiType> TYPE_CALCULATOR = new NullableFunction<GrIndexPropertyImpl, PsiType>() {
@Override
public PsiType fun(GrIndexPropertyImpl index) {
return index.inferType(null);
}
};
private static final ResolveCache.PolyVariantResolver<MyReference> RESOLVER = new ResolveCache.PolyVariantResolver<MyReference>() {
@NotNull
@Override
public GroovyResolveResult[] resolve(@NotNull MyReference reference, boolean incompleteCode) {
final GrIndexPropertyImpl index = reference.getElement();
return index.resolveImpl(incompleteCode, null, null);
}
};
private MyReference myReference = new MyReference();
private PsiType inferType(@Nullable Boolean isSetter) {
GrExpression selected = getInvokedExpression();
PsiType thisType = selected.getType();
if (thisType == null) {
thisType = TypesUtil.getJavaLangObject(this);
}
GrArgumentList argList = getArgumentList();
PsiType[] argTypes = PsiUtil.getArgumentTypes(argList);
if (argTypes == null) return null;
final PsiManager manager = getManager();
final GlobalSearchScope resolveScope = getResolveScope();
if (argTypes.length == 0) {
PsiType arrType = null;
if (selected instanceof GrBuiltinTypeClassExpression) {
arrType = ((GrBuiltinTypeClassExpression)selected).getPrimitiveType();
}
if (selected instanceof GrReferenceExpression) {
final PsiElement resolved = ((GrReferenceExpression)selected).resolve();
if (resolved instanceof PsiClass) {
String qname = ((PsiClass)resolved).getQualifiedName();
if (qname != null) {
arrType = TypesUtil.createTypeByFQClassName(qname, this);
}
}
}
if (arrType != null) {
final PsiArrayType param = arrType.createArrayType();
return TypesUtil.createJavaLangClassType(param, getProject(), resolveScope);
}
}
if (PsiImplUtil.isSimpleArrayAccess(thisType, argTypes, this, isSetter != null ? isSetter.booleanValue() : PsiUtil.isLValue(this))) {
return TypesUtil.boxPrimitiveType(((PsiArrayType)thisType).getComponentType(), manager, resolveScope);
}
final GroovyResolveResult[] candidates;
if (isSetter != null) {
candidates = isSetter.booleanValue() ? multiResolveSetter(false) : multiResolveGetter(false);
}
else {
candidates = multiResolve(false);
}
//don't use short PsiUtil.getArgumentTypes(...) because it use incorrect 'isSetter' value
PsiType[] args = PsiUtil
.getArgumentTypes(argList.getNamedArguments(), argList.getExpressionArguments(), GrClosableBlock.EMPTY_ARRAY, true, null, false);
final GroovyResolveResult candidate = PsiImplUtil.extractUniqueResult(candidates);
final PsiElement element = candidate.getElement();
if (element instanceof PsiNamedElement) {
final String name = ((PsiNamedElement)element).getName();
if ("putAt".equals(name) && args != null) {
args = ArrayUtil.append(args, TypeInferenceHelper.getInitializerFor(this), PsiType.class);
}
}
PsiType overloadedOperatorType = ResolveUtil.extractReturnTypeFromCandidate(candidate, this, args);
PsiType componentType = extractMapValueType(thisType, args, manager, resolveScope);
if (overloadedOperatorType != null &&
(componentType == null || !TypesUtil.isAssignableByMethodCallConversion(overloadedOperatorType, componentType, selected))) {
return TypesUtil.boxPrimitiveType(overloadedOperatorType, manager, resolveScope);
}
return componentType;
}
@Nullable
private static PsiType extractMapValueType(PsiType thisType, PsiType[] argTypes, PsiManager manager, GlobalSearchScope resolveScope) {
if (argTypes.length != 1 || !InheritanceUtil.isInheritor(thisType, CommonClassNames.JAVA_UTIL_MAP)) return null;
final PsiType substituted = substituteTypeParameter(thisType, CommonClassNames.JAVA_UTIL_MAP, 1, true);
return TypesUtil.boxPrimitiveType(substituted, manager, resolveScope);
}
private GroovyResolveResult[] resolveImpl(boolean incompleteCode, @Nullable GrExpression upToArgument, @Nullable Boolean isSetter) {
if (isSetter == null) isSetter = PsiUtil.isLValue(this);
GrExpression invoked = getInvokedExpression();
PsiType thisType = invoked.getType();
if (thisType == null) {
thisType = TypesUtil.getJavaLangObject(this);
}
GrArgumentList argList = getArgumentList();
//don't use short PsiUtil.getArgumentTypes(...) because it use incorrect 'isSetter' value
PsiType[] argTypes = PsiUtil.getArgumentTypes(argList.getNamedArguments(), argList.getExpressionArguments(), GrClosableBlock.EMPTY_ARRAY, true, upToArgument, false);
if (argTypes == null) return GroovyResolveResult.EMPTY_ARRAY;
final GlobalSearchScope resolveScope = getResolveScope();
if (argTypes.length == 0) {
PsiType arrType = null;
if (invoked instanceof GrBuiltinTypeClassExpression) {
arrType = ((GrBuiltinTypeClassExpression)invoked).getPrimitiveType();
}
if (invoked instanceof GrReferenceExpression) {
final PsiElement resolved = ((GrReferenceExpression)invoked).resolve();
if (resolved instanceof PsiClass) {
String qname = ((PsiClass)resolved).getQualifiedName();
if (qname != null) {
arrType = TypesUtil.createTypeByFQClassName(qname, this);
}
}
}
if (arrType != null) {
return GroovyResolveResult.EMPTY_ARRAY;
}
}
GroovyResolveResult[] candidates;
final String name = isSetter ? "putAt" : "getAt";
if (isSetter && !incompleteCode) {
argTypes = ArrayUtil.append(argTypes, TypeInferenceHelper.getInitializerFor(this), PsiType.class);
}
if (PsiImplUtil.isSimpleArrayAccess(thisType, argTypes, this, isSetter)) {
return GroovyResolveResult.EMPTY_ARRAY;
}
candidates = ResolveUtil.getMethodCandidates(thisType, name, invoked, true, incompleteCode, false, argTypes);
//hack for remove DefaultGroovyMethods.getAt(Object, ...)
if (candidates.length == 2) {
for (int i = 0; i < candidates.length; i++) {
GroovyResolveResult candidate = candidates[i];
final PsiElement element = candidate.getElement();
if (element instanceof GrGdkMethod) {
final PsiMethod staticMethod = ((GrGdkMethod)element).getStaticMethod();
final PsiParameter param = staticMethod.getParameterList().getParameters()[0];
if (param.getType().equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
return new GroovyResolveResult[]{candidates[1 - i]};
}
}
}
}
if (candidates.length != 1) {
final GrTupleType tupleType = new GrTupleType(argTypes, JavaPsiFacade.getInstance(getProject()), resolveScope);
final GroovyResolveResult[] tupleCandidates = ResolveUtil.getMethodCandidates(thisType, name, invoked, tupleType);
if (incompleteCode) {
candidates = ArrayUtil.mergeArrays(candidates, tupleCandidates, new ArrayFactory<GroovyResolveResult>() {
@NotNull
@Override
public GroovyResolveResult[] create(int count) {
return new GroovyResolveResult[count];
}
});
}
else {
candidates = tupleCandidates;
}
}
return candidates;
}
public GrIndexPropertyImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(GroovyElementVisitor visitor) {
visitor.visitIndexProperty(this);
}
public String toString() {
return "Property by index";
}
@NotNull
public GrExpression getInvokedExpression() {
return findNotNullChildByClass(GrExpression.class);
}
@NotNull
public GrArgumentList getArgumentList() {
return findNotNullChildByClass(GrArgumentList.class);
}
@Nullable
@Override
public PsiType getGetterType() {
return inferType(false);
}
@Nullable
@Override
public PsiType getSetterType() {
return inferType(true);
}
@NotNull
@Override
public GroovyResolveResult[] multiResolveGetter(boolean incomplete) {
return resolveImpl(incomplete, null, false);
}
@NotNull
@Override
public GroovyResolveResult[] multiResolveSetter(boolean incomplete) {
return resolveImpl(incomplete, null, false);
}
@NotNull
@Override
public GroovyResolveResult[] multiResolve(boolean incompleteCode) {
return TypeInferenceHelper.getCurrentContext().multiResolve(myReference, incompleteCode, RESOLVER);
}
public PsiType getType() {
return TypeInferenceHelper.getCurrentContext().getExpressionType(this, TYPE_CALCULATOR);
}
@Override
public PsiType getNominalType() {
if (getParent() instanceof GrThrowStatement) return super.getNominalType();
GroovyResolveResult[] candidates = multiResolve(true);
if (candidates.length == 1) {
return extractLastParameterType(candidates[0]);
}
return null;
}
@Nullable
private PsiType extractLastParameterType(GroovyResolveResult candidate) {
PsiElement element = candidate.getElement();
if (element instanceof PsiMethod) {
PsiParameter[] parameters = ((PsiMethod)element).getParameterList().getParameters();
if (parameters.length > 1) {
PsiParameter last = parameters[parameters.length - 1];
return TypesUtil.substituteBoxAndNormalizeType(last.getType(), candidate.getSubstitutor(), candidate.getSpreadState(), this);
}
}
return null;
}
@NotNull
@Override
public GrNamedArgument[] getNamedArguments() {
GrArgumentList list = getArgumentList();
return list.getNamedArguments();
}
@NotNull
@Override
public GrExpression[] getExpressionArguments() {
GrArgumentList list = getArgumentList();
return list.getExpressionArguments();
}
@Override
public GrNamedArgument addNamedArgument(GrNamedArgument namedArgument) throws IncorrectOperationException {
GrArgumentList list = getArgumentList();
return list.addNamedArgument(namedArgument);
}
@NotNull
@Override
public GroovyResolveResult[] getCallVariants(@Nullable GrExpression upToArgument) {
if (upToArgument == null) {
return multiResolve(true);
}
return resolveImpl(true, upToArgument, null);
}
@NotNull
@Override
public GrClosableBlock[] getClosureArguments() {
return GrClosableBlock.EMPTY_ARRAY;
}
@Override
public PsiMethod resolveMethod() {
return PsiImplUtil.extractUniqueElement(multiResolve(false));
}
@NotNull
@Override
public GroovyResolveResult advancedResolve() {
GroovyResolveResult[] results = multiResolve(false);
return results.length == 1 ? results[0] : GroovyResolveResult.EMPTY_RESULT;
}
@Override
public PsiReference getReference() {
return myReference;
}
private class MyReference implements PsiPolyVariantReference {
@Override
public GrIndexPropertyImpl getElement() {
return GrIndexPropertyImpl.this;
}
@Override
public TextRange getRangeInElement() {
final int offset = getArgumentList().getStartOffsetInParent();
return new TextRange(offset, offset + 1);
}
@Override
public PsiElement resolve() {
return resolveMethod();
}
@NotNull
@Override
public String getCanonicalText() {
return "Array-style access";
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
return GrIndexPropertyImpl.this;
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
return GrIndexPropertyImpl.this;
}
@Override
public boolean isReferenceTo(PsiElement element) {
return getManager().areElementsEquivalent(resolve(), element);
}
@NotNull
@Override
public Object[] getVariants() {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@Override
public boolean isSoft() {
return false;
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
return resolveImpl(incompleteCode, null, null);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.plan.nodes.exec.batch;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.config.ExecutionConfigOptions;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.planner.codegen.CodeGeneratorContext;
import org.apache.flink.table.planner.codegen.agg.AggsHandlerCodeGenerator;
import org.apache.flink.table.planner.codegen.over.MultiFieldRangeBoundComparatorCodeGenerator;
import org.apache.flink.table.planner.codegen.over.RangeBoundComparatorCodeGenerator;
import org.apache.flink.table.planner.codegen.sort.ComparatorCodeGenerator;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
import org.apache.flink.table.planner.plan.nodes.exec.spec.OverSpec;
import org.apache.flink.table.planner.plan.nodes.exec.spec.OverSpec.GroupSpec;
import org.apache.flink.table.planner.plan.nodes.exec.spec.SortSpec;
import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
import org.apache.flink.table.planner.plan.utils.AggregateInfoList;
import org.apache.flink.table.planner.plan.utils.AggregateUtil;
import org.apache.flink.table.planner.plan.utils.OverAggregateUtil;
import org.apache.flink.table.planner.plan.utils.SortUtil;
import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
import org.apache.flink.table.runtime.generated.GeneratedRecordComparator;
import org.apache.flink.table.runtime.operators.TableStreamOperator;
import org.apache.flink.table.runtime.operators.over.BufferDataOverWindowOperator;
import org.apache.flink.table.runtime.operators.over.NonBufferOverWindowOperator;
import org.apache.flink.table.runtime.operators.over.frame.InsensitiveOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.OffsetOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.OverWindowFrame;
import org.apache.flink.table.runtime.operators.over.frame.RangeSlidingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.RangeUnboundedFollowingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.RangeUnboundedPrecedingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.RowSlidingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.RowUnboundedFollowingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.RowUnboundedPrecedingOverFrame;
import org.apache.flink.table.runtime.operators.over.frame.UnboundedOverWindowFrame;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
import org.apache.flink.table.types.logical.RowType;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rex.RexWindowBound;
import org.apache.calcite.sql.SqlKind;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Batch {@link ExecNode} for sort-based over window aggregate. */
public class BatchExecOverAggregate extends BatchExecOverAggregateBase {
public BatchExecOverAggregate(
OverSpec overSpec,
InputProperty inputProperty,
RowType outputType,
String description) {
super(overSpec, inputProperty, outputType, description);
}
@SuppressWarnings("unchecked")
@Override
protected Transformation<RowData> translateToPlanInternal(PlannerBase planner) {
final ExecEdge inputEdge = getInputEdges().get(0);
final Transformation<RowData> inputTransform =
(Transformation<RowData>) inputEdge.translateToPlan(planner);
final RowType inputType = (RowType) inputEdge.getOutputType();
final TableConfig tableConfig = planner.getTableConfig();
// The generated sort is used for generating the comparator among partitions.
// So here not care the ASC or DESC for the grouping fields.
// TODO just replace comparator to equaliser
final int[] partitionFields = overSpec.getPartition().getFieldIndices();
final GeneratedRecordComparator genComparator =
ComparatorCodeGenerator.gen(
tableConfig,
"SortComparator",
inputType,
SortUtil.getAscendingSortSpec(partitionFields));
// use aggInputType which considers constants as input instead of inputType
final RowType inputTypeWithConstants = getInputTypeWithConstants();
// Over operator could support different order-by keys with collation satisfied.
// Currently, this operator requires all order keys (combined with partition keys) are
// the same, but order-by keys may be different. Consider the following sql:
// select *, sum(b) over partition by a order by a, count(c) over partition by a from T
// So we can use any one from the groups. To keep the behavior with the rule, we use the
// last one.
final SortSpec sortSpec =
overSpec.getGroups().get(overSpec.getGroups().size() - 1).getSort();
final TableStreamOperator<RowData> operator;
final long managedMemory;
if (!needBufferData()) {
// operator needn't cache data
final int numOfGroup = overSpec.getGroups().size();
final GeneratedAggsHandleFunction[] aggsHandlers =
new GeneratedAggsHandleFunction[numOfGroup];
final boolean[] resetAccumulators = new boolean[numOfGroup];
for (int i = 0; i < numOfGroup; ++i) {
GroupSpec group = overSpec.getGroups().get(i);
AggregateInfoList aggInfoList =
AggregateUtil.transformToBatchAggregateInfoList(
inputTypeWithConstants,
JavaScalaConversionUtil.toScala(group.getAggCalls()),
null, // aggCallNeedRetractions
sortSpec.getFieldIndices());
AggsHandlerCodeGenerator generator =
new AggsHandlerCodeGenerator(
new CodeGeneratorContext(tableConfig),
planner.getRelBuilder(),
JavaScalaConversionUtil.toScala(inputType.getChildren()),
false); // copyInputField
// over agg code gen must pass the constants
aggsHandlers[i] =
generator
.needAccumulate()
.withConstants(JavaScalaConversionUtil.toScala(getConstants()))
.generateAggsHandler("BoundedOverAggregateHelper", aggInfoList);
OverWindowMode mode = inferGroupMode(group);
resetAccumulators[i] =
mode == OverWindowMode.ROW
&& group.getLowerBound().isCurrentRow()
&& group.getUpperBound().isCurrentRow();
}
operator =
new NonBufferOverWindowOperator(aggsHandlers, genComparator, resetAccumulators);
managedMemory = 0L;
} else {
List<OverWindowFrame> windowFrames =
createOverWindowFrames(planner, inputType, sortSpec, inputTypeWithConstants);
operator =
new BufferDataOverWindowOperator(
windowFrames.toArray(new OverWindowFrame[0]),
genComparator,
inputType.getChildren().stream()
.allMatch(BinaryRowData::isInFixedLengthPart));
managedMemory =
tableConfig
.getConfiguration()
.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_EXTERNAL_BUFFER_MEMORY)
.getBytes();
}
return ExecNodeUtil.createOneInputTransformation(
inputTransform,
getDescription(),
SimpleOperatorFactory.of(operator),
InternalTypeInfo.of(getOutputType()),
inputTransform.getParallelism(),
managedMemory);
}
private List<OverWindowFrame> createOverWindowFrames(
PlannerBase planner,
RowType inputType,
SortSpec sortSpec,
RowType inputTypeWithConstants) {
final List<OverWindowFrame> windowFrames = new ArrayList<>();
for (GroupSpec group : overSpec.getGroups()) {
OverWindowMode mode = inferGroupMode(group);
if (mode == OverWindowMode.OFFSET) {
for (AggregateCall aggCall : group.getAggCalls()) {
AggregateInfoList aggInfoList =
AggregateUtil.transformToBatchAggregateInfoList(
inputTypeWithConstants,
JavaScalaConversionUtil.toScala(
Collections.singletonList(aggCall)),
new boolean[] {
true
}, /* needRetraction = true, See LeadLagAggFunction */
sortSpec.getFieldIndices());
AggsHandlerCodeGenerator generator =
new AggsHandlerCodeGenerator(
new CodeGeneratorContext(planner.getTableConfig()),
planner.getRelBuilder(),
JavaScalaConversionUtil.toScala(inputType.getChildren()),
false); // copyInputField
// over agg code gen must pass the constants
GeneratedAggsHandleFunction genAggsHandler =
generator
.needAccumulate()
.needRetract()
.withConstants(JavaScalaConversionUtil.toScala(getConstants()))
.generateAggsHandler("BoundedOverAggregateHelper", aggInfoList);
// LEAD is behind the currentRow, so we need plus offset.
// LAG is in front of the currentRow, so we need minus offset.
long flag = aggCall.getAggregation().kind == SqlKind.LEAD ? 1L : -1L;
final Long offset;
final OffsetOverFrame.CalcOffsetFunc calcOffsetFunc;
// LEAD ( expression [, offset [, default] ] )
// LAG ( expression [, offset [, default] ] )
// The second arg mean the offset arg index for leag/lag function, default is 1.
if (aggCall.getArgList().size() >= 2) {
int constantIndex =
aggCall.getArgList().get(1) - overSpec.getOriginalInputFields();
if (constantIndex < 0) {
offset = null;
int rowIndex = aggCall.getArgList().get(1);
switch (inputType.getTypeAt(rowIndex).getTypeRoot()) {
case BIGINT:
calcOffsetFunc =
(OffsetOverFrame.CalcOffsetFunc)
row -> row.getLong(rowIndex) * flag;
break;
case INTEGER:
calcOffsetFunc =
(OffsetOverFrame.CalcOffsetFunc)
row -> (long) row.getInt(rowIndex) * flag;
break;
case SMALLINT:
calcOffsetFunc =
(OffsetOverFrame.CalcOffsetFunc)
row -> (long) row.getShort(rowIndex) * flag;
break;
default:
throw new RuntimeException(
"The column type must be in long/int/short.");
}
} else {
long constantOffset =
getConstants().get(constantIndex).getValueAs(Long.class);
offset = constantOffset * flag;
calcOffsetFunc = null;
}
} else {
offset = flag;
calcOffsetFunc = null;
}
windowFrames.add(new OffsetOverFrame(genAggsHandler, offset, calcOffsetFunc));
}
} else {
AggregateInfoList aggInfoList =
AggregateUtil.transformToBatchAggregateInfoList(
// use aggInputType which considers constants as input instead of
// inputSchema.relDataType
inputTypeWithConstants,
JavaScalaConversionUtil.toScala(group.getAggCalls()),
null, // aggCallNeedRetractions
sortSpec.getFieldIndices());
AggsHandlerCodeGenerator generator =
new AggsHandlerCodeGenerator(
new CodeGeneratorContext(planner.getTableConfig()),
planner.getRelBuilder(),
JavaScalaConversionUtil.toScala(inputType.getChildren()),
false); // copyInputField
// over agg code gen must pass the constants
GeneratedAggsHandleFunction genAggsHandler =
generator
.needAccumulate()
.withConstants(JavaScalaConversionUtil.toScala(getConstants()))
.generateAggsHandler("BoundedOverAggregateHelper", aggInfoList);
RowType valueType = generator.valueType();
final OverWindowFrame frame;
switch (mode) {
case RANGE:
if (isUnboundedWindow(group)) {
frame = new UnboundedOverWindowFrame(genAggsHandler, valueType);
} else if (isUnboundedPrecedingWindow(group)) {
GeneratedRecordComparator genBoundComparator =
createBoundComparator(
planner,
sortSpec,
group.getUpperBound(),
false,
inputType);
frame =
new RangeUnboundedPrecedingOverFrame(
genAggsHandler, genBoundComparator);
} else if (isUnboundedFollowingWindow(group)) {
GeneratedRecordComparator genBoundComparator =
createBoundComparator(
planner,
sortSpec,
group.getLowerBound(),
true,
inputType);
frame =
new RangeUnboundedFollowingOverFrame(
valueType, genAggsHandler, genBoundComparator);
} else if (isSlidingWindow(group)) {
GeneratedRecordComparator genLeftBoundComparator =
createBoundComparator(
planner,
sortSpec,
group.getLowerBound(),
true,
inputType);
GeneratedRecordComparator genRightBoundComparator =
createBoundComparator(
planner,
sortSpec,
group.getUpperBound(),
false,
inputType);
frame =
new RangeSlidingOverFrame(
inputType,
valueType,
genAggsHandler,
genLeftBoundComparator,
genRightBoundComparator);
} else {
throw new TableException("This should not happen.");
}
break;
case ROW:
if (isUnboundedWindow(group)) {
frame = new UnboundedOverWindowFrame(genAggsHandler, valueType);
} else if (isUnboundedPrecedingWindow(group)) {
frame =
new RowUnboundedPrecedingOverFrame(
genAggsHandler,
OverAggregateUtil.getLongBoundary(
overSpec, group.getUpperBound()));
} else if (isUnboundedFollowingWindow(group)) {
frame =
new RowUnboundedFollowingOverFrame(
valueType,
genAggsHandler,
OverAggregateUtil.getLongBoundary(
overSpec, group.getLowerBound()));
} else if (isSlidingWindow(group)) {
frame =
new RowSlidingOverFrame(
inputType,
valueType,
genAggsHandler,
OverAggregateUtil.getLongBoundary(
overSpec, group.getLowerBound()),
OverAggregateUtil.getLongBoundary(
overSpec, group.getUpperBound()));
} else {
throw new TableException("This should not happen.");
}
break;
case INSENSITIVE:
frame = new InsensitiveOverFrame(genAggsHandler);
break;
default:
throw new TableException("This should not happen.");
}
windowFrames.add(frame);
}
}
return windowFrames;
}
private GeneratedRecordComparator createBoundComparator(
PlannerBase planner,
SortSpec sortSpec,
RexWindowBound windowBound,
boolean isLowerBound,
RowType inputType) {
Object bound = OverAggregateUtil.getBoundary(overSpec, windowBound);
if (!windowBound.isCurrentRow()) {
// Range Window only support comparing based on a field.
int sortKey = sortSpec.getFieldIndices()[0];
return new RangeBoundComparatorCodeGenerator(
planner.getRelBuilder(),
planner.getTableConfig(),
inputType,
bound,
sortKey,
inputType.getTypeAt(sortKey),
sortSpec.getAscendingOrders()[0],
isLowerBound)
.generateBoundComparator("RangeBoundComparator");
} else {
// if the bound is current row, then window support comparing based on multi fields.
return new MultiFieldRangeBoundComparatorCodeGenerator(
planner.getTableConfig(), inputType, sortSpec, isLowerBound)
.generateBoundComparator("MultiFieldRangeBoundComparator");
}
}
private boolean needBufferData() {
return overSpec.getGroups().stream()
.anyMatch(
group -> {
OverWindowMode mode = inferGroupMode(group);
switch (mode) {
case INSENSITIVE:
return false;
case ROW:
return (!group.getLowerBound().isCurrentRow()
|| !group.getUpperBound().isCurrentRow())
&& (!group.getLowerBound().isUnbounded()
|| !group.getUpperBound().isCurrentRow());
default:
return true;
}
});
}
}
| |
/*
* Copyright 2006 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.reteoo.builder;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.drools.common.BaseNode;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.common.RuleBasePartitionId;
import org.drools.reteoo.LeftTupleSource;
import org.drools.reteoo.ObjectSource;
import org.drools.reteoo.ReteooBuilder;
import org.drools.rule.Behavior;
import org.drools.rule.EntryPoint;
import org.drools.rule.RuleConditionElement;
/**
* A build context for Reteoo Builder
*
* @author etirelli
*/
public class BuildContext {
// tuple source to attach next node to
private LeftTupleSource tupleSource;
// object source to attach next node to
private ObjectSource objectSource;
// object type cache to check for cross products
private LinkedList objectType;
// offset of the pattern
private int currentPatternOffset;
// rule base to add rules to
private InternalRuleBase rulebase;
// working memories attached to the given rulebase
private InternalWorkingMemory[] workingMemories;
// id generator
private ReteooBuilder.IdGenerator idGenerator;
// a build stack to track nested elements
private LinkedList buildstack;
// beta constraints from the last pattern attached
private List betaconstraints;
// alpha constraints from the last pattern attached
private List alphaConstraints;
// behaviors from the last pattern attached
private List<Behavior> behaviors;
// the current entry point
private EntryPoint currentEntryPoint;
private boolean tupleMemoryEnabled;
private boolean objectTypeNodeMemoryEnabled;
private boolean terminalNodeMemoryEnabled;
/** This one is slightly different as alphaMemory can be adaptive, only turning on for new rule attachments */
private boolean alphaNodeMemoryAllowed;
/** Stores the list of nodes being added that require partitionIds */
private List<BaseNode> nodes;
/** Stores the id of the partition this rule will be added to */
private RuleBasePartitionId partitionId;
public BuildContext(final InternalRuleBase rulebase,
final ReteooBuilder.IdGenerator idGenerator) {
this.rulebase = rulebase;
this.idGenerator = idGenerator;
this.workingMemories = null;
this.objectType = null;
this.buildstack = null;
this.tupleSource = null;
this.objectSource = null;
this.currentPatternOffset = 0;
this.tupleMemoryEnabled = true;
this.objectTypeNodeMemoryEnabled = true;
this.currentEntryPoint = EntryPoint.DEFAULT;
this.nodes = new LinkedList<BaseNode>();
this.partitionId = null;
}
/**
* @return the currentPatternOffset
*/
public int getCurrentPatternOffset() {
return this.currentPatternOffset;
}
/**
* @param currentPatternOffset the currentPatternOffset to set
*/
public void setCurrentPatternOffset(final int currentPatternIndex) {
this.currentPatternOffset = currentPatternIndex;
this.syncObjectTypesWithPatternOffset();
}
public void syncObjectTypesWithPatternOffset() {
if ( this.objectType == null ) {
this.objectType = new LinkedList();
}
while ( this.objectType.size() > this.currentPatternOffset ) {
this.objectType.removeLast();
}
}
/**
* @return the objectSource
*/
public ObjectSource getObjectSource() {
return this.objectSource;
}
/**
* @param objectSource the objectSource to set
*/
public void setObjectSource(final ObjectSource objectSource) {
this.objectSource = objectSource;
}
/**
* @return the objectType
*/
public LinkedList getObjectType() {
if ( this.objectType == null ) {
this.objectType = new LinkedList();
}
return this.objectType;
}
/**
* @param objectType the objectType to set
*/
public void setObjectType(final LinkedList objectType) {
if ( this.objectType == null ) {
this.objectType = new LinkedList();
}
this.objectType = objectType;
}
/**
* @return the tupleSource
*/
public LeftTupleSource getTupleSource() {
return this.tupleSource;
}
/**
* @param tupleSource the tupleSource to set
*/
public void setTupleSource(final LeftTupleSource tupleSource) {
this.tupleSource = tupleSource;
}
public void incrementCurrentPatternOffset() {
this.currentPatternOffset++;
}
public void decrementCurrentPatternOffset() {
this.currentPatternOffset--;
this.syncObjectTypesWithPatternOffset();
}
/**
* Returns context rulebase
* @return
*/
public InternalRuleBase getRuleBase() {
return this.rulebase;
}
/**
* Return the array of working memories associated with the given
* rulebase.
*
* @return
*/
public InternalWorkingMemory[] getWorkingMemories() {
if ( this.workingMemories == null ) {
this.workingMemories = (InternalWorkingMemory[]) this.rulebase.getWorkingMemories();
}
return this.workingMemories;
}
/**
* Returns an Id for the next node
* @return
*/
public int getNextId() {
return this.idGenerator.getNextId();
}
/**
* Method used to undo previous id assignment
*/
public void releaseId(int id) {
this.idGenerator.releaseId( id );
}
/**
* Adds the rce to the build stack
* @param rce
*/
public void push(final RuleConditionElement rce) {
if ( this.buildstack == null ) {
this.buildstack = new LinkedList();
}
this.buildstack.addLast( rce );
}
/**
* Removes the top stack element
* @return
*/
public RuleConditionElement pop() {
if ( this.buildstack == null ) {
this.buildstack = new LinkedList();
}
return (RuleConditionElement) this.buildstack.removeLast();
}
/**
* Returns the top stack element without removing it
* @return
*/
public RuleConditionElement peek() {
if ( this.buildstack == null ) {
this.buildstack = new LinkedList();
}
return (RuleConditionElement) this.buildstack.getLast();
}
/**
* Returns a list iterator to iterate over the stacked elements
* @return
*/
public ListIterator stackIterator() {
if ( this.buildstack == null ) {
this.buildstack = new LinkedList();
}
return this.buildstack.listIterator();
}
/**
* @return the betaconstraints
*/
public List getBetaconstraints() {
return this.betaconstraints;
}
/**
* @param betaconstraints the betaconstraints to set
*/
public void setBetaconstraints(final List betaconstraints) {
this.betaconstraints = betaconstraints;
}
public int getNextSequence(String groupName) {
//List list = new ArrayList();
Integer seq = (Integer) this.rulebase.getAgendaGroupRuleTotals().get( groupName );
if ( seq == null ) {
seq = new Integer( 0 );
}
Integer newSeq = new Integer( seq.intValue() + 1 );
this.rulebase.getAgendaGroupRuleTotals().put( groupName,
newSeq );
return newSeq.intValue();
}
/**
* @return
*/
public List getAlphaConstraints() {
return alphaConstraints;
}
public void setAlphaConstraints(List alphaConstraints) {
this.alphaConstraints = alphaConstraints;
}
public boolean isTupleMemoryEnabled() {
return this.tupleMemoryEnabled;
}
public void setTupleMemoryEnabled(boolean hasLeftMemory) {
this.tupleMemoryEnabled = hasLeftMemory;
}
public boolean isObjectTypeNodeMemoryEnabled() {
return objectTypeNodeMemoryEnabled;
}
public void setObjectTypeNodeMemoryEnabled(boolean hasObjectTypeMemory) {
this.objectTypeNodeMemoryEnabled = hasObjectTypeMemory;
}
public boolean isTerminalNodeMemoryEnabled() {
return terminalNodeMemoryEnabled;
}
public void setTerminalNodeMemoryEnabled(boolean hasTerminalNodeMemory) {
this.terminalNodeMemoryEnabled = hasTerminalNodeMemory;
}
public void setAlphaNodeMemoryAllowed(boolean alphaMemoryAllowed) {
this.alphaNodeMemoryAllowed = alphaMemoryAllowed;
}
public boolean isAlphaMemoryAllowed() {
return this.alphaNodeMemoryAllowed;
}
/**
* @return the currentEntryPoint
*/
public EntryPoint getCurrentEntryPoint() {
return currentEntryPoint;
}
/**
* @param currentEntryPoint the currentEntryPoint to set
*/
public void setCurrentEntryPoint(EntryPoint currentEntryPoint) {
this.currentEntryPoint = currentEntryPoint;
}
/**
* @return the behaviours
*/
public List<Behavior> getBehaviors() {
return behaviors;
}
/**
* @param behaviors the behaviours to set
*/
public void setBehaviors(List<Behavior> behaviors) {
this.behaviors = behaviors;
}
/**
* @return the nodes
*/
public List<BaseNode> getNodes() {
return nodes;
}
/**
* @param nodes the nodes to set
*/
public void setNodes(List<BaseNode> nodes) {
this.nodes = nodes;
}
/**
* @return the partitionId
*/
public RuleBasePartitionId getPartitionId() {
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(RuleBasePartitionId partitionId) {
this.partitionId = partitionId;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iot.model;
import java.io.Serializable;
import javax.annotation.Generated;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CancelJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The job ARN.
* </p>
*/
private String jobArn;
/**
* <p>
* The unique identifier you assigned to this job when it was created.
* </p>
*/
private String jobId;
/**
* <p>
* A short text description of the job.
* </p>
*/
private String description;
/**
* <p>
* The job ARN.
* </p>
*
* @param jobArn
* The job ARN.
*/
public void setJobArn(String jobArn) {
this.jobArn = jobArn;
}
/**
* <p>
* The job ARN.
* </p>
*
* @return The job ARN.
*/
public String getJobArn() {
return this.jobArn;
}
/**
* <p>
* The job ARN.
* </p>
*
* @param jobArn
* The job ARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CancelJobResult withJobArn(String jobArn) {
setJobArn(jobArn);
return this;
}
/**
* <p>
* The unique identifier you assigned to this job when it was created.
* </p>
*
* @param jobId
* The unique identifier you assigned to this job when it was created.
*/
public void setJobId(String jobId) {
this.jobId = jobId;
}
/**
* <p>
* The unique identifier you assigned to this job when it was created.
* </p>
*
* @return The unique identifier you assigned to this job when it was created.
*/
public String getJobId() {
return this.jobId;
}
/**
* <p>
* The unique identifier you assigned to this job when it was created.
* </p>
*
* @param jobId
* The unique identifier you assigned to this job when it was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CancelJobResult withJobId(String jobId) {
setJobId(jobId);
return this;
}
/**
* <p>
* A short text description of the job.
* </p>
*
* @param description
* A short text description of the job.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A short text description of the job.
* </p>
*
* @return A short text description of the job.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A short text description of the job.
* </p>
*
* @param description
* A short text description of the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CancelJobResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getJobArn() != null)
sb.append("JobArn: ").append(getJobArn()).append(",");
if (getJobId() != null)
sb.append("JobId: ").append(getJobId()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CancelJobResult == false)
return false;
CancelJobResult other = (CancelJobResult) obj;
if (other.getJobArn() == null ^ this.getJobArn() == null)
return false;
if (other.getJobArn() != null && other.getJobArn().equals(this.getJobArn()) == false)
return false;
if (other.getJobId() == null ^ this.getJobId() == null)
return false;
if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getJobArn() == null) ? 0 : getJobArn().hashCode());
hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
return hashCode;
}
@Override
public CancelJobResult clone() {
try {
return (CancelJobResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
package barqsoft.footballscores.adapters;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService.RemoteViewsFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import barqsoft.footballscores.R;
import barqsoft.footballscores.activities.MainActivity;
import barqsoft.footballscores.data.ScoreModel;
import barqsoft.footballscores.helpers.Util;
import barqsoft.footballscores.receivers.WidgetProvider;
import barqsoft.footballscores.services.ScoresFetchService;
public class WidgetDataProvider implements RemoteViewsFactory {
private static final String LOG_TAG = "WidgetDataProvider"; //NON-NLS
private static final int mCount = 10;
private ArrayList<ScoreModel> mWidgetItems = new ArrayList<>();
private Context mContext;
private int mAppWidgetId;
// 86400000 ms = 24 hours
private int updateFrequency = 86400000;
public WidgetDataProvider(Context context, Intent intent) {
mContext = context;
mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public int getCount() {
return mWidgetItems.size();
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews remoteView = new RemoteViews(mContext.getPackageName(), R.layout.widget_list_item);
remoteView.setTextViewText(R.id.home_name, mWidgetItems.get(position).getHomeName());
remoteView.setTextViewText(R.id.away_name, mWidgetItems.get(position).getAwayName());
remoteView.setTextViewText(R.id.data_textview, mWidgetItems.get(position).getDate());
if (mWidgetItems.get(position).getHomeGoals() != null &&
mWidgetItems.get(position).getAwayGoals() != null) {
remoteView.setTextViewText(R.id.score_textview,
Util.getScores(Integer.parseInt(mWidgetItems.get(position).getHomeGoals()),
Integer.parseInt(mWidgetItems.get(position).getAwayGoals())));
}
remoteView.setImageViewResource(R.id.home_crest, Util.getTeamCrestByTeamName(mContext, mWidgetItems.get(position).getHomeName()));
remoteView.setImageViewResource(R.id.away_crest, Util.getTeamCrestByTeamName(mContext, mWidgetItems.get(position).getAwayName()));
Intent appIntent = new Intent(mContext, MainActivity.class);
PendingIntent appPendingIntent = PendingIntent.getActivity(mContext, 0, appIntent, 0);
remoteView.setOnClickPendingIntent(R.id.item_container, appPendingIntent);
return remoteView;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onCreate() {
initData();
}
@Override
public void onDataSetChanged() {
initData();
}
@Override
public void onDestroy() {
}
private void updateScores() {
Intent service_start = new Intent(mContext, ScoresFetchService.class);
mContext.startService(service_start);
}
private void initData() {
// This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
// on the collection view corresponding to this factory. You can do heaving lifting in
// here, synchronously. For example, if you need to process an image, fetch something
// from the network, etc., it is ok to do it here, synchronously. The widget will remain
// in its current state while work is being done here, so you don't need to worry about
// locking up the widget.
// TODO: The following needs to be moved to a common util class so that
// TODO: both ScoresFetchService and this implementation are consolidated.
// TODO: For the future, we could set up the WidgetService and a CursorLoader to load this data (I think).
fetchDataFromAPI(mContext.getString(R.string.timeframe_next_two_days));
fetchDataFromAPI(mContext.getString(R.string.timeframe_past_two_days));
}
private void fetchDataFromAPI(String timeFrame) {
//Creating fetch URL
final String BASE_URL = mContext.getString(R.string.api_football_fixtures_url); //Base URL
final String QUERY_TIME_FRAME = mContext.getString(R.string.api_timeframe_query); //Time Frame parameter to determine days
Uri fetch_build = Uri.parse(BASE_URL).buildUpon().
appendQueryParameter(QUERY_TIME_FRAME, timeFrame).build();
HttpURLConnection m_connection = null;
BufferedReader reader = null;
String JSON_data = null;
//Opening Connection
try {
URL fetch = new URL(fetch_build.toString());
m_connection = (HttpURLConnection) fetch.openConnection();
m_connection.setRequestMethod(mContext.getString(R.string.api_requestmethod_get));
m_connection.addRequestProperty(mContext.getString(R.string.api_requestprop_x_auth_token), mContext.getString(R.string.api_key));
m_connection.connect();
Log.d(LOG_TAG, "fetchDataFromAPI: URL: " + fetch.toString()); //NON-NLS
// Read the input stream into a String
InputStream inputStream = m_connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
JSON_data = buffer.toString();
} catch (Exception e) {
Log.e(LOG_TAG, "Exception here" + e.getMessage()); //NON-NLS
} finally {
if (m_connection != null) {
m_connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error Closing Stream"); //NON-NLS
}
}
}
try {
if (JSON_data != null) {
//This bit is to check if the data contains any matches. If not, we call processJson on the dummy data
JSONArray matches = new JSONObject(JSON_data).getJSONArray(mContext.getString(R.string.api_fixtures));
if (matches.length() == 0) {
//if there is no data, call the function on dummy data
//this is expected behavior during the off season.
processJSONdata(mContext.getString(R.string.dummy_data), mContext.getApplicationContext(), false);
return;
}
processJSONdata(JSON_data, mContext.getApplicationContext(), true);
} else {
//Could not Connect
Log.d(LOG_TAG, "Could not connect to server."); //NON-NLS
}
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage());
}
}
private void processJSONdata(String JSONdata, Context mContext, boolean isReal) {
//JSON data
final String SEASON_LINK = mContext.getString(R.string.api_url_soccerseasons);
final String MATCH_LINK = mContext.getString(R.string.api_url_fixtures);
final String FIXTURES = mContext.getString(R.string.api_fixtures);
final String LINKS = mContext.getString(R.string.api_links);
final String SOCCER_SEASON = mContext.getString(R.string.api_soccerseason);
final String SELF = mContext.getString(R.string.api_self);
final String MATCH_DATE = mContext.getString(R.string.api_date);
final String HOME_TEAM = mContext.getString(R.string.api_hometeamname);
final String AWAY_TEAM = mContext.getString(R.string.api_awayteamname);
final String RESULT = mContext.getString(R.string.api_result);
final String HOME_GOALS = mContext.getString(R.string.api_goalshometeam);
final String AWAY_GOALS = mContext.getString(R.string.api_goalsawayteam);
final String MATCH_DAY = mContext.getString(R.string.api_matchday);
//Match data
String leagueStr = null;
String dateStr = null;
String timeStr = null;
String homeStr = null;
String awayStr = null;
String homeGoalsStr = null;
String awayGoalsStr = null;
String matchIdStr = null;
String matchDayStr = null;
try {
JSONArray matches = new JSONObject(JSONdata).getJSONArray(FIXTURES);
//ContentValues to be inserted
for (int i = 0; i < matches.length(); i++) {
JSONObject match_data = matches.getJSONObject(i);
leagueStr = match_data.getJSONObject(LINKS).getJSONObject(SOCCER_SEASON).
getString(mContext.getString(R.string.api_href));
leagueStr = leagueStr.replace(SEASON_LINK, "");
//This if statement controls which leagues we're interested in the data from.
//add leagues here in order to have them be added to the DB.
// If you are finding no data in the app, check that this contains all the leagues.
// If it doesn't, that can cause an empty DB, bypassing the dummy data routine.
if (leagueStr.equals(Integer.toString(Util.PREMIER_LEAGUE)) ||
leagueStr.equals(Integer.toString(Util.SERIE_A)) ||
leagueStr.equals(Integer.toString(Util.BUNDESLIGA1)) ||
leagueStr.equals(Integer.toString(Util.BUNDESLIGA2)) ||
leagueStr.equals(Integer.toString(Util.PRIMERA_DIVISION))) {
matchIdStr = match_data.getJSONObject(LINKS).getJSONObject(SELF).getString(mContext.getString(R.string.api_href));
matchIdStr = matchIdStr.replace(MATCH_LINK, "");
if (!isReal) {
//This if statement changes the match ID of the dummy data so that it all goes into the database
matchIdStr = matchIdStr + Integer.toString(i);
}
dateStr = match_data.getString(MATCH_DATE);
timeStr = dateStr.substring(dateStr.indexOf("T") + 1, dateStr.indexOf("Z")); //NON-NLS
dateStr = dateStr.substring(0, dateStr.indexOf("T")); //NON-NLS
SimpleDateFormat match_date = new SimpleDateFormat(mContext.getString(R.string.date_format_hms));
match_date.setTimeZone(TimeZone.getTimeZone(mContext.getString(R.string.timezone_utc)));
try {
Date parseddate = match_date.parse(dateStr + timeStr);
SimpleDateFormat new_date = new SimpleDateFormat(mContext.getString(R.string.date_format_hm));
new_date.setTimeZone(TimeZone.getDefault());
dateStr = new_date.format(parseddate);
timeStr = dateStr.substring(dateStr.indexOf(":") + 1);
dateStr = dateStr.substring(0, dateStr.indexOf(":"));
if (!isReal) {
//This if statement changes the dummy data's date to match our current date range.
Date fragmentdate = new Date(System.currentTimeMillis() + ((i - 2) * 86400000));
SimpleDateFormat mformat = new SimpleDateFormat(mContext.getString(R.string.date_format));
dateStr = mformat.format(fragmentdate);
}
} catch (Exception e) {
Log.d(LOG_TAG, "error here!"); //NON-NLS
Log.e(LOG_TAG, e.getMessage());
}
homeStr = match_data.getString(HOME_TEAM);
awayStr = match_data.getString(AWAY_TEAM);
homeGoalsStr = match_data.getJSONObject(RESULT).getString(HOME_GOALS);
awayGoalsStr = match_data.getJSONObject(RESULT).getString(AWAY_GOALS);
matchDayStr = match_data.getString(MATCH_DAY);
mWidgetItems.add(new ScoreModel(homeStr, awayStr, homeGoalsStr,
awayGoalsStr, dateStr, matchIdStr));
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.distributed.test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.FutureListener;
import org.apache.cassandra.config.EncryptionOptions;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.security.SSLFactory;
import org.apache.cassandra.utils.concurrent.SimpleCondition;
public class AbstractEncryptionOptionsImpl extends TestBaseImpl
{
Logger logger = LoggerFactory.getLogger(EncryptionOptions.class);
final static String validKeyStorePath = "test/conf/cassandra_ssl_test.keystore";
final static String validKeyStorePassword = "cassandra";
final static String validTrustStorePath = "test/conf/cassandra_ssl_test.truststore";
final static String validTrustStorePassword = "cassandra";
final static Map<String,Object> validKeystore = ImmutableMap.of("keystore", validKeyStorePath,
"keystore_password", validKeyStorePassword,
"truststore", validTrustStorePath,
"truststore_password", validTrustStorePassword);
// Result of a TlsConnection.connect call. The result is updated as the TLS connection
// sequence takes place. The nextOnFailure/nextOnSuccess allows the discard handler
// to correctly update state if an unexpected exception is thrown.
public enum ConnectResult {
UNINITIALIZED,
FAILED_TO_NEGOTIATE,
NEVER_CONNECTED,
NEGOTIATED,
CONNECTED_AND_ABOUT_TO_NEGOTIATE(FAILED_TO_NEGOTIATE, NEGOTIATED),
CONNECTING(NEVER_CONNECTED, CONNECTED_AND_ABOUT_TO_NEGOTIATE);
public final ConnectResult nextOnFailure;
public final ConnectResult nextOnSuccess;
ConnectResult()
{
nextOnFailure = null;
nextOnSuccess = null;
}
ConnectResult(ConnectResult nextOnFailure, ConnectResult nextOnSuccess)
{
this.nextOnFailure = nextOnFailure;
this.nextOnSuccess = nextOnSuccess;
}
}
public class TlsConnection
{
final String host;
final int port;
final EncryptionOptions encryptionOptions = new EncryptionOptions()
.withEnabled(true)
.withKeyStore(validKeyStorePath).withKeyStorePassword(validKeyStorePassword)
.withTrustStore(validTrustStorePath).withTrustStorePassword(validTrustStorePassword);
private Throwable lastThrowable;
public TlsConnection(String host, int port)
{
this.host = host;
this.port = port;
}
public synchronized Throwable lastThrowable()
{
return lastThrowable;
}
private synchronized void setLastThrowable(Throwable cause)
{
lastThrowable = cause;
}
final AtomicReference<ConnectResult> result = new AtomicReference<>(ConnectResult.UNINITIALIZED);
void setResult(String why, ConnectResult expected, ConnectResult newResult)
{
if (newResult == null)
return;
logger.debug("Setting progress from {} to {}", expected, expected.nextOnSuccess);
result.getAndUpdate(v -> {
if (v == expected)
return newResult;
else
throw new IllegalStateException(
String.format("CAS attempt on %s failed from %s to %s but %s did not match expected value",
why, expected, newResult, v));
});
}
void successProgress()
{
ConnectResult current = result.get();
setResult("success", current, current.nextOnSuccess);
}
void failure()
{
ConnectResult current = result.get();
setResult("failure", current, current.nextOnFailure);
}
ConnectResult connect() throws Throwable
{
AtomicInteger connectAttempts = new AtomicInteger(0);
result.set(ConnectResult.UNINITIALIZED);
setLastThrowable(null);
SslContext sslContext = SSLFactory.getOrCreateSslContext(encryptionOptions, true,
SSLFactory.SocketType.CLIENT);
EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
SimpleCondition attemptCompleted = new SimpleCondition();
// Listener on the SSL handshake makes sure that the test completes immediately as
// the server waits to receive a message over the TLS connection, so the discardHandler.decode
// will likely never be called. The lambda has to handle it's own exceptions as it's a listener,
// not in the request pipeline to pass them on to discardHandler.
FutureListener<Channel> handshakeResult = channelFuture -> {
try
{
logger.debug("handshakeFuture() listener called");
channelFuture.get();
successProgress();
}
catch (Throwable cause)
{
logger.info("handshakeFuture() threw", cause);
failure();
setLastThrowable(cause);
}
attemptCompleted.signalAll();
};
ChannelHandler connectHandler = new ByteToMessageDecoder()
{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{
logger.debug("connectHandler.channelActive");
int count = connectAttempts.incrementAndGet();
if (count > 1)
{
logger.info("connectHandler.channelActive called more than once - {}", count);
}
successProgress();
// Add the handler after the connection is established to make sure the connection
// progress is recorded
final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
sslHandler.handshakeFuture().addListener(handshakeResult);
super.channelActive(ctx);
}
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
{
logger.debug("connectHandler.decode - readable bytes {}", in.readableBytes());
ctx.pipeline().remove(this);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
{
logger.debug("connectHandler.exceptionCaught", cause);
setLastThrowable(cause);
failure();
attemptCompleted.signalAll();
}
};
ChannelHandler discardHandler = new ByteToMessageDecoder()
{
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
{
logger.info("discardHandler.decode - {} readable bytes made it past SSL negotiation, discarding.",
in.readableBytes());
in.readBytes(in.readableBytes());
attemptCompleted.signalAll();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
{
logger.debug("discardHandler.exceptionCaught", cause);
setLastThrowable(cause);
failure();
attemptCompleted.signalAll();
}
};
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<Channel>()
{
@Override
protected void initChannel(Channel channel)
{
SslHandler sslHandler = sslContext.newHandler(channel.alloc());
channel.pipeline().addFirst(connectHandler, sslHandler, discardHandler);
}
});
result.set(ConnectResult.CONNECTING);
ChannelFuture f = b.connect(host, port);
try
{
f.sync();
attemptCompleted.await(15, TimeUnit.SECONDS);
}
finally
{
f.channel().close();
}
return result.get();
}
void assertCannotConnect() throws Throwable
{
try
{
connect();
}
catch (java.net.ConnectException ex)
{
// verify it was not possible to connect before starting the server
}
}
}
/* Provde the cluster cannot start with the configured options */
void assertCannotStartDueToConfigurationException(Cluster cluster)
{
Throwable tr = null;
try
{
cluster.startup();
}
catch (Throwable maybeConfigException)
{
tr = maybeConfigException;
}
if (tr == null)
{
Assert.fail("Expected a ConfigurationException");
}
else
{
Assert.assertEquals(ConfigurationException.class.getName(), tr.getClass().getName());
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.convertToInstanceMethod;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.util.EditorHelper;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringEventData;
import com.intellij.refactoring.move.moveInstanceMethod.MoveInstanceMethodViewDescriptor;
import com.intellij.refactoring.util.*;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author dsl
*/
public class ConvertToInstanceMethodProcessor extends BaseRefactoringProcessor {
private static final Logger LOG =
Logger.getInstance("#com.intellij.refactoring.convertToInstanceMethod.ConvertToInstanceMethodProcessor");
private PsiMethod myMethod;
private @Nullable PsiParameter myTargetParameter;
private PsiClass myTargetClass;
private Map<PsiTypeParameter, PsiTypeParameter> myTypeParameterReplacements;
private static final Key<PsiTypeParameter> BIND_TO_TYPE_PARAMETER = Key.create("REPLACEMENT");
private final String myOldVisibility;
private final String myNewVisibility;
public ConvertToInstanceMethodProcessor(final Project project,
final PsiMethod method,
@Nullable final PsiParameter targetParameter,
final String newVisibility) {
super(project);
myMethod = method;
myTargetParameter = targetParameter;
LOG.assertTrue(method.hasModifierProperty(PsiModifier.STATIC));
if (myTargetParameter != null) {
LOG.assertTrue(myTargetParameter.getDeclarationScope() == myMethod);
LOG.assertTrue(myTargetParameter.getType() instanceof PsiClassType);
final PsiType type = myTargetParameter.getType();
LOG.assertTrue(type instanceof PsiClassType);
myTargetClass = ((PsiClassType)type).resolve();
}
else {
myTargetClass = method.getContainingClass();
}
myOldVisibility = VisibilityUtil.getVisibilityModifier(method.getModifierList());
myNewVisibility = newVisibility;
}
public PsiClass getTargetClass() {
return myTargetClass;
}
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) {
return new MoveInstanceMethodViewDescriptor(myMethod, myTargetParameter, myTargetClass);
}
protected void refreshElements(@NotNull PsiElement[] elements) {
LOG.assertTrue(elements.length > 1);
myMethod = (PsiMethod)elements[0];
myTargetParameter = elements.length == 3 ? (PsiParameter)elements[1] : null;
myTargetClass = (PsiClass)elements[elements.length - 1];
}
@NotNull
protected UsageInfo[] findUsages() {
LOG.assertTrue(myTargetParameter == null || myTargetParameter.getDeclarationScope() == myMethod);
final Project project = myMethod.getProject();
final PsiReference[] methodReferences =
ReferencesSearch.search(myMethod, GlobalSearchScope.projectScope(project), false).toArray(PsiReference.EMPTY_ARRAY);
List<UsageInfo> result = new ArrayList<>();
for (final PsiReference ref : methodReferences) {
final PsiElement element = ref.getElement();
if (element instanceof PsiReferenceExpression) {
PsiElement parent = element.getParent();
if (parent instanceof PsiMethodCallExpression) {
result.add(new MethodCallUsageInfo((PsiMethodCallExpression)parent));
}
else if (element instanceof PsiMethodReferenceExpression) {
result.add(new MethodReferenceUsageInfo((PsiMethodReferenceExpression)element, myTargetParameter == null || myMethod.getParameterList().getParameterIndex(myTargetParameter) == 0));
}
}
else if (element instanceof PsiDocTagValue) {
result.add(new JavaDocUsageInfo(ref)); //TODO:!!!
}
}
if (myTargetParameter != null) {
for (final PsiReference ref : ReferencesSearch.search(myTargetParameter, new LocalSearchScope(myMethod), false)) {
final PsiElement element = ref.getElement();
if (element instanceof PsiReferenceExpression || element instanceof PsiDocParamRef) {
result.add(new ParameterUsageInfo(ref));
}
}
}
if (myTargetClass.isInterface()) {
PsiClass[] implementingClasses = RefactoringHierarchyUtil.findImplementingClasses(myTargetClass);
for (final PsiClass implementingClass : implementingClasses) {
result.add(new ImplementingClassUsageInfo(implementingClass));
}
}
return result.toArray(new UsageInfo[result.size()]);
}
@Nullable
@Override
protected String getRefactoringId() {
return "refactoring.makeInstance";
}
@Nullable
@Override
protected RefactoringEventData getBeforeData() {
RefactoringEventData data = new RefactoringEventData();
data.addElements(new PsiElement[]{myMethod, myTargetClass});
return data;
}
@Nullable
@Override
protected RefactoringEventData getAfterData(@NotNull UsageInfo[] usages) {
RefactoringEventData data = new RefactoringEventData();
data.addElement(myTargetClass);
return data;
}
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
UsageInfo[] usagesIn = refUsages.get();
MultiMap<PsiElement, String> conflicts = new MultiMap<>();
final Set<PsiMember> methods = Collections.singleton((PsiMember)myMethod);
if (!myTargetClass.isInterface()) {
RefactoringConflictsUtil.analyzeAccessibilityConflicts(methods, myTargetClass, conflicts, myNewVisibility);
}
else {
for (final UsageInfo usage : usagesIn) {
if (usage instanceof ImplementingClassUsageInfo) {
RefactoringConflictsUtil
.analyzeAccessibilityConflicts(methods, ((ImplementingClassUsageInfo)usage).getPsiClass(), conflicts, PsiModifier.PUBLIC);
}
}
}
for (final UsageInfo usageInfo : usagesIn) {
PsiElement place = null;
if (usageInfo instanceof MethodCallUsageInfo) {
place = ((MethodCallUsageInfo)usageInfo).getMethodCall();
if (myTargetParameter != null) {
final PsiExpression[] expressions = ((PsiMethodCallExpression)place).getArgumentList().getExpressions();
final int index = myMethod.getParameterList().getParameterIndex(myTargetParameter);
if (index < expressions.length) {
PsiExpression instanceValue = expressions[index];
instanceValue = RefactoringUtil.unparenthesizeExpression(instanceValue);
if (instanceValue instanceof PsiLiteralExpression && ((PsiLiteralExpression)instanceValue).getValue() == null) {
String message = RefactoringBundle.message("0.contains.call.with.null.argument.for.parameter.1",
RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(place), true),
CommonRefactoringUtil.htmlEmphasize(myTargetParameter.getName()));
conflicts.putValue(place, message);
}
}
}
}
else if (usageInfo instanceof MethodReferenceUsageInfo) {
place = ((MethodReferenceUsageInfo)usageInfo).getExpression();
if (!((MethodReferenceUsageInfo)usageInfo).isApplicableBySecondSearch()) {
conflicts.putValue(place, RefactoringBundle.message("expand.method.reference.warning"));
}
}
if (myTargetParameter == null && place != null && myTargetClass.hasTypeParameters() && !thisAccessExpressionApplicable(place)) {
conflicts.putValue(place, "Impossible to infer class type arguments. When proceed, raw " + myTargetClass.getName() + " would be created");
}
}
return showConflicts(conflicts, usagesIn);
}
protected void performRefactoring(@NotNull UsageInfo[] usages) {
LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
try {
doRefactoring(usages);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
finally {
a.finish();
}
}
private void doRefactoring(UsageInfo[] usages) throws IncorrectOperationException {
myTypeParameterReplacements = buildTypeParameterReplacements();
List<PsiClass> inheritors = new ArrayList<>();
CommonRefactoringUtil.sortDepthFirstRightLeftOrder(usages);
// Process usages
for (final UsageInfo usage : usages) {
if (usage instanceof MethodCallUsageInfo) {
processMethodCall(((MethodCallUsageInfo)usage).getMethodCall());
}
else if (usage instanceof ParameterUsageInfo) {
processParameterUsage((ParameterUsageInfo)usage);
}
else if (usage instanceof ImplementingClassUsageInfo) {
inheritors.add(((ImplementingClassUsageInfo)usage).getPsiClass());
}
else if (usage instanceof MethodReferenceUsageInfo) {
processMethodReference((MethodReferenceUsageInfo)usage);
}
}
prepareTypeParameterReplacement();
if (myTargetParameter != null) myTargetParameter.delete();
ChangeContextUtil.encodeContextInfo(myMethod, true);
if (!myTargetClass.isInterface()) {
PsiMethod method = addMethodToClass(myTargetClass);
fixVisibility(method, usages);
EditorHelper.openInEditor(method);
}
else {
final PsiMethod interfaceMethod = addMethodToClass(myTargetClass);
final PsiModifierList modifierList = interfaceMethod.getModifierList();
final boolean markAsDefault = PsiUtil.isLanguageLevel8OrHigher(myTargetClass);
if (markAsDefault) {
modifierList.setModifierProperty(PsiModifier.DEFAULT, true);
}
RefactoringUtil.makeMethodAbstract(myTargetClass, interfaceMethod);
EditorHelper.openInEditor(interfaceMethod);
if (!markAsDefault) {
for (final PsiClass psiClass : inheritors) {
final PsiMethod newMethod = addMethodToClass(psiClass);
PsiUtil.setModifierProperty(newMethod, myNewVisibility != null && !myNewVisibility.equals(VisibilityUtil.ESCALATE_VISIBILITY) ? myNewVisibility
: PsiModifier.PUBLIC, true);
}
}
}
myMethod.delete();
}
private void processMethodReference(MethodReferenceUsageInfo usage) {
PsiMethodReferenceExpression expression = usage.getExpression();
if (usage.isApplicableBySecondSearch()) {
PsiExpression qualifierExpression = expression.getQualifierExpression();
LOG.assertTrue(qualifierExpression != null);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(myProject);
PsiElement qualifier;
if (myTargetParameter != null) {
qualifier = factory.createReferenceExpression(myTargetClass);
}
else {
boolean thisAccess = thisAccessExpressionApplicable(expression);
qualifier = thisAccess
? factory.createExpressionFromText("this", qualifierExpression)
: createSyntheticAccessExpression(factory, expression);
}
qualifierExpression.replace(qualifier);
}
else {
PsiLambdaExpression lambdaExpression = LambdaRefactoringUtil.convertMethodReferenceToLambda(expression, false, true);
List<PsiExpression> returnExpressions = LambdaUtil.getReturnExpressions(lambdaExpression);
if (!returnExpressions.isEmpty()) {
PsiMethodCallExpression methodCall = (PsiMethodCallExpression)returnExpressions.get(0);
processMethodCall(methodCall);
usage.setReplacement(methodCall);
}
}
}
private void fixVisibility(final PsiMethod method, final UsageInfo[] usages) throws IncorrectOperationException {
final PsiModifierList modifierList = method.getModifierList();
if (VisibilityUtil.ESCALATE_VISIBILITY.equals(myNewVisibility)) {
for (UsageInfo usage : usages) {
PsiElement place = null;
if (usage instanceof MethodCallUsageInfo) {
place = usage.getElement();
}
else if (usage instanceof MethodReferenceUsageInfo) {
PsiMethodReferenceExpression expression = ((MethodReferenceUsageInfo)usage).getExpression();
if (expression != null && expression.isValid()) {
place = expression;
}
else {
place = ((MethodReferenceUsageInfo)usage).getReplacement();
}
}
if (place != null) {
VisibilityUtil.escalateVisibility(method, place);
}
}
}
else if (myNewVisibility != null && !myNewVisibility.equals(myOldVisibility)) {
modifierList.setModifierProperty(myNewVisibility, true);
}
}
private void prepareTypeParameterReplacement() throws IncorrectOperationException {
if (myTypeParameterReplacements == null) return;
final Collection<PsiTypeParameter> typeParameters = myTypeParameterReplacements.keySet();
for (final PsiTypeParameter parameter : typeParameters) {
for (final PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(myMethod), false)) {
if (reference.getElement() instanceof PsiJavaCodeReferenceElement) {
reference.getElement().putCopyableUserData(BIND_TO_TYPE_PARAMETER, myTypeParameterReplacements.get(parameter));
}
}
}
final Set<PsiTypeParameter> methodTypeParameters = myTypeParameterReplacements.keySet();
for (final PsiTypeParameter methodTypeParameter : methodTypeParameters) {
methodTypeParameter.delete();
}
}
private PsiMethod addMethodToClass(final PsiClass targetClass) throws IncorrectOperationException {
final PsiMethod newMethod = (PsiMethod)targetClass.add(myMethod);
final PsiModifierList modifierList = newMethod.getModifierList();
modifierList.setModifierProperty(PsiModifier.STATIC, false);
ChangeContextUtil.decodeContextInfo(newMethod, null, null);
if (myTypeParameterReplacements == null) return newMethod;
final Map<PsiTypeParameter, PsiTypeParameter> additionalReplacements;
if (targetClass != myTargetClass) {
final PsiSubstitutor superClassSubstitutor =
TypeConversionUtil.getSuperClassSubstitutor(myTargetClass, targetClass, PsiSubstitutor.EMPTY);
final Map<PsiTypeParameter, PsiTypeParameter> map = calculateReplacementMap(superClassSubstitutor, myTargetClass, targetClass);
if (map == null) return newMethod;
additionalReplacements = new HashMap<>();
for (final Map.Entry<PsiTypeParameter, PsiTypeParameter> entry : map.entrySet()) {
additionalReplacements.put(entry.getValue(), entry.getKey());
}
}
else {
additionalReplacements = null;
}
newMethod.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
PsiTypeParameter typeParameterToBind = reference.getCopyableUserData(BIND_TO_TYPE_PARAMETER);
if (typeParameterToBind != null) {
reference.putCopyableUserData(BIND_TO_TYPE_PARAMETER, null);
try {
if (additionalReplacements != null) {
typeParameterToBind = additionalReplacements.get(typeParameterToBind);
}
reference.bindToElement(typeParameterToBind);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
else {
visitElement(reference);
}
}
});
return newMethod;
}
private void processParameterUsage(ParameterUsageInfo usage) throws IncorrectOperationException {
final PsiReference reference = usage.getReferenceExpression();
if (reference instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference;
PsiElement parent = referenceExpression.getParent();
if (parent instanceof PsiReferenceExpression && sameUnqualified(parent)) {
referenceExpression.delete();
}
else {
final PsiExpression expression =
JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory().createExpressionFromText("this", null);
referenceExpression.replace(expression);
}
} else {
final PsiElement element = reference.getElement();
if (element instanceof PsiDocParamRef) {
element.getParent().delete();
}
}
}
private static boolean sameUnqualified(PsiElement parent) {
if (parent instanceof PsiMethodReferenceExpression) return false;
PsiElement resolve = ((PsiReferenceExpression)parent).resolve();
if (resolve instanceof PsiField) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(resolve.getProject());
final PsiExpression unqualifiedFieldReference = elementFactory.createExpressionFromText(((PsiField)resolve).getName(), parent);
return resolve == ((PsiReferenceExpression)unqualifiedFieldReference).resolve();
}
return true;
}
private void processMethodCall(final PsiMethodCallExpression methodCall) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory();
final PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
PsiExpression argument;
if (myTargetParameter != null) {
PsiParameterList parameterList = myMethod.getParameterList();
int parameterIndex = parameterList.getParameterIndex(myTargetParameter);
PsiExpression[] arguments = methodCall.getArgumentList().getExpressions();
if (arguments.length <= parameterIndex) return;
argument = arguments[parameterIndex];
}
else {
if (thisAccessExpressionApplicable(methodCall)) {
PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
if (qualifierExpression != null) {
qualifierExpression.delete();
}
return;
}
argument = createSyntheticAccessExpression(factory, methodCall);
}
final PsiExpression qualifier;
if (methodExpression.getQualifierExpression() != null) {
qualifier = methodExpression.getQualifierExpression();
}
else {
final PsiReferenceExpression newRefExpr = (PsiReferenceExpression)factory.createExpressionFromText("x." + myMethod.getName(), null);
qualifier = ((PsiReferenceExpression)methodExpression.replace(newRefExpr)).getQualifierExpression();
}
qualifier.replace(argument);
argument.delete();
}
private PsiExpression createSyntheticAccessExpression(PsiElementFactory factory, PsiElement context) {
return factory.createExpressionFromText("new " + myTargetClass.getName() + "()", context);
}
private boolean thisAccessExpressionApplicable(PsiElement expression) {
return PsiTreeUtil.isAncestor(myTargetClass, expression, false) && PsiUtil.getEnclosingStaticElement(expression, myTargetClass) == null;
}
@NotNull
protected String getCommandName() {
return ConvertToInstanceMethodHandler.REFACTORING_NAME;
}
@Nullable
public Map<PsiTypeParameter, PsiTypeParameter> buildTypeParameterReplacements() {
if (myTargetParameter == null) {
return Collections.emptyMap();
}
final PsiClassType type = (PsiClassType)myTargetParameter.getType();
final PsiSubstitutor substitutor = type.resolveGenerics().getSubstitutor();
return calculateReplacementMap(substitutor, myTargetClass, myMethod);
}
@Nullable
private static Map<PsiTypeParameter, PsiTypeParameter> calculateReplacementMap(final PsiSubstitutor substitutor,
final PsiClass targetClass,
final PsiElement containingElement) {
final HashMap<PsiTypeParameter, PsiTypeParameter> result = new HashMap<>();
for (PsiTypeParameter classTypeParameter : PsiUtil.typeParametersIterable(targetClass)) {
final PsiType substitution = substitutor.substitute(classTypeParameter);
if (!(substitution instanceof PsiClassType)) return null;
final PsiClass aClass = ((PsiClassType)substitution).resolve();
if (!(aClass instanceof PsiTypeParameter)) return null;
final PsiTypeParameter methodTypeParameter = (PsiTypeParameter)aClass;
if (methodTypeParameter.getOwner() != containingElement) return null;
if (result.keySet().contains(methodTypeParameter)) return null;
result.put(methodTypeParameter, classTypeParameter);
}
return result;
}
public PsiMethod getMethod() {
return myMethod;
}
@Nullable
public PsiParameter getTargetParameter() {
return myTargetParameter;
}
}
| |
/*
* Copyright Northwestern University
* Copyright Stanford University (ATB 1.0 and ATS 1.0)
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
*/
package edu.stanford.isis.atb.ui;
/**
* Keeps all text (labels, messages) from UI.
* Will be useful for possible future internationalization.
*
* @author Vitaliy Semeshko
*/
public class Const {
// texts
public static final String TTL_APPLICATION = "Aim Template Builder";
public static final String TTL_LEXICON_SEARCH = "Lexicon Search";
public static final String TTL_IMPORT = "Import";
public static final String TTL_EXPORT = "Export";
public static final String TAB_TEMPLATE_GROUPS = "Template Groups";
public static final String TAB_TEMPLATES = "Templates";
public static final String TAB_LEXICONS = "Lexicons";
public static final String TAB_HELP = "About/Help";
public static final String TAB_LOCAL_LEXICON_SEARCH = "Local";
public static final String TAB_BIOPORTAL_LEXICON_SEARCH = "Bioportal";
public static final String LBL_GROUPS = "Groups";
public static final String LBL_TEMPLATES = "Templates";
public static final String LBL_LEXICONS = "Lexicons";
public static final String LBL_LEXICON_TERMS = "Lexicon Terms";
public static final String LBL_TEMPLATE_COMPONENTS = "Template Components";
public static final String LBL_GROUP_MEMBERS = "Group Members";
public static final String LBL_GROUP_MEMBERSHIPS = "Group Memberships";
public static final String LBL_LEXICON_TERM = "Lexicon Term";
public static final String LBL_ALLOWED_TERMS = "Allowed Terms";
public static final String LBL_CURRENT_USER = "User: %s";
public static final String LBL_UNLIMITED = "Unlimited";
public static final String LBL_FILE = "File";
public static final String LBL_INFORMATION = "Information";
public static final String LBL_SELECTED_TERMS = "Selected %s terms...";
public static final String LBL_TEMPLATE_FILE_NAME = "Template File Name";
public static final String BTN_SUBMIT = "Save";
public static final String BTN_CANCEL = "Cancel";
public static final String BTN_SELECT_TERM = "Select Term";
public static final String BTN_OK = "OK";
public static final String BTN_SEARCH = "Search";
public static final String BTN_RESET = "Reset";
public static final String BTN_LOGIN = "Login";
public static final String BTN_WHOLE_WORD = "Whole word";
public static final String BTN_IMPORT = "Import";
public static final String BTN_EXPORT = "Export";
public static final String BTN_BROWSE = "Browse...";
public static final String BTN_PUBLISH = "Publish";
public static final String HNT_INCLUDE_TEMPLATES = "Include Selected Templates";
public static final String HNT_CREATE_TEMPLATE = "Create Template";
public static final String HNT_DELETE_TEMPLATE = "Delete Template";
public static final String HNT_COPY_TEMPLATE = "Copy Template";
public static final String HNT_SEARCH_TEMPLATES = "Search Templates";
public static final String HNT_CREATE_GROUP = "Add Template Container";
public static final String HNT_DELETE_GROUP = "Delete Template Container";
public static final String HNT_COPY_GROUP = "Copy Template Container";
public static final String HNT_EDIT_GROUP = "Edit Template Container";
public static final String HNT_IMPORT_EXPORT_GROUP = "Import/Export Template Container";
public static final String HNT_IMPORT = "Import";
public static final String HNT_EXPORT = "Export";
public static final String HNT_IMPORT_EXPORT_LEXICON = "Import/Export Lexicon";
public static final String HNT_SEARCH_PUBLISH_GROUP = "Search/Publish Template Container";
public static final String HNT_SEARCH_GROUPS = "Search";
public static final String HNT_PUBLISH_GROUP = "Publish";
public static final String HNT_CREATE_LEXICON = "Create Lexicon";
public static final String HNT_DELETE_LEXICON = "Delete Lexicon";
public static final String HNT_SEARCH_TERMINOLOGY = "Search Terminology";
public static final String HNT_ADD_TERM = "Create Lexicon Entry";
public static final String HNT_DELETE_TERM = "Delete Lexicon Entry";
public static final String HNT_REMOVE_TERM = "Remove Lexicon Term From The List";
public static final String HNT_SELECT_DIRECT_CHILDREN = "Select direct children";
public static final String HNT_SELECT_ALL_NESTED_TERMS = "Select all nested terms";
public static final String HNT_EXPAND_TREE = "Expand Tree";
public static final String HNT_COLLAPSE_TREE = "Collapse Tree";
public static final String HNT_CREATE_COMPONENT = "Create Template Component";
public static final String HNT_EDIT_COMPONENT = "Edit Template Component";
public static final String HNT_EDIT_QST_TYPE = "Edit Question";
public static final String HNT_DELETE_QST_TYPE = "Delete Question";
public static final String HNT_EDIT_GEOM_SHAPE = "Edit Geometric Shape";
public static final String HNT_DELETE_GEOM_SHAPE = "Delete Geometric Shape";
public static final String HNT_EDIT_CALCULATION = "Edit Calculation";
public static final String HNT_DELETE_ALLOWED_TERM = "Delete Allowed Term";
public static final String HNT_DELETE_VALID_TERM = "Delete Valid Term";
public static final String HNT_EDIT_ALLOWED_TERM = "Edit Allowed Term";
public static final String HNT_DELETE_INFERENCE = "Delete Inference";
public static final String HNT_EDIT_INFERENCE = "Edit Inference";
public static final String HNT_CREATE_NON_QUANT = "Create Non Quantifiable";
public static final String HNT_DELETE_NON_QUANT = "Delete Non Quantifiable";
public static final String HNT_DELETE_AN_ENTITY = "Delete Anatomic Entity";
public static final String HNT_CREATE_IMG_OBS_CHAR = "Create Imaging Observation Characteristic";
public static final String HNT_DELETE_IMG_OBS = "Delete Imaging Observation";
public static final String HNT_DELETE_IMG_OBS_CHAR = "Delete Imaging Observation Characteristic";
public static final String HNT_EDIT_AN_ENTITY = "Edit Anatomic Entity";
public static final String HNT_CREATE_AN_ENTITY_CHAR = "Create Anatomic Entity Characteristic";
public static final String HNT_DELETE_AN_ENTITY_CHAR = "Delete Anatomic Entity Characteristic";
public static final String HNT_CREATE_CHAR_QUANT = "Create Characteristic Quantification";
public static final String HNT_DELETE_CHAR_QUANT = "Delete Characteristic Quantification";
public static final String HNT_CREATE_CALC_TYPE = "Create Calculation Type";
public static final String HNT_EDIT_CALC_TYPE = "Edit Calculation Type";
public static final String HNT_DELETE_CALC_TYPE = "Delete Calculation Type";
public static final String HNT_CREATE_ALGORITHM_TYPE = "Create Algorithm Type";
public static final String HNT_EDIT_ALGORITHM_TYPE = "Edit Algorithm Type";
public static final String HNT_DELETE_ALGORITHM_TYPE = "Delete Algorithm Type";
public static final String HNT_DELETE_CALCULATION = "Delete Calculation";
public static final String HNT_DELETE_COMPONENT = "Delete Template Component";
public static final String HNT_CREATE_TAG = "Create Tag";
public static final String HNT_DELETE_TAG = "Delete Tag";
public static final String HNT_EDIT_TAG_NAME = "Edit Tag Name";
public static final String HNT_CREATE_QST_TYPE = "Create Question";
public static final String HNT_CREATE_AN_ENTITY = "Create Anatomic Entity";
public static final String HNT_CREATE_IMG_OBS = "Create Imaging Observation";
public static final String HNT_CREATE_INFERENCE = "Create Inference";
public static final String HNT_CREATE_CALCULATION = "Create Calculation";
public static final String HNT_CREATE_GEOM_SHAPE = "Create Geometric Shape";
public static final String HNT_ADD_ALLOWED_TERMS = "Add Allowed Terms";
public static final String HNT_ADD_VALID_TERMS = "Add Valid Terms";
public static final String HNT_CREATE_SCALE = "Create Scale";
public static final String HNT_DELETE_SCALE = "Delete Scale";
public static final String HNT_CREATE_NUMERICAL = "Create Numerical";
public static final String HNT_CREATE_INTERVAL = "Create Interval";
public static final String HNT_CREATE_QUANTILE = "Create Quantile";
public static final String HNT_CREATE_ORDINAL_LEVEL = "Create Ordinal Level";
public static final String HNT_DELETE_ORDINAL_LEVEL = "Delete Ordinal Level";
public static final String HNT_DELETE_NUMERICAL = "Delete Numerical";
public static final String HNT_DELETE_INTERVAL = "Delete Interval";
public static final String HNT_DELETE_QUANTILE = "Delete Quantile";
public static final String HNT_MOVE_UP = "Move Up";
public static final String HNT_MOVE_DOWN = "Move Down";
public static final String FRM_LBL_UID = "UID";
public static final String FRM_LBL_NAME = "Name";
public static final String FRM_LBL_VERSION = "Version";
public static final String FRM_LBL_DESCRIPTION = "Description";
public static final String FRM_LBL_AUTHORS = "Authors";
public static final String FRM_LBL_DATE = "Date";
public static final String FRM_LBL_BODY_PART = "Body Part";
public static final String FRM_LBL_DISEASE = "Disease";
public static final String FRM_LBL_MODALITY = "Modality";
public static final String FRM_LBL_LABEL = "Label";
public static final String FRM_LBL_CARDINALITY = "Cardinality";
public static final String FRM_LBL_ITEM_NUMBER = "Item Number";
public static final String FRM_LBL_SHOULD_DISPLAY = "Should Display";
public static final String FRM_LBL_EXPLANATORY_TEXT = "Explanatory Text";
public static final String FRM_LBL_GROUP_LABEL = "Group Label";
public static final String FRM_LBL_GROUP = "Group";
public static final String FRM_LBL_ANNOTATOR_CONFIDENCE = "Annotator Confidence";
public static final String FRM_LBL_SHAPE_TYPE = "Shape Type";
public static final String FRM_LBL_UNIQUE_IDENTIFIER = "Unique Identifier";
public static final String FRM_LBL_ALGORITHM_NAME = "Algorithm Name";
public static final String FRM_LBL_ALGORITHM_VERSION = "Algorithm Version";
public static final String FRM_LBL_MATH_ML = "Math ML";
public static final String FRM_LBL_TAG_NAME = "Tag Name";
public static final String FRM_LBL_TAG_VALUE = "Tag Value";
public static final String FRM_LBL_VALUE = "Value";
public static final String FRM_LBL_STRING_VALUE = "String Value";
public static final String FRM_LBL_USE_STRING_VALUE = "Use String Value";
public static final String FRM_LBL_USE_LEXICON_TERM = "Use Lexicon Term";
public static final String FRM_LBL_SCHEMA_DESIGNATOR = "Schema Designator";
public static final String FRM_LBL_SCHEMA_VERSION = "Schema Version";
public static final String FRM_LBL_IS_READ_ONLY = "Is Read-only";
public static final String FRM_LBL_CREATION_DATE = "Created";
public static final String FRM_LBL_MODIFICATION_DATE = "Modified";
public static final String FRM_LBL_CODE_MEANING = "Code Meaning";
public static final String FRM_LBL_CODE_VALUE = "Code Value";
public static final String FRM_LBL_COMMENT = "Comment";
public static final String FRM_LBL_OPERATOR = "Operator";
public static final String FRM_LBL_UCUM_STRING = "UCUM String";
public static final String FRM_LBL_MIN_VALUE = "Min Value";
public static final String FRM_LBL_MAX_VALUE = "Max Value";
public static final String FRM_LBL_MIN_OPERATOR = "Min Operator";
public static final String FRM_LBL_MAX_OPERATOR = "Max Operator";
public static final String FRM_LBL_BINS = "Bins";
public static final String FRM_LBL_TEMPLATE_NAME = "Template Name";
public static final String FRM_LBL_TEMPLATE_CODE_DESC = "Template Code Desc";
public static final String FRM_LBL_TEMPLATE_DESCRIPTION = "Template Description";
public static final String FRM_LBL_TEMPLATE_AUTHOR = "Template Author";
public static final String FRM_LBL_USERNAME = "Username";
public static final String FRM_LBL_PASSWORD = "Password";
public static final String FRM_LBL_CONTAINER_NAME = "Container Name";
public static final String FRM_LBL_CONTAINER_DESCRIPTION = "Container Description";
public static final String FRM_LBL_CONTAINER_AUTHOR = "Container Author";
public static final String FRM_LBL_LEXICON_TERM = "Lexicon Term";
public static final String FRM_LBL_PRECEDING_ANNOTATION = "Preceding Annotation";
public static final String TXT_NAME = "Name";
public static final String TXT_VALUE = "Value";
public static final String TXT_FORM_NO_ATTRIBUTES = "No attributes to edit";
public static final String TXT_AUTHENTICATION_FAILED = "Authentication Failed";
public static final String TXT_COPY_OF = "Copy Of";
public static final String TXT_INFINITY = "\u221E";
public static final String COLUMN_NAME = "Name";
public static final String COLUMN_DATE = "Date";
public static final String COLUMN_VERSION = "Version";
public static final String COLUMN_CODE_MEANING = "Code Meaning";
public static final String COLUMN_AUTH = "Auth";
public static final String COLUMN_AUTHORS = "Authors";
public static final String COLUMN_DESCRIPTION = "Description";
public static final String COLUMN_LEXICON = "Lexicon";
public static final String COLUMN_VALUE = "Value";
public static final String COLUMN_MEANING = "Meaning";
public static final String COLUMN_DISEASE = "Disease";
public static final String COLUMN_BODY_PART = "Body Part";
public static final String COLUMN_MODALITY = "Modality";
public static final String COLUMN_UID = "UID";
public static final String COLUMN_TERM_COUNT = "Term Count";
public static final String COLUMN_ELEMENT = "Element";
public static final String MSG_CANT_CONNECT_TO_DB = "Can't connect to database.\nIf there is another application running, please close it and try again.";
public static final String MSG_NO_CONTAINER_SELECTED = "No template container selected";
public static final String MSG_NO_TEMPLATE_SELECTED = "No template selected";
public static final String MSG_NO_LEXICON_SELECTED = "No lexicon selected";
public static final String MSG_LEXICON_IS_EMPTY = "Lexicon is empty";
public static final String MSG_LEXICON_IS_NOT_ALLOWED_FOR_EXPORT = "Lexicon is not allowed for the export";
public static final String MSG_LEXICON_IS_READONLY = "This Lexicon is Read-Only.";
public static final String MSG_WRONG_FIELD_VALUE = "Incorrect value in field \"%s\"";
public static final String MSG_CONTAINER_EXPORTED = "Template Container \"%s\" successfully exported";
public static final String MSG_CONTAINER_EXPORT_FAILED = "Template Container \"%s\" export failed.";
public static final String MSG_CONTAINER_IMPORTED = "Template Container \"%s\" successfully imported";
public static final String MSG_TEMPLATE_IMPORTED = "Template \"%s\" successfully imported";
public static final String MSG_CONTAINER_IMPORT_FAILED = "Template Container import failed.";
public static final String MSG_EMPTY_SEARCH_TEXT = "No search text specified";
public static final String MSG_SHORT_SEARCH_TEXT = "Search text is too short";
public static final String MSG_NO_LEXICON_SELECTED_FOR_SEARCH = "No Lexicon selected";
public static final String MSG_LEXICON_EXPORT_FAILED = "Lexicon \"%s\" export failed.";
public static final String MSG_LEXICON_IMPORT_FAILED = "Lexicon import failed.";
public static final String MSG_LEXICON_EXPORTED = "Lexicon \"%s\" successfully exported";
public static final String MSG_LEXICON_IMPORTED = "Lexicon \"%s\" successfully imported";
public static final String MSG_TERM_ALREADY_SELECTED = "Term '%s' has been already selected.";
public static final String MSG_CONTAINER_PUBLISHED = "Template Container \"%s\" successfully published.";
public static final String MSG_CONTAINER_IS_EMPTY = "Template Container is empty";
public static final String MSG_CONTAINER_IS_INCORRECT = "Template Container is not correct.\nPlease fix warnings previously";
public static final String MSG_TEMPLATE_COPIED = "Template Copy created: '%s'";
public static final String MSG_CONTAINER_COPIED = "Template Container copy created: '%s'";
public static final String MSG_INVALID_TEMPLATE = "Invalid AIM Template";
public static final String MSG_ERROR = "Error happened...";
public static final String MSG_OPERATION_INTERRUPTED = "Operation interrupted...";
public static final String MSG_OPERATION_FINISHED = "Operation finished";
public static final String MSG_OPERATION_FAILED = "Operation failed";
public static final String MSG_EXPORTED_TERMS = "Exported %d Term(s)";
public static final String MSG_IMPORTED_TERMS = "Imported %d Term(s)";
public static final String MSG_INCORRECT_FILE_LOCATION = "File location is incorrect: '%s'";
public static final String DLG_TITLE_INFORMATION = "Information";
public static final String DLG_TITLE_ERROR = "Error";
public static final String DLG_TITLE_CONFIRMATION = "Confirmation";
public static final String DLG_TITLE_VALIDATION_ERROR = "Validation Error";
public static final String DLG_TITLE_PUBLISHED_TEMPLATE_FILE_NAME = "Published Template File Name";
public static final String QST_DELETE_GROUP = "Are you sure you want to delete this Template Container?";
public static final String QST_DELETE_TEMPLATE = "Are you sure you want to delete this Template?";
public static final String QST_DELETE_LEXICON = "Are you sure you want to delete this Lexicon?";
public static final String EMPTY = "";
// formats
public static final String FMT_DATE_DISPLAY = "yyyy-MM-dd";
public static final String FMT_TIME_DATE_DISPLAY = "hh:mm yyyy-MM-dd";
public static final String FMT_DATE_TIME_WITH_SECONDS = "yyyy-MM-dd hh:mm:ss";
// templates
public static final String TPL_FORM_LABEL = "%s :";
public static final String TPL_FORM_LABEL_MANDATORY = "<html>%s<font color=red>*</font> :</html>";
// defaults
public static final String DEF_CODE_MEANING = "New Lexicon Entry";
public static final String DEF_CODE_VALUE = "";
// extensions
public static final String EXT_XML = "xml";
public static final String EXT_XML_TEXT = "XML-files (*.xml)";
public static final String EXT_CSV = "csv";
public static final String EXT_CSV_TEXT = "CSV-files (*.csv)";
// resource separator (platform-independent)
public static final String R_SEP = "/";
}
| |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.netcfglinks;
import java.nio.ByteBuffer;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.ChassisId;
import org.onlab.packet.Ethernet;
import org.onlab.packet.ONOSLLDP;
import org.onosproject.cluster.ClusterMetadataServiceAdapter;
import org.onosproject.core.CoreServiceAdapter;
import org.onosproject.mastership.MastershipServiceAdapter;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultPort;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.LinkKey;
import org.onosproject.net.NetTestTools;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistryAdapter;
import org.onosproject.net.config.basics.BasicLinkConfig;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkProviderRegistryAdapter;
import org.onosproject.net.link.LinkProviderServiceAdapter;
import org.onosproject.net.packet.DefaultInboundPacket;
import org.onosproject.net.packet.InboundPacket;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketServiceAdapter;
import com.google.common.collect.ImmutableList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Unit tests for the network config links provider.
*/
public class NetworkConfigLinksProviderTest {
private NetworkConfigLinksProvider provider;
private PacketProcessor testProcessor;
private LinkProviderServiceAdapter providerService;
private NetworkConfigListener configListener;
private final TestNetworkConfigRegistry configRegistry =
new TestNetworkConfigRegistry();
static Device dev1 = NetTestTools.device("sw1");
static Device dev2 = NetTestTools.device("sw2");
static Device dev3 = NetTestTools.device("sw3");
static PortNumber portNumber1 = PortNumber.portNumber(1);
static PortNumber portNumber2 = PortNumber.portNumber(2);
static PortNumber portNumber3 = PortNumber.portNumber(3);
static ConnectPoint src = new ConnectPoint(dev1.id(), portNumber2);
static ConnectPoint dst = new ConnectPoint(dev2.id(), portNumber2);
static DeviceListener deviceListener;
/**
* Test device manager. Returns a known set of devices and ports.
*/
static class TestDeviceManager extends DeviceServiceAdapter {
@Override
public Iterable<Device> getAvailableDevices() {
return ImmutableList.of(dev1, dev2);
}
@Override
public List<Port> getPorts(DeviceId deviceId) {
return ImmutableList.of(new DefaultPort(dev1, portNumber1, true),
new DefaultPort(dev2, portNumber2, true));
}
@Override
public void addListener(DeviceListener listener) {
deviceListener = listener;
}
@Override
public Device getDevice(DeviceId deviceId) {
if (deviceId.equals(dev1.id())) {
return dev1;
} else {
return dev2;
}
}
}
/**
* Test mastership service. All devices owned by the local node for testing.
*/
static class TestMastershipService extends MastershipServiceAdapter {
@Override
public boolean isLocalMaster(DeviceId deviceId) {
return true;
}
}
/**
* Test packet context for generation of LLDP packets.
*/
private class TestPacketContext implements PacketContext {
protected ConnectPoint src;
protected ConnectPoint dst;
protected boolean blocked = false;
public TestPacketContext(ConnectPoint src, ConnectPoint dst) {
this.src = src;
this.dst = dst;
}
@Override
public long time() {
return 0;
}
@Override
public InboundPacket inPacket() {
ONOSLLDP lldp = ONOSLLDP.onosLLDP(src.deviceId().toString(),
new ChassisId(),
(int) src.port().toLong());
Ethernet ethPacket = new Ethernet();
ethPacket.setEtherType(Ethernet.TYPE_LLDP);
ethPacket.setDestinationMACAddress(ONOSLLDP.LLDP_NICIRA);
ethPacket.setPayload(lldp);
ethPacket.setPad(true);
ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11");
return new DefaultInboundPacket(dst, ethPacket,
ByteBuffer.wrap(ethPacket.serialize()));
}
@Override
public OutboundPacket outPacket() {
return null;
}
@Override
public TrafficTreatment.Builder treatmentBuilder() {
return null;
}
@Override
public void send() {
}
@Override
public boolean block() {
blocked = true;
return true;
}
@Override
public boolean isHandled() {
return blocked;
}
}
/**
* Test packet service for capturing the packet processor from the service
* under test.
*/
private class TestPacketService extends PacketServiceAdapter {
@Override
public void addProcessor(PacketProcessor processor, int priority) {
testProcessor = processor;
}
}
/**
* Test network config registry. Captures the network config listener from
* the service under test.
*/
private final class TestNetworkConfigRegistry
extends NetworkConfigRegistryAdapter {
@Override
public void addListener(NetworkConfigListener listener) {
configListener = listener;
}
}
/**
* Sets up a network config links provider under test and the services
* required to run it.
*/
@Before
public void setUp() {
provider = new NetworkConfigLinksProvider();
provider.coreService = new CoreServiceAdapter();
provider.packetService = new PacketServiceAdapter();
LinkProviderRegistryAdapter linkRegistry =
new LinkProviderRegistryAdapter();
provider.providerRegistry = linkRegistry;
provider.deviceService = new TestDeviceManager();
provider.masterService = new TestMastershipService();
provider.packetService = new TestPacketService();
provider.metadataService = new ClusterMetadataServiceAdapter();
provider.netCfgService = configRegistry;
provider.activate();
providerService = linkRegistry.registeredProvider();
}
/**
* Tears down the provider under test.
*/
@After
public void tearDown() {
provider.deactivate();
}
/**
* Tests that a network config links provider object can be created.
* The actual creation is done in the setUp() method.
*/
@Test
public void testCreation() {
assertThat(provider, notNullValue());
assertThat(provider.configuredLinks, empty());
}
/**
* Tests loading of devices from the device manager.
*/
@Test
public void testDeviceLoad() {
assertThat(provider, notNullValue());
assertThat(provider.discoverers.entrySet(), hasSize(2));
}
/**
* Tests discovery of a link that is not expected in the configuration.
*/
@Test
public void testNotConfiguredLink() {
PacketContext pktCtx = new TestPacketContext(src, dst);
testProcessor.process(pktCtx);
assertThat(providerService.discoveredLinks().entrySet(), hasSize(1));
DeviceId destination = providerService.discoveredLinks().get(dev1.id());
assertThat(destination, notNullValue());
LinkKey key = LinkKey.linkKey(src, dst);
LinkDescription linkDescription = providerService
.discoveredLinkDescriptions().get(key);
assertThat(linkDescription, notNullValue());
assertThat(linkDescription.isExpected(), is(false));
}
/**
* Tests discovery of an expected link.
*/
@Test
public void testConfiguredLink() {
LinkKey key = LinkKey.linkKey(src, dst);
configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED,
key,
BasicLinkConfig.class));
PacketContext pktCtx = new TestPacketContext(src, dst);
testProcessor.process(pktCtx);
assertThat(providerService.discoveredLinks().entrySet(), hasSize(1));
DeviceId destination = providerService.discoveredLinks().get(dev1.id());
assertThat(destination, notNullValue());
LinkDescription linkDescription = providerService
.discoveredLinkDescriptions().get(key);
assertThat(linkDescription, notNullValue());
assertThat(linkDescription.isExpected(), is(true));
}
/**
* Tests removal of a link from the configuration.
*/
@Test
public void testRemoveLink() {
LinkKey key = LinkKey.linkKey(src, dst);
configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED,
key,
BasicLinkConfig.class));
assertThat(provider.configuredLinks, hasSize(1));
configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_REMOVED,
key,
BasicLinkConfig.class));
assertThat(provider.configuredLinks, hasSize(0));
}
/**
* Tests adding a new device via an event.
*/
@Test
public void testAddDevice() {
deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3));
assertThat(provider.discoverers.entrySet(), hasSize(3));
}
/**
* Tests adding a new port via an event.
*/
@Test
public void testAddPort() {
deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_ADDED, dev3,
new DefaultPort(dev3, portNumber3, true)));
assertThat(provider.discoverers.entrySet(), hasSize(3));
}
/**
* Tests removing a device via an event.
*/
@Test
public void testRemoveDevice() {
assertThat(provider.discoverers.entrySet(), hasSize(2));
deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3));
assertThat(provider.discoverers.entrySet(), hasSize(3));
deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, dev3));
assertThat(provider.discoverers.entrySet(), hasSize(2));
}
/**
* Tests removing a port via an event.
*/
@Test
public void testRemovePort() {
assertThat(provider.discoverers.entrySet(), hasSize(2));
deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_ADDED, dev3,
new DefaultPort(dev3, portNumber3, true)));
assertThat(provider.discoverers.entrySet(), hasSize(3));
deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_REMOVED, dev3,
new DefaultPort(dev3, portNumber3, true)));
assertThat(provider.discoverers.entrySet(), hasSize(3));
}
/**
* Tests changing device availability via an event.
*/
@Test
public void testDeviceAvailabilityChanged() {
assertThat(providerService.vanishedDpid(), hasSize(0));
deviceListener.event(
new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3));
assertThat(providerService.vanishedDpid(), hasSize(0));
deviceListener.event(
new DeviceEvent(DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED, dev3));
assertThat(providerService.vanishedDpid(), hasSize(1));
}
}
| |
package com.airbnb.lottie;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import android.view.View;
import android.view.animation.LinearInterpolator;
import java.util.ArrayList;
import java.util.List;
/**
* This can be used to show an lottie animation in any place that would normally take a drawable.
* If there are masks or mattes, then you MUST call {@link #recycleBitmaps()} when you are done
* or else you will leak bitmaps.
* <p>
* It is preferable to use {@link com.airbnb.lottie.LottieAnimationView} when possible because it
* handles bitmap recycling and asynchronous loading
* of compositions.
*/
public class LottieDrawable extends AnimatableLayer implements Drawable.Callback {
private LottieComposition composition;
private final ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
private float speed = 1f;
private float scale = 1f;
@Nullable private ImageAssetBitmapManager imageAssetBitmapManager;
@Nullable private String imageAssetsFolder;
@Nullable private ImageAssetDelegate imageAssetDelegate;
private boolean playAnimationWhenLayerAdded;
private boolean reverseAnimationWhenLayerAdded;
private boolean systemAnimationsAreDisabled;
@SuppressWarnings("WeakerAccess") public LottieDrawable() {
super(null);
animator.setRepeatCount(0);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
if (systemAnimationsAreDisabled) {
animator.cancel();
setProgress(1f);
} else {
setProgress((float) animation.getAnimatedValue());
}
}
});
}
/**
* Returns whether or not any layers in this composition has masks.
*/
@SuppressWarnings({"unused", "WeakerAccess"}) public boolean hasMasks() {
for (AnimatableLayer layer : layers) {
if (!(layer instanceof LayerView)) {
continue;
}
if (((LayerView) layer).hasMasks()){
return true;
}
}
return false;
}
/**
* Returns whether or not any layers in this composition has a matte layer.
*/
@SuppressWarnings({"unused", "WeakerAccess"}) public boolean hasMatte() {
for (AnimatableLayer layer : layers) {
if (!(layer instanceof LayerView)) {
continue;
}
if (((LayerView) layer).hasMatte()){
return true;
}
}
return false;
}
/**
* If you use image assets, you must explicitly specify the folder in assets/ in which they are
* located because bodymovin uses the name filenames across all compositions (img_#).
* Do NOT rename the images themselves.
*
* If your images are located in src/main/assets/airbnb_loader/ then call
* `setImageAssetsFolder("airbnb_loader/");`.
*
*
* If you use LottieDrawable directly, you MUST call {@link #recycleBitmaps()} when you
* are done. Calling {@link #recycleBitmaps()} doesn't have to be final and {@link LottieDrawable}
* will recreate the bitmaps if needed but they will leak if you don't recycle them.
*/
@SuppressWarnings("WeakerAccess") public void setImagesAssetsFolder(@Nullable String imageAssetsFolder) {
this.imageAssetsFolder = imageAssetsFolder;
}
/**
* If you have image assets and use {@link LottieDrawable} directly, you must call this yourself.
*
* Calling recycleBitmaps() doesn't have to be final and {@link LottieDrawable}
* will recreate the bitmaps if needed but they will leak if you don't recycle them.
*
*/
@SuppressWarnings("WeakerAccess") public void recycleBitmaps() {
if (imageAssetBitmapManager != null) {
imageAssetBitmapManager.recycleBitmaps();
}
}
/**
* @return True if the composition is different from the previously set composition, false otherwise.
*/
@SuppressWarnings("WeakerAccess") public boolean setComposition(LottieComposition composition) {
if (getCallback() == null) {
throw new IllegalStateException(
"You or your view must set a Drawable.Callback before setting the composition. This " +
"gets done automatically when added to an ImageView. " +
"Either call ImageView.setImageDrawable() before setComposition() or call " +
"setCallback(yourView.getCallback()) first.");
}
if (this.composition == composition) {
return false;
}
clearComposition();
this.composition = composition;
setSpeed(speed);
setScale(1f);
updateBounds();
buildLayersForComposition(composition);
setProgress(getProgress());
return true;
}
private void clearComposition() {
recycleBitmaps();
clearLayers();
imageAssetBitmapManager = null;
}
private void buildLayersForComposition(LottieComposition composition) {
if (composition == null) {
throw new IllegalStateException("Composition is null");
}
LongSparseArray<LayerView> layerMap = new LongSparseArray<>(composition.getLayers().size());
List<LayerView> layers = new ArrayList<>(composition.getLayers().size());
LayerView mattedLayer = null;
for (int i = composition.getLayers().size() - 1; i >= 0; i--) {
Layer layer = composition.getLayers().get(i);
LayerView layerView;
layerView = new LayerView(layer, composition, this);
layerMap.put(layerView.getId(), layerView);
if (mattedLayer != null) {
mattedLayer.setMatteLayer(layerView);
mattedLayer = null;
} else {
layers.add(layerView);
if (layer.getMatteType() == Layer.MatteType.Add) {
mattedLayer = layerView;
} else if (layer.getMatteType() == Layer.MatteType.Invert) {
mattedLayer = layerView;
}
}
}
for (int i = 0; i < layers.size(); i++) {
LayerView layerView = layers.get(i);
addLayer(layerView);
}
for (int i = 0; i < layerMap.size(); i++) {
long key = layerMap.keyAt(i);
LayerView layerView = layerMap.get(key);
LayerView parentLayer = layerMap.get(layerView.getLayerModel().getParentId());
if (parentLayer != null) {
layerView.setParentLayer(parentLayer);
}
}
}
@Override public void invalidateSelf() {
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateDrawable(this);
}
}
@Override public void draw(@NonNull Canvas canvas) {
if (composition == null) {
return;
}
int saveCount = canvas.save();
canvas.clipRect(0, 0, getIntrinsicWidth(), getIntrinsicHeight());
super.draw(canvas);
canvas.restoreToCount(saveCount);
}
void systemAnimationsAreDisabled() {
systemAnimationsAreDisabled = true;
}
void loop(boolean loop) {
animator.setRepeatCount(loop ? ValueAnimator.INFINITE : 0);
}
boolean isLooping() {
return animator.getRepeatCount() == ValueAnimator.INFINITE;
}
boolean isAnimating() {
return animator.isRunning();
}
@SuppressWarnings("WeakerAccess") public void playAnimation() {
playAnimation(false);
}
@SuppressWarnings("WeakerAccess") public void resumeAnimation() {
playAnimation(true);
}
private void playAnimation(boolean setStartTime) {
if (layers.isEmpty()) {
playAnimationWhenLayerAdded = true;
reverseAnimationWhenLayerAdded = false;
return;
}
if (setStartTime) {
animator.setCurrentPlayTime((long) (getProgress() * animator.getDuration()));
}
animator.start();
}
@SuppressWarnings({"unused", "WeakerAccess"}) public void resumeReverseAnimation() {
reverseAnimation(true);
}
@SuppressWarnings("WeakerAccess") public void reverseAnimation() {
reverseAnimation(false);
}
private void reverseAnimation(boolean setStartTime) {
if (layers.isEmpty()) {
playAnimationWhenLayerAdded = false;
reverseAnimationWhenLayerAdded = true;
return;
}
if (setStartTime) {
animator.setCurrentPlayTime((long) (getProgress() * animator.getDuration()));
}
animator.reverse();
}
@SuppressWarnings("WeakerAccess") public void setSpeed(float speed) {
this.speed = speed;
if (speed < 0) {
animator.setFloatValues(1f, 0f);
} else {
animator.setFloatValues(0f, 1f);
}
if (composition != null) {
animator.setDuration((long) (composition.getDuration() / Math.abs(speed)));
}
}
@SuppressWarnings("WeakerAccess") public void setScale(float scale) {
this.scale = scale;
updateBounds();
}
/**
* Use this if you can't bundle images with your app. This may be useful if you download the
* animations from the network or have the images saved to an SD Card. In that case, Lottie
* will defer the loading of the bitmap to this delegate.
*/
@SuppressWarnings({"unused", "WeakerAccess"}) public void setImageAssetDelegate(
@SuppressWarnings("NullableProblems") ImageAssetDelegate assetDelegate) {
this.imageAssetDelegate = assetDelegate;
if (imageAssetBitmapManager != null) {
imageAssetBitmapManager.setAssetDelegate(assetDelegate);
}
}
@SuppressWarnings("WeakerAccess") public float getScale() {
return scale;
}
private void updateBounds() {
if (composition == null) {
return;
}
setBounds(0, 0, (int) (composition.getBounds().width() * scale),
(int) (composition.getBounds().height() * scale));
}
void cancelAnimation() {
playAnimationWhenLayerAdded = false;
reverseAnimationWhenLayerAdded = false;
animator.cancel();
}
@Override
void addLayer(AnimatableLayer layer) {
super.addLayer(layer);
if (playAnimationWhenLayerAdded) {
playAnimationWhenLayerAdded = false;
playAnimation();
}
if (reverseAnimationWhenLayerAdded) {
reverseAnimationWhenLayerAdded = false;
reverseAnimation();
}
}
void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
animator.addUpdateListener(updateListener);
}
void removeAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
animator.removeUpdateListener(updateListener);
}
void addAnimatorListener(Animator.AnimatorListener listener) {
animator.addListener(listener);
}
void removeAnimatorListener(Animator.AnimatorListener listener) {
animator.removeListener(listener);
}
@Override public int getIntrinsicWidth() {
return composition == null ? -1 : (int) (composition.getBounds().width() * scale);
}
@Override public int getIntrinsicHeight() {
return composition == null ? -1 : (int) (composition.getBounds().height() * scale);
}
Bitmap getImageAsset(String id) {
return getImageAssetBitmapManager().bitmapForId(id);
}
private ImageAssetBitmapManager getImageAssetBitmapManager() {
if (imageAssetBitmapManager != null && !imageAssetBitmapManager.hasSameContext(getContext())) {
imageAssetBitmapManager.recycleBitmaps();
imageAssetBitmapManager = null;
}
if (imageAssetBitmapManager == null) {
imageAssetBitmapManager = new ImageAssetBitmapManager(getCallback(),
imageAssetsFolder, imageAssetDelegate, composition.getImages());
}
return imageAssetBitmapManager;
}
private @Nullable Context getContext() {
Callback callback = getCallback();
if (callback == null) {
return null;
}
if (callback instanceof View) {
return ((View) callback).getContext();
}
return null;
}
/**
* These Drawable.Callback methods proxy the calls so that this is the drawable that is
* actually invalidated, not a child one which will not pass the view's validateDrawable check.
*/
@Override public void invalidateDrawable(Drawable who) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.invalidateDrawable(this);
}
@Override public void scheduleDrawable(Drawable who, Runnable what, long when) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.scheduleDrawable(this, what, when);
}
@Override public void unscheduleDrawable(Drawable who, Runnable what) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.unscheduleDrawable(this, what);
}
}
| |
package org.apache.archiva.maven.proxy;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.policies.CachedFailuresPolicy;
import org.apache.archiva.policies.ChecksumPolicy;
import org.apache.archiva.policies.PolicyOption;
import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
import org.apache.archiva.policies.ProxyDownloadException;
import org.apache.archiva.policies.ReleasesPolicy;
import org.apache.archiva.policies.SnapshotsPolicy;
import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
import org.apache.archiva.repository.content.LayoutException;
import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.junit.Test;
import org.mockito.stubbing.Stubber;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
/**
* ErrorHandlingTest
*
*
*/
public class ErrorHandlingTest
extends AbstractProxyTestCase
{
private static final String PATH_IN_BOTH_REMOTES_NOT_LOCAL =
"org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
private static final String PATH_IN_BOTH_REMOTES_AND_LOCAL =
"org/apache/maven/test/get-on-multiple-repos/1.0/get-on-multiple-repos-1.0.pom";
private static final String ID_MOCKED_PROXIED1 = "badproxied1";
private static final String NAME_MOCKED_PROXIED1 = "Bad Proxied 1";
private static final String ID_MOCKED_PROXIED2 = "badproxied2";
private static final String NAME_MOCKED_PROXIED2 = "Bad Proxied 2";
@Test
public void testPropagateErrorImmediatelyWithErrorThenSuccess()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateErrorImmediatelyWithNotFoundThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
simulateGetError( path, expectedFile, Arrays.asList( createResourceNotFoundException( ), createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
}
@Test
public void testPropagateErrorImmediatelyWithSuccessThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
}
@Test
public void testPropagateErrorImmediatelyWithNotFoundThenSuccess()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
simulateGetError( path, expectedFile, Arrays.asList( createResourceNotFoundException( ) ) );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
}
@Test
public void testPropagateErrorAtEndWithErrorThenSuccess()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateErrorAtEndWithSuccessThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
}
@Test
public void testPropagateErrorAtEndWithNotFoundThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
simulateGetError( path, expectedFile, Arrays.asList( createResourceNotFoundException( ), createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
}
@Test
public void testPropagateErrorAtEndWithErrorThenNotFound()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createResourceNotFoundException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateErrorAtEndWithErrorThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmFailures( path, new String[]{ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2} );
}
@Test
public void testPropagateErrorAtEndWithNotFoundThenSuccess()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
simulateGetError( path, expectedFile, Arrays.asList( createResourceNotFoundException( ) ) );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
}
@Test
public void testIgnoreErrorWithErrorThenSuccess()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ) ) );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
}
@Test
public void testIgnoreErrorWithSuccessThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
}
@Test
public void testIgnoreErrorWithNotFoundThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
simulateGetError( path, expectedFile, Arrays.asList( createResourceNotFoundException( ), createTransferException( ) ) );
confirmNotDownloadedNoError( path );
}
@Test
public void testIgnoreErrorWithErrorThenNotFound()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createResourceNotFoundException( ) ) );
confirmNotDownloadedNoError( path );
}
@Test
public void testIgnoreErrorWithErrorThenError()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmNotDownloadedNoError( path );
}
@Test
public void testPropagateOnUpdateAlwaysArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateOnUpdateAlwaysArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateOnUpdateAlwaysQueueArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
}
@Test
public void testPropagateOnUpdateAlwaysQueueArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
}
@Test
public void testPropagateOnUpdateAlwaysIgnoreArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmNotDownloadedNoError( path );
}
@Test
public void testPropagateOnUpdateAlwaysIgnoreArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmNotDownloadedNoError( path );
assertTrue( Files.exists(expectedFile) );
}
@Test
public void testPropagateOnUpdateNotPresentArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ) ) );
confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
}
@Test
public void testPropagateOnUpdateNotPresentArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmNotDownloadedNoError( path );
assertTrue( Files.exists(expectedFile) );
}
@Test
public void testPropagateOnUpdateNotPresentQueueArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
}
@Test
public void testPropagateOnUpdateNotPresentQueueArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmNotDownloadedNoError( path );
assertTrue( Files.exists(expectedFile));
}
@Test
public void testPropagateOnUpdateNotPresentIgnoreArtifactNotPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetError( path, expectedFile, Arrays.asList( createTransferException( ), createTransferException( ) ) );
confirmNotDownloadedNoError( path );
}
@Test
public void testPropagateOnUpdateNotPresentIgnoreArtifactPresent()
throws Exception
{
String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
simulateGetIfNewerError( path, expectedFile, createTransferException() );
confirmNotDownloadedNoError( path );
assertTrue( Files.exists(expectedFile));
}
// ------------------------------------------
// HELPER METHODS
// ------------------------------------------
private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy )
{
saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
CachedFailuresPolicy.NO, errorPolicy, false );
}
private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy, PolicyOption errorOnUpdatePolicy )
{
saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
CachedFailuresPolicy.NO, errorPolicy, errorOnUpdatePolicy, false );
}
private Path setupRepositoriesWithLocalFileNotPresent( String path )
throws Exception
{
setupTestableManagedRepository( path );
Path file = managedDefaultDir.resolve( path );
assertNotExistsInManagedDefaultRepo( file );
return file;
}
private Path setupRepositoriesWithLocalFilePresent( String path )
throws Exception
{
setupTestableManagedRepository( path );
Path file = managedDefaultDir.resolve( path );
assertTrue( Files.exists(file) );
return file;
}
private void simulateGetError( String path, Path expectedFile, List<Exception> throwables )
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
{
Stubber stubber = doThrow( throwables.get( 0 ) );
if (throwables.size()>1) {
for(int i=1; i<throwables.size(); i++)
{
stubber = stubber.doThrow( throwables.get( i ) );
}
}
stubber.when( wagonMock ).get( eq( path ), any( ) );
}
private void simulateGetIfNewerError( String path, Path expectedFile, TransferFailedException exception )
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException, IOException
{
doThrow( exception ).when( wagonMock ).getIfNewer( eq( path ), any( ), eq( Files.getLastModifiedTime( expectedFile ).toMillis( ) ) );
}
private Path createExpectedTempFile( Path expectedFile )
{
return managedDefaultDir.resolve(expectedFile.getFileName().toString() + ".tmp" ).toAbsolutePath();
}
private void confirmSingleFailure( String path, String id )
throws LayoutException
{
confirmFailures( path, new String[]{id} );
}
private void confirmFailures( String path, String[] ids )
throws LayoutException
{
// Attempt the proxy fetch.
StorageAsset downloadedFile = null;
try
{
BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
layout.getArtifact( path ) );
fail( "Proxy should not have succeeded" );
}
catch ( ProxyDownloadException e )
{
assertEquals( ids.length, e.getFailures().size() );
for ( String id : ids )
{
assertTrue( e.getFailures().keySet().contains( id ) );
}
}
assertNotDownloaded( downloadedFile );
}
private void confirmSuccess( String path, Path expectedFile, String basedir )
throws Exception
{
StorageAsset downloadedFile = performDownload( path );
Path proxied1File = Paths.get( basedir, path );
assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied1File );
}
private void confirmNotDownloadedNoError( String path )
throws Exception
{
StorageAsset downloadedFile = performDownload( path );
assertNotDownloaded( downloadedFile );
}
private StorageAsset performDownload( String path )
throws ProxyDownloadException, LayoutException
{
// Attempt the proxy fetch.
BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
layout.getArtifact( path ) );
return downloadedFile;
}
private static TransferFailedException createTransferException()
{
return new TransferFailedException( "test download exception" );
}
private static ResourceDoesNotExistException createResourceNotFoundException()
{
return new ResourceDoesNotExistException( "test download not found" );
}
}
| |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p/>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyEventSubscription" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModifyEventSubscriptionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the modified Amazon Redshift event notification subscription.
* </p>
*/
private String subscriptionName;
/**
* <p>
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
* </p>
*/
private String snsTopicArn;
/**
* <p>
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events are
* returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order to specify
* source IDs.
* </p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
* </p>
*/
private String sourceType;
/**
* <p>
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type
* as was specified in the source type parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects within the source type specified.
* </p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> sourceIds;
/**
* <p>
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.
* </p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> eventCategories;
/**
* <p>
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.
* </p>
* <p>
* Values: ERROR, INFO
* </p>
*/
private String severity;
/**
* <p>
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* </p>
*/
private Boolean enabled;
/**
* <p>
* The name of the modified Amazon Redshift event notification subscription.
* </p>
*
* @param subscriptionName
* The name of the modified Amazon Redshift event notification subscription.
*/
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
/**
* <p>
* The name of the modified Amazon Redshift event notification subscription.
* </p>
*
* @return The name of the modified Amazon Redshift event notification subscription.
*/
public String getSubscriptionName() {
return this.subscriptionName;
}
/**
* <p>
* The name of the modified Amazon Redshift event notification subscription.
* </p>
*
* @param subscriptionName
* The name of the modified Amazon Redshift event notification subscription.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSubscriptionName(String subscriptionName) {
setSubscriptionName(subscriptionName);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
* </p>
*
* @param snsTopicArn
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
*/
public void setSnsTopicArn(String snsTopicArn) {
this.snsTopicArn = snsTopicArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
* </p>
*
* @return The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
*/
public String getSnsTopicArn() {
return this.snsTopicArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
* </p>
*
* @param snsTopicArn
* The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSnsTopicArn(String snsTopicArn) {
setSnsTopicArn(snsTopicArn);
return this;
}
/**
* <p>
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events are
* returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order to specify
* source IDs.
* </p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
* </p>
*
* @param sourceType
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events
* are returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order
* to specify source IDs.</p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
*/
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
/**
* <p>
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events are
* returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order to specify
* source IDs.
* </p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
* </p>
*
* @return The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events
* are returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order
* to specify source IDs.</p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
*/
public String getSourceType() {
return this.sourceType;
}
/**
* <p>
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events are
* returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order to specify
* source IDs.
* </p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
* </p>
*
* @param sourceType
* The type of source that will be generating the events. For example, if you want to be notified of events
* generated by a cluster, you would set this parameter to cluster. If this value is not specified, events
* are returned for all Amazon Redshift objects in your AWS account. You must specify a source type in order
* to specify source IDs.</p>
* <p>
* Valid values: cluster, cluster-parameter-group, cluster-security-group, and cluster-snapshot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSourceType(String sourceType) {
setSourceType(sourceType);
return this;
}
/**
* <p>
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type
* as was specified in the source type parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects within the source type specified.
* </p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* </p>
*
* @return A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the
* same type as was specified in the source type parameter. The event subscription will return only events
* generated by the specified objects. If not specified, then events are returned for all objects within the
* source type specified.</p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
*/
public java.util.List<String> getSourceIds() {
if (sourceIds == null) {
sourceIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return sourceIds;
}
/**
* <p>
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type
* as was specified in the source type parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects within the source type specified.
* </p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* </p>
*
* @param sourceIds
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the
* same type as was specified in the source type parameter. The event subscription will return only events
* generated by the specified objects. If not specified, then events are returned for all objects within the
* source type specified.</p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
*/
public void setSourceIds(java.util.Collection<String> sourceIds) {
if (sourceIds == null) {
this.sourceIds = null;
return;
}
this.sourceIds = new com.amazonaws.internal.SdkInternalList<String>(sourceIds);
}
/**
* <p>
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type
* as was specified in the source type parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects within the source type specified.
* </p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSourceIds(java.util.Collection)} or {@link #withSourceIds(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param sourceIds
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the
* same type as was specified in the source type parameter. The event subscription will return only events
* generated by the specified objects. If not specified, then events are returned for all objects within the
* source type specified.</p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSourceIds(String... sourceIds) {
if (this.sourceIds == null) {
setSourceIds(new com.amazonaws.internal.SdkInternalList<String>(sourceIds.length));
}
for (String ele : sourceIds) {
this.sourceIds.add(ele);
}
return this;
}
/**
* <p>
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type
* as was specified in the source type parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects within the source type specified.
* </p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* </p>
*
* @param sourceIds
* A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the
* same type as was specified in the source type parameter. The event subscription will return only events
* generated by the specified objects. If not specified, then events are returned for all objects within the
* source type specified.</p>
* <p>
* Example: my-cluster-1, my-cluster-2
* </p>
* <p>
* Example: my-snapshot-20131010
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSourceIds(java.util.Collection<String> sourceIds) {
setSourceIds(sourceIds);
return this;
}
/**
* <p>
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.
* </p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* </p>
*
* @return Specifies the Amazon Redshift event categories to be published by the event notification
* subscription.</p>
* <p>
* Values: Configuration, Management, Monitoring, Security
*/
public java.util.List<String> getEventCategories() {
if (eventCategories == null) {
eventCategories = new com.amazonaws.internal.SdkInternalList<String>();
}
return eventCategories;
}
/**
* <p>
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.
* </p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* </p>
*
* @param eventCategories
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.</p>
* <p>
* Values: Configuration, Management, Monitoring, Security
*/
public void setEventCategories(java.util.Collection<String> eventCategories) {
if (eventCategories == null) {
this.eventCategories = null;
return;
}
this.eventCategories = new com.amazonaws.internal.SdkInternalList<String>(eventCategories);
}
/**
* <p>
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.
* </p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setEventCategories(java.util.Collection)} or {@link #withEventCategories(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param eventCategories
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.</p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withEventCategories(String... eventCategories) {
if (this.eventCategories == null) {
setEventCategories(new com.amazonaws.internal.SdkInternalList<String>(eventCategories.length));
}
for (String ele : eventCategories) {
this.eventCategories.add(ele);
}
return this;
}
/**
* <p>
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.
* </p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* </p>
*
* @param eventCategories
* Specifies the Amazon Redshift event categories to be published by the event notification subscription.</p>
* <p>
* Values: Configuration, Management, Monitoring, Security
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withEventCategories(java.util.Collection<String> eventCategories) {
setEventCategories(eventCategories);
return this;
}
/**
* <p>
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.
* </p>
* <p>
* Values: ERROR, INFO
* </p>
*
* @param severity
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.</p>
* <p>
* Values: ERROR, INFO
*/
public void setSeverity(String severity) {
this.severity = severity;
}
/**
* <p>
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.
* </p>
* <p>
* Values: ERROR, INFO
* </p>
*
* @return Specifies the Amazon Redshift event severity to be published by the event notification subscription.</p>
* <p>
* Values: ERROR, INFO
*/
public String getSeverity() {
return this.severity;
}
/**
* <p>
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.
* </p>
* <p>
* Values: ERROR, INFO
* </p>
*
* @param severity
* Specifies the Amazon Redshift event severity to be published by the event notification subscription.</p>
* <p>
* Values: ERROR, INFO
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withSeverity(String severity) {
setSeverity(severity);
return this;
}
/**
* <p>
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* </p>
*
* @param enabled
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
/**
* <p>
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* </p>
*
* @return A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription
* is enabled
*/
public Boolean getEnabled() {
return this.enabled;
}
/**
* <p>
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* </p>
*
* @param enabled
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyEventSubscriptionRequest withEnabled(Boolean enabled) {
setEnabled(enabled);
return this;
}
/**
* <p>
* A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription is
* enabled
* </p>
*
* @return A Boolean value indicating if the subscription is enabled. <code>true</code> indicates the subscription
* is enabled
*/
public Boolean isEnabled() {
return this.enabled;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSubscriptionName() != null)
sb.append("SubscriptionName: ").append(getSubscriptionName()).append(",");
if (getSnsTopicArn() != null)
sb.append("SnsTopicArn: ").append(getSnsTopicArn()).append(",");
if (getSourceType() != null)
sb.append("SourceType: ").append(getSourceType()).append(",");
if (getSourceIds() != null)
sb.append("SourceIds: ").append(getSourceIds()).append(",");
if (getEventCategories() != null)
sb.append("EventCategories: ").append(getEventCategories()).append(",");
if (getSeverity() != null)
sb.append("Severity: ").append(getSeverity()).append(",");
if (getEnabled() != null)
sb.append("Enabled: ").append(getEnabled());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ModifyEventSubscriptionRequest == false)
return false;
ModifyEventSubscriptionRequest other = (ModifyEventSubscriptionRequest) obj;
if (other.getSubscriptionName() == null ^ this.getSubscriptionName() == null)
return false;
if (other.getSubscriptionName() != null && other.getSubscriptionName().equals(this.getSubscriptionName()) == false)
return false;
if (other.getSnsTopicArn() == null ^ this.getSnsTopicArn() == null)
return false;
if (other.getSnsTopicArn() != null && other.getSnsTopicArn().equals(this.getSnsTopicArn()) == false)
return false;
if (other.getSourceType() == null ^ this.getSourceType() == null)
return false;
if (other.getSourceType() != null && other.getSourceType().equals(this.getSourceType()) == false)
return false;
if (other.getSourceIds() == null ^ this.getSourceIds() == null)
return false;
if (other.getSourceIds() != null && other.getSourceIds().equals(this.getSourceIds()) == false)
return false;
if (other.getEventCategories() == null ^ this.getEventCategories() == null)
return false;
if (other.getEventCategories() != null && other.getEventCategories().equals(this.getEventCategories()) == false)
return false;
if (other.getSeverity() == null ^ this.getSeverity() == null)
return false;
if (other.getSeverity() != null && other.getSeverity().equals(this.getSeverity()) == false)
return false;
if (other.getEnabled() == null ^ this.getEnabled() == null)
return false;
if (other.getEnabled() != null && other.getEnabled().equals(this.getEnabled()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSubscriptionName() == null) ? 0 : getSubscriptionName().hashCode());
hashCode = prime * hashCode + ((getSnsTopicArn() == null) ? 0 : getSnsTopicArn().hashCode());
hashCode = prime * hashCode + ((getSourceType() == null) ? 0 : getSourceType().hashCode());
hashCode = prime * hashCode + ((getSourceIds() == null) ? 0 : getSourceIds().hashCode());
hashCode = prime * hashCode + ((getEventCategories() == null) ? 0 : getEventCategories().hashCode());
hashCode = prime * hashCode + ((getSeverity() == null) ? 0 : getSeverity().hashCode());
hashCode = prime * hashCode + ((getEnabled() == null) ? 0 : getEnabled().hashCode());
return hashCode;
}
@Override
public ModifyEventSubscriptionRequest clone() {
return (ModifyEventSubscriptionRequest) super.clone();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package
///////////////
package org.apache.jena.ontology.impl;
// Imports
///////////////
import java.util.List;
import junit.framework.TestSuite;
import org.apache.jena.ontology.* ;
import org.apache.jena.rdf.model.ModelFactory ;
import org.apache.jena.rdf.model.Property ;
import org.apache.jena.reasoner.test.TestUtil ;
import org.apache.jena.util.FileManager ;
import org.apache.jena.vocabulary.RDF ;
/**
* <p>
* Unit test cases for the OntProperty class
* </p>
*/
public class TestProperty
extends OntTestBase
{
// Constants
//////////////////////////////////
// Static variables
//////////////////////////////////
// Instance variables
//////////////////////////////////
// Constructors
//////////////////////////////////
static public TestSuite suite() {
return new TestProperty( "TestProperty" );
}
public TestProperty( String name ) {
super( name );
}
// External signature methods
//////////////////////////////////
@Override
public OntTestCase[] getTests() {
return new OntTestCase[] {
new OntTestCase( "OntProperty.super-property", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createOntProperty( NS + "p" );
OntProperty q = m.createOntProperty( NS + "q" );
OntProperty r = m.createOntProperty( NS + "r" );
p.addSuperProperty( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.SUB_PROPERTY_OF() ) );
assertEquals( "p have super-prop q", q, p.getSuperProperty() );
p.addSuperProperty( r );
assertEquals( "Cardinality should be 2", 2, p.getCardinality( prof.SUB_PROPERTY_OF() ) );
iteratorTest( p.listSuperProperties(), new Object[] {q, r} );
p.setSuperProperty( r );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.SUB_PROPERTY_OF() ) );
assertEquals( "p shuold have super-prop r", r, p.getSuperProperty() );
p.removeSuperProperty( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.SUB_PROPERTY_OF() ) );
p.removeSuperProperty( r );
assertEquals( "Cardinality should be 0", 0, p.getCardinality( prof.SUB_PROPERTY_OF() ) );
// for symmetry with listSuperClasses(), exclude the reflexive case
List<? extends OntProperty> sp = p.listSuperProperties().toList();
assertFalse( "super-properties should not include reflexive case", sp.contains( p ) );
}
},
new OntTestCase( "OntProperty.sub-property", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createOntProperty( NS + "p" );
OntProperty q = m.createOntProperty( NS + "q" );
OntProperty r = m.createOntProperty( NS + "r" );
p.addSubProperty( q );
assertEquals( "Cardinality should be 1", 1, q.getCardinality( prof.SUB_PROPERTY_OF() ) );
assertEquals( "p have sub-prop q", q, p.getSubProperty() );
p.addSubProperty( r );
assertEquals( "Cardinality should be 2", 2, q.getCardinality( prof.SUB_PROPERTY_OF() ) + r.getCardinality( prof.SUB_PROPERTY_OF() ) );
iteratorTest( p.listSubProperties(), new Object[] {q, r} );
iteratorTest( q.listSuperProperties(), new Object[] {p} );
iteratorTest( r.listSuperProperties(), new Object[] {p} );
p.setSubProperty( r );
assertEquals( "Cardinality should be 1", 1, q.getCardinality( prof.SUB_PROPERTY_OF() ) + r.getCardinality( prof.SUB_PROPERTY_OF() ) );
assertEquals( "p should have sub-prop r", r, p.getSubProperty() );
p.removeSubProperty( q );
assertTrue( "Should have sub-prop r", p.hasSubProperty( r, false ) );
p.removeSubProperty( r );
assertTrue( "Should not have sub-prop r", !p.hasSubProperty( r, false ) );
}
},
new OntTestCase( "OntProperty.domain", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createOntProperty( NS + "p" );
OntResource a = m.getResource( NS + "a" ).as( OntResource.class );
OntResource b = m.getResource( NS + "b" ).as( OntResource.class );
p.addDomain( a );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.DOMAIN() ) );
assertEquals( "p have domain a", a, p.getDomain() );
p.addDomain( b );
assertEquals( "Cardinality should be 2", 2, p.getCardinality( prof.DOMAIN() ) );
iteratorTest( p.listDomain(), new Object[] {a, b} );
p.setDomain( b );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.DOMAIN() ) );
assertEquals( "p should have domain b", b, p.getDomain() );
p.removeDomain( a );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.DOMAIN() ) );
p.removeDomain( b );
assertEquals( "Cardinality should be 0", 0, p.getCardinality( prof.DOMAIN() ) );
}
},
new OntTestCase( "OntProperty.range", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createOntProperty( NS + "p" );
OntResource a = m.getResource( NS + "a" ).as( OntResource.class );
OntResource b = m.getResource( NS + "b" ).as( OntResource.class );
p.addRange( a );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.RANGE() ) );
assertEquals( "p have range a", a, p.getRange() );
p.addRange( b );
assertEquals( "Cardinality should be 2", 2, p.getCardinality( prof.RANGE() ) );
iteratorTest( p.listRange(), new Object[] {a, b} );
p.setRange( b );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.RANGE() ) );
assertEquals( "p should have range b", b, p.getRange() );
p.removeRange( a );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.RANGE() ) );
p.removeRange( b );
assertEquals( "Cardinality should be 0", 0, p.getCardinality( prof.RANGE() ) );
}
},
new OntTestCase( "OntProperty.equivalentProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createObjectProperty( NS + "p" );
OntProperty q = m.createObjectProperty( NS + "q" );
OntProperty r = m.createObjectProperty( NS + "r" );
p.addEquivalentProperty( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.EQUIVALENT_PROPERTY() ) );
assertEquals( "p have equivalentProperty q", q, p.getEquivalentProperty() );
p.addEquivalentProperty( r );
assertEquals( "Cardinality should be 2", 2, p.getCardinality( prof.EQUIVALENT_PROPERTY() ) );
iteratorTest( p.listEquivalentProperties(), new Object[] {q,r} );
p.setEquivalentProperty( r );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.EQUIVALENT_PROPERTY() ) );
assertEquals( "p should have equivalentProperty r", r, p.getEquivalentProperty() );
p.removeEquivalentProperty( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.EQUIVALENT_PROPERTY() ) );
p.removeEquivalentProperty( r );
assertEquals( "Cardinality should be 0", 0, p.getCardinality( prof.EQUIVALENT_PROPERTY() ) );
}
},
new OntTestCase( "OntProperty.inverseOf", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Profile prof = m.getProfile();
OntProperty p = m.createObjectProperty( NS + "p" );
OntProperty q = m.createObjectProperty( NS + "q" );
OntProperty r = m.createObjectProperty( NS + "r" );
assertFalse( p.isInverseOf( q ) );
assertEquals( null, p.getInverseOf() );
p.addInverseOf( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.INVERSE_OF() ) );
assertEquals( "p should have inverse q", q, p.getInverseOf() );
assertTrue( "inverse value should be an object property", p.getInverseOf() instanceof ObjectProperty );
assertTrue( "inverse value should be an object property", q.getInverse() instanceof ObjectProperty );
p.addInverseOf( r );
assertEquals( "Cardinality should be 2", 2, p.getCardinality( prof.INVERSE_OF() ) );
iteratorTest( p.listInverseOf(), new Object[] {q,r} );
p.setInverseOf( r );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.INVERSE_OF() ) );
assertEquals( "p should have inverse r", r, p.getInverseOf() );
p.removeInverseProperty( q );
assertEquals( "Cardinality should be 1", 1, p.getCardinality( prof.INVERSE_OF() ) );
p.removeInverseProperty( r );
assertEquals( "Cardinality should be 0", 0, p.getCardinality( prof.INVERSE_OF() ) );
}
},
new OntTestCase( "OntProperty.subproperty.fromFile", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
String lang = m_owlLang ? "owl" : "rdfs" ;
String fileName = "file:testing/ontology/" + lang + "/Property/test.rdf";
m.read( fileName );
OntProperty p = m.getProperty( NS, "p" ).as( OntProperty.class );
OntProperty q = m.getProperty( NS, "q" ).as( OntProperty.class );
iteratorTest( p.listSuperProperties(), new Object[] {q} );
iteratorTest( q.listSubProperties(), new Object[] {p} );
}
},
new OntTestCase( "OntProperty.domain.fromFile", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
String lang = m_owlLang ? "owl" : "rdfs" ;
String fileName = "file:testing/ontology/" + lang + "/Property/test.rdf";
m.read( fileName );
OntProperty p = m.getProperty( NS, "p" ).as( OntProperty.class );
OntClass A = m.getResource( NS + "ClassA").as( OntClass.class);
assertTrue( "p should have domain A", p.hasDomain( A ) );
}
},
new OntTestCase( "OntProperty.range.fromFile", true, true, true ) {
@Override
public void ontTest( OntModel m ) {
String lang = m_owlLang ? "owl" : "rdfs" ;
String fileName = "file:testing/ontology/" + lang + "/Property/test.rdf";
m.read( fileName );
OntProperty p = m.getProperty( NS, "p" ).as( OntProperty.class );
OntClass B = m.getResource( NS + "ClassB").as( OntClass.class);
assertTrue( "p should have domain B", p.hasRange( B ) );
}
},
new OntTestCase( "OntProperty.equivalentProeprty.fromFile", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
String lang = m_owlLang ? "owl" : "rdfs" ;
String fileName = "file:testing/ontology/" + lang + "/Property/test.rdf";
m.read( fileName );
OntProperty p = m.getProperty( NS, "p" ).as( OntProperty.class );
OntProperty r = m.getProperty( NS, "r" ).as( OntProperty.class );
assertTrue( "p should have equiv prop r", p.hasEquivalentProperty( r ) );
}
},
new OntTestCase( "OntProperty.inversePropertyOf.fromFile", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
String lang = m_owlLang ? "owl" : "rdfs" ;
String fileName = "file:testing/ontology/" + lang + "/Property/test.rdf";
m.read( fileName );
OntProperty p = m.getProperty( NS, "p" ).as( OntProperty.class );
OntProperty s = m.getProperty( NS, "s" ).as( OntProperty.class );
assertTrue( "p should have inv prop s", p.isInverseOf( s ) );
}
},
// type tests
new OntTestCase( "OntProperty.isFunctionalProperty dt", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createDatatypeProperty( NS + "p", true );
assertTrue( "isFunctionalProperty not correct", p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isFunctionalProperty object", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createObjectProperty( NS + "p", true );
assertTrue( "isFunctionalProperty not correct", p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isDatatypeProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createDatatypeProperty( NS + "p", false );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isObjectProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createObjectProperty( NS + "p", false );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isTransitiveProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createTransitiveProperty( NS + "p" );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() ); // this should be true by entailment, but we have reasoning switched off
assertTrue( "isTransitiveProperty not correct", p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isInverseFunctionalProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createInverseFunctionalProperty( NS + "p" );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() ); // this should be true by entailment, but we have reasoning switched off
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.isSymmetricProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
OntProperty p = m.createSymmetricProperty( NS + "p" );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() ); // this should be true by entailment, but we have reasoning switched off
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {
assertTrue( "isSymmetricProperty not correct", p.isSymmetricProperty() );
}
}
},
new OntTestCase( "OntProperty.convertToFunctionalProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToFunctionalProperty();
assertTrue( "isFunctionalProperty not correct", p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
}
},
new OntTestCase( "OntProperty.convertToDatatypeProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToDatatypeProperty();
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
}
},
new OntTestCase( "OntProperty.convertToObjectProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToObjectProperty();
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
}
},
new OntTestCase( "OntProperty.convertToTransitiveProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToTransitiveProperty();
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
}
},
new OntTestCase( "OntProperty.convertToInverseFunctionalProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToInverseFunctionalProperty();
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
}
},
new OntTestCase( "OntProperty.convertToSymmetricProperty", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
Property pSimple = m.createProperty( NS, "p" );
pSimple.addProperty( RDF.type, RDF.Property );
OntProperty p = pSimple.as( OntProperty.class );
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", !p.isSymmetricProperty() ); }
p = p.convertToSymmetricProperty();
assertTrue( "isFunctionalProperty not correct", !p.isFunctionalProperty() );
assertTrue( "isDatatypeProperty not correct", !p.isDatatypeProperty() );
assertTrue( "isObjectProperty not correct", !p.isObjectProperty() );
assertTrue( "isTransitiveProperty not correct", !p.isTransitiveProperty() );
assertTrue( "isInverseFunctionalProperty not correct", !p.isInverseFunctionalProperty() );
if (m_owlLang) {assertTrue( "isSymmetricProperty not correct", p.isSymmetricProperty() ); }
}
},
new OntTestCase( "ObjectProperty.inverse", true, true, false ) {
@Override
public void ontTest( OntModel m ) {
ObjectProperty p = m.createObjectProperty( NS + "p" );
ObjectProperty q = m.createObjectProperty( NS + "q" );
ObjectProperty r = m.createObjectProperty( NS + "r" );
assertFalse( "No inverse of p", p.hasInverse() );
assertEquals( null, p.getInverse() );
q.addInverseOf( p );
assertTrue( "Inverse of p", p.hasInverse() );
assertEquals( "inverse of p ", q, p.getInverse() );
r.addInverseOf( p );
iteratorTest( p.listInverse(), new Object[] {q,r} );
}
},
new OntTestCase( "OntProperty.listReferringRestrictions", true, true, false ) {
@Override
protected void ontTest( OntModel m ) {
ObjectProperty p = m.createObjectProperty( NS+"p" );
ObjectProperty q = m.createObjectProperty( NS+"q" );
Restriction r0 = m.createCardinalityRestriction( null, p, 2 );
Restriction r1 = m.createCardinalityRestriction( null, p, 3 );
Restriction r2 = m.createCardinalityRestriction( null, q, 2 );
Restriction r3 = m.createCardinalityRestriction( null, q, 3 );
assertTrue( iteratorContains( p.listReferringRestrictions(), r0 ) );
assertTrue( iteratorContains( p.listReferringRestrictions(), r1 ) );
assertFalse( iteratorContains( p.listReferringRestrictions(), r2 ) );
assertFalse( iteratorContains( p.listReferringRestrictions(), r3 ) );
assertNotNull( p.listReferringRestrictions().next() );
}
},
new OntTestCase( "no duplication from imported models", true, true, true ) {
@Override
protected void ontTest( OntModel m ) {
OntModel m0 = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM_RULE_INF, null );
FileManager.get().readModel( m0, "file:testing/ontology/testImport9/a.ttl" );
OntProperty p0 = m0.getOntProperty( "http://incubator.apache.org/jena/2011/10/testont/b#propB" );
TestUtil.assertIteratorLength( p0.listDomain(), 3 );
// repeat test - thus using previously cached model for import
OntModel m1 = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM_RULE_INF, null );
FileManager.get().readModel( m1, "file:testing/ontology/testImport9/a.ttl" );
OntProperty p1 = m1.getOntProperty( "http://incubator.apache.org/jena/2011/10/testont/b#propB" );
TestUtil.assertIteratorLength( p1.listDomain(), 3 );
}
}
};
}
// Internal implementation methods
//////////////////////////////////
//==============================================================================
// Inner class definitions
//==============================================================================
}
| |
package gr.iti.mklab.sm;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import gr.iti.mklab.sm.feeds.Feed;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import gr.iti.mklab.sm.input.FeedsCreator;
import gr.iti.mklab.sm.management.StorageHandler;
import gr.iti.mklab.sm.streams.Stream;
import gr.iti.mklab.sm.streams.StreamException;
import gr.iti.mklab.sm.streams.StreamsManagerConfiguration;
import gr.iti.mklab.sm.streams.monitors.StreamsMonitor;
/**
* Class for retrieving content according to keywords - user - location feeds from social networks.
* Currently 7 social networks are supported (Twitter,Youtube,Facebook,Flickr,Instagram,Tumblr,GooglePlus)
*
* @author Manos Schinas
* @email manosetro@iti.gr
*
*/
public class FeedsManager implements Runnable {
public final Logger logger = Logger.getLogger(FeedsManager.class);
enum ManagerState {
OPEN, CLOSE
}
private Map<String, Stream> streams = null;
private StreamsManagerConfiguration config = null;
private StorageHandler storageHandler;
private StreamsMonitor monitor;
private ManagerState state = ManagerState.CLOSE;
private FeedsCreator feedsCreator;
private Set<Feed> feeds = new HashSet<Feed>();
public FeedsManager(StreamsManagerConfiguration config) throws StreamException {
if (config == null) {
throw new StreamException("Manager's configuration must be specified");
}
//Set the configuration files
this.config = config;
//Set up the Streams
initStreams();
}
/**
* Opens Manager by starting the auxiliary modules and setting up
* the database for reading/storing
*
* @throws StreamException
*/
public synchronized void open() throws StreamException {
if (state == ManagerState.OPEN) {
return;
}
state = ManagerState.OPEN;
logger.info("StreamsManager is open now.");
try {
//If there are Streams to monitor start the StreamsMonitor
if(streams != null && !streams.isEmpty()) {
monitor = new StreamsMonitor(streams.size());
}
else {
throw new StreamException("There are no streams to open.");
}
//Start stream handler
storageHandler = new StorageHandler(config);
storageHandler.start();
logger.info("Storage Manager is ready to store.");
feedsCreator = new FeedsCreator(config.getInputConfig());
//Start the Streams
for (String streamId : streams.keySet()) {
logger.info("Start Stream : " + streamId);
Configuration sconfig = config.getStreamConfig(streamId);
Stream stream = streams.get(streamId);
stream.setHandler(storageHandler);
stream.open(sconfig);
monitor.addStream(stream);
}
monitor.start();
}
catch(Exception e) {
e.printStackTrace();
throw new StreamException("Error during streams open", e);
}
}
/**
* Closes Manager and its auxiliary modules
*
* @throws StreamException
*/
public synchronized void close() throws StreamException {
if (state == ManagerState.CLOSE) {
logger.info("StreamManager is already closed.");
return;
}
try {
for (Stream stream : streams.values()) {
logger.info("Close " + stream);
stream.close();
}
if (storageHandler != null) {
storageHandler.stop();
}
state = ManagerState.CLOSE;
}
catch(Exception e) {
throw new StreamException("Error during streams close", e);
}
}
/**
* Initializes the streams apis that are going to be searched for
* relevant content
* @throws StreamException
*/
private void initStreams() throws StreamException {
streams = new HashMap<String, Stream>();
try {
for (String streamId : config.getStreamIds()) {
Configuration sconfig = config.getStreamConfig(streamId);
String streamName = sconfig.getParameter(Configuration.CLASS_PATH);
Stream stream = (Stream)Class.forName(streamName).newInstance();
streams.put(streamId, stream);
}
}
catch(Exception e) {
e.printStackTrace();
throw new StreamException("Error during streams initialization", e);
}
}
@Override
public void run() {
if(state != ManagerState.OPEN) {
logger.error("Streams Manager is not open!");
return;
}
while(state == ManagerState.OPEN) {
Set<Feed> newFeeds = feedsCreator.createFeeds();
Set<Feed> toBeRemoved = new HashSet<Feed>(feeds);
toBeRemoved.removeAll(newFeeds);
newFeeds.removeAll(feeds);
feeds.addAll(newFeeds);
feeds.removeAll(toBeRemoved);
// Add/Remove feeds from monitor's list
if(!toBeRemoved.isEmpty() || !newFeeds.isEmpty()) {
logger.info("Remove " + toBeRemoved.size() + " feeds");
for(Feed feed : toBeRemoved) {
String streamId = feed.getSource();
if(monitor != null) {
Stream stream = monitor.getStream(streamId);
if(stream != null) {
monitor.addFeed(streamId, feed);
}
else {
logger.error("Stream " + streamId + " has not initialized");
}
}
}
logger.info("Add " + newFeeds.size() + " new feeds");
for(Feed feed : newFeeds) {
String streamId = feed.getSource();
if(monitor != null) {
Stream stream = monitor.getStream(streamId);
if(stream != null) {
monitor.addFeed(streamId, feed);
}
else {
logger.error("Stream " + streamId + " has not initialized");
}
}
}
}
try {
// Check for new feeds every one minute
Thread.sleep(60000);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
}
public static void main(String[] args) {
Logger logger = Logger.getLogger(FeedsManager.class);
File streamConfigFile;
if(args.length != 1 ) {
streamConfigFile = new File("./conf/streams.conf.xml");
}
else {
streamConfigFile = new File(args[0]);
}
FeedsManager manager = null;
try {
StreamsManagerConfiguration config = StreamsManagerConfiguration.readFromFile(streamConfigFile);
manager = new FeedsManager(config);
manager.open();
Thread thread = new Thread(manager);
thread.start();
} catch (ParserConfigurationException e) {
logger.error(e.getMessage());
} catch (SAXException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
} catch (StreamException e) {
logger.error(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.fusepool.p3.accept.util;
import java.util.*;
import javax.activation.MimeType;
import javax.activation.MimeTypeParameterList;
import javax.activation.MimeTypeParseException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static eu.fusepool.p3.accept.util.MimeUtils.isSameOrSubtype;
import static eu.fusepool.p3.accept.util.MimeUtils.mimeType;
/**
* This class represents the media-type acceptance preference as expressed by
* the values of HTTP Accept headers,
*
* @author reto
* @author Giuliano Mega
*/
public class AcceptPreference {
private static final Logger logger = LoggerFactory.getLogger(AcceptPreference.class);
public static final String RFC7231_HEADER = "Accept";
public static final String RFC7231_MEDIA_SEPARATOR = ",";
public static class AcceptHeaderEntry implements Comparable<AcceptHeaderEntry> {
private final MimeTypeComparator mediaTypeComparator = new MimeTypeComparator();
final MimeType mediaType;
final int quality; //from 0 to 1000
AcceptHeaderEntry(MimeType mediaType) {
MimeTypeParameterList parametersWithoutQ = mediaType.getParameters();
String qValue = parametersWithoutQ.get("q");
parametersWithoutQ.remove("q");
this.mediaType = mimeType(mediaType.getBaseType() + parametersWithoutQ.toString());
if (qValue == null) {
quality = 1000;
} else {
quality = (int) (Float.parseFloat(qValue) * 1000);
}
}
@Override
public int compareTo(AcceptHeaderEntry o) {
if (equals(o)) {
return 0;
}
if (quality == o.quality) {
return mediaTypeComparator.compare(mediaType, o.mediaType);
}
return (o.quality - quality);
}
public MimeType getMediaType() {
return mediaType;
}
/**
* The quality in permille
*
* @return the quality as integer from 0 to 1000,
*/
public int getQuality() {
return quality;
}
@Override
public String toString() {
return mediaType + " with q=" + quality + ";";
}
}
/**
* Constructs an {@link AcceptPreference} array from an {@link javax.servlet.http.HttpServletRequest}.
*
* @param request the request to extract the {@link AcceptPreference} from.
* @return the {@link AcceptPreference}s reflecting all Accept-Headers in
* the request, in case the request contains no header an
* AcceptPreference quivalent to a single "*/*" header value is returned.
*/
public static AcceptPreference fromRequest(HttpServletRequest request) {
ArrayList<AcceptPreference> headers = new ArrayList<AcceptPreference>();
Enumeration<String> strHeaders = request.getHeaders(RFC7231_HEADER);
while (strHeaders.hasMoreElements()) {
headers.add(fromString(strHeaders.nextElement()));
}
if (headers.isEmpty()) {
return fromString("*/*");
} else {
return fromHeaders(headers);
}
}
/**
* @return a new {@link AcceptPreference} from a RFC7231 media/quality list. Example:
* <code>
* fromString("image/png;q=1.0,image/*;q=0.7,text/plain;q=0.5");
* </code>
*/
public static AcceptPreference fromString(String header) {
if (header == null) {
throw new NullPointerException("Header string can't be null.");
}
List<String> entries = new ArrayList<String>();
for (String entry : header.split(RFC7231_MEDIA_SEPARATOR)) {
entries.add(entry);
}
return new AcceptPreference(entries);
}
/**
* Constructs an {@link AcceptPreference} that is equivalent to
* the union of the <code>AcceptPreference</code>s passed as argument.
*
* @param headers a collection of accept headers that are part of single request.
*
* @return an {@link AcceptPreference} that corresponds to the merge of all headers in
* the parameter list. Example:
*
* <code>
AcceptPreference merged = fromHeaders(fromString("text/html;q=1.0"),
fromString("image/png;q=0.5"));
</code>
*
* is equivalent to:
*
* <code>
AcceptPreference merged = fromString("text/html;q=1.0,image/png;q=0.5");
</code>
*/
public static AcceptPreference fromHeaders(Collection<AcceptPreference> headers) {
if (headers.isEmpty()) {
throw new IllegalArgumentException("Header list must contain at least one element.");
}
TreeSet<AcceptHeaderEntry> entries = new TreeSet<>();
for (AcceptPreference header : headers) {
// It's OK to do this as AcceptHeaderEntry is immutable.
entries.addAll(header.entries);
}
return new AcceptPreference(entries);
}
private final TreeSet<AcceptHeaderEntry> entries;
protected AcceptPreference(List<String> entryStrings) {
entries = new TreeSet<AcceptHeaderEntry>();
if ((entryStrings == null) || (entryStrings.size() == 0)) {
entries.add(new AcceptHeaderEntry(MimeUtils.WILDCARD_TYPE));
} else {
for (String string : entryStrings) {
try {
entries.add(new AcceptHeaderEntry(new MimeType(string)));
} catch (MimeTypeParseException ex) {
logger.warn("The string \"" + string + "\" is not a valid mediatype", ex);
}
}
}
}
protected AcceptPreference(TreeSet<AcceptHeaderEntry> entries) {
this.entries = entries;
}
/**
* @return a sorted list of the {@link AcceptHeaderEntry} that compose this
* {@link AcceptPreference}.
*/
public List<AcceptHeaderEntry> getEntries() {
List<AcceptHeaderEntry> result = new ArrayList<AcceptHeaderEntry>();
for (AcceptHeaderEntry entry : entries) {
result.add(entry);
}
return result;
}
/**
* @return the {@link MimeType} with the highest quality parameter amongst the ones
* specified in this {@link AcceptPreference}.
*/
public MimeType getPreferredAccept() {
return entries.first().mediaType;
}
/**
* Given a set of supported {@link MimeType}s, returns the one that best
* satisfies this accept header.
*
* @param supportedTypes a set of supported {@link MimeType}s.
* @return the best candidate in the set, or <code>null</code> if the
* header does not allow any of supported {@link MimeType}s.
*/
public MimeType getPreferredAccept(Set<MimeType> supportedTypes) {
// Starts from the highest.
for (AcceptHeaderEntry clientSupported : entries) {
for (MimeType serverSupported : supportedTypes) {
if (isSameOrSubtype(serverSupported, clientSupported.mediaType)) {
return serverSupported;
}
}
}
return null;
}
/**
* @param type
* @return a value from 0 to 1000 to indicate the quality in which type is accepted
*/
public int getAcceptedQuality(MimeType type) {
for (AcceptHeaderEntry acceptHeaderEntry : entries) {
if (isSameOrSubtype(type, acceptHeaderEntry.mediaType)) {
return acceptHeaderEntry.quality;
}
}
Object[] reverseEntries = entries.toArray();
for (int i = entries.size() - 1; i >= 0; i--) {
AcceptHeaderEntry entry = (AcceptHeaderEntry) reverseEntries[i];
if (isSameOrSubtype(entry.mediaType, type)) {
return entry.quality;
}
}
return 0;
}
@Override
public String toString() {
return entries.toString();
}
}
| |
package org.eminmamedov.smscenter.receivers.smpp;
import static org.eminmamedov.smscenter.receivers.smpp.BoundState.*;
import static org.eminmamedov.smscenter.receivers.smpp.SmppCommandType.BIND;
import static org.eminmamedov.smscenter.receivers.smpp.SmppCommandType.SUBMIT_SM;
import static org.eminmamedov.smscenter.receivers.smpp.SmppConnectionType.TRANSMITTER;
import ie.omk.smpp.BadCommandIDException;
import ie.omk.smpp.NotBoundException;
import ie.omk.smpp.message.SMPPPacket;
import ie.omk.smpp.message.SMPPProtocolException;
import ie.omk.smpp.message.SMPPRequest;
import ie.omk.smpp.message.SMPPResponse;
import ie.omk.smpp.message.Unbind;
import ie.omk.smpp.util.PacketFactory;
import ie.omk.smpp.util.SMPPIO;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.eminmamedov.smscenter.datamodel.User;
import org.springframework.beans.factory.annotation.Autowired;
public class SmppConnectionHandler implements Runnable {
private static final Logger log = Logger.getLogger(SmppConnectionHandler.class);
private static final int ID_OFFSET = 4;
private static final int ID_LENGTH = 4;
private static final int READ_BUFFER_SIZE = 300;
@Autowired
private SmppConnectionPool smppConnectionPool;
@Autowired
private SmppReceiverHelper smppReceiverHelper;
@Resource(name = "requestProcessors")
private Map<SmppCommandType, SmppRequestProcessor> requestProcessors;
private BoundState boundState;
private SmsClientLink link;
private User user = new User();
private byte[] buf = new byte[READ_BUFFER_SIZE];
private SmppConnectionType connectionType;
private AtomicInteger enquireLinkCount = new AtomicInteger(0);
public SmppConnectionHandler(Socket clientSocket) throws IOException {
this.boundState = BINDING;
this.link = new SmsClientLink(clientSocket);
log.debug("Channel with client has been created successfully");
}
@Override
public void run() {
try {
while ((!Thread.interrupted()) && (link.getClientSocket().isConnected()) && (boundState != UNBOUND)) {
SMPPPacket pak = null;
try {
pak = readNextPacket();
if (pak == null) {
log.warn("Unknown package type has been received from user " + user.getName());
continue;
}
} catch (SMPPProtocolException e) {
log.warn("Error in SMPP protocol for user " + user.getName(), e);
}
}
} catch (IOException e) {
log.warn(e, e);
smppConnectionPool.close(this);
} catch (Exception e) {
log.warn("FATAL UNKNOWN ERROR! PLEASE CHECK LOGS!", e);
smppConnectionPool.close(this);
}
}
private SMPPPacket readNextPacket() throws IOException, BadCommandIDException {
this.buf = link.read(this.buf);
int id = SMPPIO.bytesToInt(this.buf, ID_OFFSET, ID_LENGTH);
SMPPPacket pak = PacketFactory.newInstance(id);
if (pak != null) {
pak.readFrom(this.buf, 0);
if (log.isDebugEnabled()) {
StringBuilder b = new StringBuilder("Package has been received: ");
int packageLength = pak.getLength();
int commandStatus = pak.getCommandStatus();
int sequenceNumber = pak.getSequenceNum();
b.append(pak);
b.append(" from " + user.getName() + ": ");
b.append("id:");
b.append(Integer.toHexString(id));
b.append(" len:");
b.append(Integer.toString(packageLength));
b.append(" st:");
b.append(Integer.toString(commandStatus));
b.append(" sq:");
b.append(Integer.toString(sequenceNumber));
log.debug(b.toString());
}
processInboundPacket(pak);
}
return pak;
}
private void processInboundPacket(SMPPPacket packet) throws IOException, BadCommandIDException {
SmppCommandType commandType = SmppCommandType.getValueByTypeCode(packet.getCommandId());
if (commandType == null) {
log.warn("Unknown command has been received from user " + user.getName());
log.warn("Package: " + packet);
throw new BadCommandIDException("Wrong command id [ " + packet.getCommandId() + " ]");
}
requestProcessors.get(commandType).processRequest(this, packet);
}
public void sendRequest(SMPPRequest request) throws IOException {
validateRequest(request);
log.info("Send request " + request + " to user " + user.getName());
link.write(request, true);
}
private void validateRequest(SMPPRequest request) {
int id = request.getCommandId();
if (isNotBound()) {
throw new NotBoundException("Connection should be in BOUND state to send requests");
}
SmppCommandType commandType = SmppCommandType.getValueByTypeCode(id);
if (commandType == BIND) {
throw new UnsupportedOperationException("SMSC doesn't allow to send this type of packet. ID=" + id);
}
if ((connectionType == TRANSMITTER) && (commandType == SUBMIT_SM)) {
throw new UnsupportedOperationException(
"Connection has been opened in TRANSMITTER mode. It doesn't allow to send this type of packet");
}
}
public void sendResponse(SMPPResponse response) throws IOException {
log.info("Send response " + response + " to user " + user.getName());
link.write(response, true);
}
public boolean isNotBound() {
return boundState != BoundState.BOUND;
}
public BoundState getBoundState() {
return boundState;
}
public void setBoundState(BoundState boundState) {
if (boundState == UNBOUNDING) {
try {
Unbind req = (Unbind) smppReceiverHelper.newInstance(SMPPPacket.UNBIND);
sendRequest(req);
} catch (BadCommandIDException e) {
log.warn("Unknown command ID", e);
} catch (UnsupportedOperationException e) {
log.warn(e, e);
} catch (IOException e) {
log.warn(e, e);
}
} else if (boundState == UNBOUND) {
try {
link.close();
} catch (IOException e) {
log.error("Unknown error occured", e);
}
}
this.boundState = boundState;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public SmsClientLink getLink() {
return link;
}
public void setConnectionType(SmppConnectionType connectionType) {
this.connectionType = connectionType;
}
public void incEnquireLinkCount() {
this.enquireLinkCount.incrementAndGet();
}
public int getEnquireLinkCount() {
return enquireLinkCount.intValue();
}
public void resetEnquireLinkCount() {
enquireLinkCount.set(0);
}
}
| |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
@SuppressWarnings("serial")
public class Game2 extends JPanel{
public static final int FRAME_HEIGHT = 768; //25 frame height pixels used up by header
public static final int FRAME_WIDTH = 1366; // 1 meter = 25 pixels
public Game2(){ //constructs levels and adds player
level = 0;
player = new Player(10,10);
ui = new UI(FRAME_WIDTH,FRAME_HEIGHT);
levels.add(new Level(200,200,1920,1536,"Play Ground"));
cameras.add(new Camera(0,0, FRAME_WIDTH, FRAME_HEIGHT, levels.get(0).getWidth()));
player.setXY(levels.get(level).getStartX(),levels.get(level).getStartY());
//levels.get(0).addEnvObj(0,500,3840,100,"Floor", new Color(0,0,0), true);
levels.get(0).addEnvObj(0,500,300,100,"GapFloor", new Color(0,0,0), true);
levels.get(0).addEnvObj(460,500,3840,100,"GapFloor", new Color(0,0,0), true);
levels.get(0).addEnvObj(800,-500,200,850,"Wall", new Color(0,0,0), true);
levels.get(0).addEnvObj(465,-500,200,850,"Wall", new Color(0,0,0), true);
//levels.get(0).addEnvObj(1200,100,200,100,"Platform", new Color(0,0,0), true);
//levels.get(0).addEnvObj(1400,000,200,100,"Platform", new Color(0,0,0), true);
levels.get(0).addPickup(732,300,25,25,"coin",null,1);
levels.get(0).addPickup(732,0,25,25,"coin",null,5);
levels.get(0).addPickup(732,-500,25,25,"coin",null,10);
levels.get(0).addPickup(900,-550,25,25,"heal",null,10);
levels.get(0).addEnemy(800,450, 25, 50, "BasicEnemy", new Color(200,0,0), "walk", 10, 300, 0, 1);
//levels.get(0).addEnemy(900,450, 25, 50, "BasicEnemy", new Color(200,100,0), "walk", 10, 200, 0, 1);
//levels.get(0).addEnemy(1300,400, 25, 50, "BasicEnemy", new Color(200,0,0), "walk", 10, 200, 0, 1);
addKeyListener(new KeyAdapter(){ //necessary for key presses and releases
@Override
public void keyPressed(KeyEvent evt){ //for when key is pressed
switch(evt.getKeyCode()){
case KeyEvent.VK_UP: //keys are coded as "KeyEvent.VK_" and then the key name or letter in caps
player.jump();
break;
case KeyEvent.VK_RIGHT:
player.accRight();
break;
case KeyEvent.VK_LEFT:
player.accLeft();
break;
case KeyEvent.VK_W: //keys are coded as "KeyEvent.VK_" and then the key name or letter in caps
player.jump();
break;
case KeyEvent.VK_D:
player.accRight();
break;
case KeyEvent.VK_A:
player.accLeft();
break;
case KeyEvent.VK_SHIFT:
player.run();
break;
case KeyEvent.VK_P:
if(running){
running = false;
System.out.println("PAUSE");
} else{
running = true;
System.out.println("PLAY");
}
break;
case KeyEvent.VK_BACK_SPACE:
running=true;
gameover=false;
player.heal(100);
player.setXY(levels.get(level).getStartX(),levels.get(level).getStartY());
counter=0;
}
}
@Override
public void keyReleased(KeyEvent evt){ //for when key is released
switch(evt.getKeyCode()){
case KeyEvent.VK_RIGHT:
player.decRight();
break;
case KeyEvent.VK_LEFT:
player.decLeft();
break;
case KeyEvent.VK_D:
player.decRight();
break;
case KeyEvent.VK_A:
player.decLeft();
break;
case KeyEvent.VK_SHIFT:
player.walk();
break;
}
}
});
setFocusable(true);
}
@Override
public void paint(Graphics g){
if(running){
super.paint(g); //resets canvas
player.move();
cameras.get(level).move(player.getX(),player.getY());
levels.get(level).moveLevel(cameras.get(level).getX(), cameras.get(level).getY()); //moves Environment
player.giveCamXY(cameras.get(level).getX(), cameras.get(level).getY());
player.calcFallDamage();
checkPlayerCollisions();
checkEnemyCollisions();
ui.givePlayerStats(player.getHealth(),player.getScore());
levels.get(level).drawLevel(g); //draws level
player.draw(g); //draws player
ui.drawUI(g);
if(player.getHealth()<=0){
gameover=true;
running=false;
}
if(player.getY()>FRAME_HEIGHT){
gameover=true;
running=false;
}
//System.out.println((levels.get(level).getEnvObj(0).getName()) + " y= " + levels.get(level).getEnvObj(0).getY());
} else if(gameover){
gameOver(g);
} else if(levelIntro){
levelIntro(g);
}
}
public void checkPlayerCollisions(){
String c;
Hitbox h;
EnvObj o;
Pickup p;
Enemy e;
player.isGrounded(false);
player.isWalled("null");
for(int i=0;i<levels.get(level).getObjListSize();i++){
h=levels.get(level).getEnvObj(i).getHitbox(); //gets object hitbox
o=levels.get(level).getEnvObj(i);
c=player.getHitbox().getCollision(h); //checks player hitbox with object hitbox
if(!(c.equals("null"))){
if(c.equals("bottom")){
player.isGrounded(true);
player.setXY(player.getX(),(h.getTop()-(player.getHitbox().getBottom()-player.getHitbox().getTop())));
player.applyFallDamage();
} else if(c.equals("top")){
player.stopY();
player.setXY(player.getX(),h.getBottom());
} else if(c.equals("right")){
player.stopX();
player.isWalled("right");
player.setXY((h.getLeft()-(player.getHitbox().getRight()-player.getHitbox().getLeft())), player.getY());
} else if(c.equals("left")){
player.stopX();
player.isWalled("left");
player.setXY(h.getRight(), player.getY());
}
}
}
for(int i=0;i<levels.get(level).getPupListSize();i++){
h=levels.get(level).getPickup(i).getHitbox(); //gets object hitbox
p=levels.get(level).getPickup(i);
c=player.getHitbox().getCollision(h);
if(!c.equals("null") && p.isExisting()){
if(p.isHeal()){
player.heal(p.getValue());
} else if(p.isCoin()){
player.addScore(p.getValue());
}
p.used();
}else if(!p.isExisting()){
p.remove();
if(p.isRemovable()){
levels.get(level).removePickup(i);
i--;
}
}
}
for(int i=0;i<levels.get(level).getEneListSize();i++){
h=levels.get(level).getEnemy(i).getHitbox(); //gets object hitbox
e=levels.get(level).getEnemy(i);
c=player.getHitbox().getCollision(h);
if(!(c.equals("null") && e.isAlive())){
if(c.equals("bottom")){
player.setXY(player.getX(),(h.getTop()-(player.getHitbox().getBottom()-player.getHitbox().getTop())));
player.miniJump();
e.killed();
} else if(c.equals("top")){
player.stopY();
player.setXY(player.getX(),h.getBottom());
player.miniJumpDown();
} else if(c.equals("right")){
player.stopX();
player.setXY((h.getLeft()-(player.getHitbox().getRight()-player.getHitbox().getLeft())), player.getY());
player.jumpBack("right");
player.takeDamage(e.getDamage());
} else if(c.equals("left")){
player.stopX();
player.setXY(h.getRight(), player.getY());
player.jumpBack("left");
player.takeDamage(e.getDamage());
} else if(!e.isAlive()){
e.remove();
if(e.isRemovable()){
levels.get(level).removeEnemy(i);
i--;
}
}
}
}
}
public void gameOver(Graphics g){
counter++;
g.setColor(new Color(0,0,0));
g.fillRect(0,0,FRAME_WIDTH,FRAME_HEIGHT);
if(counter>40){
g.setColor(new Color(255,255,255));
g.drawString("GAME OVER",FRAME_WIDTH/2-10,FRAME_HEIGHT/2-3);
}
if(counter>100){
g.setColor(new Color(255,255,255));
g.drawString("Press BACKSPACE to restart level...",FRAME_WIDTH/2-50,FRAME_HEIGHT/2-3+30);
}
}
public void levelIntro(Graphics g){
counter++;
g.setColor(new Color(0,0,0));
g.fillRect(0,0,FRAME_WIDTH,FRAME_HEIGHT);
if(counter>20 && counter<120){
g.setColor(new Color(255,255,255));
g.drawString(levels.get(level).getName(),FRAME_WIDTH/2-10,FRAME_HEIGHT/2-3);
}
if(counter==140){
levelIntro=false;
running=true;
counter=0;
}
}
public void checkEnemyCollisions(){
for(int j=0;j<levels.get(level).getEneListSize();j++){
String c;
Hitbox h;
EnvObj o;
Enemy e;
Enemy enemy=levels.get(level).getEnemy(j);
enemy.isGrounded(false);
for(int i=0;i<levels.get(level).getObjListSize();i++){
h=levels.get(level).getEnvObj(i).getHitbox(); //gets object hitbox
o=levels.get(level).getEnvObj(i);
c=enemy.getHitbox().getCollision(h); //checks enemy hitbox with object hitbox
if(!(c.equals("null"))){
if(c.equals("bottom")){
enemy.isGrounded(true);
enemy.setXY(enemy.getX(),(h.getTop()-(enemy.getHitbox().getBottom()-enemy.getHitbox().getTop())));
} else if(c.equals("right")){
enemy.changeDir("left");
enemy.setXY((h.getLeft()-(enemy.getHitbox().getRight()-enemy.getHitbox().getLeft())), enemy.getY());
} else if(c.equals("left")){
enemy.changeDir("right");
enemy.setXY(h.getRight(), enemy.getY());
}
}
}
for(int i=0;i<levels.get(level).getEneListSize();i++){
h=levels.get(level).getEnemy(i).getHitbox(); //gets object hitbox
e=levels.get(level).getEnemy(i);
c=enemy.getHitbox().getCollision(h);
if(!(c.equals("null") && e.isAlive())){
if(c.equals("bottom")){
enemy.isGrounded(true);
enemy.setXY(enemy.getX(),(h.getTop()-(enemy.getHitbox().getBottom()-enemy.getHitbox().getTop())));
} else if(c.equals("right")){
enemy.changeDir("left");
enemy.setXY((h.getLeft()-(enemy.getHitbox().getRight()-enemy.getHitbox().getLeft())), enemy.getY());
} else if(c.equals("left")){
enemy.changeDir("right");
enemy.setXY(h.getRight(), enemy.getY());
}
}
}
}
}
public static void main(String[] args) throws InterruptedException{
JFrame frame = new JFrame("Game2");
Game2 game= new Game2();
frame.add(game);
game.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setResizable(false);
frame.setVisible(true);
while(true){
game.repaint();
Thread.sleep(1000/60);
}
}
int counter;
int score;
boolean levelIntro=false;
boolean running =true;
boolean gameover=false;
int level=0;
Player player;
Camera camera;
UI ui;
ArrayList<Camera> cameras = new ArrayList<Camera>();
ArrayList<Level> levels = new ArrayList<Level>();
}
| |
/*
* Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.base;
/**
* Common constants of the identity solution.
*/
public class IdentityConstants {
public static final String DEFULT_RESOURCES = "org.wso2.carbon.identity.core.resources";
public static final String SELF_ISSUED_ISSUER = "http://schemas.xmlsoap.org/ws/2005/05/identity/issuer/self";
public static final String PREFIX = "ic";
public static final String NS = "http://schemas.xmlsoap.org/ws/2005/05/identity";
public static final String OPENID_NS = "http://schema.openid.net/2007/05";
public final static String NS_MSFT_ADDR = "http://schemas.microsoft.com/ws/2005/05/addressing/none";
public static final String IDENTITY_ADDRESSING_NS = "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity";
public final static String CLAIM_TENANT_DOMAIN = "http://wso2.org/claims/tenant";
public final static String CLAIM_PPID = NS
+ "/claims/privatepersonalidentifier";
public final static String CLAIM_OPENID = OPENID_NS + "/claims/identifier";
public final static String PARAM_SUPPORTED_TOKEN_TYPES = "SupportedTokenTypes";
public final static String PARAM_NOT_SUPPORTED_TOKEN_TYPES = "NotSupportedTokenTypes";
public final static String PARAM_CARD_NAME = "CardName";
public final static String PARAM_VALUE_CARD_NAME = "WSO2 Managed Card";
public final static String PARAM_VALID_PERIOD = "ValidPeriod";
public final static String PARAM_VALUE_VALID_PERIOD = "365";
public final static String SAML10_URL = "urn:oasis:names:tc:SAML:1.0:assertion";
public final static String SAML11_URL = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
public final static String SAML20_URL = "urn:oasis:names:tc:SAML:2.0:assertion";
public final static String CARD_IMAGE_PATH = "/card.jpg";
public final static String PARAM_USE_SYMM_BINDING = "useSymmBinding";
public final static String USER_VERIFICATION_PAGE = "/UserVerification.action";
public final static String USER_VERIFICATION_PARAM = "confString";
public final static String XML_TOKEN = "xmlToken";
public final static String PROFILE_NAME = "profileName";
public final static String PASSWORD = "oppassword";
public final static String INFOCARD_LOGIN = "opinfocardlogin";
public static final String USER_APPROVED = "userApproved";
public final static String WSO2_IS_NS = "http://www.wso2.org/solutions/identity";
public final static String RESOURCES = "org.wso2.solutions.identity.resources";
public final static String INITIAL_CLAIMS_FILE_PATH = "conf/initial-claims.xml";
public static final String PROPERTY_USER = "IdentityProvier.User";
public static final String HTTPS = "https://";
public static final String HTTPS_PORT = "Ports.HTTPS";
public static final String HOST_NAME = "HostName";
public static final String TRUE = "true";
public static final String PHISHING_RESISTANCE = "phishingResistanceAuthentication";
public static final String MULTI_FACTOR_AUTH = "multifactorlogin";
public static final String PARAM_MAP = "parameterMap";
public static final String DESTINATION_URL = "destinationUrl";
public static final String FORM_REDIRECTION = "jsp/redirect.jsp";
public final static String ISSUER_SELF = "Self";
public final static String CARD_ISSUSER_LOG = "org.wso2.solutions.identity.card";
public final static String TOKEN_ISSUSER_LOG = "org.wso2.solutions.identity.token";
public static final String SERVICE_NAME_STS_UT = "sts-ut";
public static final String SERVICE_NAME_STS_UT_SYMM = "sts-ut-symm";
public static final String SERVICE_NAME_STS_IC = "sts-ic";
public static final String SERVICE_NAME_STS_IC_SYMM = "sts-ic-symm";
public static final String SERVICE_NAME_MEX_UT = "mex-ut";
public static final String SERVICE_NAME_MEX_UT_SYMM = "mex-ut-symm";
public static final String SERVICE_NAME_MEX_IC = "mex-ic";
public static final String SERVICE_NAME_MEX_IC_SYMM = "mex-ic-symm";
public static final String INFOCARD_DIALECT = "http://schemas.xmlsoap.org/ws/2005/05/identity";
public static final String OPENID_SREG_DIALECT = "http://schema.openid.net/2007/05/claims";
public static final String OPENID_AX_DIALECT = "http://axschema.org";
// Authentication mechanism
public static final int AUTH_TYPE_USERNAME_TOKEN = 1;
public static final int AUTH_TYPE_KEBEROS_TICKET = 2;
public static final int AUTH_TYPE_X509_CERTIFICATE = 3;
public static final int AUTH_TYPE_SELF_ISSUED = 4;
public static final String RP_USER_ROLE = "Rp_User_Role";
public final static String PARAM_NAME_ALLOW_USER_REGISTRATION = "allowUserReg";
public final static String PARAM_NAME_ENABLE_OPENID_LOGIN = "enableOpenIDLogin";
public final static String IDENTITY_DEFAULT_ROLE = "identity";
public final static String DEFAULT_SUPER_TENAT = "identity.cloud.wso2.com";
public static String PPID_DISPLAY_VALUE = "Private personal identifier";
//Event Listeners attributes
public final static String EVENT_LISTENER_TYPE = "type";
public final static String EVENT_LISTENER_NAME = "name";
public final static String EVENT_LISTENER_ORDER = "orderId";
public final static String EVENT_LISTENER_ENABLE = "enable";
public final static String EVENT_LISTENERS = "EventListeners";
public final static String EVENT_LISTENER = "EventListener";
// Cache Config constants
public final static String CACHE_CONFIG = "CacheConfig";
public final static String CACHE_MANAGER = "CacheManager";
public final static String CACHE_MANAGER_NAME = "name";
public final static String CACHE = "Cache";
public final static String CACHE_NAME = "name";
public final static String CACHE_ENABLE = "enable";
public final static String CACHE_TIMEOUT = "timeout";
public final static String CACHE_CAPACITY = "capacity";
private IdentityConstants() {
}
/**
* Server Configuration data retrieval Strings.
*/
public static class ServerConfig {
public final static String USER_TRUSTED_RP_STORE_LOCATION = "Security.UserTrustedRPStore.Location";
public final static String USER_TRUSTED_RP_STORE_PASSWORD = "Security.UserTrustedRPStore.Password";
public final static String USER_TRUSTED_RP_STORE_TYPE = "Security.UserTrustedRPStore.Type";
public final static String USER_TRUSTED_RP_KEY_PASSWORD = "Security.UserTrustedRPStore.KeyPassword";
public final static String USER_SSO_STORE_LOCATION = "Security.UserSSOStore.Location";
public final static String USER_SSO_STORE_PASSWORD = "Security.UserSSOStore.Password";
public final static String USER_SSO_STORE_TYPE = "Security.UserSSOStore.Type";
public final static String USER_SSO_KEY_PASSWORD = "Security.UserSSOStore.KeyPassword";
public final static String OPENID_SERVER_URL = "OpenID.OpenIDServerUrl";
public final static String OPENID_USER_PATTERN = "OpenID.OpenIDUserPattern";
public final static String OPENID_LOGIN_PAGE_URL = "OpenID.OpenIDLoginUrl";
public final static String OPENID_SKIP_USER_CONSENT = "OpenID.OpenIDSkipUserConsent";
public final static String OPENID_REMEMBER_ME_EXPIRY = "OpenID.OpenIDRememberMeExpiry";
public final static String OPENID_USE_MULTIFACTOR_AUTHENTICATION = "OpenID.UseMultifactorAuthentication";
public final static String OPENID_DISABLE_DUMB_MODE = "OpenID.DisableOpenIDDumbMode";
public final static String OPENID_SESSION_TIMEOUT = "OpenID.SessionTimeout";
public static final String ACCEPT_SAMLSSO_LOGIN = "OpenID.AcceptSAMLSSOLogin";
public static final String OPENID_PRIVATE_ASSOCIATION_STORE_CLASS = "OpenID.OpenIDPrivateAssociationStoreClass";
public static final String OPENID_ASSOCIATION_EXPIRY_TIME = "OpenID.OpenIDAssociationExpiryTime";
public static final String ENABLE_OPENID_ASSOCIATION_CLEANUP_TASK = "OpenID.EnableOpenIDAssociationCleanupTask";
public static final String OPENID_ASSOCIATION_CLEANUP_PERIOD = "OpenID.OpenIDAssociationCleanupPeriod";
public static final String OPENID_PRIVATE_ASSOCIATION_SERVER_KEY = "OpenID.OpenIDPrivateAssociationServerKey";
public static final String ISSUER_POLICY = "Identity.IssuerPolicy";
public static final String TOKEN_VALIDATE_POLICY = "Identity.TokenValidationPolicy";
public static final String BLACK_LIST = "Identity.BlackList";
public static final String WHITE_LIST = "Identity.WhiteList";
public static final String SYSTEM_KEY_STORE_PASS = "Identity.System.StorePass";
public static final String SYSTEM_KEY_STORE = "Identity.System.KeyStore";
// Location of the identity provider main key store
public final static String IDP_STORE_LOCATION = "Security.KeyStore.Location";
// Password of the identity provider main key store
public final static String IDP_STORE_PASSWORD = "Security.KeyStore.Password";
// Store type of the identity provider main key store
public final static String IDP_STORE_TYPE = "Security.KeyStore.Type";
// Location of the key store used to store users' personal certificates
public final static String USER_PERSONAL_STORE_LOCATION = "Security.UserPersonalCeritificateStore.Location";
// Password of the key store used to store users' personal certificates
public final static String USER_PERSONAL_STORE_PASSWORD = "Security.UserPersonalCeritificateStore.Password";
// Type of the key store used to store users' personal certificates
public final static String USER_PERSONAL_STORE_TYPE = "Security.UserPersonalCeritificateStore.Type";
public final static String USER_PERSONAL_KEY_PASSWORD = "Security.UserPersonalCeritificateStore.KeyPassword";
//XMPP Settings for multifactor authentication
public final static String XMPP_SETTINGS_PROVIDER = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPProvider";
public final static String XMPP_SETTINGS_SERVER = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPServer";
public final static String XMPP_SETTINGS_PORT = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPPort";
public final static String XMPP_SETTINGS_EXT = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPExt";
public final static String XMPP_SETTINGS_USERNAME = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPUserName";
public final static String XMPP_SETTINGS_PASSWORD = "MultifactorAuthentication.XMPPSettings.XMPPConfig.XMPPPassword";
//SAML SSO Service config
public final static String ENTITY_ID = "SSOService.EntityID";
public final static String SSO_IDP_URL = "SSOService.IdentityProviderURL";
public final static String DEFAULT_LOGOUT_ENDPOINT = "SSOService.DefaultLogoutEndpoint";
public final static String NOTIFICATION_ENDPOINT = "SSOService.NotificationEndpoint";
public final static String SSO_ATTRIB_CLAIM_DIALECT = "SSOService.AttributesClaimDialect";
public static final String SINGLE_LOGOUT_RETRY_COUNT = "SSOService.SingleLogoutRetryCount";
public static final String SINGLE_LOGOUT_RETRY_INTERVAL = "SSOService.SingleLogoutRetryInterval";
public static final String SSO_TENANT_PARTITIONING_ENABLED = "SSOService.TenantPartitioningEnabled";
public static final String ACCEPT_OPENID_LOGIN = "SSOService.AcceptOpenIDLogin";
public static final String SAML_RESPONSE_VALIDITY_PERIOD = "SSOService.SAMLResponseValidityPeriod";
public static final String SSO_DEFAULT_SIGNING_ALGORITHM = "SSOService.SAMLDefaultSigningAlgorithmURI";
public static final String SSO_DEFAULT_DIGEST_ALGORITHM = "SSOService.SAMLDefaultDigestAlgorithmURI";
//Identity Persistence Manager
public static final String SKIP_DB_SCHEMA_CREATION = "JDBCPersistenceManager.SkipDBSchemaCreation";
//Timeout Configurations
public static final String SESSION_IDLE_TIMEOUT = "TimeConfig.SessionIdleTimeout";
public static final String REMEMBER_ME_TIME_OUT = "TimeConfig.RememberMeTimeout";
public static final String CLEAN_UP_PERIOD = "JDBCPersistenceManager.SessionDataPersist.SessionDataCleanUp.CleanUpPeriod";
public static final String CLEAN_UP_TIMEOUT = "JDBCPersistenceManager.SessionDataPersist.SessionDataCleanUp.CleanUpTimeout";
public static final String CLEAN_UP_TIMEOUT_DEFAULT = "20160";
public static final String CLEAN_UP_PERIOD_DEFAULT = "1140";
//PassiveSTS
public static final String PASSIVE_STS_RETRY = "PassiveSTS.RetryURL";
}
/**
* Local names of the identity provider constants
*/
public static class LocalNames {
public static final String REQUESTED_DISPLAY_TOKEN = "RequestedDisplayToken";
public static final String REQUEST_DISPLAY_TOKEN = "RequestDisplayToken";
public static final String DISPLAY_TOKEN = "DisplayToken";
public static final String DISPLAY_CLAIM = "DisplayClaim";
public static final String DISPLAY_TAG = "DisplayTag";
public static final String DISPLAY_VALUE = "DisplayValue";
public static final String IDENTITY_CLAIM = "Claim";
public static final String IDENTITY_CLAIM_TYPE = "ClaimType";
public static final String INFO_CARD_REFERENCE = "InformationCardReference";
public static final String CARD_ID = "CardId";
public final static String SELFISSUED_AUTHENTICATE = "SelfIssuedAuthenticate";
public final static String USERNAME_PASSWORD_AUTHENTICATE = "UserNamePasswordAuthenticate";
public final static String KEBEROSV5_AUTHENTICATE = "KerberosV5Authenticate";
public final static String X509V3_AUTNENTICATE = "X509V3Authenticate";
public final static String IDENTITY = "Identity";
public final static String OPEN_ID_TOKEN = "OpenIDToken";
}
public static class IdentityTokens {
public static final String FILE_NAME = "identity_log_tokens.properties";
public static final String READ_LOG_TOKEN_PROPERTIES = "Read_Log_Token_Properties";
public static final String USER_CLAIMS = "UserClaims";
public static final String USER_ID_TOKEN = "UserIdToken";
public static final String XACML_REQUEST = "XACML_Request";
public static final String XACML_RESPONSE = "XACML_Response";
public static final String NTLM_TOKEN = "NTLM_Token";
public static final String SAML_ASSERTION = "SAML_Assertion";
public static final String SAML_REQUEST = "SAML_Request";
}
/**
* Common constants related to OpenID.
*/
public static class OpenId {
public final static String NS = "http://schema.openid.net";
public final static String OPENID_URL = "http://specs.openid.net/auth/2.0";
public final static String ATTR_MODE = "openid.mode";
public final static String ATTR_IDENTITY = "openid.identity";
public final static String ATTR_RESPONSE_NONCE = "openid.response_nonce";
public final static String ATTR_OP_ENDPOINT = "openid.op_endpoint";
public final static String ATTR_NS = "openid.ns";
public final static String ATTR_CLAIM_ID = "openid.claimed_id";
public final static String ATTR_RETURN_TO = "openid.return_to";
public final static String ATTR_ASSOC_HANDLE = "openid.assoc_handle";
public final static String ATTR_SIGNED = "openid.signed";
public final static String ATTR_SIG = "openid.sig";
public final static String OPENID_IDENTIFIER = "openid_identifier";
public final static String ASSOCIATE = "associate";
public final static String CHECKID_SETUP = "checkid_setup";
public final static String CHECKID_IMMEDIATE = "checkid_immediate";
public final static String CHECK_AUTHENTICATION = "check_authentication";
public final static String DISC = "openid-disc";
public static final String PREFIX = "openid";
public final static String ASSERTION = "openidAssertion";
public final static String AUTHENTICATED = "authenticated";
public final static String ONLY_ONCE = "Only Once";
public final static String ONCE = "once";
public final static String ALWAYS = "always";
public final static String DENY = "Deny";
public final static String ACTION = "_action";
public final static String OPENID_RESPONSE = "id_res";
public static final String AUTHENTICATED_AND_APPROVED = "authenticatedAndApproved";
public final static String CANCEL = "cancel";
public final static String FALSE = "false";
public final static String PARAM_LIST = "parameterlist";
public final static String PASSWORD = "password";
public static final String SERVICE_NAME_STS_OPENID = "sts-openid-ut";
public static final String SERVICE_NAME_MEX_OPENID = "mex-openid-ut";
public static final String SERVICE_NAME_MEX_IC_OPENID = "mex-openid-ic";
public static final String SERVICE_NAME_STS_IC_OPENID = "sts-openid-ic";
public static final String SIMPLE_REGISTRATION = "sreg";
public static final String ATTRIBUTE_EXCHANGE = "ax";
public static final String PAPE = "pape";
public static class PapeAttributes {
public final static String AUTH_POLICIES = "auth_policies";
public final static String NIST_AUTH_LEVEL = "nist_auth_level";
public final static String AUTH_AGE = "auth_age";
public final static String PHISHING_RESISTANCE = "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant";
public final static String MULTI_FACTOR = "http://schemas.openid.net/pape/policies/2007/06/multi-factor";
public final static String MULTI_FACTOR_PHYSICAL = "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical";
public final static String XMPP_BASED_MULTIFACTOR_AUTH = "xmpp_based_multifactor_auth";
public final static String INFOCARD_BASED_MULTIFACTOR_AUTH = "infocard_based_multifactor_auth";
}
public static class SimpleRegAttributes {
// As per the OpenID Simple Registration Extension 1.0 specification
// fields below should
// be included in the Identity Provider's response when
// "openid.mode" is "id_res"
public final static String NS_SREG = "http://openid.net/sreg/1.0";
public final static String NS_SREG_1 = "http://openid.net/extensions/sreg/1.1";
public final static String SREG = "openid.sreg.";
public final static String OP_SREG = "openid.ns.sreg";
}
public static class ExchangeAttributes extends SimpleRegAttributes {
public final static String NS = "http://axschema.org";
public final static String NS_AX = "http://openid.net/srv/ax/1.0";
public final static String EXT = "openid.ns.ext1";
public final static String MODE = "openid.ext1.mode";
public final static String TYPE = "openid.ext1.type.";
public final static String VALUE = "openid.ext1.value.";
public final static String FETCH_RESPONSE = "fetch_response";
}
}
public static class CarbonPlaceholders {
public static final String CARBON_HOST = "${carbon.host}";
public static final String CARBON_PORT = "${carbon.management.port}";
public static final String CARBON_PORT_HTTP = "${mgt.transport.http.port}";
public static final String CARBON_PORT_HTTPS = "${mgt.transport.https.port}";
public static final String CARBON_PROXY_CONTEXT_PATH = "${carbon.proxycontextpath}";
public static final String CARBON_WEB_CONTEXT_ROOT = "${carbon.webcontextroot}";
public static final String CARBON_PROTOCOL = "${carbon.protocol}";
public static final String CARBON_CONTEXT = "${carbon.context}";
public static final String CARBON_PORT_HTTP_PROPERTY = "mgt.transport.http.port";
public static final String CARBON_PORT_HTTPS_PROPERTY = "mgt.transport.https.port";
}
}
| |
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.scene.control;
import com.jme3.bounding.BoundingVolume;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.math.FastMath;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Spatial;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
/**
* Determines what Level of Detail a spatial should be, based on how many pixels
* on the screen the spatial is taking up. The more pixels covered, the more
* detailed the spatial should be. It calculates the area of the screen that the
* spatial covers by using its bounding box. When initializing, it will ask the
* spatial for how many triangles it has for each LOD. It then uses that, along
* with the trisPerPixel value to determine what LOD it should be at. It
* requires the camera to do this. The controlRender method is called each frame
* and will update the spatial's LOD if the camera has moved by a specified
* amount.
*/
public class LodControl extends AbstractControl implements Cloneable, JmeCloneable {
private float trisPerPixel = 1f;
private float distTolerance = 1f;
private float lastDistance = 0f;
private int lastLevel = 0;
private int numLevels;
private int[] numTris;
/**
* Creates a new
* <code>LodControl</code>.
*/
public LodControl() {
}
/**
* Returns the distance tolerance for changing LOD.
*
* @return the distance tolerance for changing LOD.
*
* @see #setDistTolerance(float)
*/
public float getDistTolerance() {
return distTolerance;
}
/**
* Specifies the distance tolerance for changing the LOD level on the
* geometry. The LOD level will only get changed if the geometry has moved
* this distance beyond the current LOD level.
*
* @param distTolerance distance tolerance for changing LOD
*/
public void setDistTolerance(float distTolerance) {
this.distTolerance = distTolerance;
}
/**
* Returns the triangles per pixel value.
*
* @return the triangles per pixel value.
*
* @see #setTrisPerPixel(float)
*/
public float getTrisPerPixel() {
return trisPerPixel;
}
/**
* Sets the triangles per pixel value. The
* <code>LodControl</code> will use this value as an error metric to
* determine which LOD level to use based on the geometry's area on the
* screen.
*
* @param trisPerPixel triangles per pixel
*/
public void setTrisPerPixel(float trisPerPixel) {
this.trisPerPixel = trisPerPixel;
}
@Override
public void setSpatial(Spatial spatial) {
if (!(spatial instanceof Geometry)) {
throw new IllegalArgumentException("LodControl can only be attached to Geometry!");
}
super.setSpatial(spatial);
Geometry geom = (Geometry) spatial;
Mesh mesh = geom.getMesh();
numLevels = mesh.getNumLodLevels();
numTris = new int[numLevels];
for (int i = numLevels - 1; i >= 0; i--) {
numTris[i] = mesh.getTriangleCount(i);
}
}
@Override
public Control cloneForSpatial(Spatial spatial) {
LodControl clone = (LodControl) super.cloneForSpatial(spatial);
clone.lastDistance = 0;
clone.lastLevel = 0;
clone.numTris = numTris != null ? numTris.clone() : null;
return clone;
}
@Override
public Object jmeClone() {
LodControl clone = (LodControl)super.jmeClone();
clone.lastDistance = 0;
clone.lastLevel = 0;
clone.numTris = numTris != null ? numTris.clone() : null;
return clone;
}
@Override
protected void controlUpdate(float tpf) {
}
protected void controlRender(RenderManager rm, ViewPort vp) {
BoundingVolume bv = spatial.getWorldBound();
Camera cam = vp.getCamera();
float atanNH = FastMath.atan(cam.getFrustumNear() * cam.getFrustumTop());
float ratio = (FastMath.PI / (8f * atanNH));
float newDistance = bv.distanceTo(vp.getCamera().getLocation()) / ratio;
int level;
if (Math.abs(newDistance - lastDistance) <= distTolerance) {
level = lastLevel; // we haven't moved relative to the model, send the old measurement back.
} else if (lastDistance > newDistance && lastLevel == 0) {
level = lastLevel; // we're already at the lowest setting and we just got closer to the model, no need to keep trying.
} else if (lastDistance < newDistance && lastLevel == numLevels - 1) {
level = lastLevel; // we're already at the highest setting and we just got further from the model, no need to keep trying.
} else {
lastDistance = newDistance;
// estimate area of polygon via bounding volume
float area = AreaUtils.calcScreenArea(bv, lastDistance, cam.getWidth());
float trisToDraw = area * trisPerPixel;
level = numLevels - 1;
for (int i = numLevels; --i >= 0;) {
if (trisToDraw - numTris[i] < 0) {
break;
}
level = i;
}
lastLevel = level;
}
spatial.setLodLevel(level);
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(trisPerPixel, "trisPerPixel", 1f);
oc.write(distTolerance, "distTolerance", 1f);
oc.write(numLevels, "numLevels", 0);
oc.write(numTris, "numTris", null);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
trisPerPixel = ic.readFloat("trisPerPixel", 1f);
distTolerance = ic.readFloat("distTolerance", 1f);
numLevels = ic.readInt("numLevels", 0);
numTris = ic.readIntArray("numTris", null);
}
}
| |
/*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.execution.engine.aggregation.impl;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable;
import org.apache.commons.math3.util.FastMath;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.Version;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import io.crate.Streamer;
import io.crate.breaker.RamAccounting;
import io.crate.common.collections.Lists2;
import io.crate.data.Input;
import io.crate.execution.engine.aggregation.AggregationFunction;
import io.crate.execution.engine.aggregation.DocValueAggregator;
import io.crate.execution.engine.aggregation.impl.templates.SortedNumericDocValueAggregator;
import io.crate.expression.symbol.Literal;
import io.crate.memory.MemoryManager;
import io.crate.metadata.Reference;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.metadata.functions.Signature;
import io.crate.types.ByteType;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import io.crate.types.DoubleType;
import io.crate.types.FixedWidthType;
import io.crate.types.FloatType;
import io.crate.types.IntegerType;
import io.crate.types.LongType;
import io.crate.types.ShortType;
import io.crate.types.TimestampType;
public class GeometricMeanAggregation extends AggregationFunction<GeometricMeanAggregation.GeometricMeanState, Double> {
public static final String NAME = "geometric_mean";
static {
DataTypes.register(GeometricMeanStateType.ID, in -> GeometricMeanStateType.INSTANCE);
}
static final List<DataType<?>> SUPPORTED_TYPES = Lists2.concat(
DataTypes.NUMERIC_PRIMITIVE_TYPES, DataTypes.TIMESTAMPZ);
public static void register(AggregationImplModule mod) {
for (var supportedType : SUPPORTED_TYPES) {
mod.register(
Signature.aggregate(
NAME,
supportedType.getTypeSignature(),
DataTypes.DOUBLE.getTypeSignature()
),
GeometricMeanAggregation::new
);
}
}
public static class GeometricMeanState implements Comparable<GeometricMeanState>, Writeable {
/**
* Number of values that have been added
*/
private long n;
/**
* The currently running value
*/
private double value;
public GeometricMeanState() {
value = 0d;
n = 0;
}
public GeometricMeanState(StreamInput in) throws IOException {
n = in.readVLong();
value = in.readDouble();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(n);
out.writeDouble(value);
}
private void addValue(double val) {
this.value += FastMath.log(val);
n++;
}
private void subValue(double val) {
this.value -= FastMath.log(val);
n--;
}
private Double value() {
if (n > 0) {
return FastMath.exp(value / n);
} else {
return null;
}
}
private void merge(GeometricMeanState other) {
this.value += other.value;
this.n += other.n;
}
@Override
public int compareTo(GeometricMeanState o) {
return Comparator.comparing(GeometricMeanState::value)
.thenComparing(x -> x.n)
.compare(this, o);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GeometricMeanState that = (GeometricMeanState) o;
return Objects.equals(value(), that.value());
}
@Override
public int hashCode() {
return Objects.hash(value());
}
}
public static class GeometricMeanStateType extends DataType<GeometricMeanState>
implements Streamer<GeometricMeanState>, FixedWidthType {
public static final GeometricMeanStateType INSTANCE = new GeometricMeanStateType();
public static final int ID = 4096;
@Override
public int id() {
return ID;
}
@Override
public Precedence precedence() {
return Precedence.UNDEFINED;
}
@Override
public String getName() {
return "geometric_mean_state";
}
@Override
public Streamer<GeometricMeanState> streamer() {
return this;
}
@Override
public GeometricMeanState sanitizeValue(Object value) {
return (GeometricMeanState) value;
}
@Override
public int compare(GeometricMeanState val1, GeometricMeanState val2) {
return val1.compareTo(val2);
}
@Override
public int fixedSize() {
return 40;
}
@Override
public GeometricMeanState readValueFrom(StreamInput in) throws IOException {
return new GeometricMeanState(in);
}
@Override
public void writeValueTo(StreamOutput out, GeometricMeanState v) throws IOException {
v.writeTo(out);
}
}
private final Signature signature;
private final Signature boundSignature;
public GeometricMeanAggregation(Signature signature, Signature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
}
@Nullable
@Override
public GeometricMeanState newState(RamAccounting ramAccounting,
Version indexVersionCreated,
Version minNodeInCluster,
MemoryManager memoryManager) {
ramAccounting.addBytes(GeometricMeanStateType.INSTANCE.fixedSize());
return new GeometricMeanState();
}
@Override
public GeometricMeanState iterate(RamAccounting ramAccounting,
MemoryManager memoryManager,
GeometricMeanState state,
Input... args) throws CircuitBreakingException {
if (state != null) {
Number value = (Number) args[0].value();
if (value != null) {
state.addValue(value.doubleValue());
}
}
return state;
}
@Override
public GeometricMeanState reduce(RamAccounting ramAccounting, GeometricMeanState state1, GeometricMeanState state2) {
if (state1 == null) {
return state2;
}
if (state2 == null) {
return state1;
}
state1.merge(state2);
return state1;
}
@Override
public Double terminatePartial(RamAccounting ramAccounting, GeometricMeanState state) {
return state.value();
}
@Override
public boolean isRemovableCumulative() {
return true;
}
@Override
public GeometricMeanState removeFromAggregatedState(RamAccounting ramAccounting,
GeometricMeanState previousAggState,
Input[] stateToRemove) {
if (previousAggState != null) {
Number value = (Number) stateToRemove[0].value();
if (value != null) {
previousAggState.subValue(value.doubleValue());
}
}
return previousAggState;
}
@Override
public DataType<?> partialType() {
return GeometricMeanStateType.INSTANCE;
}
@Override
public Signature signature() {
return signature;
}
@Override
public Signature boundSignature() {
return boundSignature;
}
@Nullable
@Override
public DocValueAggregator<?> getDocValueAggregator(List<Reference> aggregationReferences,
DocTableInfo table,
List<Literal<?>> optionalParams) {
Reference reference = aggregationReferences.get(0);
if (!reference.hasDocValues()) {
return null;
}
switch (reference.valueType().id()) {
case ByteType.ID:
case ShortType.ID:
case IntegerType.ID:
case LongType.ID:
case TimestampType.ID_WITH_TZ:
case TimestampType.ID_WITHOUT_TZ:
return new SortedNumericDocValueAggregator<>(
reference.column().fqn(),
(ramAccounting, memoryManager, minNodeVersion) -> {
ramAccounting.addBytes(GeometricMeanStateType.INSTANCE.fixedSize());
return new GeometricMeanState();
},
(values, state) -> state.addValue(values.nextValue())
);
case FloatType.ID:
return new SortedNumericDocValueAggregator<>(
reference.column().fqn(),
(ramAccounting, memoryManager, minNodeVersion) -> {
ramAccounting.addBytes(GeometricMeanStateType.INSTANCE.fixedSize());
return new GeometricMeanState();
},
(values, state) -> {
var value = NumericUtils.sortableIntToFloat((int) values.nextValue());
state.addValue(value);
}
);
case DoubleType.ID:
return new SortedNumericDocValueAggregator<>(
reference.column().fqn(),
(ramAccounting, memoryManager, minNodeVersion) -> {
ramAccounting.addBytes(GeometricMeanStateType.INSTANCE.fixedSize());
return new GeometricMeanState();
},
(values, state) -> {
var value = NumericUtils.sortableLongToDouble((values.nextValue()));
state.addValue(value);
}
);
default:
return null;
}
}
}
| |
/*
* Copyright (C) 2005-2008 Jive Software, 2022 Ignite Realtime Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.interceptor;
import org.dom4j.Element;
import org.jivesoftware.openfire.RoutingTable;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.component.ComponentEventListener;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.TaskEngine;
import org.jivesoftware.util.XMPPDateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Packet interceptor that notifies of packets activity to components that previously
* subscribed to the notificator. Notifications to components will be made using
* a Message sent to the component itself. The Message will include an extension that will
* contain the intercepted packet as well as extra information such us {@code incoming}
* and {@code processed}.
*
* @author Gaston Dombiak
*/
public class PacketCopier implements PacketInterceptor, ComponentEventListener {
private static final Logger Log = LoggerFactory.getLogger(PacketCopier.class);
private final static PacketCopier instance = new PacketCopier();
private Map<String, Subscription> subscribers = new ConcurrentHashMap<>();
private String serverName;
private RoutingTable routingTable;
/**
* Timer to save queued logs to the XML file.
*/
private ProcessPacketsTask packetsTask;
/**
* Queue that holds the audited packets that will be later saved to an XML file.
*/
private BlockingQueue<InterceptedPacket> packetQueue = new LinkedBlockingQueue<>(10000);
/**
* Returns unique instance of this class.
*
* @return unique instance of this class.
*/
public static PacketCopier getInstance() {
return instance;
}
private PacketCopier() {
// Add the new instance as a listener of component events. We need to react when
// a component is no longer valid
InternalComponentManager.getInstance().addListener(this);
XMPPServer server = XMPPServer.getInstance();
serverName = server.getServerInfo().getXMPPDomain();
routingTable = server.getRoutingTable();
// Add new instance to the PacketInterceptors list
InterceptorManager.getInstance().addInterceptor(this);
// Create a new task and schedule it with the new timeout
packetsTask = new ProcessPacketsTask();
TaskEngine.getInstance().schedule(packetsTask, Duration.ofSeconds(5), Duration.ofSeconds(5));
}
/**
* Creates new subscription for the specified component with the specified settings.
*
* @param componentJID the address of the component connected to the server.
* @param iqEnabled true if interested in IQ packets of any type.
* @param messageEnabled true if interested in Message packets.
* @param presenceEnabled true if interested in Presence packets.
* @param incoming true if interested in incoming traffic. false means outgoing.
* @param processed true if want to be notified after packets were processed.
*/
public void addSubscriber(JID componentJID, boolean iqEnabled, boolean messageEnabled, boolean presenceEnabled,
boolean incoming, boolean processed) {
subscribers.put(componentJID.toString(),
new Subscription(iqEnabled, messageEnabled, presenceEnabled, incoming, processed));
}
/**
* Removes the subscription of the specified component.
*
* @param componentJID the address of the component connected to the server.
*/
public void removeSubscriber(JID componentJID) {
subscribers.remove(componentJID.toString());
}
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
throws PacketRejectedException {
// Queue intercepted packet only if there are subscribers interested
if (!subscribers.isEmpty()) {
boolean queue = false;
Class packetClass = packet.getClass();
for (Subscription subscription : subscribers.values()) {
if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
queue = true;
}
else if (subscription.isMessageEnabled() && packetClass == Message.class) {
queue = true;
}
else if (subscription.isIQEnabled() && packetClass == IQ.class) {
queue = true;
}
}
if (queue) {
// Queue packet with extra information and let the background thread process it
packetQueue.add(new InterceptedPacket(packet, incoming, processed));
}
}
}
@Override
public void componentInfoReceived(IQ iq) {
//Ignore
}
@Override
public void componentRegistered(JID componentJID) {
//Ignore
}
@Override
public void componentUnregistered(JID componentJID) {
//Remove component from the list of subscribers (if subscribed)
removeSubscriber(componentJID);
}
private void processPackets() {
List<InterceptedPacket> packets = new ArrayList<>(packetQueue.size());
packetQueue.drainTo(packets);
for (InterceptedPacket interceptedPacket : packets) {
for (Map.Entry<String, Subscription> entry : subscribers.entrySet()) {
boolean notify = false;
String componentJID = entry.getKey();
Subscription subscription = entry.getValue();
if (subscription.isIncoming() == interceptedPacket.isIncoming() &&
subscription.isProcessed() == interceptedPacket.isProcessed()) {
Class packetClass = interceptedPacket.getPacketClass();
if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
notify = true;
}
else if (subscription.isMessageEnabled() && packetClass == Message.class) {
notify = true;
}
else if (subscription.isIQEnabled() && packetClass == IQ.class) {
notify = true;
}
}
if (notify) {
try {
Message message = new Message();
message.setFrom(serverName);
message.setTo(componentJID);
Element childElement = message.addChildElement("copy",
"http://jabber.org/protocol/packet#event");
childElement.addAttribute("incoming", subscription.isIncoming() ? "true" : "false");
childElement.addAttribute("processed", subscription.isProcessed() ? "true" : "false");
childElement.addAttribute("date", XMPPDateTimeFormat.format(interceptedPacket.getCreationDate()));
childElement.add(interceptedPacket.getElement().createCopy());
// Send message notification to subscribed component
routingTable.routePacket(message.getTo(), message, true);
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
}
}
private class ProcessPacketsTask extends TimerTask {
@Override
public void run() {
try {
// Notify components of intercepted packets
processPackets();
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
private static class Subscription {
private boolean presenceEnabled;
private boolean messageEnabled;
private boolean iqEnabled;
private boolean incoming;
private boolean processed;
/**
* Creates a new subscription for the specified Component with the
* specified configuration.
*
* @param iqEnabled true if interested in IQ packets of any type.
* @param messageEnabled true if interested in Message packets.
* @param presenceEnabled true if interested in Presence packets.
* @param incoming true if interested in incoming traffic. false means outgoing.
* @param processed true if want to be notified after packets were processed.
*/
public Subscription(boolean iqEnabled, boolean messageEnabled,
boolean presenceEnabled, boolean incoming, boolean processed) {
this.incoming = incoming;
this.iqEnabled = iqEnabled;
this.messageEnabled = messageEnabled;
this.presenceEnabled = presenceEnabled;
this.processed = processed;
}
/**
* Returns true if the component is interested in receiving notifications
* of intercepted IQ packets.
*
* @return true if the component is interested in receiving notifications
* of intercepted IQ packets.
*/
public boolean isIQEnabled() {
return iqEnabled;
}
/**
* Returns true if the component is interested in receiving notifications
* of intercepted Message packets.
*
* @return true if the component is interested in receiving notifications
* of intercepted Message packets.
*/
public boolean isMessageEnabled() {
return messageEnabled;
}
/**
* Returns true if the component is interested in receiving notifications
* of intercepted Presence packets.
*
* @return true if the component is interested in receiving notifications
* of intercepted Presence packets.
*/
public boolean isPresenceEnabled() {
return presenceEnabled;
}
/**
* Returns true if the component wants to be notified of incoming traffic. A false
* value means that the component is interested in outgoing traffic.
*
* @return true if interested in incoming traffic. false means outgoing.
*/
public boolean isIncoming() {
return incoming;
}
/**
* Returns true if the component wants to be notified of after packets were
* processed. Processed has different meaning depending if the packet is incoming
* or outgoing. An incoming packet that was processed means that the server
* routed the packet to the recipient and nothing else should be done with the packet.
* However, an outgoing packet that was processed means that the packet was already
* sent to the target entity.
*
* @return true if interested in incoming traffic. false means outgoing.
*/
public boolean isProcessed() {
return processed;
}
}
private static class InterceptedPacket {
private Element element;
private Class packetClass;
private Date creationDate;
private boolean incoming;
private boolean processed;
public InterceptedPacket(Packet packet, boolean incoming, boolean processed) {
packetClass = packet.getClass();
this.element = packet.getElement();
this.incoming = incoming;
this.processed = processed;
creationDate = new Date();
}
public Class getPacketClass() {
return packetClass;
}
public Date getCreationDate() {
return creationDate;
}
public Element getElement() {
return element;
}
public boolean isIncoming() {
return incoming;
}
public boolean isProcessed() {
return processed;
}
}
}
| |
/*******************************************************************************
* OulipoMachine licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*******************************************************************************/
package org.oulipo.streams.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.oulipo.streams.types.InvariantSpan;
public class RopeUtilsTest {
public static final String documentHash = "fakeHash";
@Test
public void addWeightsOfRightLeaningChildNodesChained() throws Exception {
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 20, documentHash));
right.right = right2;
Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(0).right(right).build();
assertEquals(30, RopeUtils.addWeightsOfRightLeaningChildNodes(x));
}
@Test
public void addWeightsOfRightLeaningChildNodesLeftOnly() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash));
Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(1).left(left).build();
assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(x));
}
@Test
public void addWeightsOfRightLeaningChildNodesNoChildren() throws Exception {
Node<InvariantSpan> x = new Node<>(new InvariantSpan(1, 1, documentHash));
assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(x));
}
@Test
public void addWeightsOfRightLeaningChildNodesNullNode() throws Exception {
assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(null));
}
@Test
public void addWeightsOfRightLeaningChildNodesSimple() throws Exception {
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(0).right(right).build();
assertEquals(10, RopeUtils.addWeightsOfRightLeaningChildNodes(x));
}
@Test
public void addWeightsOfRightLeaningParentNodesChainedRight() throws Exception {
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 3, documentHash));
Node<InvariantSpan> right = new Node.Builder<InvariantSpan>(1).right(right2).build();
new Node.Builder<InvariantSpan>(1).right(right).build();
assertEquals(2, RopeUtils.addWeightsOfRightLeaningParentNodes(right2));
}
@Test
public void addWeightsOfRightLeaningParentNodesLeftNodeChild() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash));
new Node.Builder<InvariantSpan>(1).left(left).build();
assertEquals(0, RopeUtils.addWeightsOfRightLeaningParentNodes(left));
}
@Test(expected = IllegalStateException.class)
public void addWeightsOfRightLeaningParentNodesNull() throws Exception {
RopeUtils.addWeightsOfRightLeaningParentNodes(null);
}
@Test
public void addWeightsOfRightLeaningParentNodesNullParent() throws Exception {
Node<InvariantSpan> x = new Node<>(new InvariantSpan(1, 1, documentHash));
assertEquals(0, RopeUtils.addWeightsOfRightLeaningParentNodes(x));
}
@Test
public void addWeightsOfRightLeaningParentNodesRightNodeChild() throws Exception {
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 1, documentHash));
new Node.Builder<InvariantSpan>(1).right(right).build();
assertEquals(1, RopeUtils.addWeightsOfRightLeaningParentNodes(right));
}
@Test
public void characterCount() throws Exception {
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 20, documentHash));
right.right = right2;
Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(10).right(right).build();
assertEquals(40, RopeUtils.characterCount(x));
}
@Test
public void characterCountLeafNode() throws Exception {
assertEquals(3, RopeUtils.characterCount(new Node<>(new InvariantSpan(1, 3, documentHash))));
}
@Test
public void characterCountNullNode() throws Exception {
assertEquals(0, RopeUtils.characterCount(null));
}
@Test
public void concatLeft() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> parent = RopeUtils.concat(left, null);
assertEquals(10, parent.weight);
assertNotNull(left.parent);
}
@Test
public void concatNullLeftNullRight() throws Exception {
assertEquals(0, RopeUtils.concat(null, null).weight);
}
@Test
public void concatRight() throws Exception {
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> parent = RopeUtils.concat(null, right);
assertEquals(0, parent.weight);
assertNotNull(right.parent);
}
@Test
public void findSearchNode() throws Exception {
// RopeUtils.findSearchNode(x, weight, root)
}
@Test
public void indexDisplacement() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash));
Node<InvariantSpan> right = new Node<>(new InvariantSpan(2, 3, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(1).left(left).right(right).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(2, root, 0);
assertEquals(1, index.displacement);
}
@Test
public void indexLeft() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(5, root, 0);
assertEquals(new InvariantSpan(1, 10, documentHash), index.node.value);
assertEquals(0, index.displacement);
}
@Test
public void indexLeftLeftChain() throws Exception {
Node<InvariantSpan> left2 = new Node<>(new InvariantSpan(100, 10, documentHash));
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(200, 5, documentHash));
Node<InvariantSpan> left1 = new Node.Builder<InvariantSpan>(10).left(left2).right(right2).build();
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(15).left(left1).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(10, root, 0);
assertEquals(new InvariantSpan(100, 10, documentHash), index.node.value);
assertEquals(0, index.displacement);
}
@Test
public void indexLeftLower() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(1, root, 0);
assertEquals(new InvariantSpan(1, 10, documentHash), index.node.value);
assertEquals(0, index.displacement);
}
@Test
public void indexLeftRightChain() throws Exception {
Node<InvariantSpan> left2 = new Node<>(new InvariantSpan(100, 10, documentHash));
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(200, 5, documentHash));
Node<InvariantSpan> left1 = new Node.Builder<InvariantSpan>(10).left(left2).right(right2).build();
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(15).left(left1).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(11, root, 0);
assertEquals(new InvariantSpan(200, 5, documentHash), index.node.value);
assertEquals(10, index.displacement);
}
@Test(expected = IndexOutOfBoundsException.class)
public void indexLeftTooHigh() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).build();
RopeUtils.index(11, root, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void indexLeftTooLow() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).build();
RopeUtils.index(0, root, 0);
}
@Test
public void indexLeftUpper() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(10, root, 0);
assertEquals(new InvariantSpan(1, 10, documentHash), index.node.value);
assertEquals(0, index.displacement);
}
@Test(expected = IndexOutOfBoundsException.class)
public void indexOutOutBoundsRight() throws Exception {
Node<InvariantSpan> left2 = new Node<>(new InvariantSpan(100, 10, documentHash));
Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(200, 5, documentHash));
Node<InvariantSpan> left1 = new Node.Builder<InvariantSpan>(10).left(left2).right(right2).build();
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(15).left(left1).build();
RopeUtils.index(20, root, 0);
}
@Test
public void indexRight() throws Exception {
Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash));
Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 20, documentHash));
Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).right(right).build();
NodeIndex<InvariantSpan> index = RopeUtils.index(15, root, 0);
assertEquals(new InvariantSpan(1, 20, documentHash), index.node.value);
assertEquals(10, index.displacement);
}
}
| |
package org.diorite.utils.reflections;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.Map;
import org.diorite.cfg.system.ConfigField;
import org.diorite.utils.SimpleEnum;
@SuppressWarnings({"unchecked", "ObjectEquality"})
public final class DioriteReflectionUtils
{
private DioriteReflectionUtils()
{
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final ConfigField field)
{
return getReflectElement(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find element.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final String fieldName, final Class<?> clazz)
{
final ReflectGetter<T> getter = getReflectGetter(fieldName, clazz);
if (getter instanceof ReflectField)
{
final ReflectField<T> reflectField = (ReflectField<T>) getter;
return new ReflectElement<>(reflectField, reflectField);
}
else
{
return new ReflectElement<>(getter, getReflectSetter(fieldName, clazz));
}
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final Field field)
{
return getReflectElement(field, field.getDeclaringClass());
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final Field field, final Class<?> clazz)
{
final ReflectGetter<T> getter = getReflectGetter(field, clazz);
if (getter instanceof ReflectField)
{
final ReflectField<T> reflectField = (ReflectField<T>) getter;
return new ReflectElement<>(reflectField, reflectField);
}
else
{
return new ReflectElement<>(getter, getReflectSetter(field, clazz));
}
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final ConfigField field)
{
return getReflectSetter(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find setter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(String fieldName, final Class<?> clazz)
{
final String fieldNameCpy = fieldName;
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final NoSuchMethodException ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final NoSuchMethodException ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodSetter<>(m);
}
else
{
return new ReflectField<>(getField(clazz, fieldNameCpy));
}
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final Field field)
{
return getReflectSetter(field, field.getDeclaringClass());
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final Field field, final Class<?> clazz)
{
String fieldName = field.getName();
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("set" + fieldName);
} catch (final NoSuchMethodException ignored1)
{
for (final Method cm : clazz.getMethods())
{
if (cm.getName().equalsIgnoreCase("set" + fieldName) && (cm.getParameterCount() == 1))
{
m = cm;
break;
}
}
}
if (m != null)
{
return new ReflectMethodSetter<>(m);
}
else
{
return new ReflectField<>(field);
}
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final ConfigField field)
{
return getReflectGetter(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find getter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(String fieldName, final Class<?> clazz)
{
final String fieldNameCpy = fieldName;
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final NoSuchMethodException ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final NoSuchMethodException ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodGetter<>(m);
}
else
{
return new ReflectField<>(getField(clazz, fieldNameCpy));
}
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final Field field)
{
return getReflectGetter(field, field.getDeclaringClass());
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final Field field, final Class<?> clazz)
{
String fieldName = field.getName();
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final NoSuchMethodException ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final NoSuchMethodException ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodGetter<>(m);
}
else
{
return new ReflectField<>(field);
}
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param enumClass class of enum.
* @param <T> type of enum.
*
* @return enum element or null.
*/
public static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, final Class<? extends SimpleEnum<T>> enumClass)
{
return getSimpleEnumValueSafe(name, id, enumClass, null);
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param def default value, can't be null.
* @param <T> type of enum.
*
* @return enum element or def.
*/
public static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, final T def)
{
return getSimpleEnumValueSafe(name, id, def.getClass(), def);
}
private static final Map<Class<?>, Method> simpleEnumMethods = new IdentityHashMap<>(40);
private static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, Class<?> enumClass, final Object def)
{
do
{
try
{
Method m = simpleEnumMethods.get(enumClass);
if (m == null)
{
m = enumClass.getMethod("values");
simpleEnumMethods.put(enumClass, m);
}
final SimpleEnum<?>[] objects = (SimpleEnum<?>[]) m.invoke(null);
for (final SimpleEnum<?> object : objects)
{
if (object.name().equalsIgnoreCase(name) || (object.ordinal() == id))
{
return (T) object;
}
}
} catch (final Exception ignored)
{
}
enumClass = enumClass.getSuperclass();
} while ((enumClass != null) && ! (enumClass.equals(Object.class)));
return (T) def;
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param enumClass class of enum.
* @param <T> type of enum.
*
* @return enum element or null.
*/
public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass)
{
return getEnumValueSafe(name, id, enumClass, null);
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param def default value, can't be null.
* @param <T> type of enum.
*
* @return enum element or def.
*/
public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final T def)
{
return getEnumValueSafe(name, id, def.getDeclaringClass(), def);
}
private static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass, final T def)
{
final T[] elements = enumClass.getEnumConstants();
for (final T element : elements)
{
if (element.name().equalsIgnoreCase(name) || (element.ordinal() == id))
{
return element;
}
}
return def;
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType)
{
return getField(target, name, fieldType, 0);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final String className, final String name, final Class<T> fieldType)
{
return getField(getCanonicalClass(className), name, fieldType, 0);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final Class<T> fieldType, final int index)
{
return getField(target, null, fieldType, index);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final String className, final Class<T> fieldType, final int index)
{
return getField(getCanonicalClass(className), fieldType, index);
}
/**
* Set given accessible object as accessible if needed.
*
* @param o accessible to get access.
* @param <T> type of accessible object, used to keep type of returned value.
*
* @return this same object as given.
*/
public static <T extends AccessibleObject> T getAccess(final T o)
{
if (! o.isAccessible())
{
o.setAccessible(true);
}
return o;
}
/**
* Set field as accessible, and remove final flag if set.
*
* @param field field to get access.
*
* @return this same field.
*/
public static Field getAccess(final Field field)
{
getAccess((AccessibleObject) field);
if (Modifier.isFinal(field.getModifiers()))
{
try
{
final Field modifiersField = Field.class.getDeclaredField("modifiers");
getAccess(modifiersField);
modifiersField.setInt(field, field.getModifiers() & ~ Modifier.FINAL);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
{
throw new IllegalArgumentException("That shouldn't happend (0)");
}
}
return field;
}
/**
* Search for the first publically and privately defined field of thie given name.
*
* @param target class to search in.
* @param name name of field.
* @param <T> type of field.
*
* @return field accessor for this field.
*
* @throws IllegalStateException If we cannot find this field.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final String name)
{
for (final Field field : target.getDeclaredFields())
{
if (((name == null) || field.getName().equals(name)))
{
getAccess(field);
return new FieldAccessor<>(field);
}
}
// Search in parent classes
if (target.getSuperclass() != null)
{
return getField(target.getSuperclass(), name);
}
throw new IllegalArgumentException("Cannot find field with name " + name);
}
// Common method
private static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType, int index)
{
for (final Field field : target.getDeclaredFields())
{
if (((name == null) || field.getName().equals(name)) && (fieldType.isAssignableFrom(field.getType()) && (index-- <= 0)))
{
getAccess(field);
return new FieldAccessor<>(field);
}
}
// Search in parent classes
if (target.getSuperclass() != null)
{
return getField(target.getSuperclass(), name, fieldType, index);
}
throw new IllegalArgumentException("Cannot find field with type " + fieldType + " in " + target + ", index: " + index);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws IllegalStateException If we cannot find this method.
*/
public static MethodInvoker getMethod(final String className, final String methodName, final Class<?>... params)
{
return getSimpleMethod(getCanonicalClass(className), methodName, null, params);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws IllegalStateException If we cannot find this method.
*/
public static MethodInvoker getMethod(final Class<?> clazz, final String methodName, final Class<?>... params)
{
return getSimpleMethod(clazz, methodName, null, params);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param returnType - the expected return type, or NULL to ignore.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws IllegalStateException If we cannot find this method.
*/
public static MethodInvoker getTypedMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
{
for (final Method method : clazz.getDeclaredMethods())
{
if (((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)) && Arrays.equals(method.getParameterTypes(), params))
{
getAccess(method);
return new MethodInvoker(method);
}
}
// Search in every superclass
if (clazz.getSuperclass() != null)
{
return getMethod(clazz.getSuperclass(), methodName, params);
}
throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param returnType - the expected return type, or NULL to ignore.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws IllegalStateException If we cannot find this method.
*/
private static MethodInvoker getSimpleMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
{
for (final Method method : clazz.getDeclaredMethods())
{
if (((params.length == 0) || Arrays.equals(method.getParameterTypes(), params)) && ((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)))
{
getAccess(method);
return new MethodInvoker(method);
}
}
// Search in every superclass
if (clazz.getSuperclass() != null)
{
return getMethod(clazz.getSuperclass(), methodName, params);
}
throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param params - the expected parameters.
*
* @return An object that invokes this constructor.
*
* @throws IllegalStateException If we cannot find this method.
*/
public static ConstructorInvoker getConstructor(final String className, final Class<?>... params)
{
return getConstructor(getCanonicalClass(className), params);
}
/**
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param params - the expected parameters.
*
* @return An object that invokes this constructor.
*
* @throws IllegalStateException If we cannot find this method.
*/
public static ConstructorInvoker getConstructor(final Class<?> clazz, final Class<?>... params)
{
for (final Constructor<?> constructor : clazz.getDeclaredConstructors())
{
if (Arrays.equals(constructor.getParameterTypes(), params))
{
getAccess(constructor);
return new ConstructorInvoker(constructor);
}
}
throw new IllegalStateException(String.format("Unable to find constructor for %s (%s).", clazz, Arrays.asList(params)));
}
/**
* Search for nested class with givan name.
*
* @param clazz - a class to start with.
* @param name - name of class.
*
* @return nested class form given class.
*/
public static Class<?> getNestedClass(final Class<?> clazz, final String name)
{
for (final Class<?> nc : clazz.getDeclaredClasses())
{
if ((name == null) || nc.getSimpleName().equals(name))
{
return nc;
}
}
if (clazz.getSuperclass() != null)
{
return getNestedClass(clazz.getSuperclass(), name);
}
throw new IllegalStateException("Unable to find nested class: " + name + " in " + clazz.getName());
}
/**
* If given class is non-primitive type {@link Class#isPrimitive()} then it will return
* privitive class for it. Like: Boolean.class {@literal ->} boolean.class
* If given class is primitive, then it will return given class.
* If given class can't be primitive (like {@link String}) then it will return given class.
*
* @param clazz class to get primitive of it.
*
* @return primitive class if possible.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getPrimitive(final Class<?> clazz)
{
if (clazz.isPrimitive())
{
return clazz;
}
if (clazz == Boolean.class)
{
return boolean.class;
}
if (clazz == Byte.class)
{
return byte.class;
}
if (clazz == Short.class)
{
return short.class;
}
if (clazz == Character.class)
{
return char.class;
}
if (clazz == Integer.class)
{
return int.class;
}
if (clazz == Long.class)
{
return long.class;
}
if (clazz == Float.class)
{
return float.class;
}
if (clazz == Double.class)
{
return double.class;
}
return clazz;
}
/**
* If given class is primitive type {@link Class#isPrimitive()} then it will return
* wrapper class for it. Like: boolean.class {@literal ->} Boolean.class
* If given class isn't primitive, then it will return given class.
*
* @param clazz class to get wrapper of it.
*
* @return non-primitive class.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getWrapperClass(final Class<?> clazz)
{
if (! clazz.isPrimitive())
{
return clazz;
}
if (clazz == boolean.class)
{
return Boolean.class;
}
if (clazz == byte.class)
{
return Byte.class;
}
if (clazz == short.class)
{
return Short.class;
}
if (clazz == char.class)
{
return Character.class;
}
if (clazz == int.class)
{
return Integer.class;
}
if (clazz == long.class)
{
return Long.class;
}
if (clazz == float.class)
{
return Float.class;
}
if (clazz == double.class)
{
return Double.class;
}
throw new Error("Unknown primitive type?"); // not possible?
}
/**
* Get array class for given class.
*
* @param clazz class to get array type of it.
*
* @return array version of class.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getArrayClass(final Class<?> clazz)
{
if (clazz.isPrimitive())
{
if (clazz == boolean.class)
{
return boolean[].class;
}
if (clazz == byte.class)
{
return byte[].class;
}
if (clazz == short.class)
{
return short[].class;
}
if (clazz == char.class)
{
return char[].class;
}
if (clazz == int.class)
{
return int[].class;
}
if (clazz == long.class)
{
return long[].class;
}
if (clazz == float.class)
{
return float[].class;
}
if (clazz == double.class)
{
return double[].class;
}
}
if (clazz.isArray())
{
return getCanonicalClass("[" + clazz.getName());
}
return getCanonicalClass("[L" + clazz.getName() + ";");
}
/**
* Return class for given name or throw exception.
*
* @param canonicalName name of class to find.
*
* @return class for given name.
*
* @throws IllegalArgumentException if there is no class with given name.
*/
public static Class<?> getCanonicalClass(final String canonicalName) throws IllegalArgumentException
{
try
{
return Class.forName(canonicalName);
} catch (final ClassNotFoundException e)
{
throw new IllegalArgumentException("Cannot find " + canonicalName, e);
}
}
}
| |
/* Copyright (C) 2013-2020 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.incremental.dfa;
import java.lang.reflect.InvocationTargetException;
import javax.swing.SwingUtilities;
import net.automatalib.automata.fsa.impl.compact.CompactDFA;
import net.automatalib.commons.util.system.JVMUtil;
import net.automatalib.incremental.ConflictException;
import net.automatalib.incremental.dfa.IncrementalDFABuilder.TransitionSystemView;
import net.automatalib.visualization.Visualization;
import net.automatalib.words.Alphabet;
import net.automatalib.words.GrowingAlphabet;
import net.automatalib.words.Word;
import net.automatalib.words.impl.Alphabets;
import net.automatalib.words.impl.GrowingMapAlphabet;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test
public abstract class AbstractIncrementalPCDFABuilderTest {
private static final Alphabet<Character> TEST_ALPHABET = Alphabets.characters('a', 'c');
private static final Word<Character> W_1 = Word.fromString("abc");
private static final Word<Character> W_2 = Word.fromString("acb");
private static final Word<Character> W_3 = Word.fromString("ac");
private IncrementalDFABuilder<Character> incPcDfa;
@BeforeClass
public void setUp() {
this.incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
}
protected abstract <I> IncrementalDFABuilder<I> createIncrementalPCDFABuilder(Alphabet<I> alphabet);
@Test
public void testConfluenceBug() {
Word<Character> wB1 = Word.fromString("aaa");
Word<Character> wB2 = Word.fromString("bba");
Word<Character> wB3 = Word.fromString("aabaa");
incPcDfa.insert(wB1, true);
incPcDfa.insert(wB2, true);
incPcDfa.insert(wB3, true);
Assert.assertEquals(incPcDfa.lookup(Word.fromString("aababaa")), Acceptance.DONT_KNOW);
this.incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
}
@Test(dependsOnMethods = "testConfluenceBug")
public void testLookup() {
Assert.assertEquals(incPcDfa.lookup(W_1), Acceptance.DONT_KNOW);
Assert.assertEquals(incPcDfa.lookup(W_2), Acceptance.DONT_KNOW);
Assert.assertEquals(incPcDfa.lookup(W_3), Acceptance.DONT_KNOW);
incPcDfa.insert(W_1, true);
Assert.assertEquals(incPcDfa.lookup(W_1), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_1.prefix(2)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_1.prefix(1)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_1.prefix(0)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_2), Acceptance.DONT_KNOW);
Assert.assertEquals(incPcDfa.lookup(W_3), Acceptance.DONT_KNOW);
incPcDfa.insert(W_2, false);
Assert.assertEquals(incPcDfa.lookup(W_1), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_2), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(W_2.append('a')), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(W_3), Acceptance.DONT_KNOW);
Assert.assertEquals(incPcDfa.lookup(W_1.prefix(1)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_2.prefix(1)), Acceptance.TRUE);
incPcDfa.insert(W_3, true);
Assert.assertEquals(incPcDfa.lookup(W_1), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_2), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(W_3), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_1.prefix(2)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_2.prefix(1)), Acceptance.TRUE);
Assert.assertEquals(incPcDfa.lookup(W_3.append('a')), Acceptance.DONT_KNOW);
}
@Test(dependsOnMethods = "testLookup")
public void testInsertSame() {
int oldSize = incPcDfa.asGraph().size();
incPcDfa.insert(W_1, true);
Assert.assertEquals(incPcDfa.asGraph().size(), oldSize);
}
@Test(expectedExceptions = ConflictException.class, dependsOnMethods = "testLookup")
public void testConflict() {
incPcDfa.insert(W_1, false);
}
@Test(dependsOnMethods = "testLookup")
public void testFindSeparatingWord() {
CompactDFA<Character> testDfa = new CompactDFA<>(TEST_ALPHABET);
int s0 = testDfa.addInitialState(true);
int s1 = testDfa.addState(true);
int s2 = testDfa.addState(true);
int s3 = testDfa.addState(true);
testDfa.addTransition(s0, 'a', s1);
testDfa.addTransition(s1, 'b', s2);
testDfa.addTransition(s2, 'c', s3);
Word<Character> sepWord;
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, true);
Assert.assertNull(sepWord);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, false);
Assert.assertEquals(sepWord, Word.fromString("ac"));
int s4 = testDfa.addState(true);
testDfa.addTransition(s1, 'c', s4);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, true);
Assert.assertNull(sepWord);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, false);
Assert.assertNull(sepWord);
int s5 = testDfa.addState(false);
testDfa.addTransition(s4, 'b', s5);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, true);
Assert.assertNull(sepWord);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, false);
Assert.assertNull(sepWord);
int s6 = testDfa.addState(false);
testDfa.addTransition(s3, 'a', s6);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, true);
Assert.assertNull(sepWord);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, false);
Assert.assertNull(sepWord);
int s7 = testDfa.addState(true);
testDfa.addTransition(s5, 'a', s7);
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, true);
Assert.assertEquals(sepWord, Word.fromString("acba"));
sepWord = incPcDfa.findSeparatingWord(testDfa, TEST_ALPHABET, false);
Assert.assertEquals(sepWord, Word.fromString("acba"));
}
@Test(dependsOnMethods = "testLookup")
public void testVisualization() throws InvocationTargetException, InterruptedException {
if (JVMUtil.getCanonicalSpecVersion() > 8) {
throw new SkipException("The headless AWT environment currently only works with Java 8 and below");
}
// invokeAndWait so that TestNG doesn't kill our GUI thread that we want to check.
SwingUtilities.invokeAndWait(() -> Visualization.visualize(incPcDfa.asGraph(), false));
}
@Test(dependsOnMethods = "testLookup")
public void testTSView() {
testTSViewInternal(incPcDfa.asTransitionSystem());
}
private static <S> void testTSViewInternal(TransitionSystemView<S, Character, ?> view) {
final S s1 = view.getState(W_1);
final S s2 = view.getState(W_2);
final S s3 = view.getState(W_3);
Assert.assertTrue(view.getAcceptance(s1).toBoolean());
Assert.assertFalse(view.getAcceptance(s2).toBoolean());
Assert.assertTrue(view.getAcceptance(s3).toBoolean());
}
@Test(dependsOnMethods = "testLookup")
public void testNewInputSymbol() {
final GrowingAlphabet<Character> alphabet = new GrowingMapAlphabet<>(TEST_ALPHABET);
final IncrementalDFABuilder<Character> growableBuilder = createIncrementalPCDFABuilder(alphabet);
growableBuilder.addAlphabetSymbol('d');
growableBuilder.addAlphabetSymbol('d');
final Word<Character> input1 = Word.fromCharSequence("dcba");
growableBuilder.insert(input1, true);
Assert.assertTrue(growableBuilder.hasDefinitiveInformation(input1));
Assert.assertEquals(growableBuilder.lookup(input1), Acceptance.TRUE);
Assert.assertEquals(growableBuilder.lookup(input1.prefix(2)), Acceptance.TRUE);
final Word<Character> input2 = Word.fromCharSequence("dddd");
Assert.assertFalse(growableBuilder.hasDefinitiveInformation(input2));
Assert.assertEquals(growableBuilder.lookup(input2), Acceptance.DONT_KNOW);
growableBuilder.insert(input2, false);
Assert.assertEquals(growableBuilder.lookup(input2), Acceptance.FALSE);
Assert.assertEquals(growableBuilder.lookup(input2.append('d')), Acceptance.FALSE);
}
@Test
public void testCounterexampleOfLengthOne() {
final IncrementalDFABuilder<Character> incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
incPcDfa.insert(Word.fromCharSequence("a"), true);
final CompactDFA<Character> dfa = new CompactDFA<>(TEST_ALPHABET);
final Integer q0 = dfa.addInitialState(true);
final Integer q1 = dfa.addState(false);
dfa.addTransition(q0, 'a', q1);
final Word<Character> ce = incPcDfa.findSeparatingWord(dfa, TEST_ALPHABET, false);
Assert.assertNotNull(ce);
}
@Test
public void testRejectAll() {
final IncrementalDFABuilder<Character> incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
incPcDfa.insert(Word.epsilon(), false);
Assert.assertEquals(incPcDfa.lookup(W_1), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(W_2), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(W_3), Acceptance.FALSE);
Assert.assertThrows(ConflictException.class, () -> incPcDfa.insert(W_1, true));
Assert.assertThrows(ConflictException.class, () -> incPcDfa.insert(W_2, true));
Assert.assertThrows(ConflictException.class, () -> incPcDfa.insert(W_3, true));
}
@Test
public void testLateSink() {
final IncrementalDFABuilder<Character> incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
Word<Character> w1 = Word.fromString("abc");
Word<Character> w2 = Word.fromString("bca");
Word<Character> w3 = Word.fromString("cb");
incPcDfa.insert(w1, false);
incPcDfa.insert(w2, false);
Assert.assertEquals(incPcDfa.asGraph().size(), 6);
incPcDfa.insert(Word.epsilon(), false);
Assert.assertEquals(incPcDfa.asGraph().size(), 1);
Assert.assertEquals(incPcDfa.lookup(w1), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(w2), Acceptance.FALSE);
Assert.assertEquals(incPcDfa.lookup(w3), Acceptance.FALSE);
Assert.assertThrows(ConflictException.class, () -> incPcDfa.insert(w3, true));
}
@Test
public void testInvalidSink() {
final IncrementalDFABuilder<Character> incPcDfa = createIncrementalPCDFABuilder(TEST_ALPHABET);
incPcDfa.insert(Word.fromString("abc"), false);
incPcDfa.insert(Word.fromString("bca"), true);
Assert.assertEquals(incPcDfa.asGraph().size(), 7);
Assert.assertThrows(ConflictException.class, () -> incPcDfa.insert(Word.epsilon(), false));
}
}
| |
package com.x5.template;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.x5.template.filters.ChunkFilter;
import com.x5.template.filters.RegexFilter;
import com.x5.util.JarResource;
// Project Title: Chunk
// Description: Template Util
// Copyright: Copyright (c) 2007
// Author: Tom McClure
/**
* TemplateSet is a Chunk "factory" and an easy way to parse
* template files into Strings. The default caching behavior is
* great for high traffic applications.
*
* <PRE>
* // Dynamic content in templates is marked with {~...}
* //
* // Previously the syntax was {$...} but then I had a project where
* // some of the templates were shared by a perl script and I got
* // tired of escaping the $ signs in inline templates in my perl code.
* //
* // Before that there was an escaped-HTML-inspired syntax which
* // looked like &tag_...; since this was thought to be most
* // compatible with HTML editors like DreamWeaver but it was hard
* // to read and as it turned out DreamWeaver choked on it.
* //
* // See TemplateSet.convertTags(...) and .convertToMyTags(...) for
* // quick search-and-replace routines for updating tag syntax on
* // old templates...
* //
* // ...Or, if an entire template set uses another syntax just call
* // .setTagBoundaries("{$", "}") on the TemplateSet object before
* // you use it to make any chunks. All subsequent chunks made from
* // that TemplateSet will find and replace the {$...} style tags.
* //
* // Be careful: for interoperability you will need to call
* // .setTagBoundaries() individually on any blank chunks you make
* // without the aid of the TemplateSet object, ie with the Chunk
* // constructor -- better to use the no-arg .makeChunk() method of
* // the TemplateSet instead, since that automatically coerces the
* // blank Chunk's tag boundaries correctly.
* //
* ///// In summary, for back-compatibility:
* //
* // TemplateSet templates = new TemplateSet(...);
* // templates.setTagBoundaries("{$", "}");
* // ...
* //
* // *** (A) BAD ***
* // ...
* // Chunk c = new Chunk(); // will only explode tags like default {~...}
* //
* // *** (B) NOT AS BAD ***
* // ...
* // Chunk c = new Chunk();
* // c.setTagBoundaries("{$", "}"); // manually match tag format :(
* //
* // *** (C) BEST ***
* // ...
* // Chunk c = templates.makeChunk(); // inherits TemplateSet's tag format :)
* //
* </PRE>
*
* Copyright: waived, free to use<BR>
* Company: <A href="http://www.x5software.com/">X5 Software</A><BR>
* Updates: <A href="http://www.x5software.com/chunk/wiki/">Chunk Documentation</A><BR>
*
* @author Tom McClure
*/
public class TemplateSet implements ContentSource, ChunkFactory
{
public static String DEFAULT_TAG_START = "{$";
public static String DEFAULT_TAG_END = "}";
public static final String INCLUDE_SHORTHAND = "{+";
public static final String PROTOCOL_SHORTHAND = "{.";
// allow {^if}...{/if} and {^loop}...{/loop} by auto-expanding these
public static final String BLOCKEND_SHORTHAND = "{/";
public static final String BLOCKEND_LONGHAND = "{~./"; // ie "{^/"
private static final long oneMinuteInMillis = 60 * 1000;
// having a minimum cache time of five seconds improves
// performance by avoiding typical multiple parses of a
// file for its subtemplates in a short span of code.
private static final long MIN_CACHE = 5 * 1000;
private static final int DEFAULT_REFRESH = 15; // minutes
private static final String DEFAULT_EXTENSION = "chtml";
private Hashtable<String,Snippet> cache = new Hashtable<String,Snippet>();
private Hashtable<String,Long> cacheFetch = new Hashtable<String,Long>();
private int dirtyInterval = DEFAULT_REFRESH; // minutes
private String defaultExtension = DEFAULT_EXTENSION;
private String tagStart = DEFAULT_TAG_START;
private String tagEnd = DEFAULT_TAG_END;
private String templatePath = System.getProperty("templateset.folder","");
private String layerName = null;
private Class<?> classInJar = null;
private Object resourceContext = null;
private boolean prettyFail = true;
private String expectedEncoding = TemplateDoc.getDefaultEncoding();
public TemplateSet() {}
/**
* Makes a template "factory" which reads in template files from the
* file system in the templatePath folder. Caches for 15 minutes.
* Assumes .html is default file extension.
* @param templatePath folder where template files are located.
*/
public TemplateSet(String templatePath)
{
this(templatePath, DEFAULT_EXTENSION, DEFAULT_REFRESH);
}
/**
* Makes a template "factory" which reads in template files from the
* file system in the templatePath folder. Caches for refreshMins.
* Uses "extensions" for the default file extension (do not include dot).
* @param templatePath folder where template files are located.
* @param extension appends dot plus this String to a template name stub to find template files.
* @param refreshMins returns template from cache unless this many minutes have passed.
*/
public TemplateSet(String templatePath, String extension, int refreshMins)
{
if (templatePath != null) {
// ensure trailing fileseparator
char lastChar = templatePath.charAt(templatePath.length()-1);
char fs = System.getProperty("file.separator").charAt(0);
if (lastChar != '\\' && lastChar != '/' && lastChar != fs) {
templatePath += fs;
}
this.templatePath = templatePath;
}
this.dirtyInterval = refreshMins;
this.defaultExtension = (extension == null ? DEFAULT_EXTENSION : extension);
}
/**
* Retrieve as String the template specified by name.
* If name contains one or more dots it is assumed that the template
* definition is nested inside another template. Everything up to the
* first dot is part of the filename (appends the DEFAULT extension to
* find the file) and everything after refers to a location within the
* file where the template contents are defined.
* <P>
* For example: String myTemplate = templateSet.get("outer_file.inner_template");
* <P>
* will look for {#inner_template}bla bla bla{#} inside the file
* "outer_file.html" or "outer_file.xml" ie whatever your TemplateSet extension is.
* @param name the location of the template definition.
* @return the template definition from the file as a String
*/
public Snippet getSnippet(String name)
{
if (name.charAt(0) == ';') {
int nextSemi = name.indexOf(';',1);
if (nextSemi < 0) {
// missing delimiter
return getSnippet(name, defaultExtension);
} else {
String tpl = name.substring(nextSemi+1);
String ext = name.substring(1,nextSemi);
return getSnippet(tpl, ext);
}
} else {
return getSnippet(name, defaultExtension);
}
}
public String fetch(String name)
{
Snippet s = getCleanTemplate(name);
if (s == null) return null;
// otherwise...
return s.toString();
}
public String getProtocol()
{
return "include";
}
private Snippet getCleanTemplate(String name)
{
return getSnippet(name, "_CLEAN_:"+defaultExtension);
}
/**
* Retrieve as String the template specified by name and extension.
* If name contains one or more dots it is assumed that the template
* definition is nested inside another template. Everything up to the
* first dot is part of the filename (appends the PASSED extension to
* find the file) and everything after refers to a location within the
* file where the template contents are defined.
* @param name the location of the template definition.
* @param extension the nonstandard extension which forms the template filename.
* @return the template definition from the file as a String
*/
public Snippet getSnippet(String name, String extension)
{
return _get(name, extension, this.prettyFail);
}
private void importTemplates(InputStream in, String stub, String extension)
throws IOException
{
TemplateDoc doc = new TemplateDoc(stub, in);
for (TemplateDoc.Doclet doclet : doc.parseTemplates(expectedEncoding)) {
cacheTemplate(doclet, extension);
}
}
private Snippet _get(String name, String extension, boolean prettyFail)
{
Snippet template = getFromCache(name, extension);
String filename = null;
// if not in cache, parse file and place all pieces in cache
if (template == null) {
String stub = TemplateDoc.truncateNameToStub(name);
filename = getTemplatePath(name,extension);
char fs = System.getProperty("file.separator").charAt(0);
filename = filename.replace('\\',fs);
filename = filename.replace('/',fs);
try {
File templateFile = new File(filename);
if (templateFile.exists()) {
FileInputStream in = new FileInputStream(templateFile);
importTemplates(in, stub, extension);
in.close();
template = getFromCache(name, extension);
} else {
// file does not exist, check around in classpath/jars
String resourcePath = getResourcePath(name,extension);
InputStream inJar = null;
if (classInJar == null) {
// theme resource is probably in same
// vicinity as calling class.
classInJar = grokCallerClass();
}
// ideally, somebody called Theme.setJarContext(this.getClass())
// and we have a pointer to the jar where the templates live.
if (classInJar != null) {
inJar = classInJar.getResourceAsStream(resourcePath);
}
// last ditch effort, check in surrounding jars in classpath...
if (inJar == null) inJar = fishForTemplate(resourcePath);
if (inJar != null) {
importTemplates(inJar, stub, extension);
template = getFromCache(name, extension);
inJar.close();
}
}
} catch (IOException e) {
if (!prettyFail) return null;
StringBuilder errmsg = new StringBuilder("[error fetching ");
errmsg.append(extension);
errmsg.append(" template '");
errmsg.append(name);
errmsg.append("']<!-- ");
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
errmsg.append(w.toString());
errmsg.append(" -->");
template = Snippet.getSnippet(errmsg.toString());
}
}
if (template == null) {
if (prettyFail) {
StringBuilder errmsg = new StringBuilder();
errmsg.append("[");
errmsg.append(extension);
errmsg.append(" template '");
errmsg.append(name);
errmsg.append("' not found]<!-- looked in [");
errmsg.append(filename);
errmsg.append("] -->");
template = Snippet.getSnippet(errmsg.toString());
} else {
return null;
}
}
return template;
}
// default (package) visibility intentional
static Class<?> grokCallerClass()
{
Throwable t = new Throwable();
StackTraceElement[] stackTrace = t.getStackTrace();
if (stackTrace == null) return null;
// calling class is at least four call levels back up the stack trace.
// makes an excellent candidate for where to look for theme resources.
for (int i=4; i<stackTrace.length; i++) {
StackTraceElement e = stackTrace[i];
if (e.getClassName().matches("^com\\.x5\\.template\\.[^\\.]*$")) {
continue;
}
try {
return Class.forName(e.getClassName());
} catch (ClassNotFoundException e2) {}
}
return null;
}
// should run a benchmark and see how expensive this is...
private InputStream fishForTemplate(String resourcePath)
{
if (resourceContext != null) {
InputStream in = fishForTemplateInContext(resourcePath);
if (in != null) return in;
}
// fish around for this resource in other jars in the classpath
String cp = System.getProperty("java.class.path");
if (cp == null) return null;
String[] jars = cp.split(":");
if (jars == null) return null;
for (String jar : jars) {
if (jar.endsWith(".jar")) {
InputStream in = JarResource.peekInsideJar("jar:file:"+jar, resourcePath);
if (in != null) return in;
}
}
return null;
}
/**
* fishForTemplateInContext is able to use reflection to call methods
* in javax.http.ResourceContext without actually requiring the class
* to be present/loaded during compile.
*/
@SuppressWarnings("rawtypes")
private InputStream fishForTemplateInContext(String resourcePath)
{
// call getResourceAsStream via reflection
Class<?> ctxClass = resourceContext.getClass();
Method m = null;
try {
final Class[] oneString = new Class[]{String.class};
m = ctxClass.getMethod("getResourceAsStream", oneString);
if (m != null) {
InputStream in = (InputStream)m.invoke(resourceContext, new Object[]{resourcePath});
if (in != null) return in;
}
// no dice, start peeking inside jars in WEB-INF/lib/
m = ctxClass.getMethod("getResourcePaths", oneString);
if (m != null) {
Set paths = (Set)m.invoke(resourceContext, new Object[]{"/WEB-INF/lib"});
if (paths != null) {
for (Object urlString : paths) {
String jar = (String)urlString;
if (jar.endsWith(".jar")) {
m = ctxClass.getMethod("getResource", oneString);
URL jarURL = (URL)m.invoke(resourceContext, new Object[]{jar});
InputStream in = JarResource.peekInsideJar("jar:"+jarURL.toString(), resourcePath);
if (in != null) return in;
}
}
}
}
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return null;
}
/**
* Creates a Chunk with no starter template and sets its tag boundary
* markers to match the other templates in this set. The Chunk will need
* to obtain template pieces via its .append() method.
* @return blank Chunk.
*/
public Chunk makeChunk()
{
Chunk c = new Chunk();
c.setMacroLibrary(this,this);
shareContentSources(c);
return c;
}
/**
* Creates a Chunk with a starting template. If templateName contains one
* or more dots it is assumed that the template definition is nested inside
* another template. Everything up to the first dot is part of the filename
* (appends the DEFAULT extension to find the file) and everything after
* refers to a location within the file where the template contents are
* defined.
*
* @param templateName the location of the template definition.
* @return a Chunk pre-initialized with a snippet of template.
*/
public Chunk makeChunk(String templateName)
{
Chunk c = new Chunk();
c.setMacroLibrary(this,this);
c.append( getSnippet(templateName) );
shareContentSources(c);
return c;
}
/**
* Creates a Chunk with a starting template. If templateName contains one
* or more dots it is assumed that the template definition is nested inside
* another template. Everything up to the first dot is part of the filename
* (appends the PASSED extension to find the file) and everything after
* refers to a location within the file where the template contents are
* defined.
*
* @param templateName the location of the template definition.
* @param extension the nonstandard extension which forms the template filename.
* @return a Chunk pre-initialized with a snippet of template.
*/
public Chunk makeChunk(String templateName, String extension)
{
Chunk c = new Chunk();
c.setMacroLibrary(this,this);
c.append( getSnippet(templateName, extension) );
shareContentSources(c);
return c;
}
private void cacheTemplate(TemplateDoc.Doclet doclet, String extension)
{
String name = doclet.getName().replace('#','.');
String ref = extension + "." + name;
String cleanRef = "_CLEAN_:" + ref;
String template = doclet.getTemplate();
cache.put(cleanRef, Snippet.makeLiteralSnippet(template));
cacheFetch.put(cleanRef, System.currentTimeMillis());
StringBuilder tpl = TemplateDoc.expandShorthand(name,new StringBuilder(template));
if (tpl == null) return;
String fastTpl = removeBlockTagIndents(tpl.toString());
cache.put(ref, Snippet.getSnippet(fastTpl, doclet.getOrigin()));
cacheFetch.put(ref, System.currentTimeMillis());
}
public static String removeBlockTagIndents(String template)
{
// this regex: s/^\s*({^\/?(...)[^}]*})\s*/$1/g removes leading and trailing whitespace
// from lines that only contain {^loop} ...
// NB: this regex will not catch {^if (~tag =~ /\/x{1,3}/)} but it's already nigh-unreadable...
return RegexFilter.applyRegex(template, "s/^[ \\t]*(\\{(\\% *(\\~\\.)?(end)?|(\\^|\\~\\.)\\/?)(loop|exec|if|else|elseIf|divider|onEmpty|body|data)([^\\}]*|[^\\}]*\\/[^\\/]*\\/[^\\}]*)\\})[ \\t]*$/$1/gmi");
}
protected Snippet getFromCache(String name, String extension)
{
String ref = extension + "." + name.replace('#','.');
Snippet template = null;
long cacheHowLong = dirtyInterval * oneMinuteInMillis;
if (cacheHowLong < MIN_CACHE) cacheHowLong = MIN_CACHE;
if (cache.containsKey(ref)) {
long lastFetch = cacheFetch.get(ref); // millis
long expireTime = lastFetch + cacheHowLong;
if (System.currentTimeMillis() < expireTime) {
template = cache.get(ref);
}
}
return template;
}
/**
* Forces subsequent template fetching to re-read the template contents
* from the filesystem instead of the cache.
*/
public void clearCache()
{
cache.clear();
cacheFetch.clear();
}
/**
* Controls caching behavior. Set to zero to minimize caching.
* @param minutes how long to keep a template in the cache.
*/
public void setDirtyInterval(int minutes)
{
dirtyInterval = minutes;
}
/**
* Converts a template with an alternate tag syntax to one that matches
* this TemplateSet's tags.
* @param withOldTags Template text which contains tags with the old syntax
* @param oldTagStart old tag beginning marker
* @param oldTagEnd old tag end marker
* @return template with tags converted
*/
public String convertToMyTags(String withOldTags, String oldTagStart, String oldTagEnd)
{
return convertTags(withOldTags, oldTagStart, oldTagEnd, this.tagStart, this.tagEnd);
}
/**
* Converts a template with an alternate tag syntax to one that matches
* the default tag syntax {~myTag}.
* @param withOldTags Template text which contains tags with the old syntax
* @param oldTagStart old tag beginning marker
* @param oldTagEnd old tag end marker
* @return template with tags converted
*/
public static String convertTags(String withOldTags, String oldTagStart, String oldTagEnd)
{
return convertTags(withOldTags, oldTagStart, oldTagEnd,
DEFAULT_TAG_START, DEFAULT_TAG_END);
}
/**
* Converts a template from one tag syntax to another.
* @param withOldTags Template text which contains tags with the old syntax
* @param oldTagStart old tag beginning marker
* @param oldTagEnd old tag end marker
* @param newTagStart new tag beginning marker
* @param newTagEnd new tag end marker
* @return template with tags converted
*/
public static String convertTags(String withOldTags, String oldTagStart, String oldTagEnd,
String newTagStart, String newTagEnd)
{
StringBuilder converted = new StringBuilder();
int j, k, marker = 0;
while ((j = withOldTags.indexOf(oldTagStart,marker)) > -1) {
converted.append(withOldTags.substring(marker,j));
marker = j + oldTagStart.length();
if ((k = withOldTags.indexOf(oldTagEnd)) > -1) {
converted.append(newTagStart);
converted.append(withOldTags.substring(marker,k));
converted.append(newTagEnd);
marker = k + oldTagEnd.length();
} else {
converted.append(oldTagStart);
}
}
if (marker == 0) {
return withOldTags;
} else {
converted.append(withOldTags.substring(marker));
return converted.toString();
}
}
public TemplateSet getSubset(String context)
{
return new TemplateSetSlice(this, context);
}
// chunk factory now supports sharing content sources with its factory-created chunks
private HashSet<ContentSource> altSources = null;
public void addProtocol(ContentSource src)
{
if (altSources == null) altSources = new HashSet<ContentSource>();
altSources.add(src);
}
private void shareContentSources(Chunk c)
{
if (altSources == null) return;
java.util.Iterator<ContentSource> iter = altSources.iterator();
while (iter.hasNext()) {
ContentSource src = iter.next();
c.addProtocol(src);
}
}
public void signalFailureWithNull()
{
this.prettyFail = false;
}
public String getTemplatePath(String templateName, String ext)
{
String stub = TemplateDoc.truncateNameToStub(templateName);
String path = templatePath + stub;
if (ext != null && ext.length() > 0) {
path += '.' + ext;
}
return path;
}
public String getResourcePath(String templateName, String ext)
{
String stub = TemplateDoc.truncateNameToStub(templateName);
String path;
if (layerName == null) {
path = "/themes/" + stub;
} else {
path = "/themes/" + layerName + stub;
}
if (ext != null && ext.length() > 0) {
path += '.' + ext;
}
return path;
}
public String getDefaultExtension()
{
return this.defaultExtension;
}
public boolean provides(String itemName)
{
Snippet found = _get(itemName, defaultExtension, false);
if (found == null) {
return false;
} else {
return true;
}
}
public void setJarContext(Class<?> classInSameJar)
{
this.classInJar = classInSameJar;
}
public void setJarContext(Object ctx)
{
// an object with an InputStream getResourceAsStream(String) method
this.resourceContext = ctx;
}
public void setLayerName(String layerName)
{
this.layerName = layerName;
if (layerName != null && !layerName.endsWith("/")) {
this.layerName = this.layerName + "/";
}
}
public void setEncoding(String encoding)
{
this.expectedEncoding = encoding;
}
public Map<String,ChunkFilter> getFilters()
{
return null;
}
}
| |
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.adwords.axis.utils.v201506.shopping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.api.ads.adwords.axis.v201506.cm.ProductAdwordsGrouping;
import com.google.api.ads.adwords.axis.v201506.cm.ProductAdwordsLabels;
import com.google.api.ads.adwords.axis.v201506.cm.ProductBiddingCategory;
import com.google.api.ads.adwords.axis.v201506.cm.ProductBrand;
import com.google.api.ads.adwords.axis.v201506.cm.ProductCanonicalCondition;
import com.google.api.ads.adwords.axis.v201506.cm.ProductCanonicalConditionCondition;
import com.google.api.ads.adwords.axis.v201506.cm.ProductChannel;
import com.google.api.ads.adwords.axis.v201506.cm.ProductChannelExclusivity;
import com.google.api.ads.adwords.axis.v201506.cm.ProductCustomAttribute;
import com.google.api.ads.adwords.axis.v201506.cm.ProductDimension;
import com.google.api.ads.adwords.axis.v201506.cm.ProductDimensionType;
import com.google.api.ads.adwords.axis.v201506.cm.ProductLegacyCondition;
import com.google.api.ads.adwords.axis.v201506.cm.ProductOfferId;
import com.google.api.ads.adwords.axis.v201506.cm.ProductType;
import com.google.api.ads.adwords.axis.v201506.cm.ProductTypeFull;
import com.google.api.ads.adwords.axis.v201506.cm.ShoppingProductChannel;
import com.google.api.ads.adwords.axis.v201506.cm.ShoppingProductChannelExclusivity;
import com.google.api.ads.adwords.axis.v201506.cm.UnknownProductDimension;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests for {@link ProductDimensions}.
*
* @author Josh Radcliff
*/
@RunWith(JUnit4.class)
public class ProductDimensionsTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static final String STRING_VALUE = "dummy";
/**
* Set of {@link ProductDimension} subclasses to ignore because they either are not supported by
* shopping campaigns or are not ADD-able.
*/
private static final ImmutableSet<Class<? extends ProductDimension>> DIMENSION_TYPES_TO_IGNORE =
ImmutableSet
.<Class<? extends ProductDimension>>builder()
.add(ProductAdwordsGrouping.class)
.add(ProductAdwordsLabels.class)
.add(ProductLegacyCondition.class)
.add(ProductTypeFull.class)
.add(UnknownProductDimension.class)
.build();
/**
* Test method for createType.
*/
@Test
public void testCreateType() {
ProductType type =
ProductDimensions.createType(ProductDimensionType.PRODUCT_TYPE_L1, STRING_VALUE);
assertEquals(STRING_VALUE, type.getValue());
}
/**
* Test method for createType with a null product type level. This should fail.
*/
@Test
public void testCreateType_nullTypeLevel_fails() {
thrown.expect(NullPointerException.class);
ProductDimensions.createType(null, STRING_VALUE);
}
/**
* Test method for createCanonicalCondition.
*/
@Test
public void testCreateCanonicalCondition() {
ProductCanonicalCondition condition =
ProductDimensions.createCanonicalCondition(ProductCanonicalConditionCondition.NEW);
assertEquals(ProductCanonicalConditionCondition.NEW, condition.getCondition());
}
/**
* Test method for createBiddingCategory.
*/
@Test
public void testCreateBiddingCategory() {
ProductBiddingCategory category =
ProductDimensions.createBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1, 1L);
assertEquals(ProductDimensionType.BIDDING_CATEGORY_L1, category.getType());
assertEquals(Long.valueOf(1), category.getValue());
}
/**
* Test method for testCreateBiddingCategory with a null category level. This should fail.
*/
@Test
public void testCreateBiddingCategory_nullCategoryLevel_fails() {
thrown.expect(NullPointerException.class);
ProductDimensions.createBiddingCategory(null, 1L);
}
/**
* Test method for createOfferId.
*/
@Test
public void testCreateOfferId() {
ProductOfferId offerId = ProductDimensions.createOfferId(STRING_VALUE);
assertEquals(STRING_VALUE, offerId.getValue());
}
/**
* Test method for createBrand.
*/
@Test
public void testCreateBrand() {
ProductBrand brand = ProductDimensions.createBrand(STRING_VALUE);
assertEquals(STRING_VALUE, brand.getValue());
}
/**
* Test method for createCustomAttribute.
*/
@Test
public void testCreateCustomAttribute() {
ProductCustomAttribute attribute = ProductDimensions.createCustomAttribute(
ProductDimensionType.CUSTOM_ATTRIBUTE_2, STRING_VALUE);
assertEquals(ProductDimensionType.CUSTOM_ATTRIBUTE_2, attribute.getType());
assertEquals(STRING_VALUE, attribute.getValue());
}
/**
* Test method for testCreateBiddingCategory with a null category level. This should fail.
*/
@Test
public void testCreateCustomAttribute_nullAttributeLevel_fails() {
thrown.expect(NullPointerException.class);
ProductDimensions.createCustomAttribute(null, STRING_VALUE);
}
/**
* Test method for createChannel.
*/
@Test
public void testCreateChannel() {
ProductChannel channel = ProductDimensions.createChannel(ShoppingProductChannel.LOCAL);
assertEquals(ShoppingProductChannel.LOCAL, channel.getChannel());
}
/**
* Test method for createChannelExclusivity.
*/
@Test
public void testCreateChannelExclusivity() {
ProductChannelExclusivity channelExclusivity =
ProductDimensions.createChannelExclusivity(ShoppingProductChannelExclusivity.MULTI_CHANNEL);
assertEquals(ShoppingProductChannelExclusivity.MULTI_CHANNEL,
channelExclusivity.getChannelExclusivity());
}
/**
* Test that verifies that {@link ProductDimensions} has a {@code createX} method for every
* subclass {@code X} of {@link ProductDimension}.
*/
@SuppressWarnings("unchecked")
@Test
public void testCreateMethodExistsForEveryDimensionSubclass() throws Exception {
String basePackageNameForVersion = ProductDimension.class.getPackage().getName()
.substring(0, ProductDimension.class.getPackage().getName().length() - ".cm".length());
ClassPath classPath = ClassPath.from(ProductDimension.class.getClassLoader());
Set<Class<? extends ProductDimension>> dimensionSubclasses = Sets.newHashSet();
for (ClassInfo classInfo : classPath.getTopLevelClassesRecursive(basePackageNameForVersion)) {
Class<?> classInfoClass = classInfo.load();
if (ProductDimension.class.isAssignableFrom(classInfoClass)
&& ProductDimension.class != classInfoClass) {
dimensionSubclasses.add((Class<? extends ProductDimension>) classInfoClass);
}
}
Map<Class<? extends ProductDimension>, Method> factoryMethodsMap =
getAllProductDimensionFactoryMethods();
for (Class<? extends ProductDimension> dimensionSubclass : dimensionSubclasses) {
if (!DIMENSION_TYPES_TO_IGNORE.contains(dimensionSubclass)) {
assertThat(
"No factory method exists for subclass " + dimensionSubclass + " of ProductDimension",
dimensionSubclass, Matchers.isIn(factoryMethodsMap.keySet()));
}
}
}
/**
* Test that verifies that this test class has a test method for every {@code createX} method of
* {@link ProductDimensions}.
*/
@Test
public void testCoverageOfAllCreateMethods() throws Exception {
// Collect all of the testCreateX methods from this test class.
Set<String> actualTestMethodNames = Sets.newHashSet();
for (Method method : getClass().getMethods()) {
String methodName = method.getName();
if (methodName.startsWith("testCreate") && !methodName.contains("_")) {
actualTestMethodNames.add(methodName);
}
}
// Assert that each createX method of ProductDimensions has a corresponding
// testCreateX method in this test class.
for (Entry<Class<? extends ProductDimension>, Method> methodEntry :
getAllProductDimensionFactoryMethods().entrySet()) {
Method method = methodEntry.getValue();
String methodName = method.getName();
if (methodName.startsWith("create")) {
String expectedTestMethodName = "testCreate" + methodName.substring("create".length());
assertThat("No test exists for factory method", expectedTestMethodName,
Matchers.isIn(actualTestMethodNames));
}
}
}
/**
* Returns a map of return type to {@code createX} method from {@link ProductDimensions}.
*/
@SuppressWarnings("unchecked")
static Map<Class<? extends ProductDimension>, Method> getAllProductDimensionFactoryMethods() {
Map<Class<? extends ProductDimension>, Method> methodsMap = Maps.newHashMap();
for (Method method : ProductDimensions.class.getMethods()) {
String methodName = method.getName();
if (methodName.startsWith("create")) {
Class<?> returnType = method.getReturnType();
assertTrue(String.format("Return type %s of %s is not a subclass of ProductDimension",
returnType, methodName), ProductDimension.class.isAssignableFrom(returnType));
methodsMap.put((Class<? extends ProductDimension>) returnType, method);
}
}
return methodsMap;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.imagebuilder.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateComponent" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateComponentResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The request ID that uniquely identifies this request.
* </p>
*/
private String requestId;
/**
* <p>
* The idempotency token used to make this request idempotent.
* </p>
*/
private String clientToken;
/**
* <p>
* The Amazon Resource Name (ARN) of the component that was created by this request.
* </p>
*/
private String componentBuildVersionArn;
/**
* <p>
* The request ID that uniquely identifies this request.
* </p>
*
* @param requestId
* The request ID that uniquely identifies this request.
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* <p>
* The request ID that uniquely identifies this request.
* </p>
*
* @return The request ID that uniquely identifies this request.
*/
public String getRequestId() {
return this.requestId;
}
/**
* <p>
* The request ID that uniquely identifies this request.
* </p>
*
* @param requestId
* The request ID that uniquely identifies this request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateComponentResult withRequestId(String requestId) {
setRequestId(requestId);
return this;
}
/**
* <p>
* The idempotency token used to make this request idempotent.
* </p>
*
* @param clientToken
* The idempotency token used to make this request idempotent.
*/
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
/**
* <p>
* The idempotency token used to make this request idempotent.
* </p>
*
* @return The idempotency token used to make this request idempotent.
*/
public String getClientToken() {
return this.clientToken;
}
/**
* <p>
* The idempotency token used to make this request idempotent.
* </p>
*
* @param clientToken
* The idempotency token used to make this request idempotent.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateComponentResult withClientToken(String clientToken) {
setClientToken(clientToken);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the component that was created by this request.
* </p>
*
* @param componentBuildVersionArn
* The Amazon Resource Name (ARN) of the component that was created by this request.
*/
public void setComponentBuildVersionArn(String componentBuildVersionArn) {
this.componentBuildVersionArn = componentBuildVersionArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the component that was created by this request.
* </p>
*
* @return The Amazon Resource Name (ARN) of the component that was created by this request.
*/
public String getComponentBuildVersionArn() {
return this.componentBuildVersionArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the component that was created by this request.
* </p>
*
* @param componentBuildVersionArn
* The Amazon Resource Name (ARN) of the component that was created by this request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateComponentResult withComponentBuildVersionArn(String componentBuildVersionArn) {
setComponentBuildVersionArn(componentBuildVersionArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRequestId() != null)
sb.append("RequestId: ").append(getRequestId()).append(",");
if (getClientToken() != null)
sb.append("ClientToken: ").append(getClientToken()).append(",");
if (getComponentBuildVersionArn() != null)
sb.append("ComponentBuildVersionArn: ").append(getComponentBuildVersionArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateComponentResult == false)
return false;
CreateComponentResult other = (CreateComponentResult) obj;
if (other.getRequestId() == null ^ this.getRequestId() == null)
return false;
if (other.getRequestId() != null && other.getRequestId().equals(this.getRequestId()) == false)
return false;
if (other.getClientToken() == null ^ this.getClientToken() == null)
return false;
if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
return false;
if (other.getComponentBuildVersionArn() == null ^ this.getComponentBuildVersionArn() == null)
return false;
if (other.getComponentBuildVersionArn() != null && other.getComponentBuildVersionArn().equals(this.getComponentBuildVersionArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRequestId() == null) ? 0 : getRequestId().hashCode());
hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
hashCode = prime * hashCode + ((getComponentBuildVersionArn() == null) ? 0 : getComponentBuildVersionArn().hashCode());
return hashCode;
}
@Override
public CreateComponentResult clone() {
try {
return (CreateComponentResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
package com.rarchives.ripme.ripper.rippers;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.rarchives.ripme.ripper.AbstractJSONRipper;
import com.rarchives.ripme.utils.Http;
import org.json.JSONObject;
public class ArtStationRipper extends AbstractJSONRipper {
enum URL_TYPE {
SINGLE_PROJECT, USER_PORTFOLIO, UNKNOWN
}
private ParsedURL albumURL;
private String projectName;
private Integer projectIndex;
private Integer projectPageNumber;
public ArtStationRipper(URL url) throws IOException {
super(url);
}
@Override
protected String getDomain() {
return "artstation.com";
}
@Override
public String getHost() {
return "ArtStation";
}
@Override
public String getGID(URL url) throws MalformedURLException {
JSONObject groupData;
// Parse URL and store for later use
albumURL = parseURL(url);
if (albumURL.getType() == URL_TYPE.SINGLE_PROJECT) {
// URL points to single project, use project title as GID
try {
groupData = Http.url(albumURL.getLocation()).getJSON();
} catch (IOException e) {
throw new MalformedURLException("Couldn't load JSON from " + albumURL.getLocation());
}
return groupData.getString("title");
}
if (albumURL.getType() == URL_TYPE.USER_PORTFOLIO) {
// URL points to user portfolio, use user's full name as GID
String userInfoURL = "https://www.artstation.com/users/" + albumURL.getID() + "/quick.json";
try {
groupData = Http.url(userInfoURL).getJSON();
} catch (IOException e) {
throw new MalformedURLException("Couldn't load JSON from " + userInfoURL);
}
return groupData.getString("full_name");
}
// No JSON found in the URL entered, can't rip
throw new MalformedURLException(
"Expected URL to an ArtStation project or user profile - got " + url + " instead");
}
@Override
protected JSONObject getFirstPage() throws IOException {
if (albumURL.getType() == URL_TYPE.SINGLE_PROJECT) {
// URL points to JSON of a single project, just return it
return Http.url(albumURL.getLocation()).getJSON();
}
if (albumURL.getType() == URL_TYPE.USER_PORTFOLIO) {
// URL points to JSON of a list of projects, load it to parse individual
// projects
JSONObject albumContent = Http.url(albumURL.getLocation()).getJSON();
if (albumContent.getInt("total_count") > 0) {
// Get JSON of the first project and return it
JSONObject projectInfo = albumContent.getJSONArray("data").getJSONObject(0);
ParsedURL projectURL = parseURL(new URL(projectInfo.getString("permalink")));
return Http.url(projectURL.getLocation()).getJSON();
}
}
throw new IOException("URL specified points to an user with empty portfolio");
}
@Override
protected JSONObject getNextPage(JSONObject doc) throws IOException {
if (albumURL.getType() == URL_TYPE.USER_PORTFOLIO) {
// Initialize the page number if it hasn't been initialized already
if (projectPageNumber == null) {
projectPageNumber = 1;
}
// Each page holds a maximum of 50 projects. Initialize the index if it hasn't
// been initialized already or increment page number and reset the index if all
// projects of the current page were already processed
if (projectIndex == null) {
projectIndex = 0;
} else if (projectIndex > 49) {
projectPageNumber++;
projectIndex = 0;
}
Integer currentProject = ((projectPageNumber - 1) * 50) + (projectIndex + 1);
JSONObject albumContent = Http.url(albumURL.getLocation() + "?page=" + projectPageNumber).getJSON();
if (albumContent.getInt("total_count") > currentProject) {
// Get JSON of the next project and return it
JSONObject projectInfo = albumContent.getJSONArray("data").getJSONObject(projectIndex);
ParsedURL projectURL = parseURL(new URL(projectInfo.getString("permalink")));
projectIndex++;
return Http.url(projectURL.getLocation()).getJSON();
}
throw new IOException("No more projects");
}
throw new IOException("Downloading a single project");
}
@Override
protected List<String> getURLsFromJSON(JSONObject json) {
List<String> assetURLs = new ArrayList<>();
JSONObject currentObject;
// Update project name variable from JSON data. Used by downloadURL() to create
// subfolders when input URL is URL_TYPE.USER_PORTFOLIO
projectName = json.getString("title");
for (int i = 0; i < json.getJSONArray("assets").length(); i++) {
currentObject = json.getJSONArray("assets").getJSONObject(i);
if (!currentObject.getString("image_url").isEmpty()) {
// TODO: Find a way to rip external content.
// ArtStation hosts only image content, everything else (videos, 3D Models, etc)
// is hosted in other websites and displayed through embedded HTML5 players
assetURLs.add(currentObject.getString("image_url"));
}
}
return assetURLs;
}
@Override
protected void downloadURL(URL url, int index) {
if (albumURL.getType() == URL_TYPE.USER_PORTFOLIO) {
// Replace not allowed characters with underlines
String folderName = projectName.replaceAll("[\\\\/:*?\"<>|]", "_");
// Folder name also can't end with dots or spaces, strip them
folderName = folderName.replaceAll("\\s+$", "");
folderName = folderName.replaceAll("\\.+$", "");
// Downloading multiple projects, separate each one in subfolders
addURLToDownload(url, "", folderName);
} else {
addURLToDownload(url);
}
}
@Override
public String normalizeUrl(String url) {
// Strip URL parameters
return url.replaceAll("\\?\\w+$", "");
}
private static class ParsedURL {
URL_TYPE urlType;
String jsonURL, urlID;
/**
* Construct a new ParsedURL object.
*
* @param urlType URL_TYPE enum containing the URL type
* @param jsonURL String containing the JSON URL location
* @param urlID String containing the ID of this URL
*
*/
ParsedURL(URL_TYPE urlType, String jsonURL, String urlID) {
this.urlType = urlType;
this.jsonURL = jsonURL;
this.urlID = urlID;
}
/**
* Get URL Type of this ParsedURL object.
*
* @return URL_TYPE enum containing this object type
*
*/
URL_TYPE getType() {
return this.urlType;
}
/**
* Get JSON location of this ParsedURL object.
*
* @return String containing the JSON URL
*
*/
String getLocation() {
return this.jsonURL;
}
/**
* Get ID of this ParsedURL object.
*
* @return For URL_TYPE.SINGLE_PROJECT, returns the project hash. For
* URL_TYPE.USER_PORTFOLIO, returns the account name
*/
String getID() {
return this.urlID;
}
}
/**
* Parses an ArtStation URL.
*
* @param url URL to an ArtStation user profile
* (https://www.artstation.com/username) or single project
* (https://www.artstation.com/artwork/projectid)
* @return ParsedURL object containing URL type, JSON location and ID (stores
* account name or project hash, depending of the URL type identified)
*
*/
private ParsedURL parseURL(URL url) {
String htmlSource;
ParsedURL parsedURL;
// Load HTML Source of the specified URL
try {
htmlSource = Http.url(url).get().html();
} catch (IOException e) {
htmlSource = "";
}
// Check if HTML Source of the specified URL references a project
Pattern p = Pattern.compile("'/projects/(\\w+)\\.json'");
Matcher m = p.matcher(htmlSource);
if (m.find()) {
parsedURL = new ParsedURL(URL_TYPE.SINGLE_PROJECT,
"https://www.artstation.com/projects/" + m.group(1) + ".json", m.group(1));
return parsedURL;
}
// Check if HTML Source of the specified URL references a user profile
p = Pattern.compile("'/users/([\\w-]+)/quick\\.json'");
m = p.matcher(htmlSource);
if (m.find()) {
parsedURL = new ParsedURL(URL_TYPE.USER_PORTFOLIO,
"https://www.artstation.com/users/" + m.group(1) + "/projects.json", m.group(1));
return parsedURL;
}
// HTML Source of the specified URL doesn't reference a user profile or project
parsedURL = new ParsedURL(URL_TYPE.UNKNOWN, null, null);
return parsedURL;
}
}
| |
/**
* Codesearch global settings configuration servlet.
*/
package com.palantir.stash.codesearch.admin;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_BODY_BOOST_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_BODY_BOOST_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_HASH_BOOST_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_HASH_BOOST_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_SUBJECT_BOOST_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.COMMIT_SUBJECT_BOOST_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.FILE_NAME_BOOST_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.FILE_NAME_BOOST_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_CONCURRENT_INDEXING_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_CONCURRENT_INDEXING_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_FILE_SIZE_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_FILE_SIZE_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_FRAGMENTS_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_FRAGMENTS_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_MATCH_LINES_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_MATCH_LINES_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_PREVIEW_LINES_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.MAX_PREVIEW_LINES_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.PAGE_SIZE_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.PAGE_SIZE_UB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.SEARCH_TIMEOUT_LB;
import static com.palantir.stash.codesearch.admin.GlobalSettings.SEARCH_TIMEOUT_UB;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.soy.renderer.SoyTemplateRenderer;
import com.atlassian.stash.exception.AuthorisationException;
import com.atlassian.stash.server.ApplicationPropertiesService;
import com.atlassian.stash.user.EscalatedSecurityContext;
import com.atlassian.stash.user.Permission;
import com.atlassian.stash.user.PermissionValidationService;
import com.atlassian.stash.user.SecurityService;
import com.atlassian.stash.util.Operation;
import com.google.common.collect.ImmutableMap;
import com.palantir.stash.codesearch.updater.SearchUpdater;
public class GlobalSettingsServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(GlobalSettingsServlet.class);
private final ApplicationPropertiesService propertiesService;
private final SettingsManager settingsManager;
private final PermissionValidationService validationService;
private final SearchUpdater searchUpdater;
private final SecurityService securityService;
private final SoyTemplateRenderer soyTemplateRenderer;
public GlobalSettingsServlet(
ApplicationPropertiesService propertiesService,
SettingsManager settingsManager,
PermissionValidationService validationService,
SearchUpdater searchUpdater,
SecurityService securityService,
SoyTemplateRenderer soyTemplateRenderer) {
this.propertiesService = propertiesService;
this.settingsManager = settingsManager;
this.validationService = validationService;
this.searchUpdater = searchUpdater;
this.securityService = securityService;
this.soyTemplateRenderer = soyTemplateRenderer;
}
private static int parseInt(
String fieldName, int min, int max, String value)
throws IllegalArgumentException {
int intValue;
try {
intValue = Integer.parseInt(value);
} catch (Exception e) {
throw new IllegalArgumentException("\"" + fieldName + "\" must be an integer.");
}
if (intValue < min) {
throw new IllegalArgumentException("\"" + fieldName + "\" must be at least " + min + ".");
}
if (intValue > max) {
throw new IllegalArgumentException("\"" + fieldName + "\" must not exceed " + max + ".");
}
return intValue;
}
private static double parseDouble(
String fieldName, double min, double max, String value)
throws IllegalArgumentException {
double doubleValue;
try {
doubleValue = Double.parseDouble(value);
} catch (Exception e) {
throw new IllegalArgumentException("\"" + fieldName + "\" must be a floating-point value.");
}
if (doubleValue < min) {
throw new IllegalArgumentException("\"" + fieldName + "\" must be at least " + min + ".");
}
if (doubleValue > max) {
throw new IllegalArgumentException("\"" + fieldName + "\" must not exceed " + max + ".");
}
return doubleValue;
}
// Make sure the current user is authenticated and a sysadmin
private boolean verifySysAdmin(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try {
validationService.validateAuthenticated();
} catch (AuthorisationException notLoggedInException) {
try {
resp.sendRedirect(propertiesService.getLoginUri(URI.create(req.getRequestURL() +
(req.getQueryString() == null ? "" : "?" + req.getQueryString())
)).toASCIIString());
} catch (Exception e) {
log.error("Unable to redirect unauthenticated user to login page", e);
}
return false;
}
try {
validationService.validateForGlobal(Permission.SYS_ADMIN);
} catch (AuthorisationException notSysAdminException) {
log.warn("User {} is not a system administrator", req.getRemoteUser());
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to access this page.");
return false;
}
return true;
}
private void renderPage(HttpServletRequest req, HttpServletResponse resp,
GlobalSettings globalSettings, Collection<? extends Object> errors)
throws ServletException, IOException {
resp.setContentType("text/html");
try {
ImmutableMap<String, Object> data = new ImmutableMap.Builder<String, Object>()
.put("settings", globalSettings)
.put("errors", errors)
.build();
soyTemplateRenderer.render(resp.getWriter(),
"com.palantir.stash.stash-code-search:codesearch-soy",
"plugin.page.codesearch.globalSettingsPage",
data);
} catch (Exception e) {
log.error("Error rendering Soy template", e);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (verifySysAdmin(req, resp)) {
renderPage(req, resp, settingsManager.getGlobalSettings(), Collections.emptyList());
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (!verifySysAdmin(req, resp)) {
return;
}
// Parse arguments
ArrayList<String> errors = new ArrayList<String>();
boolean indexingEnabled = "on".equals(req.getParameter("indexingEnabled"));
int maxConcurrentIndexing = 0;
try {
maxConcurrentIndexing = parseInt("Indexing Concurrency Limit",
MAX_CONCURRENT_INDEXING_LB, MAX_CONCURRENT_INDEXING_UB,
req.getParameter("maxConcurrentIndexing"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
int maxFileSize = 0;
try {
maxFileSize = parseInt("Max Filesize", MAX_FILE_SIZE_LB, MAX_FILE_SIZE_UB,
req.getParameter("maxFileSize"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
int searchTimeout = 0;
try {
searchTimeout = parseInt("Search Timeout", SEARCH_TIMEOUT_LB, SEARCH_TIMEOUT_UB,
req.getParameter("searchTimeout"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
String noHighlightExtensions = req.getParameter("noHighlightExtensions");
int maxPreviewLines = 0;
try {
maxPreviewLines = parseInt("Preview Limit", MAX_PREVIEW_LINES_LB, MAX_PREVIEW_LINES_UB,
req.getParameter("maxPreviewLines"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
int maxMatchLines = 0;
try {
maxMatchLines = parseInt("Match Limit", MAX_MATCH_LINES_LB, MAX_MATCH_LINES_UB,
req.getParameter("maxMatchLines"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
int maxFragments = 0;
try {
maxFragments = parseInt("Fragment Limit", MAX_FRAGMENTS_LB, MAX_FRAGMENTS_UB,
req.getParameter("maxFragments"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
int pageSize = 0;
try {
pageSize = parseInt("Page Size", PAGE_SIZE_LB, PAGE_SIZE_UB,
req.getParameter("pageSize"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
double commitHashBoost = 0.0;
try {
commitHashBoost = parseDouble("Commit Hash Boost", COMMIT_HASH_BOOST_LB, COMMIT_HASH_BOOST_UB,
req.getParameter("commitHashBoost"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
double commitSubjectBoost = 0.0;
try {
commitSubjectBoost = parseDouble("Commit Subject Boost", COMMIT_SUBJECT_BOOST_LB, COMMIT_SUBJECT_BOOST_UB,
req.getParameter("commitSubjectBoost"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
double commitBodyBoost = 0.0;
try {
commitBodyBoost = parseDouble("Commit Body Boost", COMMIT_BODY_BOOST_LB, COMMIT_BODY_BOOST_UB,
req.getParameter("commitBodyBoost"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
double fileNameBoost = 0.0;
try {
fileNameBoost = parseDouble("Filename Boost", FILE_NAME_BOOST_LB, FILE_NAME_BOOST_UB,
req.getParameter("fileNameBoost"));
} catch (IllegalArgumentException e) {
errors.add(e.getMessage());
}
// Update settings object iff no parse errors
GlobalSettings settings;
if (errors.isEmpty()) {
settings = settingsManager.setGlobalSettings(indexingEnabled,
maxConcurrentIndexing, maxFileSize, searchTimeout, noHighlightExtensions,
maxPreviewLines, maxMatchLines, maxFragments, pageSize, commitHashBoost,
commitSubjectBoost, commitBodyBoost, fileNameBoost);
// Trigger reindex is requested
if ("true".equals(req.getParameter("reindex"))) {
log.info("User {} submitted an async full reindex", req.getRemoteUser());
new Thread(new Runnable() {
@Override
public void run() {
try {
EscalatedSecurityContext esc =
securityService.withPermission(Permission.SYS_ADMIN, "full reindex by sysadmin");
esc.call(new Operation<Void, Exception>() {
@Override
public Void perform() {
searchUpdater.reindexAll();
return null;
}
});
} catch (Exception e) {
log.warn("Caught exception while reindexing", e);
}
}
}).start();
}
} else {
settings = settingsManager.getGlobalSettings();
}
renderPage(req, resp, settings, errors);
}
}
| |
package org.guvnor.asset.management.backend.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.guvnor.asset.management.model.ProjectStructureModel;
import org.guvnor.asset.management.service.ProjectStructureService;
import org.guvnor.common.services.backend.exceptions.ExceptionUtilities;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.POM;
import org.guvnor.common.services.project.model.Project;
import org.guvnor.common.services.project.service.POMService;
import org.guvnor.common.services.project.service.ProjectService;
import org.guvnor.common.services.shared.metadata.MetadataService;
import org.guvnor.m2repo.backend.server.GuvnorM2Repository;
import org.guvnor.structure.repositories.Repository;
import org.guvnor.common.services.backend.util.CommentedOptionFactory;
import org.guvnor.structure.repositories.RepositoryService;
import org.jboss.errai.bus.server.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.Path;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.FileSystem;
import org.uberfire.java.nio.file.Files;
import static org.guvnor.structure.backend.repositories.EnvironmentParameters.*;
@Service
@ApplicationScoped
public class ProjectStructureServiceImpl
implements ProjectStructureService {
private static final Logger logger = LoggerFactory.getLogger( ProjectStructureServiceImpl.class );
@Inject
private POMService pomService;
@Inject
private ProjectService<? extends Project> projectService;
@Inject
private RepositoryService repositoryService;
@Inject
private MetadataService metadataService;
// @Inject
// private ValidationService validationService;
@Inject
private GuvnorM2Repository m2service;
@Inject
private CommentedOptionFactory optionsFactory;
@Inject
@Named( "ioStrategy" )
private IOService ioService;
public Path initProjectStructure( GAV gav, Repository repo ) {
POM pom = new POM( repo.getAlias(), repo.getAlias(), gav
, true );
//Creating the parent pom
final Path fsRoot = repo.getRoot();
final Path pathToPom = pomService.create( fsRoot,
"",
pom );
//Deploying the parent pom artifact,
// it needs to be deployed before the first child is created
m2service.deployParentPom( gav );
updateManagedStatus( repo, true );
return pathToPom;
}
@Override
public Repository initRepository( final Repository repo, boolean managed ) {
return updateManagedStatus( repo, managed );
}
private Repository updateManagedStatus( final Repository repo, final boolean managed) {
Map<String, Object> config = new HashMap<String, Object>( );
config.put( MANAGED, managed );
return repositoryService.updateRepository( repo, config );
}
@Override
public Path convertToMultiProjectStructure( final List<Project> projects,
final GAV parentGav,
final Repository repo,
final boolean updateChildrenGav,
final String comment ) {
if ( projects == null || parentGav == null || repo == null ) {
return null;
}
try {
POM parentPom;
Path path = initProjectStructure( parentGav, repo );
parentPom = pomService.load( path );
if ( parentPom == null ) {
//uncommon case, the pom was just created.
return null;
}
ioService.startBatch( new FileSystem[] { Paths.convert( path ).getFileSystem() }, optionsFactory.makeCommentedOption( comment != null ? comment : "" ) );
POM pom;
boolean saveParentPom = false;
for ( Project project : projects ) {
pom = pomService.load( project.getPomXMLPath() );
pom.setParent( parentGav );
if ( updateChildrenGav ) {
pom.getGav().setGroupId( parentGav.getGroupId() );
pom.getGav().setVersion( parentGav.getVersion() );
}
pomService.save( project.getPomXMLPath(), pom, null, comment );
parentPom.setMultiModule( true );
parentPom.getModules().add( pom.getName() != null ? pom.getName() : pom.getGav().getArtifactId() );
saveParentPom = true;
}
if ( saveParentPom ) {
pomService.save( path, parentPom, null, comment );
}
return path;
} catch ( Exception e ) {
throw ExceptionUtilities.handleException( e );
} finally {
ioService.endBatch();
}
}
@Override
public ProjectStructureModel load( final Repository repository ) {
return load( repository, true );
}
@Override
public ProjectStructureModel load( final Repository repository, boolean includeModules ) {
if ( repository == null ) return null;
Repository _repository = repositoryService.getRepository( repository.getAlias() );
if ( _repository == null ) return null;
ProjectStructureModel model = new ProjectStructureModel();
Boolean managedStatus = _repository.getEnvironment() != null ? (Boolean)_repository.getEnvironment().get( MANAGED ) : null;
if ( managedStatus != null) {
model.setManaged( managedStatus );
}
Path path = repository.getRoot();
final Project project = projectService.resolveToParentProject( path );
if ( project != null ) {
if ( !model.isManaged() ) {
//uncommon case, the repository is managed. Update managed status.
updateManagedStatus( _repository, true );
model.setManaged( true );
}
model.setPOM( pomService.load( project.getPomXMLPath() ) );
model.setPOMMetaData( metadataService.getMetadata( project.getPomXMLPath() ) );
model.setPathToPOM( project.getPomXMLPath() );
model.setModules( new ArrayList<String>( project.getModules() ) );
if ( includeModules && project.getModules() != null ) {
org.uberfire.java.nio.file.Path parentPath = Paths.convert( project.getRootPath() );
Project moduleProject;
for ( String module : project.getModules() ) {
moduleProject = projectService.resolveProject( Paths.convert( parentPath.resolve( module ) ) );
model.getModulesProject().put( module, moduleProject );
}
}
} else {
//if no parent pom.xml present we must check if there are orphan projects for this repository.
List<Project> repositoryProjects = getProjects( repository );
if ( !repositoryProjects.isEmpty() ) {
model.setOrphanProjects( repositoryProjects );
POM pom;
for ( Project orphanProject : repositoryProjects ) {
pom = pomService.load( orphanProject.getPomXMLPath() );
model.getOrphanProjectsPOM().put( orphanProject.getSignatureId(), pom );
}
if ( managedStatus == null && repositoryProjects.size() > 1 ) {
//update managed status
updateManagedStatus( _repository, false );
}
} else if ( managedStatus == null) {
//there are no projects and the managed attribute is not set, means the repository was never initialized.
model = null;
}
}
return model;
}
@Override
public void save( final Path pathToPomXML,
final ProjectStructureModel model,
final String comment ) {
final FileSystem fs = Paths.convert( pathToPomXML ).getFileSystem();
try {
pomService.save( pathToPomXML,
model.getPOM(),
model.getPOMMetaData(),
comment,
true );
} catch ( final Exception e ) {
throw ExceptionUtilities.handleException( e );
}
}
@Override
public boolean validate( final POM pom ) {
PortablePreconditions.checkNotNull( "pom",
pom );
final String name = pom.getName();
final String groupId = pom.getGav().getGroupId();
final String artifactId = pom.getGav().getArtifactId();
final String version = pom.getGav().getVersion();
final String[] groupIdComponents = ( groupId == null ? new String[] { } : groupId.split( "\\.",
-1 ) );
final String[] artifactIdComponents = ( artifactId == null ? new String[] { } : artifactId.split( "\\.",
-1 ) );
// final boolean validName = !( name == null || name.isEmpty() ) && validationService.isProjectNameValid( name );
// final boolean validGroupId = !( groupIdComponents.length == 0 || validationService.evaluateIdentifiers( groupIdComponents ).containsValue( Boolean.FALSE ) );
// final boolean validArtifactId = !( artifactIdComponents.length == 0 || validationService.evaluateArtifactIdentifiers( artifactIdComponents ).containsValue( Boolean.FALSE ) );
// final boolean validVersion = !( version == null || version.isEmpty() || !version.matches( "^[a-zA-Z0-9\\.\\-_]+$" ) );
// return validName && validGroupId && validArtifactId && validVersion;
return true;
}
@Override
public void delete( final Path pathToPomXML, final String comment ) {
projectService.delete( pathToPomXML, comment );
}
private List<Project> getProjects( final Repository repository ) {
final List<Project> repositoryProjects = new ArrayList<Project>();
if ( repository == null ) {
return repositoryProjects;
}
final Path repositoryRoot = repository.getRoot();
final DirectoryStream<org.uberfire.java.nio.file.Path> nioRepositoryPaths = ioService.newDirectoryStream( Paths.convert( repositoryRoot ) );
for ( org.uberfire.java.nio.file.Path nioRepositoryPath : nioRepositoryPaths ) {
if ( Files.isDirectory( nioRepositoryPath ) ) {
final org.uberfire.backend.vfs.Path projectPath = Paths.convert( nioRepositoryPath );
final Project project = projectService.resolveProject( projectPath );
if ( project != null ) {
repositoryProjects.add( project );
}
}
}
return repositoryProjects;
}
}
| |
/*
* Copyright 2012, 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dogecoindark.dogecoindarkj.uri;
import com.dogecoindark.dogecoindarkj.core.Address;
import com.dogecoindark.dogecoindarkj.core.AddressFormatException;
import com.dogecoindark.dogecoindarkj.core.Coin;
import com.dogecoindark.dogecoindarkj.core.NetworkParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>Provides a standard implementation of a Bitcoin URI with support for the following:</p>
*
* <ul>
* <li>URLEncoded URIs (as passed in by IE on the command line)</li>
* <li>BIP21 names (including the "req-" prefix handling requirements)</li>
* </ul>
*
* <h2>Accepted formats</h2>
*
* <p>The following input forms are accepted:</p>
*
* <ul>
* <li>{@code bitcoin:<address>}</li>
* <li>{@code bitcoin:<address>?<name1>=<value1>&<name2>=<value2>} with multiple
* additional name/value pairs</li>
* </ul>
*
* <p>The name/value pairs are processed as follows.</p>
* <ol>
* <li>URL encoding is stripped and treated as UTF-8</li>
* <li>names prefixed with {@code req-} are treated as required and if unknown or conflicting cause a parse exception</li>
* <li>Unknown names not prefixed with {@code req-} are added to a Map, accessible by parameter name</li>
* <li>Known names not prefixed with {@code req-} are processed unless they are malformed</li>
* </ol>
*
* <p>The following names are known and have the following formats:</p>
* <ul>
* <li>{@code amount} decimal value to 8 dp (e.g. 0.12345678) <b>Note that the
* exponent notation is not supported any more</b></li>
* <li>{@code label} any URL encoded alphanumeric</li>
* <li>{@code message} any URL encoded alphanumeric</li>
* </ul>
*
* @author Andreas Schildbach (initial code)
* @author Jim Burton (enhancements for MultiBit)
* @author Gary Rowe (BIP21 support)
* @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki">BIP 0021</a>
*/
public class BitcoinURI {
/**
* Provides logging for this class
*/
private static final Logger log = LoggerFactory.getLogger(BitcoinURI.class);
// Not worth turning into an enum
public static final String FIELD_MESSAGE = "message";
public static final String FIELD_LABEL = "label";
public static final String FIELD_AMOUNT = "amount";
public static final String FIELD_ADDRESS = "address";
public static final String FIELD_PAYMENT_REQUEST_URL = "r";
public static final String BITCOIN_SCHEME = "dogecoindark";
private static final String ENCODED_SPACE_CHARACTER = "%20";
private static final String AMPERSAND_SEPARATOR = "&";
private static final String QUESTION_MARK_SEPARATOR = "?";
/**
* Contains all the parameters in the order in which they were processed
*/
private final Map<String, Object> parameterMap = new LinkedHashMap<String, Object>();
/**
* Constructs a new BitcoinURI from the given string. Can be for any network.
*
* @param uri The raw URI data to be parsed (see class comments for accepted formats)
* @throws BitcoinURIParseException if the URI is not syntactically or semantically valid.
*/
public BitcoinURI(String uri) throws BitcoinURIParseException {
this(null, uri);
}
/**
* Constructs a new object by trying to parse the input as a valid Bitcoin URI.
*
* @param params The network parameters that determine which network the URI is from, or null if you don't have
* any expectation about what network the URI is for and wish to check yourself.
* @param input The raw URI data to be parsed (see class comments for accepted formats)
*
* @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks.
*/
public BitcoinURI(@Nullable NetworkParameters params, String input) throws BitcoinURIParseException {
checkNotNull(input);
log.debug("Attempting to parse '{}' for {}", input, params == null ? "any" : params.getId());
// Attempt to form the URI (fail fast syntax checking to official standards).
URI uri;
try {
uri = new URI(input);
} catch (URISyntaxException e) {
throw new BitcoinURIParseException("Bad URI syntax", e);
}
// URI is formed as bitcoin:<address>?<query parameters>
// blockchain.info generates URIs of non-BIP compliant form bitcoin://address?....
// We support both until Ben fixes his code.
// Remove the bitcoin scheme.
// (Note: getSchemeSpecificPart() is not used as it unescapes the label and parse then fails.
// For instance with : bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=0.06&label=Tom%20%26%20Jerry
// the & (%26) in Tom and Jerry gets interpreted as a separator and the label then gets parsed
// as 'Tom ' instead of 'Tom & Jerry')
String schemeSpecificPart;
if (input.startsWith("dogecoindark://")) {
schemeSpecificPart = input.substring("dogecoindark://".length());
} else if (input.startsWith("dogecoindark:")) {
schemeSpecificPart = input.substring("dogecoindark:".length());
} else {
throw new BitcoinURIParseException("Unsupported URI scheme: " + uri.getScheme());
}
// Split off the address from the rest of the query parameters.
String[] addressSplitTokens = schemeSpecificPart.split("\\?", 2);
if (addressSplitTokens.length == 0)
throw new BitcoinURIParseException("No data found after the bitcoin: prefix");
String addressToken = addressSplitTokens[0]; // may be empty!
String[] nameValuePairTokens;
if (addressSplitTokens.length == 1) {
// Only an address is specified - use an empty '<name>=<value>' token array.
nameValuePairTokens = new String[] {};
} else {
// Split into '<name>=<value>' tokens.
nameValuePairTokens = addressSplitTokens[1].split("&");
}
// Attempt to parse the rest of the URI parameters.
parseParameters(params, addressToken, nameValuePairTokens);
if (!addressToken.isEmpty()) {
// Attempt to parse the addressToken as a Bitcoin address for this network
try {
Address address = new Address(params, addressToken);
putWithValidation(FIELD_ADDRESS, address);
} catch (final AddressFormatException e) {
throw new BitcoinURIParseException("Bad address", e);
}
}
if (addressToken.isEmpty() && getPaymentRequestUrl() == null) {
throw new BitcoinURIParseException("No address and no r= parameter found");
}
}
/**
* @param params The network parameters or null
* @param nameValuePairTokens The tokens representing the name value pairs (assumed to be
* separated by '=' e.g. 'amount=0.2')
*/
private void parseParameters(@Nullable NetworkParameters params, String addressToken, String[] nameValuePairTokens) throws BitcoinURIParseException {
// Attempt to decode the rest of the tokens into a parameter map.
for (String nameValuePairToken : nameValuePairTokens) {
final int sepIndex = nameValuePairToken.indexOf('=');
if (sepIndex == -1)
throw new BitcoinURIParseException("Malformed Bitcoin URI - no separator in '" +
nameValuePairToken + "'");
if (sepIndex == 0)
throw new BitcoinURIParseException("Malformed Bitcoin URI - empty name '" +
nameValuePairToken + "'");
final String nameToken = nameValuePairToken.substring(0, sepIndex).toLowerCase(Locale.ENGLISH);
final String valueToken = nameValuePairToken.substring(sepIndex + 1);
// Parse the amount.
if (FIELD_AMOUNT.equals(nameToken)) {
// Decode the amount (contains an optional decimal component to 8dp).
try {
Coin amount = Coin.parseCoin(valueToken);
if (amount.signum() < 0)
throw new ArithmeticException("Negative coins specified");
putWithValidation(FIELD_AMOUNT, amount);
} catch (IllegalArgumentException e) {
throw new OptionalFieldValidationException(String.format("'%s' is not a valid amount", valueToken), e);
} catch (ArithmeticException e) {
throw new OptionalFieldValidationException(String.format("'%s' has too many decimal places", valueToken), e);
}
} else {
if (nameToken.startsWith("req-")) {
// A required parameter that we do not know about.
throw new RequiredFieldValidationException("'" + nameToken + "' is required but not known, this URI is not valid");
} else {
// Known fields and unknown parameters that are optional.
try {
if (valueToken.length() > 0)
putWithValidation(nameToken, URLDecoder.decode(valueToken, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Unreachable.
throw new RuntimeException(e);
}
}
}
}
// Note to the future: when you want to implement 'req-expires' have a look at commit 410a53791841
// which had it in.
}
/**
* Put the value against the key in the map checking for duplication. This avoids address field overwrite etc.
*
* @param key The key for the map
* @param value The value to store
*/
private void putWithValidation(String key, Object value) throws BitcoinURIParseException {
if (parameterMap.containsKey(key)) {
throw new BitcoinURIParseException(String.format("'%s' is duplicated, URI is invalid", key));
} else {
parameterMap.put(key, value);
}
}
/**
* The Bitcoin Address from the URI, if one was present. It's possible to have Bitcoin URI's with no address if a
* r= payment protocol parameter is specified, though this form is not recommended as older wallets can't understand
* it.
*/
@Nullable
public Address getAddress() {
return (Address) parameterMap.get(FIELD_ADDRESS);
}
/**
* @return The amount name encoded using a pure integer value based at
* 10,000,000 units is 1 BTC. May be null if no amount is specified
*/
public Coin getAmount() {
return (Coin) parameterMap.get(FIELD_AMOUNT);
}
/**
* @return The label from the URI.
*/
public String getLabel() {
return (String) parameterMap.get(FIELD_LABEL);
}
/**
* @return The message from the URI.
*/
public String getMessage() {
return (String) parameterMap.get(FIELD_MESSAGE);
}
/**
* @return The URL where a payment request (as specified in BIP 70) may
* be fetched.
*/
public String getPaymentRequestUrl() {
return (String) parameterMap.get(FIELD_PAYMENT_REQUEST_URL);
}
/**
* Returns the URLs where a payment request (as specified in BIP 70) may be fetched. The first URL is the main URL,
* all subsequent URLs are fallbacks.
*/
public List<String> getPaymentRequestUrls() {
ArrayList<String> urls = new ArrayList<String>();
while (true) {
int i = urls.size();
String paramName = FIELD_PAYMENT_REQUEST_URL + (i > 0 ? Integer.toString(i) : "");
String url = (String) parameterMap.get(paramName);
if (url == null)
break;
urls.add(url);
}
Collections.reverse(urls);
return urls;
}
/**
* @param name The name of the parameter
* @return The parameter value, or null if not present
*/
public Object getParameterByName(String name) {
return parameterMap.get(name);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BitcoinURI[");
boolean first = true;
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
if (first) {
first = false;
} else {
builder.append(",");
}
builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'");
}
builder.append("]");
return builder.toString();
}
public static String convertToBitcoinURI(Address address, Coin amount, String label, String message) {
return convertToBitcoinURI(address.toString(), amount, label, message);
}
/**
* Simple Bitcoin URI builder using known good fields.
*
* @param address The Bitcoin address
* @param amount The amount
* @param label A label
* @param message A message
* @return A String containing the Bitcoin URI
*/
public static String convertToBitcoinURI(String address, @Nullable Coin amount, @Nullable String label,
@Nullable String message) {
checkNotNull(address);
if (amount != null && amount.signum() < 0) {
throw new IllegalArgumentException("Coin must be positive");
}
StringBuilder builder = new StringBuilder();
builder.append(BITCOIN_SCHEME).append(":").append(address);
boolean questionMarkHasBeenOutput = false;
if (amount != null) {
builder.append(QUESTION_MARK_SEPARATOR).append(FIELD_AMOUNT).append("=");
builder.append(amount.toPlainString());
questionMarkHasBeenOutput = true;
}
if (label != null && !"".equals(label)) {
if (questionMarkHasBeenOutput) {
builder.append(AMPERSAND_SEPARATOR);
} else {
builder.append(QUESTION_MARK_SEPARATOR);
questionMarkHasBeenOutput = true;
}
builder.append(FIELD_LABEL).append("=").append(encodeURLString(label));
}
if (message != null && !"".equals(message)) {
if (questionMarkHasBeenOutput) {
builder.append(AMPERSAND_SEPARATOR);
} else {
builder.append(QUESTION_MARK_SEPARATOR);
}
builder.append(FIELD_MESSAGE).append("=").append(encodeURLString(message));
}
return builder.toString();
}
/**
* Encode a string using URL encoding
*
* @param stringToEncode The string to URL encode
*/
static String encodeURLString(String stringToEncode) {
try {
return java.net.URLEncoder.encode(stringToEncode, "UTF-8").replace("+", ENCODED_SPACE_CHARACTER);
} catch (UnsupportedEncodingException e) {
// should not happen - UTF-8 is a valid encoding
throw new RuntimeException(e);
}
}
}
| |
package pangpang.MainGame;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import jrcengine.Basic.GL_Screen;
import jrcengine.GL.GL_Animation;
import jrcengine.GL.GL_Camera2D;
import jrcengine.GL.GL_SpriteBatcher;
import jrcengine.GL.GL_Texture;
import jrcengine.GL.GL_TextureRegion;
import jrcengine.Interface.IFace_Game;
import jrcengine.Interface.IFace_Input.TouchEvent;
import jrcengine.Interface.Object_Dynamic;
import jrcengine.Manage.Manage_Assets;
import jrcengine.Math.Math_Overlap;
import jrcengine.Math.Math_Overlap_Rectangle;
import jrcengine.Math.Math_Vector;
import jrcengine.NetworkModule.NetworkModule;
public class ScoreScreen extends GL_Screen {
GL_Camera2D guiCam;
GL_SpriteBatcher batcher;
Math_Overlap_Rectangle nextBounds;
Math_Vector touchPoint;
GL_Texture helpImage;
GL_TextureRegion helpRegion;
ArrayList<Enemy> mEnemys;
boolean initTouch;
boolean isExit;
boolean isinit;
private Girl clientPangPangMainPlayer;
private ArrayList<Girl> pangPangPlayers = new ArrayList<Girl>();
private ArrayList<Bubble_Missile> mBubbleMis;
private ArrayList<Star_Missile> mStarMis;
public ScoreScreen(IFace_Game game) {
super(game);
isExit = false;
guiCam = new GL_Camera2D(glGraphics, 360, 280);
nextBounds = new Math_Overlap_Rectangle(60, 60, 60, 60);
touchPoint = new Math_Vector();
batcher = new GL_SpriteBatcher(glGraphics, 100);
initTouch = true;
isinit = false;
mEnemys = new ArrayList<Enemy>();
mBubbleMis = new ArrayList<Bubble_Missile>();
mStarMis = new ArrayList<Star_Missile>();
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_THE_ROOM_LIST_INFORMATION + "", "PhoneRoom",
2 + "", 4 + "");
NetworkModule.setglMainGame(this);
Girl.isOnlineMode = true;
initPangPangBubbles();
}
public void pangpangPlayerRemove(String[] packet) {
for (int i = 0; i < pangPangPlayers.size(); i++)
if (pangPangPlayers.get(i).getsName().equals(packet[1]))
pangPangPlayers.remove(i);
}
public void pangpangMissileUpdate(String[] packet) {
for (int i = 0; i < pangPangPlayers.size(); i++) {
if (pangPangPlayers.get(i).getsName().equals(packet[1])) {
Star_Missile missile = new Star_Missile(pangPangPlayers.get(i).position.x,
pangPangPlayers.get(i).position.y + Girl.GIRL_HEIGHT / 2
+ Star_Missile.Star_Missile_HEIHGT / 2);
missile.setsName(packet[2]);
mStarMis.add(missile);
break;
}
}
}
public void initStartGame(String[] packet) {
}
public void enemyMissileUpdate(String[] packet) {
Bubble_Missile missile = new Bubble_Missile(Float.parseFloat(packet[1]), 280.0f - Float.parseFloat(packet[2]),
Integer.parseInt(packet[3]));
missile.setsName(packet[4]);
mBubbleMis.add(missile);
}
private int checkPlayerInThePangPang(String name) {
for (int i = 0; i < pangPangPlayers.size(); i++)
if (pangPangPlayers.get(i).getsName().equals(name))
return i;
return -1;
}
public void updatePangPangPlayerPosition(String[] packet) {
for (int i = 0; i < pangPangPlayers.size(); i++)
if (pangPangPlayers.get(i).getsName().equals(packet[1])) {
pangPangPlayers.get(i).setStateFlag(Integer.parseInt(packet[2]));
}
}
/**
* re init the pangpang game for second time
*
* @param packet
*/
public void initRePangPangGamePlayerGamePosition(String[] packet) {
boolean isExisted = false;
if (NetworkModule.id.equals(packet[1]))
if (!NetworkModule.id.equals(packet[2])) {
for (int i = 0; i < pangPangPlayers.size(); i++) {
if (pangPangPlayers.get(i).getsName().equals(packet[2])) {
isExisted = true;
break;
}
}
if (isExisted == false) {
Girl player = new Girl(1, Float.parseFloat(packet[3]), 280 - Float.parseFloat(packet[4]), 2, 0);
player.setsName(packet[2]);
player.setStateFlag(Girl.OBJ_D_ATTAK);
player.set_Int_Life(2);
pangPangPlayers.add(player);
}
}
}
/**
* init pangpang game when first time
*
* @param packet
*/
public void initPangPangGamePlayerGamePosition(String[] packet) {
if (-1 != checkPlayerInThePangPang(packet[1]))
return;
Girl player = new Girl(1, Float.parseFloat(packet[2]), 280 - Float.parseFloat(packet[3]), 2, 0);
player.setsName(packet[1]);
player.setStateFlag(Girl.OBJ_D_ATTAK);
player.set_Int_Life(2);
pangPangPlayers.add(player);
for (int i = 0; i < pangPangPlayers.size(); i++) {
if (pangPangPlayers.get(i).getsName().equals(NetworkModule.id)) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGPANG_REINIT_GAME_PLAY + "",
NetworkModule.RoomInitNumber + "", packet[1], NetworkModule.id,
pangPangPlayers.get(i).position.x + "", 280 - pangPangPlayers.get(i).position.y + "");
clientPangPangMainPlayer = pangPangPlayers.get(i);
}
}
}
public void exitThePangPangGame(String[] packet) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGPANG_OUT_OF_PLAYER + "",
NetworkModule.RoomInitNumber + "", NetworkModule.id);
isExit = true;
}
public void outOfPlayerInPangPang(String[] packet) {
pangPangPlayers.remove(checkPlayerInThePangPang(packet[1]));
}
/**
* init pangapng enemy
*/
public void initPangPangBubbles() {
for (int i = 0; i < Manage_Assets.nPangPangEnemyHeight; i++)
for (int j = 0; j < Manage_Assets.nPangPangEnemyWidth; j++) {
Enemy bubble = new Enemy();
bubble.set_Chracter_Number(-1);
bubble.setsName("bubble" + (i * Manage_Assets.nPangPangEnemyWidth + j));
mEnemys.add(bubble);
}
}
public void pangpangEnemyInit(String[] packet) {
String temp = packet[1];
String sPositionSet[] = temp.split(Manage_Assets.NetworkProtocol.sPangPangPositionInformationWordToken);
for (int i = 1; i < sPositionSet.length; i++) {
String sSubPosition[] = sPositionSet[i]
.split(Manage_Assets.NetworkProtocol.sPangPangPositionCoordinationToken);
for (int j = 0; j < mEnemys.size(); j++)
if (mEnemys.get(j).getsName().equals(sSubPosition[0])) {
mEnemys.get(j).set_Chracter_Number(Integer.parseInt(sSubPosition[1]));
if (mEnemys.get(j).get_Chracter_Number() == 0)
mEnemys.get(j).set_Chracter_Number(39);
else if (mEnemys.get(j).get_Chracter_Number() == 1)
mEnemys.get(j).set_Chracter_Number(40);
else if (mEnemys.get(j).get_Chracter_Number() == 2)
mEnemys.get(j).set_Chracter_Number(41);
else if (mEnemys.get(j).get_Chracter_Number() == 3)
mEnemys.get(j).set_Chracter_Number(42);
else if (mEnemys.get(j).get_Chracter_Number() == 4)
mEnemys.get(j).set_Chracter_Number(43);
else
mEnemys.get(j).set_Chracter_Number(44);
mEnemys.get(j).set_Is_Dead(Boolean.parseBoolean(sSubPosition[2]));
break;
}
}
this.isinit = true;
}
/**
* pangoang enemy stack
*/
private String sPangPangEnemyStack;
public void pangpangEnemyUpdate(String[] packet) {
sPangPangEnemyStack = packet[1];
if (sPangPangEnemyStack != null) {
String sPositionSet[] = sPangPangEnemyStack
.split(Manage_Assets.NetworkProtocol.sPangPangPositionInformationWordToken);
for (int i = 1; i < sPositionSet.length; i++) {
String sSubPosition[] = sPositionSet[i]
.split(Manage_Assets.NetworkProtocol.sPangPangPositionCoordinationToken);
for (int j = 0; j < mEnemys.size(); j++)
if (mEnemys.get(j).getsName().equals(sSubPosition[0])) {
mEnemys.get(j).position.x = Float.parseFloat(sSubPosition[1]);
mEnemys.get(j).position.y = 280.0f - Float.parseFloat(sSubPosition[2]);
mEnemys.get(j).updateBound();
break;
}
}
}
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void update(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
gameupdate(deltaTime);
// if (isExit)
// game.setScreen(new Options(game));
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
touchPoint.set(event.x, event.y);
guiCam.touchToWorld(touchPoint);
if (event.type == TouchEvent.TOUCH_UP) {
if (Math_Overlap.pointInRectangle(nextBounds, touchPoint)) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_OUT_OF_THE_ROOM + "",
NetworkModule.id);
}
if (initTouch) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGPANG_INIT_GAME_PLAY + "",
NetworkModule.RoomInitNumber + "", NetworkModule.id);
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_START_THE_GAME + "",
NetworkModule.id, NetworkModule.RoomInitNumber + "",
Manage_Assets.NetworkProtocol.isGamePrepareStart + "");
initTouch = false;
}
if (null != clientPangPangMainPlayer) {
if (touchPoint.x >= clientPangPangMainPlayer.position.x) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGPANG_PLAYER_MOVING + "",
NetworkModule.RoomInitNumber + "", NetworkModule.id, Object_Dynamic.OBJ_D_RIGHT + "");
} else {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGPANG_PLAYER_MOVING + "",
NetworkModule.RoomInitNumber + "", NetworkModule.id, Object_Dynamic.OBJ_D_LEFT + "");
}
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGAPNG_ATTACK + "",
NetworkModule.RoomInitNumber + "", NetworkModule.id, NetworkModule.id);
}
}
if (event.type == TouchEvent.TOUCH_DOWN) {
touchPoint.set(event.x, event.y);
guiCam.touchToWorld(touchPoint);
if (Math_Overlap.pointInRectangle(nextBounds, touchPoint)) {
return;
}
}
}
}
public void gameupdate(float deltaTime) {
collisionDetection(deltaTime);
check_Star_Mi_To_Enemy(deltaTime);
update_Star_Missile(deltaTime);
for (int i = 0; i < pangPangPlayers.size(); i++) {
Girl _unit = pangPangPlayers.get(i);
_unit.update(deltaTime);
}
}
private void update_Star_Missile(float deltaTime) {
int len = mStarMis.size();
if (len <= 0)
return;
for (int i = 0; i < len; i++) {
Star_Missile mstar = mStarMis.get(i);
mstar.update(deltaTime);
if (mstar.get_Out_Bound() || mstar.get_Is_Dead()) {
mStarMis.remove(mstar);
len = mStarMis.size();
}
}
}
public void collisionDetection(float deltaTime) {
int len = mBubbleMis.size();
for (int i = 0; i < len; i++) {
mBubbleMis.get(i).update_mobile(deltaTime);
if (mBubbleMis.get(i).position.y <= 0) {
mBubbleMis.remove(i);
len = mBubbleMis.size();
continue;
}
for (int j = 0; j < pangPangPlayers.size(); j++) {
if (pangPangPlayers.get(j).get_Is_Dead() == false
&& Math_Overlap.overlapRectangles(mBubbleMis.get(i).bounds, pangPangPlayers.get(j).bounds)) {
mBubbleMis.remove(i);
len = mBubbleMis.size();
pangPangPlayers.get(j).set_Int_Life(pangPangPlayers.get(j).get_Int_Life() - 1);
if (pangPangPlayers.get(j).get_Is_Dead()) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGAPNG_PLAYER_DEATH + "",
NetworkModule.RoomInitNumber + "", pangPangPlayers.get(j).getsName());
}
break;
}
}
continue;
}
}
/**
* pangapng enemy delete when pangapng enemy's life under zero
*
* @param packet
*/
public void pangpangEnemyRemove(String[] packet) {
for (int i = 0; i < mEnemys.size(); i++) {
if (mEnemys.get(i).getsName().equals(packet[1])) {
Random rnd = new Random();
/*
* for (int j = 0; j < rnd.nextInt(8); j++) {
*
* Explosion_Effect temp = new
* Explosion_Effect("/Asset/ball.png", 60 * rnd.nextInt(5), 0,
* 59, 58, rnd.nextInt(16)); temp.setImageSize(10, 10);
* temp.setPosition(bubbles.get(i).getPositionX(),
* bubbles.get(i).getPositionY());
*
* pangpang_bubbles_effects.add(temp); }
*/
mEnemys.remove(i);
}
}
}
private void check_Star_Mi_To_Enemy(float deltaTime) {
int len = mStarMis.size();
if (len < 0)
return;
for (int i = 0; i < len; i++) {
Star_Missile strMis = mStarMis.get(i);
for (int j = 0; j < mEnemys.size(); j++) {
if (Math_Overlap.overlapRectangles(mEnemys.get(j).bounds, strMis.bounds)) {
NetworkModule.sendPacket(Manage_Assets.NetworkProtocol._REQUEST_PANGAPNG_ENEMY_COLLISION_EVENT + "",
NetworkModule.RoomInitNumber + "", mEnemys.get(j).getsName());
mStarMis.remove(strMis);
len = mStarMis.size();
}
}
}
}
@Override
public void present(float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
guiCam.setViewportAndMatrices();
gl.glEnable(GL10.GL_TEXTURE_2D);
batcher.beginBatch(Manage_Assets.texture.get(3));
batcher.drawSprite(360 / 2, 280 / 2, 360, 280, Manage_Assets.textureRegion.get(52));
batcher.endBatch();
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
render_User(deltaTime);
if (isinit) {
batcher.beginBatch(Manage_Assets.texture.get(39));
render_Enemy(deltaTime);
batcher.endBatch();
render_Bubble_Mis();
render_user_life();
render_player_Mis();
}
gl.glDisable(GL10.GL_BLEND);
}
private void render_Enemy(float deltaTime) {
for (int i = 0; i < mEnemys.size(); i++) {
if (!mEnemys.get(i).get_Is_Dead()) {
batcher.drawSprite(mEnemys.get(i).position.x, mEnemys.get(i).position.y, Enemy.ENEMY_WIDTH,
Enemy.ENEMY_HEIGHT, (float) (mEnemys.get(i).get_Dir() * -22.5),
Manage_Assets.textureRegion.get(mEnemys.get(i).get_Chracter_Number()));
}
}
}
private void render_player_Mis() {
if (mStarMis.size() > 0) {
batcher.beginBatch(Manage_Assets.texture.get(41));
for (int i = 0; i < mStarMis.size(); i++) {
Star_Missile mMissle = mStarMis.get(i);
batcher.drawSprite(mMissle.position.x, mMissle.position.y, Star_Missile.Star_Missile_WIDTH,
Star_Missile.Star_Missile_HEIHGT, (float) (mMissle.get_Rotate_Number() * -22.5),
Manage_Assets.textureRegion.get(mMissle.get_Image_Number()));
}
batcher.endBatch();
}
}
private void render_Bubble_Mis() {
for (int i = 0; i < mBubbleMis.size(); i++) {
Bubble_Missile mMissle = mBubbleMis.get(i);
batcher.beginBatch(Manage_Assets.texture.get(40));
batcher.drawSprite(mMissle.position.x, mMissle.position.y, Bubble_Missile.BUBLLE_MISSILE_WIDTH,
Bubble_Missile.BUBLLE_MISSILE_HEIHGT, (float) (mMissle.get_Directions() * -22.5),
Manage_Assets.textureRegion.get(mMissle.get_Image_Number()));
batcher.endBatch();
}
}
private void render_user_life() {
if (clientPangPangMainPlayer.get_Int_Life() > 0) {
batcher.beginBatch(Manage_Assets.texture.get(23));
for (int i = clientPangPangMainPlayer.get_Int_Life(); i > 0; i--)
batcher.drawSprite(160 + 20 * i, 280 - 20, 20, 20, Manage_Assets.textureRegion.get(23));
batcher.endBatch();
}
}
private void render_User(float deltaTime) {
for (int i = 0; i < pangPangPlayers.size(); i++) {
Girl _unit = pangPangPlayers.get(i);
GL_TextureRegion keyFrame;
float girl_Witdh;
switch (_unit.getStageFlag()) {
case Girl.OBJ_D_LEFT:
keyFrame = Manage_Assets.animation.get(01).getKeyFrame(_unit.getStateTime(),
GL_Animation.ANIMATION_LOOPING);
girl_Witdh = Girl.GIRL_WIDTH / 2;
break;
case Girl.OBJ_D_RIGHT:
keyFrame = Manage_Assets.animation.get(00).getKeyFrame(_unit.getStateTime(),
GL_Animation.ANIMATION_LOOPING);
girl_Witdh = Girl.GIRL_WIDTH / 2;
break;
case Girl.OBJ_D_ATTAK:
keyFrame = Manage_Assets.textureRegion.get(53);
girl_Witdh = Girl.GIRL_WIDTH;
break;
default:
keyFrame = Manage_Assets.textureRegion.get(53);
girl_Witdh = Girl.GIRL_WIDTH;
}
batcher.beginBatch(Manage_Assets.texture.get(32));
batcher.drawSprite(_unit.position.x, _unit.position.y, girl_Witdh, Girl.GIRL_HEIGHT, keyFrame);
batcher.endBatch();
}
}
@Override
public void dispose() {
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.apprunner.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/apprunner-2020-05-15/CreateVpcConnector" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateVpcConnectorRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* A name for the VPC connector.
* </p>
*/
private String vpcConnectorName;
/**
* <p>
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC.
* Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify.
* </p>
*/
private java.util.List<String> subnets;
/**
* <p>
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources under the
* specified subnets. If not specified, App Runner uses the default security group of the Amazon VPC. The default
* security group allows all outbound traffic.
* </p>
*/
private java.util.List<String> securityGroups;
/**
* <p>
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value pair.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* A name for the VPC connector.
* </p>
*
* @param vpcConnectorName
* A name for the VPC connector.
*/
public void setVpcConnectorName(String vpcConnectorName) {
this.vpcConnectorName = vpcConnectorName;
}
/**
* <p>
* A name for the VPC connector.
* </p>
*
* @return A name for the VPC connector.
*/
public String getVpcConnectorName() {
return this.vpcConnectorName;
}
/**
* <p>
* A name for the VPC connector.
* </p>
*
* @param vpcConnectorName
* A name for the VPC connector.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withVpcConnectorName(String vpcConnectorName) {
setVpcConnectorName(vpcConnectorName);
return this;
}
/**
* <p>
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC.
* Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify.
* </p>
*
* @return A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon
* VPC. Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets
* you specify.
*/
public java.util.List<String> getSubnets() {
return subnets;
}
/**
* <p>
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC.
* Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify.
* </p>
*
* @param subnets
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon
* VPC. Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets
* you specify.
*/
public void setSubnets(java.util.Collection<String> subnets) {
if (subnets == null) {
this.subnets = null;
return;
}
this.subnets = new java.util.ArrayList<String>(subnets);
}
/**
* <p>
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC.
* Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSubnets(java.util.Collection)} or {@link #withSubnets(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param subnets
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon
* VPC. Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets
* you specify.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withSubnets(String... subnets) {
if (this.subnets == null) {
setSubnets(new java.util.ArrayList<String>(subnets.length));
}
for (String ele : subnets) {
this.subnets.add(ele);
}
return this;
}
/**
* <p>
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC.
* Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify.
* </p>
*
* @param subnets
* A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon
* VPC. Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets
* you specify.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withSubnets(java.util.Collection<String> subnets) {
setSubnets(subnets);
return this;
}
/**
* <p>
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources under the
* specified subnets. If not specified, App Runner uses the default security group of the Amazon VPC. The default
* security group allows all outbound traffic.
* </p>
*
* @return A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources
* under the specified subnets. If not specified, App Runner uses the default security group of the Amazon
* VPC. The default security group allows all outbound traffic.
*/
public java.util.List<String> getSecurityGroups() {
return securityGroups;
}
/**
* <p>
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources under the
* specified subnets. If not specified, App Runner uses the default security group of the Amazon VPC. The default
* security group allows all outbound traffic.
* </p>
*
* @param securityGroups
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources
* under the specified subnets. If not specified, App Runner uses the default security group of the Amazon
* VPC. The default security group allows all outbound traffic.
*/
public void setSecurityGroups(java.util.Collection<String> securityGroups) {
if (securityGroups == null) {
this.securityGroups = null;
return;
}
this.securityGroups = new java.util.ArrayList<String>(securityGroups);
}
/**
* <p>
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources under the
* specified subnets. If not specified, App Runner uses the default security group of the Amazon VPC. The default
* security group allows all outbound traffic.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSecurityGroups(java.util.Collection)} or {@link #withSecurityGroups(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param securityGroups
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources
* under the specified subnets. If not specified, App Runner uses the default security group of the Amazon
* VPC. The default security group allows all outbound traffic.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withSecurityGroups(String... securityGroups) {
if (this.securityGroups == null) {
setSecurityGroups(new java.util.ArrayList<String>(securityGroups.length));
}
for (String ele : securityGroups) {
this.securityGroups.add(ele);
}
return this;
}
/**
* <p>
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources under the
* specified subnets. If not specified, App Runner uses the default security group of the Amazon VPC. The default
* security group allows all outbound traffic.
* </p>
*
* @param securityGroups
* A list of IDs of security groups that App Runner should use for access to Amazon Web Services resources
* under the specified subnets. If not specified, App Runner uses the default security group of the Amazon
* VPC. The default security group allows all outbound traffic.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withSecurityGroups(java.util.Collection<String> securityGroups) {
setSecurityGroups(securityGroups);
return this;
}
/**
* <p>
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value pair.
* </p>
*
* @return A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value
* pair.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value pair.
* </p>
*
* @param tags
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value
* pair.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value pair.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value
* pair.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value pair.
* </p>
*
* @param tags
* A list of metadata items that you can associate with your VPC connector resource. A tag is a key-value
* pair.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateVpcConnectorRequest withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVpcConnectorName() != null)
sb.append("VpcConnectorName: ").append(getVpcConnectorName()).append(",");
if (getSubnets() != null)
sb.append("Subnets: ").append(getSubnets()).append(",");
if (getSecurityGroups() != null)
sb.append("SecurityGroups: ").append(getSecurityGroups()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateVpcConnectorRequest == false)
return false;
CreateVpcConnectorRequest other = (CreateVpcConnectorRequest) obj;
if (other.getVpcConnectorName() == null ^ this.getVpcConnectorName() == null)
return false;
if (other.getVpcConnectorName() != null && other.getVpcConnectorName().equals(this.getVpcConnectorName()) == false)
return false;
if (other.getSubnets() == null ^ this.getSubnets() == null)
return false;
if (other.getSubnets() != null && other.getSubnets().equals(this.getSubnets()) == false)
return false;
if (other.getSecurityGroups() == null ^ this.getSecurityGroups() == null)
return false;
if (other.getSecurityGroups() != null && other.getSecurityGroups().equals(this.getSecurityGroups()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVpcConnectorName() == null) ? 0 : getVpcConnectorName().hashCode());
hashCode = prime * hashCode + ((getSubnets() == null) ? 0 : getSubnets().hashCode());
hashCode = prime * hashCode + ((getSecurityGroups() == null) ? 0 : getSecurityGroups().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public CreateVpcConnectorRequest clone() {
return (CreateVpcConnectorRequest) super.clone();
}
}
| |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.ByteArrayInputStream;
import java.io.SequenceInputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
import javax.annotation.Nullable;
import hudson.model.AperiodicWork;
import hudson.util.VersionNumber;
import jenkins.model.Jenkins;
import jenkins.model.identity.InstanceIdentityProvider;
import jenkins.security.stapler.StaplerAccessibleType;
import jenkins.slaves.RemotingVersionInfo;
import jenkins.util.SystemProperties;
import hudson.slaves.OfflineCause;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Arrays;
import java.util.Base64;
import jenkins.AgentProtocol;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Listens to incoming TCP connections, for example from agents.
*
* <p>
* Aside from the HTTP endpoint, Jenkins runs {@link TcpSlaveAgentListener} that listens on a TCP socket.
* Historically this was used for inbound connection from agents (hence the name), but over time
* it was extended and made generic, so that multiple protocols of different purposes can co-exist on the
* same socket.
*
* <p>
* This class accepts the socket, then after a short handshaking, it dispatches to appropriate
* {@link AgentProtocol}s.
*
* @author Kohsuke Kawaguchi
* @see AgentProtocol
*/
@StaplerAccessibleType
public final class TcpSlaveAgentListener extends Thread {
private final ServerSocketChannel serverSocket;
private volatile boolean shuttingDown;
public final int configuredPort;
/**
* @param port
* Use 0 to choose a random port.
*/
public TcpSlaveAgentListener(int port) throws IOException {
super("TCP agent listener port="+port);
try {
serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(port));
} catch (BindException e) {
throw (BindException)new BindException("Failed to listen on port "+port+" because it's already in use.").initCause(e);
}
this.configuredPort = port;
setUncaughtExceptionHandler((t, e) -> {
LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener " + t + ", attempting to reschedule thread", e);
shutdown();
TcpSlaveAgentListenerRescheduler.schedule(t, e);
});
LOGGER.log(Level.FINE, "TCP agent listener started on port {0}", getPort());
start();
}
/**
* Gets the TCP port number in which we are listening.
*/
public int getPort() {
return serverSocket.socket().getLocalPort();
}
/**
* Gets the TCP port number in which we are advertising.
* @since 1.656
*/
public int getAdvertisedPort() {
return CLI_PORT != null ? CLI_PORT : getPort();
}
/**
* Gets the host name that we advertise protocol clients to connect to.
* @since 2.198
*/
public String getAdvertisedHost() {
if (CLI_HOST_NAME != null) {
return CLI_HOST_NAME;
}
try {
return new URL(Jenkins.get().getRootUrl()).getHost();
} catch (MalformedURLException | NullPointerException e) {
throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e);
}
}
/**
* Gets the Base64 encoded public key that forms part of this instance's identity keypair.
* @return the Base64 encoded public key
* @since 2.16
*/
@Nullable
public String getIdentityPublicKey() {
RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey();
return key == null ? null : Base64.getEncoder().encodeToString(key.getEncoded());
}
/**
* Returns a comma separated list of the enabled {@link AgentProtocol#getName()} implementations so that
* clients can avoid creating additional work for the server attempting to connect with unsupported protocols.
*
* @return a comma separated list of the enabled {@link AgentProtocol#getName()} implementations
* @since 2.16
*/
public String getAgentProtocolNames() {
return StringUtils.join(Jenkins.get().getAgentProtocols(), ", ");
}
/**
* Gets Remoting minimum supported version to prevent unsupported agents from connecting
* @since 2.171
*/
public VersionNumber getRemotingMinimumVersion() {
return RemotingVersionInfo.getMinimumSupportedVersion();
}
@Override
public void run() {
try {
// the loop eventually terminates when the socket is closed.
while (!shuttingDown) {
Socket s = serverSocket.accept().socket();
// this prevents a connection from silently terminated by the router in between or the other peer
// and that goes without unnoticed. However, the time out is often very long (for example 2 hours
// by default in Linux) that this alone is enough to prevent that.
s.setKeepAlive(true);
// we take care of buffering on our own
s.setTcpNoDelay(true);
new ConnectionHandler(s, new ConnectionHandlerFailureCallback(this) {
@Override
public void run(Throwable cause) {
LOGGER.log(Level.WARNING, "Connection handler failed, restarting listener", cause);
shutdown();
TcpSlaveAgentListenerRescheduler.schedule(getParentThread(), cause);
}
}).start();
}
} catch (IOException e) {
if(!shuttingDown) {
LOGGER.log(Level.SEVERE,"Failed to accept TCP connections", e);
}
}
}
/**
* Initiates the shuts down of the listener.
*/
public void shutdown() {
shuttingDown = true;
try {
SocketAddress localAddress = serverSocket.getLocalAddress();
if (localAddress instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) localAddress;
Socket client = new Socket(address.getHostName(), address.getPort());
client.setSoTimeout(1000); // waking the acceptor loop should be quick
new PingAgentProtocol().connect(client);
}
} catch (IOException e) {
LOGGER.log(Level.FINE, "Failed to send Ping to wake acceptor loop", e);
}
try {
serverSocket.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to close down TCP port",e);
}
}
private final class ConnectionHandler extends Thread {
private final Socket s;
/**
* Unique number to identify this connection. Used in the log.
*/
private final int id;
public ConnectionHandler(Socket s, ConnectionHandlerFailureCallback parentTerminator) {
this.s = s;
synchronized(getClass()) {
id = iotaGen++;
}
setName("TCP agent connection handler #"+id+" with "+s.getRemoteSocketAddress());
setUncaughtExceptionHandler((t, e) -> {
LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener ConnectionHandler " + t, e);
try {
s.close();
parentTerminator.run(e);
} catch (IOException e1) {
LOGGER.log(Level.WARNING, "Could not close socket after unexpected thread death", e1);
}
});
}
@Override
public void run() {
try {
LOGGER.log(Level.FINE, "Accepted connection #{0} from {1}", new Object[] {id, s.getRemoteSocketAddress()});
DataInputStream in = new DataInputStream(s.getInputStream());
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8)),
true); // DEPRECATED: newer protocol shouldn't use PrintWriter but should use DataOutputStream
// peek the first few bytes to determine what to do with this client
byte[] head = new byte[10];
in.readFully(head);
String header = new String(head, Charsets.US_ASCII);
if (header.startsWith("GET ")) {
// this looks like an HTTP client
respondHello(header,s);
return;
}
// otherwise assume this is AgentProtocol and start from the beginning
String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF();
if(s.startsWith("Protocol:")) {
String protocol = s.substring(9);
AgentProtocol p = AgentProtocol.of(protocol);
if (p!=null) {
if (Jenkins.get().getAgentProtocols().contains(protocol)) {
LOGGER.log(p instanceof PingAgentProtocol ? Level.FINE : Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()});
p.handle(this.s);
} else {
error(out, "Disabled protocol:" + s);
}
} else
error(out, "Unknown protocol:" + s);
} else {
error(out, "Unrecognized protocol: "+s);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e);
try {
s.close();
} catch (IOException ex) {
// try to clean up the socket
}
} catch (IOException e) {
if (e instanceof EOFException) {
LOGGER.log(Level.INFO, "Connection #{0} failed: {1}", new Object[] {id, e});
} else {
LOGGER.log(Level.WARNING, "Connection #" + id + " failed", e);
}
try {
s.close();
} catch (IOException ex) {
// try to clean up the socket
}
}
}
/**
* Respond to HTTP request with simple diagnostics.
* Primarily used to test the low-level connectivity.
*/
private void respondHello(String header, Socket s) throws IOException {
try {
Writer o = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8);
if (header.startsWith("GET / ")) {
o.write("HTTP/1.0 200 OK\r\n");
o.write("Content-Type: text/plain;charset=UTF-8\r\n");
o.write("\r\n");
o.write("Jenkins-Agent-Protocols: " + getAgentProtocolNames()+"\r\n");
o.write("Jenkins-Version: " + Jenkins.VERSION + "\r\n");
o.write("Jenkins-Session: " + Jenkins.SESSION_HASH + "\r\n");
o.write("Client: " + s.getInetAddress().getHostAddress() + "\r\n");
o.write("Server: " + s.getLocalAddress().getHostAddress() + "\r\n");
o.write("Remoting-Minimum-Version: " + getRemotingMinimumVersion() + "\r\n");
o.flush();
s.shutdownOutput();
} else {
o.write("HTTP/1.0 404 Not Found\r\n");
o.write("Content-Type: text/plain;charset=UTF-8\r\n");
o.write("\r\n");
o.write("Not Found\r\n");
o.flush();
s.shutdownOutput();
}
InputStream i = s.getInputStream();
IOUtils.copy(i, new NullOutputStream());
s.shutdownInput();
} finally {
s.close();
}
}
private void error(PrintWriter out, String msg) throws IOException {
out.println(msg);
LOGGER.log(Level.WARNING, "Connection #{0} is aborted: {1}", new Object[]{id, msg});
s.close();
}
}
// This is essentially just to be able to pass the parent thread into the callback, as it can't access it otherwise
private abstract class ConnectionHandlerFailureCallback {
private Thread parentThread;
public ConnectionHandlerFailureCallback(Thread parentThread) {
this.parentThread = parentThread;
}
public Thread getParentThread() {
return parentThread;
}
public abstract void run(Throwable cause);
}
/**
* This extension provides a Ping protocol that allows people to verify that the TcpSlaveAgentListener is alive.
* We also use this to wake the acceptor thread on termination.
*
* @since 1.653
*/
@Extension
@Symbol("ping")
public static class PingAgentProtocol extends AgentProtocol {
private final byte[] ping;
public PingAgentProtocol() {
ping = "Ping\n".getBytes(StandardCharsets.UTF_8);
}
@Override
public boolean isRequired() {
return true;
}
@Override
public String getName() {
return "Ping";
}
@Override
public String getDisplayName() {
return Messages.TcpSlaveAgentListener_PingAgentProtocol_displayName();
}
@Override
public void handle(Socket socket) throws IOException, InterruptedException {
try {
try (OutputStream stream = socket.getOutputStream()) {
LOGGER.log(Level.FINE, "Received ping request from {0}", socket.getRemoteSocketAddress());
stream.write(ping);
stream.flush();
LOGGER.log(Level.FINE, "Sent ping response to {0}", socket.getRemoteSocketAddress());
}
} finally {
socket.close();
}
}
public boolean connect(Socket socket) throws IOException {
try {
LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
out.writeUTF("Protocol:Ping");
try (InputStream in = socket.getInputStream()) {
byte[] response = new byte[ping.length];
int responseLength = in.read(response);
if (responseLength == ping.length && Arrays.equals(response, ping)) {
LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
return true;
} else {
LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
socket.getRemoteSocketAddress(),
new String(ping, StandardCharsets.UTF_8),
responseLength > 0 && responseLength <= response.length ?
new String(response, 0, responseLength, StandardCharsets.UTF_8) :
"bad response length " + responseLength
});
return false;
}
}
}
} finally {
socket.close();
}
}
}
/**
* Reschedules the {@code TcpSlaveAgentListener} on demand. Disables itself after running.
*/
@Extension
@Restricted(NoExternalUse.class)
public static class TcpSlaveAgentListenerRescheduler extends AperiodicWork {
private Thread originThread;
private Throwable cause;
private long recurrencePeriod = 5000;
private boolean isActive;
public TcpSlaveAgentListenerRescheduler() {
isActive = false;
}
public TcpSlaveAgentListenerRescheduler(Thread originThread, Throwable cause) {
this.originThread = originThread;
this.cause = cause;
this.isActive = false;
}
public void setOriginThread(Thread originThread) {
this.originThread = originThread;
}
public void setCause(Throwable cause) {
this.cause = cause;
}
public void setActive(boolean active) {
isActive = active;
}
@Override
public long getRecurrencePeriod() {
return recurrencePeriod;
}
@Override
public AperiodicWork getNewInstance() {
return new TcpSlaveAgentListenerRescheduler(originThread, cause);
}
@Override
protected void doAperiodicRun() {
if (isActive) {
try {
if (originThread.isAlive()) {
originThread.interrupt();
}
int port = Jenkins.get().getSlaveAgentPort();
if (port != -1) {
new TcpSlaveAgentListener(port).start();
LOGGER.log(Level.INFO, "Restarted TcpSlaveAgentListener");
} else {
LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener " + originThread + ". Port is disabled, not rescheduling", cause);
}
isActive = false;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Could not reschedule TcpSlaveAgentListener - trying again.", cause);
}
}
}
public static void schedule(Thread originThread, Throwable cause) {
schedule(originThread, cause,5000);
}
public static void schedule(Thread originThread, Throwable cause, long approxDelay) {
TcpSlaveAgentListenerRescheduler rescheduler = AperiodicWork.all().get(TcpSlaveAgentListenerRescheduler.class);
rescheduler.originThread = originThread;
rescheduler.cause = cause;
rescheduler.recurrencePeriod = approxDelay;
rescheduler.isActive = true;
}
}
/**
* Connection terminated because we are reconnected from the current peer.
*/
public static class ConnectionFromCurrentPeer extends OfflineCause {
public String toString() {
return "The current peer is reconnecting";
}
}
private static int iotaGen=1;
private static final Logger LOGGER = Logger.getLogger(TcpSlaveAgentListener.class.getName());
/**
* Host name that we advertise protocol clients to connect to.
* This is primarily for those who have reverse proxies in place such that the HTTP host name
* and the TCP/IP connection host names are different.
* (Note: despite the name, this is used for any client, not only deprecated Remoting-based CLI.)
* TODO: think about how to expose this (including whether this needs to be exposed at all.)
*/
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts")
@Restricted(NoExternalUse.class)
public static String CLI_HOST_NAME = SystemProperties.getString(TcpSlaveAgentListener.class.getName()+".hostName");
/**
* Port number that we advertise protocol clients to connect to.
* This is primarily for the case where the port that Jenkins runs is different from the port
* that external world should connect to, because of the presence of NAT / port-forwarding / TCP reverse
* proxy.
* (Note: despite the name, this is used for any client, not only deprecated Remoting-based CLI.)
* If left to null, fall back to {@link #getPort()}
*
* @since 1.611
*/
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts")
@Restricted(NoExternalUse.class)
public static Integer CLI_PORT = SystemProperties.getInteger(TcpSlaveAgentListener.class.getName()+".port");
}
| |
/*****************************************************************
<copyright>
Morozko Java Library org.morozko.java.mod.doc
Copyright (c) 2006 Morozko
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache License v2.0
which accompanies this distribution, and is available at
http://www.apache.org/licenses/
(txt version : http://www.apache.org/licenses/LICENSE-2.0.txt
html version : http://www.apache.org/licenses/LICENSE-2.0.html)
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
</copyright>
*****************************************************************/
/*
* @(#)ITextDocHandler.java
*
* @project : org.morozko.java.mod.doc
* @package : org.morozko.java.mod.doc.itext
* @creation : 06/set/06
* @license : META-INF/LICENSE.TXT
*/
package org.morozko.java.mod.doc.itext;
import java.awt.Color;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.morozko.java.core.log.LogFacade;
import org.morozko.java.core.math.BinaryCalc;
import org.morozko.java.core.text.regex.ParamFinder;
import org.morozko.java.mod.doc.DocBarcode;
import org.morozko.java.mod.doc.DocBase;
import org.morozko.java.mod.doc.DocBorders;
import org.morozko.java.mod.doc.DocCell;
import org.morozko.java.mod.doc.DocElement;
import org.morozko.java.mod.doc.DocFooter;
import org.morozko.java.mod.doc.DocHandler;
import org.morozko.java.mod.doc.DocHeader;
import org.morozko.java.mod.doc.DocHeaderFooter;
import org.morozko.java.mod.doc.DocImage;
import org.morozko.java.mod.doc.DocInfo;
import org.morozko.java.mod.doc.DocPageBreak;
import org.morozko.java.mod.doc.DocPara;
import org.morozko.java.mod.doc.DocPhrase;
import org.morozko.java.mod.doc.DocRow;
import org.morozko.java.mod.doc.DocStyle;
import org.morozko.java.mod.doc.DocTable;
import org.morozko.java.mod.doc.itext.v2.ITextHelper;
import org.morozko.java.mod.doc.itext.v2.PdfHelper;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Header;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.html.HtmlTags;
import com.lowagie.text.pdf.Barcode;
import com.lowagie.text.pdf.Barcode128;
import com.lowagie.text.pdf.BarcodeEAN;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfArray;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfString;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter;
/**
* <p></p>
*
* @author mfranci
*
*/
public class ITextDocHandler implements DocHandler {
private static final ParamFinder PARAM_FINDER = ParamFinder.newFinder();
public static final String PARAM_PAGE_CURRENT = "currentPage";
public static final String PARAM_PAGE_TOTAL = "totalPage";
public static final String PARAM_PAGE_TOTAL_FINDER = PARAM_FINDER.DEFAULT_PRE+"totalPage"+PARAM_FINDER.DEFAULT_POST;
private static HashMap fonts = new HashMap();
public static void registerFont( String name, String path ) throws Exception {
BaseFont font = BaseFont.createFont( path, BaseFont.CP1252, true );
registerFont( name, font );
}
public static void registerFont( String name, BaseFont font ) {
fonts.put( name , font );
}
public static BaseFont findFont( String name ) {
BaseFont res = (BaseFont)fonts.get( name );
return res;
}
private static void setStyle( DocStyle parent, DocStyle current ) {
if ( current.getBackColor() == null ) {
current.setBackColor( parent.getBackColor() );
}
if ( current.getForeColor() == null ) {
current.setForeColor( parent.getForeColor() );
}
}
public static Color parseHtmlColor( String c ) {
int r = (int)BinaryCalc.hexToLong( c.substring( 1, 3 ) );
int g = (int)BinaryCalc.hexToLong( c.substring( 3, 5 ) );
int b = (int)BinaryCalc.hexToLong( c.substring( 5, 7 ) );
return new Color( r, g, b );
}
private PdfWriter pdfWriter;
private RtfWriter2 rtfWriter2;
private Document document;
private String docType;
public final static String DOC_OUTPUT_HTML = "html";
public final static String DOC_OUTPUT_PDF = "pdf";
public final static String DOC_OUTPUT_RTF = "rtf";
public final static String DOC_DEFAULT_FONT_NAME = "default-font-name";
public final static String DOC_DEFAULT_FONT_SIZE = "default-font-size";
public final static String DOC_DEFAULT_FONT_STYLE = "default-font-style";
private int totalPageCount;
public ITextDocHandler( Document document, RtfWriter2 rtfWriter2 ) {
this( document, DOC_OUTPUT_RTF );
this.rtfWriter2 = rtfWriter2;
}
public ITextDocHandler( Document document, PdfWriter pdfWriter ) {
this(document, pdfWriter, -1);
}
public ITextDocHandler( Document document, PdfWriter pdfWriter, int totalPageCount ) {
this( document, DOC_OUTPUT_PDF );
this.pdfWriter = pdfWriter;
this.totalPageCount = totalPageCount;
}
public ITextDocHandler( Document document, String docType ) {
this.document = document;
this.docType = docType;
}
private static int getAlign( int align ) {
int r = Element.ALIGN_LEFT;
if ( align == DocPara.ALIGN_RIGHT ) {
r = Element.ALIGN_RIGHT;
} else if ( align == DocPara.ALIGN_CENTER ) {
r = Element.ALIGN_CENTER;
} else if ( align == DocPara.ALIGN_JUSTIFY ) {
r = Element.ALIGN_JUSTIFIED;
} else if ( align == DocPara.ALIGN_JUSTIFY_ALL ) {
r = Element.ALIGN_JUSTIFIED_ALL;
}
return r;
}
private static int getValign( int align ) {
int r = Element.ALIGN_TOP;
if ( align == DocPara.ALIGN_BOTTOM ) {
r = Element.ALIGN_BOTTOM;
} else if ( align == DocPara.ALIGN_MIDDLE ) {
r = Element.ALIGN_MIDDLE;
}
return r;
}
protected static Image createImage( DocImage docImage ) throws Exception {
Image image = null;
String url = docImage.getUrl();
try {
image = Image.getInstance( new URL( url ) );
if ( docImage.getScaling() != null ) {
image.scalePercent( docImage.getScaling().floatValue() );
}
} catch (Exception e) {
LogFacade.getLog().error( "ITextDocHandler.createImage() Error loading image url : "+url, e );
throw e;
}
return image;
}
public static String createText( Properties params, String text ) {
return PARAM_FINDER.substitute( text , params );
}
protected static Chunk createChunk( DocPhrase docPhrase, ITextHelper docHelper ) throws Exception {
String text = createText( docHelper.getParams(), docPhrase.getText() );
int style = docPhrase.getStyle();
String fontName = docPhrase.getFontName();
Font f = createFont(fontName, docPhrase.getSize(), style, docHelper, docPhrase.getForeColor() );
Chunk p = new Chunk( text, f );
return p;
}
protected static Phrase createPhrase( DocPhrase docPhrase, ITextHelper docHelper, List fontMap ) throws Exception {
String text = createText( docHelper.getParams(), docPhrase.getText() );
int style = docPhrase.getStyle();
String fontName = docPhrase.getFontName();
Font f = createFont(fontName, docPhrase.getSize(), style, docHelper, docPhrase.getForeColor() );
Phrase p = new Phrase( text, f );
if (fontMap != null) {
fontMap.add( f );
}
return p;
}
protected static Phrase createPhrase( DocPhrase docPhrase, ITextHelper docHelper ) throws Exception {
return createPhrase(docPhrase, docHelper, null);
}
protected static Paragraph createPara( DocPara docPara, ITextHelper docHelper ) throws Exception {
return createPara(docPara, docHelper, null);
}
protected static Paragraph createPara( DocPara docPara, ITextHelper docHelper, List fontMap ) throws Exception {
int style = docPara.getStyle();
String text = createText( docHelper.getParams(), docPara.getText() );
// if ( DOC_OUTPUT_HTML.equals( this.docType ) ) {
// int count = 0;
// StringBuffer buffer = new StringBuffer();
// while ( count < text.length() && text.indexOf( " " )==count ) {
// count++;
// }
// buffer.append( text.substring( count ) );
// text = buffer.toString();
// }
String fontName = docPara.getFontName();
Font f = createFont(fontName, docPara.getSize(), style, docHelper, docPara.getForeColor() );
Phrase phrase = new Phrase( text, f );
Paragraph p = new Paragraph( new Phrase( text, f ) );
if ( docPara.getForeColor() != null ) {
Color c = parseHtmlColor( docPara.getForeColor() );
Font f1 = new Font( f.getFamily(), f.getSize(), f.getStyle(), c );
p = new Paragraph( new Phrase( text, f1 ) );
//f = f1;
}
if ( docPara.getAlign() != DocPara.ALIGN_UNSET ) {
p.setAlignment( getAlign( docPara.getAlign() ) );
}
if ( docPara.getLeading() != null ) {
p.setLeading( docPara.getLeading().floatValue() );
}
if ( docPara.getSpaceBefore() != null ) {
p.setSpacingBefore( docPara.getSpaceBefore().floatValue() );
}
if ( docPara.getSpaceAfter() != null ) {
p.setSpacingAfter( docPara.getSpaceAfter().floatValue() );
}
p.setFont( f );
phrase.setFont( f );
if ( fontMap != null ) {
fontMap.add( f );
}
return p;
}
protected static Table createTable( DocTable docTable, ITextHelper docHelper ) throws Exception {
LogFacade.getLog().debug( "Handle table DONE ! -> "+docTable.getClass().getName()+" - "+Runtime.getRuntime().freeMemory()/1000/1000+" / "+Runtime.getRuntime().totalMemory()/1000/1000+" / "+Runtime.getRuntime().maxMemory()/1000/1000 );
int maxMem = 0;
boolean startHeader = false;
Table table = new Table( docTable.getColumns() );
table.setBorderWidth(0);
table.setWidth( docTable.getWidth() );
table.setBorderColor( Color.black );
table.setPadding( docTable.getPadding() );
table.setSpacing( docTable.getSpacing() );
table.setCellsFitPage( true );
if ( docTable.getSpaceBefore() != null ) {
table.setSpacing( docTable.getSpaceBefore().floatValue() );
}
if ( docTable.getSpaceAfter() != null ) {
table.setSpacing( docTable.getSpaceAfter().floatValue() );
}
int[] cw = docTable.getColWithds();
if ( cw != null ) {
float[] w = new float[ cw.length ];
for ( int k=0; k<w.length; k++ ) {
w[k] = (float)((float)cw[k]/(float)100);
}
table.setWidths( w );
}
Iterator itRow = docTable.docElements();
while ( itRow.hasNext() ) {
DocRow docRow = (DocRow)itRow.next();
//maxMam = Math.max( Runtime.getRuntime().totalMemory()/1000/1000 , )
//System.out.println( "Handle row DONE ! -> "+Runtime.getRuntime().freeMemory()/1000/1000+" / "+Runtime.getRuntime().totalMemory()/1000/1000 );
Iterator itCell = docRow.docElements();
while ( itCell.hasNext() ) {
DocCell docCell = (DocCell)itCell.next();
setStyle( docTable, docCell );
Cell cell = new Cell();
if ( docCell.isHeader() ) {
cell.setHeader( true );
startHeader = true;
} else {
if ( startHeader ) {
startHeader = false;
table.endHeaders();
}
}
cell.setColspan( docCell.getCSpan() );
cell.setRowspan( docCell.getRSpan() );
DocBorders docBorders = docCell.getDocBorders();
if ( docBorders != null ) {
if ( docBorders.getBorderColorBottom() != null ) {
cell.setBorderColorBottom( parseHtmlColor( docBorders.getBorderColorBottom() ) );
}
if ( docBorders.getBorderColorTop() != null ) {
cell.setBorderColorTop( parseHtmlColor( docBorders.getBorderColorTop() ) );
}
if ( docBorders.getBorderColorLeft() != null ) {
cell.setBorderColorLeft( parseHtmlColor( docBorders.getBorderColorLeft() ) );
}
if ( docBorders.getBorderColorRight() != null ) {
cell.setBorderColorRight( parseHtmlColor( docBorders.getBorderColorRight() ) );
}
if ( docBorders.getBorderWidthBottom() != -1 ) {
cell.setBorderWidthBottom( docBorders.getBorderWidthBottom() );
}
if ( docBorders.getBorderWidthTop() != -1 ) {
cell.setBorderWidthTop( docBorders.getBorderWidthTop() );
}
if ( docBorders.getBorderWidthLeft() != -1 ) {
cell.setBorderWidthLeft( docBorders.getBorderWidthLeft() );
}
if ( docBorders.getBorderWidthRight() != -1 ) {
cell.setBorderWidthRight( docBorders.getBorderWidthRight() );
}
}
if ( docCell.getBackColor() != null ) {
cell.setBackgroundColor( parseHtmlColor( docCell.getBackColor() ) );
}
if ( docCell.getAlign() != DocPara.ALIGN_UNSET ) {
cell.setHorizontalAlignment( getAlign( docCell.getAlign() ) );
}
if ( docCell.getValign() != DocPara.ALIGN_UNSET ) {
cell.setVerticalAlignment( getValign( docCell.getValign() ) );
}
CellParent cellParent = new CellParent( cell );
Iterator itCurrent = docCell.docElements();
List fontList = new ArrayList();
while ( itCurrent.hasNext() ) {
DocElement docElement = (DocElement) itCurrent.next();
if ( docElement instanceof DocPara ) {
DocPara docPara = (DocPara)docElement;
setStyle( docCell , docPara );
Paragraph paragraph = createPara( docPara, docHelper, fontList );
cellParent.add( paragraph );
} else if ( docElement instanceof DocPhrase ) {
DocPhrase docPhrase = (DocPhrase)docElement;
//setStyle( docCell , docPara );
cellParent.add( createPhrase( docPhrase, docHelper, fontList ) );
} else if ( docElement instanceof DocTable ) {
LogFacade.getLog().debug( "nested table" );
table.insertTable( createTable( (DocTable)docElement, docHelper ) );
} else if ( docElement instanceof DocImage ) {
LogFacade.getLog().debug( "cell DocImage : "+docElement );
cellParent.add( createImage( (DocImage)docElement ) );
} else if ( docElement instanceof DocBarcode ) {
LogFacade.getLog().info( "cell DocBarcode : "+docElement );
cellParent.add( createBarcode( (DocBarcode)docElement, docHelper ) );
}
}
table.addCell( cell );
List listChunk = cell.getChunks();
if ( listChunk.size() == fontList.size() ) {
for ( int k=0; k<listChunk.size(); k++ ) {
Chunk c = (Chunk)listChunk.get( k );
Font f = (Font) fontList.get( k );
c.setFont( f );
}
}
if ( docHelper.getPdfWriter() != null ) {
docHelper.getPdfWriter().flush();
}
}
}
return table;
}
private static Image createBarcode( DocBarcode docBarcode, ITextHelper helper ) throws Exception {
Barcode barcode = null;
if ( "128".equalsIgnoreCase( docBarcode.getType() ) ) {
barcode = new Barcode128();
} else {
barcode = new BarcodeEAN();
}
if ( docBarcode.getSize() != -1 ) {
barcode.setBarHeight( docBarcode.getSize() );
}
barcode.setCode( docBarcode.getText() );
barcode.setAltText( docBarcode.getText() );
java.awt.Image awtImage = barcode.createAwtImage( Color.white, Color.black );
Image img = Image.getInstance( awtImage, null );
return img;
}
private static RtfHeaderFooter createRtfHeaderFooter( DocHeaderFooter docHeaderFooter, Document document, boolean header, ITextHelper docHelper ) throws Exception {
List list = new ArrayList();
Iterator itDoc = docHeaderFooter.docElements();
while ( itDoc.hasNext() ) {
list.add( itDoc.next() );
}
Element[] e = new Element[ list.size() ];
for ( int k=0; k<list.size(); k++ ) {
e[k] = (Element)getElement( document, (DocElement)list.get( k ) , false, docHelper );
}
RtfHeaderFooter rtfHeaderFooter = new RtfHeaderFooter( e );
rtfHeaderFooter.setDisplayAt( RtfHeaderFooter.DISPLAY_ALL_PAGES );
if ( header ) {
rtfHeaderFooter.setType( RtfHeaderFooter.TYPE_HEADER );
} else {
rtfHeaderFooter.setType( RtfHeaderFooter.TYPE_FOOTER );
}
return rtfHeaderFooter;
}
public static Font createFont( String fontName, int fontSize, int fontStyle, ITextHelper docHelper, String color ) throws Exception {
return createFont(fontName, fontName, fontSize, fontStyle, docHelper, color);
}
private static Font createFont( String fontName, String fontPath, int fontSize, int fontStyle, ITextHelper docHelper, String color ) throws Exception {
Font font = null;
int size = fontSize;
int style = Font.NORMAL;
BaseFont bf = null;
int bfV = -1;
if ( size == -1 ) {
size = Integer.parseInt( docHelper.getDefFontSize() );
}
if ( fontStyle == DocPara.STYLE_BOLD ) {
style = Font.BOLD;
} else if ( fontStyle == DocPara.STYLE_UNDERLINE ) {
style = Font.UNDERLINE;
} else if ( fontStyle == DocPara.STYLE_ITALIC ) {
style = Font.ITALIC;
} else if ( fontStyle == DocPara.STYLE_BOLDITALIC ) {
style = Font.BOLDITALIC;
}
if ( fontName == null ) {
fontName = docHelper.getDefFontName();
}
if ( "helvetica".equalsIgnoreCase( fontName ) ) {
bfV = Font.HELVETICA;
} else if ( "courier".equalsIgnoreCase( fontName ) ) {
bfV = Font.COURIER;
} else if ( "times-roman".equalsIgnoreCase( fontName ) ) {
bfV = Font.TIMES_ROMAN;
} else if ( "symbol".equalsIgnoreCase( fontName ) ) {
bfV = Font.SYMBOL;
} else {
bf = findFont( fontName );
if ( bf == null) {
bf = BaseFont.createFont( fontPath, BaseFont.CP1252, true );
registerFont( fontName, bf );
}
}
Color c = Color.BLACK;
if ( color != null ) {
c = parseHtmlColor( color );
}
if ( bfV == -1 ) {
font = new Font( bf, size, style, c );
} else {
font = new Font( bfV, size, style, c );
}
return font;
}
/* (non-Javadoc)
* @see org.morozko.java.mod.doc.DocHandler#handleDoc(org.morozko.java.mod.doc.DocBase)
*/
public void handleDoc(DocBase docBase) throws Exception {
Properties info = docBase.getInfo();
String defaultFontName = info.getProperty( DOC_DEFAULT_FONT_NAME, "helvetica" );
String defaultFontSize = info.getProperty( DOC_DEFAULT_FONT_SIZE, "10" );
String defaultFontStyle = info.getProperty( DOC_DEFAULT_FONT_STYLE, "normal" );
ITextHelper docHelper = new ITextHelper();
if ( this.pdfWriter != null ) {
docHelper.setPdfWriter( this.pdfWriter );
}
docHelper.setDefFontName( defaultFontName );
docHelper.setDefFontStyle( defaultFontStyle );
docHelper.setDefFontSize( defaultFontSize );
if ( this.totalPageCount != -1 ) {
docHelper.getParams().setProperty( PARAM_PAGE_TOTAL , String.valueOf( this.totalPageCount ) );
}
// per documenti tipo HTML
if ( DOC_OUTPUT_HTML.equalsIgnoreCase( this.docType ) ) {
String cssLink = info.getProperty( DocInfo.INFO_NAME_CSS_LINK );
if ( cssLink != null ) {
this.document.add( new Header( HtmlTags.STYLESHEET, cssLink ) );
}
}
// per documenti tipo word o pdf
if ( DOC_OUTPUT_PDF.equalsIgnoreCase( this.docType ) || DOC_OUTPUT_RTF.equalsIgnoreCase( this.docType ) ) {
Rectangle size = this.document.getPageSize();
String pageOrient = info.getProperty( DocInfo.INFO_NAME_PAGE_ORIENT );
if ( pageOrient != null ) {
if ( "horizontal".equalsIgnoreCase( pageOrient ) ) {
size = new Rectangle( size.getHeight(), size.getWidth() );
this.document.setPageSize( size );
}
}
if ( DOC_OUTPUT_PDF.equalsIgnoreCase( this.docType ) ) {
String pdfFormat = info.getProperty( DocInfo.INFO_NAME_PDF_FORMAT );
if ( "pdf-a".equalsIgnoreCase( pdfFormat ) ) {
this.pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);
PdfDictionary outi = new PdfDictionary( PdfName.OUTPUTINTENT );
outi.put( PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1") );
outi.put( PdfName.INFO, new PdfString("sRGB IEC61966-2.1") );
outi.put( PdfName.S, PdfName.GTS_PDFA1 );
// FontFactory.
// BaseFont bf = BaseFont.createFont( Font.HELVETICA, BaseFont.WINANSI, true );
this.pdfWriter.getExtraCatalog().put( PdfName.OUTPUTINTENTS, new PdfArray( outi ) );
System.out.println( "PDF-A 2 <<<<<<<<<<<<<<<<<<<<<" );
}
}
}
// header / footer section
PdfHelper pdfHelper = new PdfHelper( docHelper );
DocHeader docHeader = docBase.getDocHeader();
if ( docHeader != null && docHeader.isUseHeader() ) {
if ( docHeader.isBasic() ) {
HeaderFooter header = this.createHeaderFoter( docHeader, docHeader.getAlign(), docHelper );
this.document.setHeader( header );
} else {
if ( DOC_OUTPUT_PDF.equals( this.docType ) ) {
pdfHelper.setDocHeader( docHeader );
} else if ( DOC_OUTPUT_RTF.equals( this.docType ) ) {
this.document.setHeader( new RtfHeaderFooter( createRtfHeaderFooter( docHeader , this.document, true, docHelper ) ) );
}
}
}
DocFooter docFooter = docBase.getDocFooter();
if ( docFooter != null && docFooter.isUseFooter() ) {
if ( docFooter.isBasic() ) {
HeaderFooter footer = this.createHeaderFoter( docFooter, docFooter.getAlign(), docHelper );
this.document.setFooter( footer );
} else {
if ( DOC_OUTPUT_PDF.equals( this.docType ) ) {
pdfHelper.setDocFooter( docFooter );
} else if ( DOC_OUTPUT_RTF.equals( this.docType ) ) {
this.document.setFooter( new RtfHeaderFooter( createRtfHeaderFooter( docFooter , this.document, false, docHelper ) ) );
}
}
}
if ( DOC_OUTPUT_PDF.equals( this.docType ) ) {
this.pdfWriter.setPageEvent( pdfHelper );
}
this.document.open();
Iterator itDoc = docBase.getDocBody().docElements();
handleElements(document, itDoc, docHelper);
this.document.close();
}
public static void handleElements( Document document, Iterator itDoc, ITextHelper docHelper ) throws Exception {
while ( itDoc.hasNext() ) {
DocElement docElement = (DocElement)itDoc.next();
getElement(document, docElement, true, docHelper );
}
}
public static Element getElement( Document document, DocElement docElement, boolean addElement, ITextHelper docHelper ) throws Exception {
Element result = null;
DocumentParent documentParent = new DocumentParent( document );
if ( docElement instanceof DocPhrase ) {
result = createPhrase( (DocPhrase)docElement, docHelper );
if ( addElement ) {
documentParent.add( result );
}
} else if ( docElement instanceof DocPara ) {
result = createPara( (DocPara)docElement, docHelper );
if ( addElement ) {
documentParent.add( result );
}
} else if ( docElement instanceof DocTable ) {
result = createTable( (DocTable)docElement, docHelper );
if ( addElement ) {
document.add( result );
}
} else if ( docElement instanceof DocImage ) {
result = createImage( (DocImage)docElement );
if ( addElement ) {
documentParent.add( result );
}
} else if ( docElement instanceof DocPageBreak ) {
document.newPage();
}
return result;
}
private HeaderFooter createHeaderFoter( DocHeaderFooter container, int align, ITextHelper docHelper ) throws Exception {
Iterator it = container.docElements();
Phrase phrase = new Phrase();
float leading = (float)-1.0;
while ( it.hasNext() ) {
DocElement docElement = (DocElement)it.next();
if ( docElement instanceof DocPhrase ) {
DocPhrase docPhrase = (DocPhrase) docElement;
Chunk ck = createChunk( docPhrase, docHelper );
if( docPhrase.getLeading() != null && docPhrase.getLeading().floatValue() != leading ) {
leading = docPhrase.getLeading().floatValue();
phrase.setLeading( leading );
}
phrase.add( ck );
} else if ( docElement instanceof DocPara ) {
DocPara docPara = (DocPara) docElement;
if ( docPara.getLeading() != null ) {
phrase.setLeading( docPara.getLeading().floatValue() );
}
Font f = new Font( Font.HELVETICA, docPara.getSize() );
if ( docPara.getForeColor() != null ) {
try {
f.setColor( parseHtmlColor( docPara.getForeColor() ) );
} catch (Exception fe) {
LogFacade.getLog().warn( "Error setting fore color on footer : "+docPara.getForeColor(), fe );
}
}
Chunk ck = new Chunk( docPara.getText(), f );
phrase.add( ck );
} else if ( docElement instanceof DocImage ) {
DocImage docImage = (DocImage)docElement;
Image img = createImage( docImage );
Chunk ck = new Chunk( img, 0, 0, true );
phrase.add( ck );
}
}
HeaderFooter headerFooter = new HeaderFooter( phrase, container.isNumbered() );
if ( align == DocPara.ALIGN_UNSET ) {
align = DocPara.ALIGN_CENTER;
}
headerFooter.setAlignment( getAlign( align ) );
headerFooter.setBorder( container.getBorderWidth() );
//headerFooter.setUseVariableBorders( true );
return headerFooter;
}
}
interface ParentElement {
public void add( Element element ) throws Exception;
}
class PhraseParent implements ParentElement {
private Phrase phrase;
public PhraseParent( Phrase phrase ) {
this.phrase = phrase;
}
/* (non-Javadoc)
* @see org.morozko.java.mod.doc.itext.ParentElement#add(com.lowagie.text.Element)
*/
public void add(Element element) throws Exception {
this.phrase.add( element );
}
}
class DocumentParent implements ParentElement {
private Document document;
public DocumentParent( Document document) {
this.document = document;
}
/* (non-Javadoc)
* @see org.morozko.java.mod.doc.itext.ParentElement#add(com.lowagie.text.Element)
*/
public void add(Element element) throws Exception {
this.document.add( element );
}
}
class CellParent implements ParentElement {
private Cell cell;
public CellParent( Cell cell ) {
this.cell = cell;
}
/* (non-Javadoc)
* @see org.morozko.java.mod.doc.itext.ParentElement#add(com.lowagie.text.Element)
*/
public void add(Element element) throws Exception {
this.cell.addElement( element );
}
}
| |
//========================================================================
//
//File: GraphicalEditor.java
//
//========================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//========================================================================
//
package org.xtuml.bp.ui.graphics.editor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.ToolTipHelper;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.draw2d.text.FlowPage;
import org.eclipse.draw2d.text.TextFlow;
import org.eclipse.gef.ContextMenuProvider;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.KeyHandler;
import org.eclipse.gef.MouseWheelHandler;
import org.eclipse.gef.MouseWheelZoomHandler;
import org.eclipse.gef.SnapToGrid;
import org.eclipse.gef.Tool;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gef.editparts.ZoomListener;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.palette.ConnectionCreationToolEntry;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteGroup;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.PanningSelectionToolEntry;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gef.print.PrintGraphicalViewerOperation;
import org.eclipse.gef.tools.AbstractTool;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.AlignmentAction;
import org.eclipse.gef.ui.actions.DirectEditAction;
import org.eclipse.gef.ui.actions.MatchHeightAction;
import org.eclipse.gef.ui.actions.MatchWidthAction;
import org.eclipse.gef.ui.actions.SelectAllAction;
import org.eclipse.gef.ui.actions.ZoomInAction;
import org.eclipse.gef.ui.actions.ZoomOutAction;
import org.eclipse.gef.ui.palette.FlyoutPaletteComposite;
import org.eclipse.gef.ui.palette.FlyoutPaletteComposite.FlyoutPreferences;
import org.eclipse.gef.ui.parts.DomainEventDispatcher;
import org.eclipse.gef.ui.parts.GraphicalEditorWithFlyoutPalette;
import org.eclipse.gef.ui.parts.GraphicalViewerKeyHandler;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.JFacePreferences;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.osgi.framework.Bundle;
import org.xtuml.bp.core.ActionHome_c;
import org.xtuml.bp.core.Action_c;
import org.xtuml.bp.core.Actiondialect_c;
import org.xtuml.bp.core.Attribute_c;
import org.xtuml.bp.core.BaseAttribute_c;
import org.xtuml.bp.core.Component_c;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.DerivedBaseAttribute_c;
import org.xtuml.bp.core.ModelClass_c;
import org.xtuml.bp.core.MooreActionHome_c;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.PackageableElement_c;
import org.xtuml.bp.core.StateMachineState_c;
import org.xtuml.bp.core.TransitionActionHome_c;
import org.xtuml.bp.core.Transition_c;
import org.xtuml.bp.core.common.BridgePointPreferencesStore;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.ModelRoot;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.core.common.PersistableModelComponent;
import org.xtuml.bp.core.common.PersistenceManager;
import org.xtuml.bp.core.common.Transaction;
import org.xtuml.bp.core.common.TransactionException;
import org.xtuml.bp.core.common.TransactionManager;
import org.xtuml.bp.core.ui.RenameAction;
import org.xtuml.bp.core.ui.Selection;
import org.xtuml.bp.core.util.EditorUtil;
import org.xtuml.bp.core.util.HierarchyUtil;
import org.xtuml.bp.ui.canvas.CanvasPlugin;
import org.xtuml.bp.ui.canvas.Cl_c;
import org.xtuml.bp.ui.canvas.Connector_c;
import org.xtuml.bp.ui.canvas.Diagram_c;
import org.xtuml.bp.ui.canvas.ElementSpecification_c;
import org.xtuml.bp.ui.canvas.FloatingText_c;
import org.xtuml.bp.ui.canvas.Gr_c;
import org.xtuml.bp.ui.canvas.Graphelement_c;
import org.xtuml.bp.ui.canvas.GraphicalElement_c;
import org.xtuml.bp.ui.canvas.ModelTool_c;
import org.xtuml.bp.ui.canvas.Model_c;
import org.xtuml.bp.ui.canvas.Ooaofgraphics;
import org.xtuml.bp.ui.canvas.Ooatype_c;
import org.xtuml.bp.ui.canvas.Shape_c;
import org.xtuml.bp.ui.canvas.util.GraphicsUtil;
import org.xtuml.bp.ui.graphics.Activator;
import org.xtuml.bp.ui.graphics.actions.CanvasCopyAction;
import org.xtuml.bp.ui.graphics.actions.CanvasCutAction;
import org.xtuml.bp.ui.graphics.actions.CanvasPasteAction;
import org.xtuml.bp.ui.graphics.actions.GraphicalActionConstants;
import org.xtuml.bp.ui.graphics.factories.ConnectorCreationFactory;
import org.xtuml.bp.ui.graphics.factories.ShapeCreationFactory;
import org.xtuml.bp.ui.graphics.figures.DecoratedPolylineConnection;
import org.xtuml.bp.ui.graphics.figures.ShapeImageFigure;
import org.xtuml.bp.ui.graphics.listeners.GraphicsEditorListener;
import org.xtuml.bp.ui.graphics.outline.GraphicalOutlinePage;
import org.xtuml.bp.ui.graphics.palette.GraphicsConnectionCreationToolEntry;
import org.xtuml.bp.ui.graphics.palette.GraphicsCreationToolEntry;
import org.xtuml.bp.ui.graphics.palette.ZoomToolEntry;
import org.xtuml.bp.ui.graphics.parts.GraphicalZoomManager;
import org.xtuml.bp.ui.graphics.parts.GraphicsEditPartFactory;
import org.xtuml.bp.ui.graphics.parts.GraphicsScalableFreeformEditPart;
import org.xtuml.bp.ui.graphics.parts.TextEditPart;
import org.xtuml.bp.ui.graphics.print.PrintDiagramOperation;
import org.xtuml.bp.ui.graphics.properties.GraphicsPropertySourceProvider;
import org.xtuml.bp.ui.graphics.providers.CanvasEditorContextMenuProvider;
import org.xtuml.bp.ui.graphics.selection.GraphicalSelectionManager;
import org.xtuml.bp.ui.graphics.tools.GraphicalPanningSelectionTool;
import org.xtuml.bp.ui.properties.BridgepointPropertySheetPage;
import org.xtuml.bp.ui.text.activity.ActivityEditorInput;
import org.xtuml.bp.ui.text.description.DescriptionEditorInput;
import org.xtuml.bp.ui.text.masl.MASLEditorInput;
import org.xtuml.bp.ui.text.masl.MASLPartListener;
public class GraphicalEditor extends GraphicalEditorWithFlyoutPalette implements
IPartListener, IPropertyChangeListener {
private static ArrayList<GraphicalEditor> fInstances = new ArrayList<GraphicalEditor>();
private ModelEditor fParentEditor;
public GraphicalEditor(ModelEditor parent) {
super();
fInstances.add(this);
fParentEditor = parent;
}
public ModelEditor getParentEditor() {
return fParentEditor;
}
public static GraphicalEditor getEditor(Model_c model) {
for (GraphicalEditor editor : fInstances) {
if (editor.getModel() == model)
return editor;
}
return null;
}
Model_c fModel;
private PaletteRoot fPaletteRoot;
private PaletteDrawer fToolDrawer;
private static final String OPEN = "open";
protected Action undo, redo, selectAll;
protected CanvasPasteAction paste;
protected CanvasCutAction cut;
protected CanvasCopyAction copy;
protected Action open, delete, rename;
protected Action print;
private GraphicsEditorListener fEditorListener;
private String DIAGRAM_VIEWPORT_X = "__DIAGRAM_VIEWPORT_X"; //$NON-NLS-1$
private String DIAGRAM_VIEWPORT_Y = "__DIAGRAM_VIEWPORT_Y"; //$NON-NLS-1$
private String DIAGRAM_ZOOM = "__DIAGRAM_ZOOM"; //$NON-NLS-1$
private static Font diagramFont;
private HashMap<IFigure, BPToolTipHelper> tooltipMap = new HashMap<IFigure, BPToolTipHelper>();
@Override
protected FlyoutPreferences getPalettePreferences() {
FlyoutPreferences preferences = super.getPalettePreferences();
preferences.setPaletteState(FlyoutPaletteComposite.STATE_PINNED_OPEN);
return preferences;
}
public void refreshPalette() {
fPaletteRoot = null;
getEditDomain().setPaletteRoot(getPaletteRoot());
}
@Override
protected PaletteRoot getPaletteRoot() {
if (fPaletteRoot == null || fPaletteRoot.getChildren().isEmpty()) {
if (fPaletteRoot == null)
fPaletteRoot = new PaletteRoot();
PaletteGroup controlGroup = new PaletteGroup("");
ToolEntry tool = new PanningSelectionToolEntry() {
@Override
public Tool createTool() {
Tool tool;
try {
tool = (Tool) GraphicalPanningSelectionTool.class
.newInstance();
} catch (IllegalAccessException iae) {
return null;
} catch (InstantiationException ie) {
return null;
}
tool.setProperties(getToolProperties());
return tool;
}
};
getEditDomain().setActiveTool(tool.createTool());
controlGroup.add(tool);
ToolEntry zoomToolEntry = new ZoomToolEntry(
"Zoom Tool",
"- Left click to zoom in. "
+ "\n- Hold shift and left click to zoom out. "
+ "\n- Select a group of symbols to zoom selection. "
+ "\n- Hold ctrl and left click to zoom all. "
+ "\n- Hold ctrl and use the mouse wheel to zoom in and out.",
CorePlugin.getImageDescriptor("zoomAll.gif"), CorePlugin.getImageDescriptor("zoomAll.gif"), this); //$NON-NLS-1$ $NON-NLS-2$
controlGroup.add(zoomToolEntry);
fPaletteRoot.add(controlGroup);
fPaletteRoot.setDefaultEntry(tool);
fToolDrawer = new PaletteDrawer("Default Toolset");
fPaletteRoot.add(fToolDrawer);
fillPalette(fToolDrawer);
}
return fPaletteRoot;
}
private void fillPalette(PaletteDrawer drawer) {
// have the editor's canvas create the tool objects that perform the
// tools' functionality
Model_c canvas = fModel;
if (canvas == null)
return;
canvas.Initializetools();
// for each tool employed by the canvas
ModelTool_c[] tools = ModelTool_c.getManyCT_MTLsOnR100(canvas);
ModelTool_c tool = null;
ArrayList<PaletteDrawer> createdDrawers = new ArrayList<PaletteDrawer>();
for (int i1 = 0; i1 < tools.length; i1++) {
tool = tools[i1];
// do not allow tool button if the element specification
// indicates that this element is created along with
// the canvas
final ElementSpecification_c elem = ElementSpecification_c
.getOneGD_ESOnR103(tool);
if (elem != null && !elem.getCreationrule().equals("manual")) // $NON-NLS-1$
continue;
// if there is a element-specification associated with this tool's
// function
// (because it is a shape-tool)
if (elem != null) {
boolean isPackage = false;
if (getModel().getRepresents() instanceof Package_c
|| getModel().getRepresents() instanceof Component_c) {
isPackage = true;
if (getModel().getRepresents() instanceof Component_c) {
Component_c self = (Component_c) getModel()
.getRepresents();
// If this component is under a EP_PKG then we do NOT
// want to allow specialized packages to be created in
// it.
//
//
// If the component is NOT under a EP_PKG then we do
// allow
// specialized packages, but we do NOT allow an eP_PKG
// to be
// created in the component.
Package_c pkg = Package_c
.getOneEP_PKGOnR8000(PackageableElement_c
.getOnePE_PEOnR8001(self));
Component_c comp = Component_c
.getOneC_COnR8003(PackageableElement_c
.getOnePE_PEOnR8001(self));
boolean isInGenericPackage = ((pkg != null) || (comp != null));
int toolType = tool.getOoa_type();
if (isInGenericPackage) {
switch (toolType) {
case Ooatype_c.Sequence:
case Ooatype_c.Communication:
case Ooatype_c.UseCaseDiagram:
case Ooatype_c.Activity:
continue;
default:
break;
}
} else {
switch (toolType) {
case Ooatype_c.Package:
continue;
case Ooatype_c.Interface:
continue;
case Ooatype_c.UserDataType:
continue;
default:
break;
}
}
}
}
String category = elem.getToolcategory();
ArrayList<PaletteDrawer> drawers = new ArrayList<PaletteDrawer>();
if (category.equals("") || !isPackage) {
drawers.add(drawer);
}
if (isPackage) {
String[] categories = category.split(","); // $NON-NLS-1$
for (int i = 0; i < categories.length; i++) {
String label = categories[i].trim();
if (label.equals(""))
continue;
boolean found = false;
for (PaletteDrawer created : createdDrawers) {
if (created.getLabel().equals(label)) {
found = true;
drawers.add(created);
break;
}
}
if (!found) {
PaletteDrawer newDrawer = new PaletteDrawer(label);
newDrawer
.setInitialState(PaletteDrawer.INITIAL_STATE_CLOSED);
fPaletteRoot.add(newDrawer);
createdDrawers.add(newDrawer);
drawers.add(newDrawer);
}
}
}
if (elem.getSymboltype().equals("shape")) {
for (PaletteDrawer group : drawers) {
GraphicsCreationToolEntry entry = new GraphicsCreationToolEntry(
elem.getName(), "New " + elem.getName(),
new ShapeCreationFactory(),
CorePlugin.getImageDescriptor(elem
.getIconname()),
CorePlugin.getImageDescriptor(elem
.getIconname()), tool.getOoa_type());
entry.setSmallIcon(CorePlugin.getImageDescriptor(elem
.getIconname()));
entry.setLargeIcon(CorePlugin.getImageDescriptor(elem
.getIconname()));
group.add(entry);
}
} else if (elem.getSymboltype().equals("connector")) {
for (PaletteDrawer group : drawers) {
ConnectionCreationToolEntry entry = new GraphicsConnectionCreationToolEntry(
elem.getName(), "New " + elem.getName(),
new ConnectorCreationFactory(),
CorePlugin.getImageDescriptor(elem
.getIconname()),
CorePlugin.getImageDescriptor(elem
.getIconname()), tool.getOoa_type());
entry.setSmallIcon(CorePlugin.getImageDescriptor(elem
.getIconname()));
entry.setLargeIcon(CorePlugin.getImageDescriptor(elem
.getIconname()));
group.add(entry);
}
}
}
}
}
@SuppressWarnings("unchecked")
public Object getAdapter(Class adapter) {
if (adapter.equals(IContentOutlinePage.class)) {
return getContentOutline();
}
if (adapter.equals(IPropertySheetPage.class)) {
return getPropertySheet();
}
if (adapter.equals(ZoomManager.class)) {
return (ZoomManager) getGraphicalViewer().getProperty(
ZoomManager.class.toString());
}
return super.getAdapter(adapter);
}
private Object getPropertySheet() {
PropertySheetPage pss = new BridgepointPropertySheetPage();
pss.setPropertySourceProvider(new GraphicsPropertySourceProvider());
return pss;
}
private Object getContentOutline() {
return new GraphicalOutlinePage(getGraphicalViewer(), this);
}
@Override
public void doSave(IProgressMonitor monitor) {
// autosaved, nothing to do here
}
@Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
if (input instanceof GraphicalEditorInput) {
GraphicalEditorInput canvasInput = (GraphicalEditorInput) input;
fModel = canvasInput.getInput();
fEditorListener = new GraphicsEditorListener(this);
CanvasPlugin.setGraphicalRepresents(fModel);
Ooaofooa.getDefaultInstance().addModelChangeListener(
fEditorListener);
Ooaofgraphics.getDefaultInstance().addModelChangeListener(
fEditorListener);
site.getPage().addPartListener(this);
getTransactionManager().addTransactionListener(fEditorListener);
setName(canvasInput.getName());
setEditDomain(new GraphicalEditDomain(this, fModel.getRepresents()));
Gr_c.cur_model = fModel;
super.init(site, input);
} else if (input instanceof FileEditorInput) {
PersistableModelComponent pmc = PersistenceManager
.findOrCreateComponent(((FileEditorInput) input).getFile()
.getFullPath());
if (pmc != null) {
if (!pmc.isLoaded()) {
try {
pmc.load(new NullProgressMonitor());
} catch (CoreException e) {
PartInitException pie = new PartInitException(
CorePlugin.createImportErrorStatus(true,
"Error loading model element"));
pie.fillInStackTrace();
throw pie;
}
}
GraphicalEditorInput cei = GraphicalEditorInput
.createInstance(pmc.getRootModelElement());
init(site, cei);
}
} else if(input instanceof SimpleGraphicalEditorInput) {
SimpleGraphicalEditorInput sgei = (SimpleGraphicalEditorInput) input;
fModel = sgei.getModel();
fEditorListener = new GraphicsEditorListener(this);
Ooaofgraphics.getDefaultInstance().addModelChangeListener(fEditorListener);
site.getPage().addPartListener(this);
setName(sgei.getName());
setEditDomain(new GraphicalEditDomain(this, fModel.getRepresents()));
Gr_c.cur_model = fModel;
super.init(site, input);
}
}
public Control getCanvas() {
if (getGraphicalViewer() == null)
return null;
return getGraphicalControl();
}
public void setName(String name) {
setPartName(name);
}
@Override
public String getTitleToolTip() {
Object element = getModel().getRepresents();
if ( element == null)
return "";
if (!(element instanceof NonRootModelElement))
return getPartName();
return HierarchyUtil.Getpath(element);
}
public void setEditorInput(IEditorInput input) {
setInput(input);
}
@Override
public boolean isDirty() {
// for now all BP diagrams are auto-persisted
return false;
}
@Override
protected void configureGraphicalViewer() {
super.configureGraphicalViewer();
GraphicalViewer viewer = getGraphicalViewer();
Gr_c.cur_canvas = (Canvas) getCanvas();
viewer.setRootEditPart(new GraphicsScalableFreeformEditPart());
// Zoom
GraphicalZoomManager manager = (GraphicalZoomManager) getGraphicalViewer()
.getProperty(ZoomManager.class.toString());
if (manager != null) {
manager.setModel(getModel());
manager.addZoomListener(new ZoomListener() {
@Override
public void zoomChanged(double zoom) {
storeZoomValue(zoom);
}
});
List<String> zoomLevels = new ArrayList<String>(3);
zoomLevels.add(ZoomManager.FIT_ALL);
zoomLevels.add(ZoomManager.FIT_WIDTH);
zoomLevels.add(ZoomManager.FIT_HEIGHT);
zoomLevels.add(GraphicalZoomManager.FIT_SELECTION);
manager.setZoomLevelContributions(zoomLevels);
manager.setZoomLevels(new double[] { .10, .20, .25, .50, .75, 1.00,
1.25, 1.50, 1.75, 2.00, 2.25, 2.50, 3.00, 3.50, 4.00 });
double zoom = getZoom();
if (zoom != -1) {
manager.configureZoomAtStartup(zoom);
}
}
// Actions
IAction zoomIn = new ZoomInAction(manager);
IAction zoomOut = new ZoomOutAction(manager);
getActionRegistry().registerAction(zoomIn);
getActionRegistry().registerAction(zoomOut);
// Scroll-wheel Zoom
getGraphicalViewer().setProperty(
MouseWheelHandler.KeyGenerator.getKey(SWT.MOD1),
MouseWheelZoomHandler.SINGLETON);
viewer.setEditPartFactory(new GraphicsEditPartFactory());
viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)
.setParent(getCommonKeyHandler()));
ContextMenuProvider cmProvider = new CanvasEditorContextMenuProvider(
viewer, this);
viewer.setContextMenu(cmProvider);
getSite().registerContextMenu(cmProvider, viewer);
viewer.setSelectionManager(new GraphicalSelectionManager());
}
@Override
protected void createGraphicalViewer(Composite parent) {
// if the diagram to be opened has no elements, or
// in the case of a component diagram only one then
// we initialize the scroll and zoom values to defaults
GraphicalElement_c[] children = GraphicalElement_c
.getManyGD_GEsOnR1(fModel);
if (children.length == 0
|| (children.length == 1 && fModel.Hascontainersymbol())) {
storeZoomValue(1.0);
setViewportLocationInStorage(4000, 3000);
}
GraphicalViewer viewer = new ScrollingGraphicalViewer() {
@Override
public void reveal(EditPart part) {
// do not support reveal at this time
// as the only time it is used is during
// selection of a graphical element when
// it is not completely visible
// We at this time do not believe that this
// is a "good feature"
}
/*
* override setEditDomain where the event dispatcher object is
* created in order to use BridgePoint custom tooltip helper
*/
@Override
public void setEditDomain(EditDomain domain){
super.setEditDomain(domain);
getLightweightSystem().setEventDispatcher(new DomainEventDispatcher(domain, this){
// Override the creation of ToolTip helper object
BPToolTipHelper defaultHelper;
@Override
protected ToolTipHelper getToolTipHelper() {
/*
* Create new helper each time to support multi tool tip
* window. In order to associate their tooltip helper
* with their editor to hide when the editor is not
* visible, reshow when it is visible, a hash map
* shall be created to store created helper, to be
* notified by editor visiblity change
*/
IFigure hoverSource = this.getCursorTarget();
if(hoverSource instanceof TextFlow) {
hoverSource = hoverSource.getParent();
}
if(hoverSource instanceof FlowPage) {
hoverSource = hoverSource.getParent();
}
if (hoverSource instanceof ShapeImageFigure || hoverSource instanceof DecoratedPolylineConnection){
BPToolTipHelper existedHelper = tooltipMap.get(hoverSource);
if ( existedHelper != null)
return existedHelper;
BPToolTipHelper newHelper = new BPToolTipHelper(control);
tooltipMap.put(hoverSource,newHelper);
return newHelper;
}
if (defaultHelper == null)
defaultHelper = new BPToolTipHelper(control);
// Notify all editor helpers to close their simple tooltip if up
Collection<BPToolTipHelper> helpers = tooltipMap.values();
for (BPToolTipHelper helper : helpers) {
helper.hideSimpleToolTip();
}
return defaultHelper;
}
});
}
};
viewer.createControl(parent);
setGraphicalViewer(viewer);
configureGraphicalViewer();
hookGraphicalViewer();
initializeGraphicalViewer();
((FigureCanvas) getCanvas()).getVerticalBar().addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
storeViewportLocation();
}
});
((FigureCanvas) getCanvas()).getHorizontalBar().addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
storeViewportLocation();
}
});
// add a control listener to zoom fit once resized
((FigureCanvas) getCanvas()).addControlListener(new ControlListener() {
@Override
public void controlResized(ControlEvent e) {
if (shouldZoomFit()
&& ((FigureCanvas) getCanvas()).getViewport()
.getHorizontalRangeModel().getExtent() > 100) {
((FigureCanvas) getCanvas()).getViewport().revalidate();
((FigureCanvas) getCanvas()).getViewport()
.getUpdateManager().performUpdate();
zoomAll();
}
}
@Override
public void controlMoved(ControlEvent e) {
// do nothing
}
});
((FigureCanvas) getCanvas()).setFont(getFont());
getCanvas().addFocusListener(new FocusListener() {
public void focusGained(FocusEvent ev) {
EditorUtil.refreshEditorTab();
}
public void focusLost(FocusEvent ev) { /* do nothing */ }
});
}
protected boolean shouldZoomFit() {
if (getZoom() == -1) {
return true;
}
return false;
}
protected Diagram_c getDiagram() {
Diagram_c diagram = Diagram_c.getOneDIM_DIAOnR18(getModel());
return diagram;
}
public double getZoom() {
double zoom = -1;
try {
zoom = Activator.getDefault().getDialogSettings().getDouble(
getZoomKey());
} catch (NumberFormatException e) {
// value was never set or was set incorrectly
// do not worry about logging an error just return
// a non set value
return -1;
}
return zoom;
}
@Override
protected void initializeGraphicalViewer() {
super.initializeGraphicalViewer();
if (fModel != null) {
getGraphicalViewer().setContents(fModel);
}
configureGridOptions();
// add self to font property change listener list
JFaceResources.getFontRegistry().addListener(this);
}
public void configureGridOptions() {
boolean showGrid = CorePlugin.getDefault().getPreferenceStore()
.getBoolean(BridgePointPreferencesStore.SHOW_GRID);
getGraphicalViewer().setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE,
new Boolean(showGrid));
boolean snapGrid = CorePlugin.getDefault().getPreferenceStore()
.getBoolean(BridgePointPreferencesStore.SNAP_TO_GRID);
getGraphicalViewer().setProperty(SnapToGrid.PROPERTY_GRID_ENABLED,
new Boolean(snapGrid));
int gridSpacing = CorePlugin.getDefault().getPreferenceStore().getInt(
BridgePointPreferencesStore.GRID_SPACING);
getGraphicalViewer().setProperty(SnapToGrid.PROPERTY_GRID_SPACING,
new Dimension(gridSpacing, gridSpacing));
}
private KeyHandler getCommonKeyHandler() {
return null;
}
public IAction getOpenAction() {
return open;
}
public IAction getUndoAction() {
return undo;
}
public IAction getRedoAction() {
return redo;
}
public CanvasCutAction getCutAction() {
return cut;
}
public CanvasCopyAction getCopyAction() {
return copy;
}
public CanvasPasteAction getPasteAction() {
return paste;
}
public IAction getSelectAllAction() {
return selectAll;
}
public IAction getDeleteAction() {
return delete;
}
public IAction getRenameAction() {
return rename;
}
@SuppressWarnings("unchecked")
@Override
protected void createActions() {
super.createActions();
// 'New' is provided as a sub-menu only. See 'createMenus'
open = new Action(OPEN) {
public void run() {
handleOpen(null, fModel,
(IStructuredSelection) getGraphicalViewer()
.getSelectionManager().getSelection());
}
};
open.setText("Open");
open.setToolTipText("Open this model Element");
// 'Open With' is provided as a sub-menu only. See 'createMenus'
cut = new CanvasCutAction(this);
cut.setId(ActionFactory.CUT.getId());
copy = new CanvasCopyAction(this);
copy.setId(ActionFactory.COPY.getId());
getActionRegistry().registerAction(copy);
getActionRegistry().registerAction(cut);
// line
paste = new CanvasPasteAction(this);
paste.setId(ActionFactory.PASTE.getId());
getActionRegistry().registerAction(paste);
TransactionManager manager = getTransactionManager();
undo = manager.getUndoAction();
undo.setId(ActionFactory.UNDO.getId());
redo = manager.getRedoAction();
redo.setId(ActionFactory.REDO.getId());
getActionRegistry().registerAction(undo);
getActionRegistry().registerAction(redo);
selectAll = new SelectAllAction(this) {
@Override
public void run() {
GraphicalViewer viewer = (GraphicalViewer) getAdapter(GraphicalViewer.class);
if (viewer != null) {
viewer
.setSelection(new StructuredSelection(filterOutTextEditParts(
getAllSymbols(getGraphicalViewer(), fModel
.Hascontainersymbol()))));
}
}
private List<GraphicalEditPart> filterOutTextEditParts(
List<GraphicalEditPart> allSymbols) {
List<GraphicalEditPart> filtered = new ArrayList<GraphicalEditPart>();
for(GraphicalEditPart part : allSymbols) {
// we filter text edit parts as they are not really selectable,
// which in-turn causes duplicates in the selection list as they
// are migrated to their owning part
if(!(part instanceof TextEditPart)) {
filtered.add(part);
}
}
return filtered;
}
};
selectAll.setId(ActionFactory.SELECT_ALL.getId());
getActionRegistry().registerAction(selectAll);
//
// Delete and Rename are retargetable actions defined by core.
//
delete = new Action() {
public void run() {
Transaction transaction = null;
TransactionManager manager = getTransactionManager();
try {
transaction = manager.startTransaction(
Transaction.DELETE_TRANS, new ModelRoot[] {
Ooaofooa.getDefaultInstance(),
Ooaofgraphics.getDefaultInstance() });
IStructuredSelection structuredSelection = Selection
.getInstance().getStructuredSelection();
Iterator<?> iterator = structuredSelection.iterator();
while (iterator.hasNext()) {
NonRootModelElement element = (NonRootModelElement) iterator
.next();
if (element instanceof GraphicalElement_c) {
((GraphicalElement_c) element).Dispose();
Selection.getInstance()
.removeFromSelection(element);
}
}
if (!Selection.getInstance().getStructuredSelection()
.isEmpty()) {
CorePlugin.getDeleteAction().run();
}
manager.endTransaction(transaction);
} catch (TransactionException e) {
if (transaction != null && manager != null
&& manager.getActiveTransaction() == transaction)
manager.cancelTransaction(transaction);
CorePlugin.logError("Unable to start transaction", e);
}
for (Object part : getGraphicalViewer().getSelectedEditParts()) {
if (part instanceof EditPart) {
if(((EditPart) part).getParent() != null) {
((EditPart) part).getParent().refresh();
}
}
}
}
@Override
public boolean isEnabled() {
return CanvasEditorContextMenuProvider
.enableDelete((IStructuredSelection) getSite()
.getSelectionProvider().getSelection());
}
};
delete.setText("Delete");
delete.setToolTipText("Delete the Model Element");
delete.setId(ActionFactory.DELETE.getId());
getActionRegistry().registerAction(delete);
// rename = CorePlugin.getRenameAction(treeViewer); <- need to
// generalize renameAction first
rename = new Action() {
public void run() {
Object selection = Selection.getInstance().getStructuredSelection()
.getFirstElement();
if (selection != null) {
String oldName = Cl_c.Getname(selection);
Shell sh = getSite().getShell();
RenameAction.handleRename(selection, oldName, sh);
}
}
@Override
public boolean isEnabled() {
if(CanvasCutAction.selectionContainsOnlyCoreElements()) {
return RenameAction.canRenameAction();
}
return false;
}
};
rename.setText("Rename");
rename.setToolTipText("Rename the Model Element");
rename.setEnabled(true); // Retargetable Actions work removes this line
rename.setId(ActionFactory.RENAME.getId());
getActionRegistry().registerAction(rename);
print = new Action() {
public void run() {
handlePrint();
}
};
print.setText("Print");
print.setToolTipText("Print the Diagram");
print.setEnabled(true);
print.setId(ActionFactory.PRINT.getId());
getActionRegistry().registerAction(print);
ActionRegistry registry = getActionRegistry();
IAction action;
action = new Action() {
@Override
public void run() {
zoomAll();
}
};
action.setText("Zoom Page");
action.setImageDescriptor(CorePlugin.getImageDescriptor("zoomAll.gif")); // $NON-NLS-1$
action.setId(GraphicalActionConstants.ZOOM_PAGE);
action.setToolTipText("Click to zoom the entire contents");
registry.registerAction(action);
action = new Action() {
@Override
public void run() {
zoomSelected();
}
};
action.setText("Zoom Selection");
action.setImageDescriptor(CorePlugin.getImageDescriptor("zoomSel.gif")); // $NON-NLS-1$
action.setId(GraphicalActionConstants.ZOOM_SEL);
action.setToolTipText("Click to zoom the current selection");
registry.registerAction(action);
action = new MatchWidthAction(this);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new MatchHeightAction(this);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new DirectEditAction((IWorkbenchPart) this);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.LEFT);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.RIGHT);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.TOP);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.BOTTOM);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.CENTER);
registry.registerAction(action);
getSelectionActions().add(action.getId());
action = new AlignmentAction((IWorkbenchPart) this,
PositionConstants.MIDDLE);
registry.registerAction(action);
getSelectionActions().add(action.getId());
}
public TransactionManager getTransactionManager() {
return fModel.getTransactionManager();
}
protected void handlePrint() {
int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell().getStyle();
Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT
: SWT.NONE);
PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
PrinterData data = dialog.open();
if (data != null) {
PrintGraphicalViewerOperation operation = new PrintDiagramOperation(
new Printer(data), getGraphicalViewer(), this);
operation.setPrintMode(PrintGraphicalViewerOperation.FIT_PAGE);
operation.run("Print canvas.");
}
}
/**
* Fire up an editor
*/
public static void handleOpen(Point location, Model_c model,
IStructuredSelection selection) {
if (!selection.isEmpty()) {
Object current = selection.iterator().next();
if (current instanceof EditPart) {
current = ((EditPart) current).getModel();
if (current instanceof FloatingText_c) {
FloatingText_c text = (FloatingText_c) current;
Connector_c connector = Connector_c.getOneGD_CONOnR8(text);
if (connector != null)
current = connector;
Shape_c shape = Shape_c.getOneGD_SHPOnR27(text);
if (shape != null)
current = shape;
}
if (current instanceof Model_c) {
current = ((Model_c) current).getRepresents();
} else if (current instanceof Shape_c) {
GraphicalElement_c elem = GraphicalElement_c
.getOneGD_GEOnR2((Shape_c) current);
current = elem.getRepresents();
} else if (current instanceof Connector_c) {
GraphicalElement_c elem = GraphicalElement_c
.getOneGD_GEOnR2((Connector_c) current);
current = elem.getRepresents();
}
}
// if a mouse event was given, and the selected element is a
// model-class
if (location != null && current instanceof ModelClass_c) {
// find the graphical element that represents the selected
// model-class
final Object finalCurrent = current;
GraphicalElement_c element = GraphicalElement_c
.GraphicalElementInstance(model.getModelRoot(),
new ClassQueryInterface_c() {
public boolean evaluate(Object candidate) {
return ((GraphicalElement_c) candidate)
.getRepresents() == finalCurrent;
}
});
// ask the shape associated with the above graphical-element
// what
// the mouse-event represents a double-click on, since the shape
// may be displaying an icon which is a link to a different
// model
// element
Shape_c shape = Shape_c.getOneGD_SHPOnR2(element);
Graphelement_c graphElement = Graphelement_c
.getOneDIM_GEOnR23(element);
current = shape.Getrepresents((int) (location.x - graphElement
.getPositionx()), (int) (location.y - graphElement
.getPositiony()));
}
// see if the current element should open
// something other than itself
current = EditorUtil.getElementToEdit(current);
String name = current.getClass().getName();
//
// Get the registry
//
IExtensionRegistry reg = Platform.getExtensionRegistry();
//
// Get all the plugins that have extended this point
//
IExtensionPoint extPt = reg
.getExtensionPoint("org.xtuml.bp.core.editors"); //$NON-NLS-1$
IExtension[] exts = extPt.getExtensions();
// Repeat for each extension until we find a default editor
for (int i = 0; i < exts.length; i++) {
IConfigurationElement[] elems = exts[i]
.getConfigurationElements();
for (int j = 0; j < elems.length; j++) {
// Find the editor elements
if (elems[j].getName().equals("editor")) { //$NON-NLS-1$
IConfigurationElement[] edElems = elems[j]
.getChildren();
for (int k = 0; k < edElems.length; k++) {
//
// Is this editor the default for the current model
// element ?
//
if (edElems[k].getName().equals("defaultFor") && //$NON-NLS-1$
edElems[k].getAttribute("class").equals(
name)) {
try {
//
// Get the class supplied for the input
//
// always use this bundle, other graphical
// plug-ins
// will provide their own open method
Bundle bundle = Platform.getBundle(elems[j]
.getContributor().getName());
Class<?> inputClass = bundle
.loadClass(elems[j]
.getAttribute("input")); //$NON-NLS-1$
String editorId = elems[j].getAttribute("class"); //$NON-NLS-1$
int dialect = -1;
if (editorId.equals(ActivityEditorInput.EDITOR_ID)) {
// see if the current element should open
// something other than itself
Object dialectObj = current;
if (dialectObj instanceof StateMachineState_c) {
StateMachineState_c state = (StateMachineState_c) dialectObj;
Action_c action = Action_c.getOneSM_ACTOnR514(ActionHome_c
.getOneSM_AHOnR513((MooreActionHome_c.getOneSM_MOAHOnR511(state))));
if (action != null) {
dialectObj = action;
}
}
else if (dialectObj instanceof Transition_c) {
Action_c action = Action_c.getOneSM_ACTOnR514(ActionHome_c.getOneSM_AHOnR513(
TransitionActionHome_c.getOneSM_TAHOnR530((Transition_c)dialectObj)));
if (action != null) {
dialectObj = action;
}
}
else if ( dialectObj instanceof Attribute_c ) {
DerivedBaseAttribute_c dbattr = DerivedBaseAttribute_c.getOneO_DBATTROnR107(
BaseAttribute_c.getOneO_BATTROnR106((Attribute_c)dialectObj));
if ( dbattr != null ) {
dialectObj = dbattr;
}
}
// Get the value of the dialect attribute
try {
Method getDialectMethod = dialectObj.getClass().getMethod("getDialect"); //$NON-NLS-1$
dialect = (Integer) getDialectMethod.invoke(dialectObj);
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
} catch (SecurityException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (IllegalArgumentException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
} catch (ExceptionInInitializerError e) {
System.out.println(e);
}
// If the "dialect" attribute is neither "oal" nor "masl",
// check the default language preference. Set "dialect" to
// be the preference value and open the proper editor.
if ( dialect != Actiondialect_c.masl && dialect != Actiondialect_c.oal && dialect != Actiondialect_c.none ) {
IPreferenceStore store = CorePlugin.getDefault().getPreferenceStore();
dialect = store
.getInt(BridgePointPreferencesStore.DEFAULT_ACTION_LANGUAGE_DIALECT);
try {
Method setDialectMethod = dialectObj.getClass().getMethod("setDialect", //$NON-NLS-1$
int.class);
setDialectMethod.invoke(dialectObj, dialect);
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
} catch (SecurityException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (IllegalArgumentException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
} catch (ExceptionInInitializerError e) {
System.out.println(e);
}
}
}
// check to see if we need to open the MASL editor
if (MASLEditorInput.isSupported(current) && dialect == Actiondialect_c.masl) { //$NON-NLS-1$
inputClass = bundle.loadClass("org.xtuml.bp.ui.text.masl.MASLEditorInput"); //$NON-NLS-1$
try {
editorId = (String) inputClass.getField("EDITOR_ID").get(null); //$NON-NLS-1$
} catch (NoSuchFieldException e) {
System.out.println(e);
}
}
// check to see if the dialect is "None" and this element has a description field
if (dialect == Actiondialect_c.none) {
if (DescriptionEditorInput.isSupported(current)) {
inputClass = bundle.loadClass("org.xtuml.bp.ui.text.description.DescriptionEditorInput"); //$$NON-NLS-1$$
try {
editorId = (String) inputClass.getField("EDITOR_ID").get(null); //$$NON-NLS-1$$
} catch (NoSuchFieldException e) {
System.out.println(e);
}
} else {
inputClass = null;
}
}
if ( inputClass != null ) {
Class<?>[] type = new Class[1];
type[0] = Object.class;
//
// Dynamically get the method
// createInstance, the supplied class must
// implement this
//
Method createInstance = inputClass
.getMethod("createInstance", type); //$NON-NLS-1$
Object[] args = new Object[1];
args[0] = current;
//
// Invoke the method.
// The method is static; no instance is
// needed, so first argument is null
//
IEditorInput input = (IEditorInput) createInstance
.invoke(null, args);
//
// pass the input to the Eclipse editor,
// along with the class name supplied by
// the extending plugin.
//
if (input != null) {
IWorkbenchPage page = (IWorkbenchPage) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
if (MASLEditorInput.EDITOR_ID == editorId) {
page.addPartListener((IPartListener2) new MASLPartListener());
}
page.openEditor(input, editorId);
}
}
return;
} catch (ClassNotFoundException e) {
CanvasPlugin.logError(
"Input Class not found", e); //$NON-NLS-1$
} catch (NoSuchMethodException e) {
CanvasPlugin
.logError(
"Class does not implement static method createInstance", e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
CanvasPlugin
.logError(
"Exception occured on invocation of static method createInstance of the Target", e.getTargetException()); //$NON-NLS-1$
} catch (IllegalAccessException e) {
CanvasPlugin
.logError(
"Target does not support static method createInstance", e); //$NON-NLS-1$
} catch (PartInitException e) {
CanvasPlugin.logError(
"Could not activate Editor", e); //$NON-NLS-1$
}
}
}
}
}
}
}
}
public Model_c getModel() {
return fModel;
}
public void refresh() {
// in case a refresh occurs where we may have changed
// our Model_c instance like a file refresh update are
// cache here
Model_c inmemoryModel = (Model_c) Ooaofgraphics.getDefaultInstance().getInstanceList(Model_c.class)
.get(getModel().getDiagramid());
if(inmemoryModel != null && inmemoryModel != getModel()) {
setModel(inmemoryModel);
}
// this refresh will update contents, but
// not visually refresh children
if (getGraphicalViewer() != null
&& getGraphicalViewer().getContents() != null) {
getGraphicalViewer().getContents().refresh();
for (Object child : getGraphicalViewer().getContents()
.getChildren()) {
EditPart part = (EditPart) child;
part.refresh();
}
}
refreshPartName();
}
public void refreshPartName() {
if (fModel != null && fModel.getRepresents() instanceof NonRootModelElement) {
setName(GraphicsUtil
.getCanvasEditorTitle((NonRootModelElement) fModel
.getRepresents()));
}
}
@Override
public void dispose() {
getEditorSite().getPage().removePartListener(this);
super.dispose();
Ooaofooa.getDefaultInstance()
.removeModelChangeListener(fEditorListener);
Ooaofgraphics.getDefaultInstance().removeModelChangeListener(
fEditorListener);
if (getTransactionManager() != null)
getTransactionManager().removeTransactionListener(fEditorListener);
fInstances.remove(this);
if(fInstances.isEmpty()) {
// if we are the last diagram editor, then dispose
// the font used
if (diagramFont != null
&& diagramFont != PlatformUI.getWorkbench().getDisplay()
.getSystemFont()) {
diagramFont.dispose();
diagramFont = null;
}
}
Collection<BPToolTipHelper> helpers = tooltipMap.values();
for (BPToolTipHelper helper : helpers) {
helper.dispose();
}
JFaceResources.getFontRegistry().removeListener(this);
}
public static Font getFont() {
if(diagramFont == null || diagramFont.isDisposed()) {
String prefFont = JFacePreferences.getPreferenceStore().getString(
"org.xtuml.bp.canvas.font");//$NON-NLS-1$
if(prefFont == null || prefFont.equals("")) {
// something strange has happened, should not occur
// but to be safe set a default
diagramFont = PlatformUI.getWorkbench().getDisplay()
.getSystemFont();
} else {
prefFont = prefFont.substring(0, prefFont.indexOf(';'));
FontData prefFontData = new FontData(prefFont);
int fontSize = (int) (prefFontData.getHeight());
prefFontData.setHeight(fontSize);
diagramFont = new Font(PlatformUI.getWorkbench().getDisplay(), prefFontData);
}
}
return diagramFont;
}
public static void setFont(Font font) {
diagramFont = font;
}
@Override
public void partActivated(IWorkbenchPart part) {
if (part == this || part == getParentEditor()) {
// when activated, synchronize the graphical selection
// with the core selection
((GraphicalSelectionManager) getGraphicalViewer()
.getSelectionManager()).synchronizeSelectionToCore();
// additionally reset the current canvas variable
// in the Gr_c class
Gr_c.cur_canvas = (Canvas) getCanvas();
// Notify all editor tooltip helpers to redisplay the tooltip if
// possible
Collection<BPToolTipHelper> helpers = tooltipMap.values();
for (BPToolTipHelper helper : helpers) {
helper.activate();
}
}
}
@Override
public void partBroughtToTop(IWorkbenchPart part) {
// do nothing
}
@Override
public void partClosed(IWorkbenchPart part) {
// do nothing
}
@Override
public void partDeactivated(IWorkbenchPart part) {
// Notify all editor tooltip helpers to hide the tooltips if
// visible
Collection<BPToolTipHelper> helpers = tooltipMap.values();
if (part == this || part == getParentEditor()) {
for (BPToolTipHelper helper : helpers) {
helper.deactivate();
}
}
}
@Override
public void partOpened(IWorkbenchPart part) {
// do nothing
}
public static void redrawAll() {
IEditorReference[] editorReferences = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if (editor instanceof ModelEditor) {
GraphicalEditor gEditor = ((ModelEditor) editor)
.getGraphicalEditor();
gEditor.redraw();
}
}
}
private void redraw() {
((GraphicalEditPart) getGraphicalViewer().getRootEditPart())
.getFigure().erase();
((GraphicalEditPart) getGraphicalViewer().getRootEditPart())
.getFigure().getUpdateManager().performUpdate();
}
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
// If not the active editor, ignore selection changed.
if (this.equals(getSite().getPage().getActiveEditor()))
updateActions(getSelectionActions());
else if (getSite().getPage().getActiveEditor() instanceof ModelEditor) {
ModelEditor editor = (ModelEditor) getSite().getPage()
.getActiveEditor();
if (this.equals(editor.getActivePart())) {
updateActions(getSelectionActions());
}
}
}
public AbstractTool getTool(String toolSet, String toolName) {
for (Object entry : fPaletteRoot.getChildren()) {
if (entry instanceof PaletteDrawer) {
PaletteDrawer drawer = (PaletteDrawer) entry;
if (drawer.getLabel().equals(toolSet)) {
AbstractTool tool = getTool(toolName, drawer.getChildren());
if (tool != null)
return tool;
}
}
}
return null;
}
public void setModel(Model_c model) {
fModel = model;
}
public AbstractTool getTool(String toolName) {
return getTool(toolName, fPaletteRoot.getChildren());
}
public AbstractTool getTool(String toolName, List<?> children) {
for (Object entry : children) {
if (entry instanceof PaletteDrawer) {
PaletteDrawer drawer = (PaletteDrawer) entry;
AbstractTool tool = getTool(toolName, drawer.getChildren());
if (tool != null)
return tool;
} else {
if (entry instanceof ToolEntry) {
ToolEntry pEntry = (ToolEntry) entry;
if (pEntry.getLabel().equals(toolName)) {
return (AbstractTool) pEntry.createTool();
}
}
}
}
return null;
}
public void doDelete() {
getDeleteAction().run();
}
public void zoomAll() {
ZoomManager manager = (ZoomManager) getAdapter(ZoomManager.class);
manager.setZoomAsText(ZoomManager.FIT_ALL);
}
public void zoomOut() {
ZoomManager manager = (ZoomManager) getAdapter(ZoomManager.class);
manager.zoomOut();
}
public void zoomSelected() {
GraphicalZoomManager manager = (GraphicalZoomManager) getAdapter(ZoomManager.class);
manager.setZoomAsText(GraphicalZoomManager.FIT_SELECTION);
}
public DefaultEditDomain getDomain() {
return super.getEditDomain();
}
public void updateModel(Model_c newModel) {
newModel.Initializetools();
GraphicalViewer viewer = (GraphicalViewer) getAdapter(GraphicalViewer.class);
setModel(newModel);
Gr_c.cur_model = newModel;
GraphicalZoomManager zoomManager = (GraphicalZoomManager) getAdapter(ZoomManager.class);
zoomManager.setModel(newModel);
viewer.setContents(newModel);
GraphicalEditDomain domain = (GraphicalEditDomain) getEditDomain();
domain.setElement(newModel.getRepresents());
}
@SuppressWarnings("unchecked")
public static List<GraphicalEditPart> getAllSymbols(GraphicalViewer root,
boolean modelHasContainer) {
List<GraphicalEditPart> symbols = new ArrayList<GraphicalEditPart>();
symbols.addAll(root.getContents().getChildren());
if (modelHasContainer) {
symbols.addAll(((GraphicalEditPart) root.getContents()
.getChildren().get(0)).getChildren());
}
ArrayList<GraphicalEditPart> shapeText = new ArrayList<GraphicalEditPart>();
ArrayList<GraphicalEditPart> allConnections = new ArrayList<GraphicalEditPart>();
for (GraphicalEditPart child : symbols) {
AbstractGraphicalEditPart childPart = (AbstractGraphicalEditPart) child;
allConnections.addAll(childPart.getSourceConnections());
shapeText.addAll(child.getChildren());
}
symbols.addAll(shapeText);
// add connections that start on connections
for (Object child : allConnections) {
AbstractGraphicalEditPart childPart = (AbstractGraphicalEditPart) child;
symbols.addAll(childPart.getSourceConnections());
// add all text for the source connections
for(Object sourceCon : childPart.getSourceConnections()) {
AbstractGraphicalEditPart source = (AbstractGraphicalEditPart) sourceCon;
symbols.addAll(source.getChildren());
}
// add all text for this connector
symbols.addAll(childPart.getChildren());
}
// add any free floating connectors
allConnections.addAll(((GraphicalEditPart) root.getRootEditPart()
.getContents()).getSourceConnections());
for(Object child : ((GraphicalEditPart) root.getRootEditPart()
.getContents()).getSourceConnections()) {
AbstractGraphicalEditPart childPart = (AbstractGraphicalEditPart) child;
// add all text for the free floating connectors;
allConnections.addAll(childPart.getChildren());
}
symbols.addAll(allConnections);
// filter out all hidden elements
List<GraphicalEditPart> filteredList = new ArrayList<GraphicalEditPart>();
for(GraphicalEditPart part : symbols) {
if (part.getFigure().getParent().isVisible()) {
filteredList.add(part);
}
}
return filteredList;
}
/**
* Generates an {@link Image} of the contents of this editor.
*
* @param fitRectangle
* @return
*/
public Image getDiagramImage(Rectangle fitRectangle) {
if (fitRectangle == null)
fitRectangle = GraphicalZoomManager
.getExtentRectangle(getAllSymbols(getGraphicalViewer(),
getModel().Hascontainersymbol()));
Image image = new Image(Display.getDefault(), fitRectangle.width,
fitRectangle.height);
PrintDiagramOperation.printImage(image, getGraphicalViewer(),
fitRectangle, getModel().Hascontainersymbol(),
PrintDiagramOperation.FIT_PAGE);
return image;
}
public GraphicalViewer getGraphicalViewer() {
return super.getGraphicalViewer();
}
public Point getPersistedViewportLocation() {
IDialogSettings dialogSettings = Activator.getDefault()
.getDialogSettings();
try {
float viewportX = dialogSettings.getInt(getViewportXValueKey());
float viewportY = dialogSettings.getInt(getViewportYValueKey());
return new Point(viewportX, viewportY);
} catch (NumberFormatException e) {
// value was never set or was incorrectly
// set, do not worry about logging an error
// just return a default value
return new Point(-1, -1);
}
}
private void storeZoomValue(double zoom) {
Activator.getDefault().getDialogSettings().put(getZoomKey(), zoom);
}
public void storeViewportLocation() {
Point location = ((FigureCanvas) getCanvas()).getViewport()
.getViewLocation().getCopy();
Activator.getDefault().getDialogSettings().put(getViewportXValueKey(),
location.x);
Activator.getDefault().getDialogSettings().put(getViewportYValueKey(),
location.y);
}
private String getViewportXValueKey() {
return getDiagramId() + ":" + DIAGRAM_VIEWPORT_X;
}
private String getViewportYValueKey() {
return getDiagramId() + ":" + DIAGRAM_VIEWPORT_Y;
}
private String getZoomKey() {
return getDiagramId() + ":" + DIAGRAM_ZOOM;
}
private String getDiagramId() {
return Cl_c.Getooa_idfrominstance(getModel().getRepresents())
.toString()
+ "-" + getModel().getOoa_type();
}
/**
* Convience method for manually setting the persisted scroll values
*/
public void setViewportLocationInStorage(int x, int y) {
Activator.getDefault().getDialogSettings().put(getViewportXValueKey(),
x);
Activator.getDefault().getDialogSettings().put(getViewportYValueKey(),
y);
}
@Override
public void propertyChange(PropertyChangeEvent event) {
if(event.getProperty().equals("org.xtuml.bp.canvas.font")) {
if(diagramFont != null) {
FontData fontData = diagramFont.getFontData()[0];
if(!((FontData[]) event.getNewValue())[0].equals(fontData)) {
diagramFont.dispose();
diagramFont = null;
}
// update the figure canvas with the new font
((FigureCanvas) getCanvas()).setFont(getFont());
refresh();
}
}
}
public static int getGridSpacing() {
return CorePlugin.getDefault().getPreferenceStore().getInt(
BridgePointPreferencesStore.GRID_SPACING);
}
}
| |
package org.renpy.android;
import android.content.Context;
import android.os.Vibrator;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.EditorInfo;
import android.view.View;
import java.util.List;
import java.util.ArrayList;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import org.kivy.android.PythonActivity;
/**
* Methods that are expected to be called via JNI, to access the
* device's non-screen hardware. (For example, the vibration and
* accelerometer.)
*/
public class Hardware {
// The context.
static Context context;
static View view;
/**
* Vibrate for s seconds.
*/
public static void vibrate(double s) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate((int) (1000 * s));
}
}
/**
* Get an Overview of all Hardware Sensors of an Android Device
*/
public static String getHardwareSensors() {
SensorManager sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
if (allSensors != null) {
String resultString = "";
for (Sensor s : allSensors) {
resultString += String.format("Name=" + s.getName());
resultString += String.format(",Vendor=" + s.getVendor());
resultString += String.format(",Version=" + s.getVersion());
resultString += String.format(",MaximumRange=" + s.getMaximumRange());
// XXX MinDelay is not in the 2.2
//resultString += String.format(",MinDelay=" + s.getMinDelay());
resultString += String.format(",Power=" + s.getPower());
resultString += String.format(",Type=" + s.getType() + "\n");
}
return resultString;
}
return "";
}
/**
* Get Access to 3 Axis Hardware Sensors Accelerometer, Orientation and Magnetic Field Sensors
*/
public static class generic3AxisSensor implements SensorEventListener {
private final SensorManager sSensorManager;
private final Sensor sSensor;
private final int sSensorType;
SensorEvent sSensorEvent;
public generic3AxisSensor(int sensorType) {
sSensorType = sensorType;
sSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
sSensor = sSensorManager.getDefaultSensor(sSensorType);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
sSensorEvent = event;
}
/**
* Enable or disable the Sensor by registering/unregistering
*/
public void changeStatus(boolean enable) {
if (enable) {
sSensorManager.registerListener(this, sSensor, SensorManager.SENSOR_DELAY_NORMAL);
} else {
sSensorManager.unregisterListener(this, sSensor);
}
}
/**
* Read the Sensor
*/
public float[] readSensor() {
if (sSensorEvent != null) {
return sSensorEvent.values;
} else {
float rv[] = { 0f, 0f, 0f };
return rv;
}
}
}
public static generic3AxisSensor accelerometerSensor = null;
public static generic3AxisSensor orientationSensor = null;
public static generic3AxisSensor magneticFieldSensor = null;
/**
* functions for backward compatibility reasons
*/
public static void accelerometerEnable(boolean enable) {
if ( accelerometerSensor == null )
accelerometerSensor = new generic3AxisSensor(Sensor.TYPE_ACCELEROMETER);
accelerometerSensor.changeStatus(enable);
}
public static float[] accelerometerReading() {
float rv[] = { 0f, 0f, 0f };
if ( accelerometerSensor == null )
return rv;
return (float[]) accelerometerSensor.readSensor();
}
public static void orientationSensorEnable(boolean enable) {
if ( orientationSensor == null )
orientationSensor = new generic3AxisSensor(Sensor.TYPE_ORIENTATION);
orientationSensor.changeStatus(enable);
}
public static float[] orientationSensorReading() {
float rv[] = { 0f, 0f, 0f };
if ( orientationSensor == null )
return rv;
return (float[]) orientationSensor.readSensor();
}
public static void magneticFieldSensorEnable(boolean enable) {
if ( magneticFieldSensor == null )
magneticFieldSensor = new generic3AxisSensor(Sensor.TYPE_MAGNETIC_FIELD);
magneticFieldSensor.changeStatus(enable);
}
public static float[] magneticFieldSensorReading() {
float rv[] = { 0f, 0f, 0f };
if ( magneticFieldSensor == null )
return rv;
return (float[]) magneticFieldSensor.readSensor();
}
static public DisplayMetrics metrics = new DisplayMetrics();
/**
* Get display DPI.
*/
public static int getDPI() {
// AND: Shouldn't have to get the metrics like this every time...
PythonActivity.mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics.densityDpi;
}
// /**
// * Show the soft keyboard.
// */
// public static void showKeyboard(int input_type) {
// //Log.i("python", "hardware.Java show_keyword " input_type);
// InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
// SDLSurfaceView vw = (SDLSurfaceView) view;
// int inputType = input_type;
// if (vw.inputType != inputType){
// vw.inputType = inputType;
// imm.restartInput(view);
// }
// imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
// }
/**
* Hide the soft keyboard.
*/
public static void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* Scan WiFi networks
*/
static List<ScanResult> latestResult;
public static void enableWifiScanner()
{
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
// Code to execute when SCAN_RESULTS_AVAILABLE_ACTION event occurs
WifiManager w = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
latestResult = w.getScanResults(); // Returns a <list> of scanResults
}
}, i);
}
public static String scanWifi() {
// Now you can call this and it should execute the broadcastReceiver's
// onReceive()
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean a = wm.startScan();
if (latestResult != null){
String latestResultString = "";
for (ScanResult result : latestResult)
{
latestResultString += String.format("%s\t%s\t%d\n", result.SSID, result.BSSID, result.level);
}
return latestResultString;
}
return "";
}
/**
* network state
*/
public static boolean network_state = false;
/**
* Check network state directly
*
* (only one connection can be active at a given moment, detects all network type)
*
*/
public static boolean checkNetwork()
{
boolean state = false;
final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
state = true;
} else {
state = false;
}
return state;
}
/**
* To recieve network state changes
*/
public static void registerNetworkCheck()
{
IntentFilter i = new IntentFilter();
i.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
network_state = checkNetwork();
}
}, i);
}
}
| |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.custommapsapp.android.kml;
import com.custommapsapp.android.CustomMaps;
import com.custommapsapp.android.FileUtil;
import com.custommapsapp.android.ImageDiskCache;
import com.custommapsapp.android.ImageHelper;
import com.custommapsapp.android.MapDisplay.MapImageTooLargeException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* IconStyle stores an icon and its hotspot for placemarks. Icon palettes are
* not supported (icon palette is a single image that contains multiple icons).
*
* @author Marko Teittinen
*/
public class IconStyle extends KmlData {
private static final long serialVersionUID = 1L;
public static enum Units {
FRACTION,
PIXELS,
INSET_PIXELS;
public static Units parseUnits(String text) {
if (text.equals("fraction")) {
return FRACTION;
}
if (text.equals("pixels")) {
return PIXELS;
}
if (text.equals("insetPixels")) {
return INSET_PIXELS;
}
return null;
}
}
private float scale = 1.5f;
private String iconPath;
private float x = 0.5f;
private float y = 0.5f;
private Units xUnits = Units.FRACTION;
private Units yUnits = Units.FRACTION;
// Transient fields for icon and its alignment on screen
private transient Bitmap icon;
private transient Integer iconWidth;
private transient Integer iconHeight;
private transient PointF iconOffset;
private transient boolean iconLoaded = false;
public float getScale() {
return scale;
}
public void setScale(float scale) {
this.scale = scale;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
if (iconPath != null) {
iconPath = iconPath.trim();
}
this.iconPath = iconPath;
// Reset transient icon info fields
icon = null;
iconWidth = null;
iconHeight = null;
iconOffset = null;
}
public boolean isIconReady() {
return iconLoaded;
}
public synchronized Bitmap getIcon() {
if (icon == null) {
try {
icon = loadIcon();
} finally {
iconLoaded = true;
}
}
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
// Initialize/reset icon info fields
iconWidth = (icon != null ? icon.getWidth() : null);
iconHeight = (icon != null ? icon.getHeight() : null);
iconOffset = null;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
iconOffset = null;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
iconOffset = null;
}
public Units getXUnits() {
return xUnits;
}
public void setXUnits(Units xUnits) {
this.xUnits = xUnits;
iconOffset = null;
}
public Units getYUnits() {
return yUnits;
}
public void setYUnits(Units yUnits) {
this.yUnits = yUnits;
iconOffset = null;
}
/**
* Returns non-scaled pixel offset for placing the bitmap. Coordinate values
* grow right and down.
*
* @return non-scaled pixel offset from map location where upper left corner
* of the icon should be drawn
*/
public synchronized PointF getIconOffset() {
if (iconOffset == null) {
computeIconOffset();
// If icon size is still unknown, return (0, 0)
if (iconOffset == null) {
return new PointF(0, 0);
}
}
// Return a copy to prevent external modifications to computed offset
return new PointF(iconOffset.x, iconOffset.y);
}
private void computeIconOffset() {
if (iconWidth == null || iconHeight == null) {
if (icon == null) {
readIconSize();
} else {
iconWidth = icon.getWidth();
iconHeight = icon.getHeight();
}
if (iconWidth == null || iconHeight == null) {
// Something failed, can't do math
return;
}
}
iconOffset = new PointF();
switch (xUnits) {
case PIXELS:
iconOffset.x = -x;
break;
case INSET_PIXELS:
iconOffset.x = x - iconWidth;
break;
case FRACTION:
iconOffset.x = -x * iconWidth;
break;
}
switch (yUnits) {
case PIXELS:
iconOffset.y = y - iconHeight;
break;
case INSET_PIXELS:
iconOffset.y = iconHeight - y;
break;
case FRACTION:
iconOffset.y = iconHeight * (y - 1);
break;
}
}
private void readIconSize() {
if (iconPath == null) {
return;
}
InputStream in = null;
try {
in = openIconFile(iconPath);
BitmapFactory.Options options = ImageHelper.decodeImageBounds(in);
iconWidth = options.outWidth;
iconHeight = options.outHeight;
} catch (Exception ex) {
Log.e(CustomMaps.LOG_TAG, "Failed to read icon size: " + iconPath, ex);
} finally {
FileUtil.tryToClose(in);
}
}
private Bitmap loadIcon() {
if (iconPath == null) {
return null;
}
InputStream in = null;
try {
in = openIconFile(iconPath);
return ImageHelper.loadImage(in, false);
} catch (IOException ex) {
Log.e(CustomMaps.LOG_TAG, "Failed to load icon: " + iconPath, ex);
return null;
} catch (MapImageTooLargeException ex) {
Log.e(CustomMaps.LOG_TAG, "Icon too large: " + iconPath, ex);
return null;
} finally {
FileUtil.tryToClose(in);
}
}
private InputStream openIconFile(String iconPath) throws IOException {
if (!iconPath.startsWith("http://")) {
// Local file, KmlInfo knows to open
return getKmlInfo().getImageStream(iconPath);
}
// Remote file, get from cache
ImageDiskCache cache = ImageDiskCache.instance(null);
URL imageUrl = new URL(iconPath);
File cachedFile = cache.getImage(imageUrl);
return new FileInputStream(cachedFile);
}
}
| |
/*
* Copyright 2013 Lyor Goldstein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.reflect;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
/**
* @author lgoldstein
*
*/
public class ExtendedFieldUtils extends FieldUtils {
public ExtendedFieldUtils() {
super();
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}.
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name or type specified
*/
public static final Field getDeclaredField(Class<?> clazz, String name, Class<?> type) {
return getDeclaredField(clazz, name, type, false);
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}.
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @param makeAccessible whether to allow any visibility to access the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name or type specified
*/
public static final Field getDeclaredField(Class<?> clazz, String name, Class<?> type, boolean makeAccessible) {
if (StringUtils.isEmpty(name) || (type == null)) {
throw new IllegalArgumentException("getField(" + clazz + ")[" + name + "]@" + type + " - incomplete specification");
}
/*
* NOTE: we do not invoke the FieldUtils#getDeclaredField since
* it returns null if makeAccessible=false and field is not accessible
*/
final Field field;
try {
field = clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) { // NOPMD
return null;
}
if (!type.isAssignableFrom(field.getType())) {
return null;
}
if (makeAccessible && (!MemberUtils.isAccessible(field))) {
field.setAccessible(true);
}
return field;
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}. Searches all superclasses
* up to {@link Object}.
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name or type specified
* @see #getField(Class, String, Class, boolean)
*/
public static final Field getField(Class<?> clazz, String name, Class<?> type) {
return getField(clazz, name, type, false);
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}. Searches all superclasses
* up to the {@link Object}
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @param makeAccessible whether to allow any visibility to access the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name, type or stop class specified
* @see #getField(Class, String, Class, Class, boolean)
*/
public static final Field getField(Class<?> clazz, String name, Class<?> type, boolean makeAccessible) {
return getField(clazz, name, type, Object.class, makeAccessible);
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}. Searches all superclasses
* up to specified stop class (but not the stop class itself)
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @param stopClass the {@link Class} where to stop climbing up the hierarchy.
* <B>Note:</B> the stop class itself is <U>not</U> checked for the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name, type or stop class specified
* @see #getField(Class, String, Class, Class, boolean)
*/
public static final Field getField(Class<?> clazz, String name, Class<?> type, Class<?> stopClass) {
return getField(clazz, name, type, stopClass, false);
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> <U>and</U> {@link Class type}. Searches all superclasses
* up to specified stop class (but not the stop class itself)
* @param clazz the class to introspect
* @param name the name of the field
* @param type the type of the field
* @param stopClass the {@link Class} where to stop climbing up the hierarchy.
* <B>Note:</B> the stop class itself is <U>not</U> checked for the field
* @param makeAccessible whether to allow any visibility to access the field
* @return the corresponding Field object, or <code>null</code> if not found
* @throws IllegalArgumentException if no name, type or stop class specified
*/
public static final Field getField(Class<?> clazz, String name, Class<?> type, Class<?> stopClass, boolean makeAccessible) {
if (StringUtils.isEmpty(name) || (type == null) || (stopClass == null)) {
throw new IllegalArgumentException("getField(" + clazz + ")[" + name + "]@" + type + " < " + stopClass
+ " - incomplete specification");
}
Class<?> searchType = clazz;
while (!stopClass.equals(searchType) && (searchType != null)) {
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields) {
if (name.equals(field.getName()) && type.isAssignableFrom(field.getType())) {
if (makeAccessible && (!MemberUtils.isAccessible(field))) {
field.setAccessible(true);
}
return field;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
public static final <T> T readStaticTypedField(Class<?> cls, String fieldName, Class<T> valType) throws IllegalAccessException {
return readStaticTypedField(cls, fieldName, valType, false);
}
/**
* Reads the named static field. Superclasses will be considered.
* @param cls the class to reflect, must not be null
* @param fieldName the field name to obtain
* @param valType The expected field value type
* @param forceAccess whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found
* @throws IllegalAccessException if the field is not made accessible
*/
public static final <T> T readStaticTypedField(Class<?> cls, String fieldName, Class<T> valType, boolean forceAccess) throws IllegalAccessException {
Object value=readStaticField(cls, fieldName, forceAccess);
if (value == null) {
return null;
} else {
return valType.cast(value);
}
}
public static final <T> T readStaticTypedField(Field field, Class<T> valType) throws IllegalAccessException {
return readStaticTypedField(field, valType, false);
}
/**
* Reads a static Field.
* @param field to read
* @param valType The expected field value type
* @param forceAccess whether to break scope restrictions using the
* <code>setAccessible</code> method.
* @return the field value
* @throws IllegalArgumentException if the field is null or not static
* @throws IllegalAccessException if the field is not made accessible
*/
public static final <T> T readStaticTypedField(Field field, Class<T> valType, boolean forceAccess) throws IllegalAccessException {
Object value=readStaticField(field, forceAccess);
if (value == null) {
return null;
} else {
return valType.cast(value);
}
}
public static final <T> T readTypedField(Field field, Object target, Class<T> valType) throws IllegalAccessException {
return readTypedField(field, target, valType, false);
}
/**
* Reads a {@link Field} and casts its value.
* @param field the field to use
* @param target the object to call on, may be null for static fields
* @param valType The expected field value type
* @param forceAccess whether to break scope restrictions using the
* <code>setAccessible</code> method.
* @return the field value
* @throws IllegalArgumentException if the field is null
* @throws IllegalAccessException if the field is not made accessible
*/
public static final <T> T readTypedField(Field field, Object target, Class<T> valType, boolean forceAccess) throws IllegalAccessException {
Object value=readField(field, target, forceAccess);
if (value == null) {
return null;
} else {
return valType.cast(value);
}
}
}
| |
/*
* MediaWiki import/export processing tools
* Copyright 2005 by Brion Vibber
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* $Id: XmlDumpReader.java 59325 2009-11-22 01:21:03Z rainman $
*/
/**
* Bug compiler, bugc, for Honeywell ACS projects
*
* Author: Tao Lee
* Date : 20.08.13
* */
/**
* Description: XML processing tool for JIRA issues, Honeywell ACS
*
* Author : Tao LEE
* Date : 05.04.13
* */
package org.honeywell.acs.jira.importer;
import java.io.IOException;
import java.io.InputStream;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XmlDumpReader2 extends DefaultHandler {
InputStream input = null;
List<InputStream> inputList = null;
DumpWriter2 writer;
private char[] buffer;
private int len;
private boolean hasContent = false;
private boolean deleted = false;
JiraIssueItem item;
JiraCustomField customfield;
boolean abortFlag;
/**
* Initialize a processor for a MediaWiki XML dump stream.
* Events are sent to a single DumpWriter output sink, but you
* can chain multiple output processors with a MultiWriter.
* @param inputStream Stream to read XML from.
* @param writer Output sink to send processed events to.
*/
public XmlDumpReader2(InputStream inputStream, DumpWriter2 writer) {
input = inputStream;
this.writer = writer;
buffer = new char[4096];
len = 0;
hasContent = false;
}
public XmlDumpReader2(List<InputStream> inputStreamList, DumpWriter2 writer) {
inputList = new ArrayList<InputStream>(inputStreamList);
this.writer = writer;
buffer = new char[4096];
len = 0;
hasContent = false;
}
/**
* Reads through the entire XML dump on the input stream, sending
* events to the DumpWriter as it goes. May throw exceptions on
* invalid input or due to problems with the output.
* @throws IOException
*/
public void readDump() throws IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
if (input != null)
parser.parse(input, this);
else if (inputList != null) {
for (InputStream in: inputList) {
parser.parse(in, this);
}
}
} catch (ParserConfigurationException e) {
throw (IOException)new IOException(e.getMessage()).initCause(e);
} catch (SAXException e) {
throw (IOException)new IOException(e.getMessage()).initCause(e);
}
}
/**
* Request that the dump processing be aborted.
* At the next element, an exception will be thrown to stop the XML parser.
* @fixme Is setting a bool thread-safe? It should be atomic...
*/
public void abort() {
abortFlag = true;
}
// --------------------------
// SAX handler interface methods:
private static final Map<String, String> startElements = new HashMap<String, String>(64);
private static final Map<String, String> endElements = new HashMap<String, String>(64);
static {
startElements.put("channel", "channel");
startElements.put("item", "item");
startElements.put("title", "title");
startElements.put("project", "project");
startElements.put("description", "description");
startElements.put("environment", "environment");
startElements.put("key", "key");
startElements.put("summary", "summary");
startElements.put("type", "type");
startElements.put("priority", "priority");
startElements.put("status", "status");
startElements.put("resolution", "resolution");
startElements.put("assignee", "assignee");
startElements.put("reporter", "reporter");
startElements.put("created", "created");
startElements.put("updated", "updated");
startElements.put("resolved", "resolved");
startElements.put("fixVersion", "fixVersion");
startElements.put("component", "component");
startElements.put("due", "due");
startElements.put("votes", "votes");
startElements.put("watches", "watches");
startElements.put("comments", "comments");
startElements.put("comment", "comment");
startElements.put("attachments", "attachments");
startElements.put("attachment", "attachment");
startElements.put("subtasks", "subtasks");
startElements.put("subtask", "subtask");
startElements.put("customfields", "customfields");
startElements.put("customfield", "customfield");
startElements.put("customfieldname", "customfieldname");
startElements.put("customfieldvalues", "customfieldvalues");
startElements.put("customfieldvalue", "customfieldvalue");
endElements.put("channel", "channel");
endElements.put("item", "item");
endElements.put("title", "title");
endElements.put("project", "project");
endElements.put("description", "description");
endElements.put("environment", "environment");
endElements.put("key", "key");
endElements.put("summary", "summary");
endElements.put("type", "type");
endElements.put("priority", "priority");
endElements.put("status", "status");
endElements.put("resolution", "resolution");
endElements.put("assignee", "assignee");
endElements.put("reporter", "reporter");
endElements.put("created", "created");
endElements.put("updated", "updated");
endElements.put("resolved", "resolved");
endElements.put("fixVersion", "fixVersion");
endElements.put("component", "component");
endElements.put("due", "due");
endElements.put("votes", "votes");
endElements.put("watches", "watches");
endElements.put("comments", "comments");
endElements.put("comment", "comment");
endElements.put("attachments", "attachments");
endElements.put("attachment", "attachment");
endElements.put("subtasks", "subtasks");
endElements.put("subtask", "subtask");
endElements.put("customfields", "customfields");
endElements.put("customfield", "customfield");
endElements.put("customfieldname", "customfieldname");
endElements.put("customfieldvalues", "customfieldvalues");
endElements.put("customfieldvalue", "customfieldvalue");
}
public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException {
// Clear the buffer for character data; we'll initialize it
// if and when character data arrives -- at that point we
// have a length.
len = 0;
hasContent = false;
if (abortFlag)
throw new SAXException("XmlDumpReader2 set abort flag.");
// check for deleted="deleted", and set deleted flag for the current element.
String d = attributes.getValue("deleted");
deleted = (d!=null && d.equals("deleted"));
try {
qName = (String)startElements.get(qName);
if (qName == null)
return;
if (qName == "channel") openChannel();
else if (qName == "item") openItem();
else if (qName == "title") openTitle();
else if (qName == "project") openProject();
else if (qName == "description") openDescription();
else if (qName == "environment") openEnvironment();
else if (qName == "key") openKey();
else if (qName == "summary") openSummary();
else if (qName == "type") openType();
else if (qName == "priority") openPriority();
else if (qName == "status") openStatus();
else if (qName == "resolution") openResolution();
else if (qName == "assignee") openAssignee();
else if (qName == "reporter") openReporter();
else if (qName == "created") openCreated();
else if (qName == "updated") openUpdated();
else if (qName == "updated") openUpdated();
else if (qName == "resolved") openResolved();
else if (qName == "fixVersion") openFixVersion();
else if (qName == "component") openComponent();
else if (qName == "due") openDue();
else if (qName == "votes") openVotes();
else if (qName == "watches") openWatches();
else if (qName == "comments") openComments();
else if (qName == "comment") openComment();
else if (qName == "attachments") openAttachments();
else if (qName == "attachment") openAttachment();
else if (qName == "subtasks") openSubtasks();
else if (qName == "subtask") openSubtask();
else if (qName == "customfields") openCustomFields();
else if (qName == "customfield") openCustomField();
else if (qName == "customfieldname") openCustomFieldName();
else if (qName == "customfieldvalues") openCustomFieldValues();
else if (qName == "customfieldvalue") openCustomFieldValue();
} catch (IOException e) {
throw new SAXException(e);
}
}
public void characters(char[] ch, int start, int length) {
if (buffer.length < len + length) {
int maxlen = buffer.length * 2;
if (maxlen < len + length)
maxlen = len + length;
char[] tmp = new char[maxlen];
System.arraycopy(buffer, 0, tmp, 0, len);
buffer = tmp;
}
System.arraycopy(ch, start, buffer, len, length);
len += length;
hasContent = true;
}
public void endElement(String uri, String localname, String qName) throws SAXException {
try {
qName = (String)endElements.get(qName);
if (qName == null)
return;
if (qName == "channel") closeChannel();
else if (qName == "item") closeItem();
else if (qName == "title") closeTitle();
else if (qName == "project") closeProject();
else if (qName == "description") closeDescription();
else if (qName == "environment") closeEnvironment();
else if (qName == "key") closeKey();
else if (qName == "summary") closeSummary();
else if (qName == "type") closeType();
else if (qName == "priority") closePriority();
else if (qName == "status") closeStatus();
else if (qName == "resolution") closeResolution();
else if (qName == "assignee") closeAssignee();
else if (qName == "reporter") closeReporter();
else if (qName == "created") closeCreated();
else if (qName == "updated") closeUpdated();
else if (qName == "resolved") closeResolved();
else if (qName == "fixVersion") closeFixVersion();
else if (qName == "component") closeComponent();
else if (qName == "due") closeDue();
else if (qName == "votes") closeVotes();
else if (qName == "watches") closeWatches();
else if (qName == "comments") closeComments();
else if (qName == "comment") closeComment();
else if (qName == "attachments") closeAttachments();
else if (qName == "attachment") closeAttachment();
else if (qName == "subtasks") closeSubtasks();
else if (qName == "subtask") closeSubtask();
else if (qName == "customfields") closeCustomFields();
else if (qName == "customfield") closeCustomField();
else if (qName == "customfieldname") closeCustomFieldName();
else if (qName == "customfieldvalues") closeCustomFieldValues();
else if (qName == "customfieldvalue") closeCustomFieldValue();
// else throw(SAXException)new SAXException("Unrecognised "+qName+"(substring "+qName.length()+qName.substring(0,6)+")");
} catch (IOException e) {
throw (SAXException)new SAXException(e.getMessage()).initCause(e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ----------
void openChannel() throws IOException {
writer.writeStartChannel();
}
void openItem() {
item = new JiraIssueItem();
}
void openTitle() {
// do nothing
}
void openProject() {
// do nothing
}
void openDescription() {
// do nothing
}
void openEnvironment() {
// do nothing
}
void openKey() {
// do nothing
}
void openSummary() {
// do nothing
}
void openType() {
// do nothing
}
void openPriority() {
// do nothing
}
void openStatus() {
// do nothing
}
void openResolution() {
// do nothing
}
void openAssignee() {
// do nothing
}
void openReporter() {
// do nothing
}
void openCreated() {
// do nothing
}
void openUpdated() {
// do nothing
}
void openResolved() {
// do nothing
}
void openFixVersion() {
// do nothing
}
void openComponent() {
// do nothing
}
void openDue() {
// do nothing
}
void openVotes() {
// do nothing
}
void openWatches() {
// do nothing
}
void openComments() {
if (item != null)
item.comments = new ArrayList<String>();
}
void openComment() {
// do nothing
}
void openAttachments() {
if (item != null)
item.attachments = new ArrayList<String>();
}
void openAttachment() {
// do nothing
}
void openSubtasks() {
if (item != null)
item.subtasks = new ArrayList<String>();
}
void openSubtask() {
// do nothing
}
void openCustomFields() {
if (item != null)
item.customfields = new ArrayList<JiraCustomField>();
}
void openCustomField() {
customfield = new JiraCustomField();
}
void openCustomFieldName() {
// do nothing
}
void openCustomFieldValues() {
if (customfield != null)
customfield.customfieldvalues = new ArrayList<String>();
}
void openCustomFieldValue() {
// do nothing
}
// ----------
void closeChannel() throws IOException {
writer.writeEndChannel();
}
void closeItem() throws IOException {
writer.writeEndItem(item);
item = null;
}
void closeTitle() {
if (item != null)
item.title = bufferContents();
}
void closeProject() {
if (item != null)
item.project = bufferContents();
}
void closeDescription() {
if (item != null)
item.description = bufferContents();
}
void closeEnvironment() {
if (item != null)
item.environment = bufferContents();
}
void closeKey() {
if (item != null)
item.key = bufferContents();
}
void closeSummary() {
if (item != null)
item.summary = bufferContents();
}
void closeType() {
if (item != null)
item.type = bufferContents();
}
void closePriority() {
if (item != null)
item.priority = bufferContents();
}
void closeStatus() {
if (item != null)
item.status = bufferContents();
}
void closeResolution() {
if (item != null)
item.resolution = bufferContents();
}
void closeAssignee() {
if (item != null)
item.assignee = bufferContents();
}
void closeReporter() {
if (item != null)
item.reporter = bufferContents();
}
void closeCreated() throws ParseException {
if (item != null)
item.created = parseJiraTimestamp(bufferContents());
}
void closeUpdated() throws ParseException {
if (item != null)
item.updated = parseJiraTimestamp(bufferContents());
}
void closeResolved() throws ParseException {
if (item != null)
item.resolved = parseJiraTimestamp(bufferContents());
}
void closeFixVersion() {
if (item != null)
item.fixVersion = bufferContents();
}
void closeComponent() {
if (item != null)
item.component = bufferContents();
}
void closeDue() {
if (item != null)
item.due = bufferContents();
}
void closeVotes() {
if (item != null)
item.votes = Integer.parseInt(bufferContents());
}
void closeWatches() {
if (item != null)
item.watches = Integer.parseInt(bufferContents());
}
void closeComments() {
// do nothing
}
void closeComment() {
if (item != null && item.comments != null)
item.comments.add(bufferContents());
}
void closeAttachments() {
// do nothing
}
void closeAttachment() {
if (item != null && item.attachments != null)
item.attachments.add(bufferContents());
}
void closeSubtasks() {
// do nothing
}
void closeSubtask() {
if (item != null && item.subtasks != null)
item.subtasks.add(bufferContents());
}
void closeCustomFields() {
// do nothing
}
void closeCustomField() {
if (item != null && item.customfields != null)
item.customfields.add(customfield);
customfield = null;
}
void closeCustomFieldName() {
if (customfield != null)
customfield.customfieldname = bufferContents();
}
void closeCustomFieldValues() {
// do nothing
}
void closeCustomFieldValue() {
if (customfield != null && customfield.customfieldvalues != null)
customfield.customfieldvalues.add(bufferContents());
}
private String bufferContents() {
return len == 0 ? "" : filterBufferContents(new String(buffer, 0, len));
}
// clear up the texts
private String filterBufferContents(String oldString) {
//return oldString;
return oldString.replaceAll("<[^>]+>|</[^>]+>", " ");
/* return oldString.
replace("<p>", "").
replace("</p>", "").
replace("<a>", "").
replace("</a>", "").
replace("<del>", "").
replace("</del>", "").
replace(">", "").
replace("<br>", "").
replace("</br>", "").
replace("<b>", "").
replace("</b>", "").
replace("<span>", "").
replace("</span>","").
replace("<br/>", "").
replace("<div>", "").
replace("</div>", "").
replace("<pre>", "").
replace("</pre>", "").
replace("<em>", "").
replace("</em>", "").
replace("<ul>", "").
replace("</ul>", "").
replace("<li>","").
replace("</li>", "").
replace("<cite>", "").
replace("</cite>", "").
replace("<h1>", "").
replace("</h1>", "").
replace("<h2>", "").
replace("</h2>", "").
replace("<h3>", "").
replace("</h3>", "").
replace("<h4>", "").
replace("</h4>", "");*/
}
private static Calendar parseJiraTimestamp(String text) throws ParseException {
// Mon, 25 Mar 2013 17:15:40 +0100
// Use DateFormat to parse the string
Format formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date date = (Date) formatter.parseObject(text);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar;
}
}
| |
/*
* Copyright 2012 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.google.bitcoin.uri;
import com.google.bitcoin.core.Address;
import com.google.bitcoin.core.AddressFormatException;
import com.google.bitcoin.core.NetworkParameters;
import com.google.bitcoin.core.Utils;
import com.google.bitcoin.params.MainNetParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* <p>Provides a standard implementation of a Bitcoin URI with support for the following:</p>
*
* <ul>
* <li>URLEncoded URIs (as passed in by IE on the command line)</li>
* <li>BIP21 names (including the "req-" prefix handling requirements)</li>
* </ul>
*
* <h2>Accepted formats</h2>
*
* <p>The following input forms are accepted:</p>
*
* <ul>
* <li>{@code bitcoin:<address>}</li>
* <li>{@code bitcoin:<address>?<name1>=<value1>&<name2>=<value2>} with multiple
* additional name/value pairs</li>
* </ul>
*
* <p>The name/value pairs are processed as follows.</p>
* <ol>
* <li>URL encoding is stripped and treated as UTF-8</li>
* <li>names prefixed with {@code req-} are treated as required and if unknown or conflicting cause a parse exception</li>
* <li>Unknown names not prefixed with {@code req-} are added to a Map, accessible by parameter name</li>
* <li>Known names not prefixed with {@code req-} are processed unless they are malformed</li>
* </ol>
*
* <p>The following names are known and have the following formats:</p>
* <ul>
* <li>{@code amount} decimal value to 8 dp (e.g. 0.12345678) <b>Note that the
* exponent notation is not supported any more</b></li>
* <li>{@code label} any URL encoded alphanumeric</li>
* <li>{@code message} any URL encoded alphanumeric</li>
* </ul>
*
* @author Andreas Schildbach (initial code)
* @author Jim Burton (enhancements for MultiBit)
* @author Gary Rowe (BIP21 support)
* @see <a href="https://en.bitcoin.it/wiki/BIP_0021">BIP 0021</a>
*/
public class BitcoinURI {
/**
* Provides logging for this class
*/
private static final Logger log = LoggerFactory.getLogger(BitcoinURI.class);
// Not worth turning into an enum
public static final String FIELD_MESSAGE = "message";
public static final String FIELD_LABEL = "label";
public static final String FIELD_AMOUNT = "amount";
public static final String FIELD_ADDRESS = "address";
public static final String FIELD_URL = "httpaddress";
public static final String BITCOIN_SCHEME = "bitcoin:";
private static final String ENCODED_SPACE_CHARACTER = "%20";
private static final String AMPERSAND_SEPARATOR = "&";
private static final String QUESTION_MARK_SEPARATOR = "?";
/**
* Contains all the parameters in the order in which they were processed
*/
private final Map<String, Object> parameterMap = new LinkedHashMap<String, Object>();
/**
* Constructs a new BitcoinURI from the given string. Can be for any network.
*
* @param uri The raw URI data to be parsed (see class comments for accepted formats)
* @throws BitcoinURIParseException if the URI is not syntactically or semantically valid.
*/
public BitcoinURI(String uri) throws BitcoinURIParseException {
this(null, uri);
}
/**
* Constructs a new object by trying to parse the input as a valid Bitcoin URI.
*
* @param params The network parameters that determine which network the URI is from, or null if you don't have
* any expectation about what network the URI is for and wish to check yourself.
* @param input The raw URI data to be parsed (see class comments for accepted formats)
*
* @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks.
*/
public BitcoinURI(@Nullable NetworkParameters params, String input) throws BitcoinURIParseException {
checkNotNull(input);
log.debug("Attempting to parse '{}' for {}", input, params == null ? "any" : params.getId());
// Attempt to form the URI (fail fast syntax checking to official standards).
URI uri;
try {
uri = new URI(input);
} catch (URISyntaxException e) {
throw new BitcoinURIParseException("Bad URI syntax", e);
}
// URI is formed as bitcoin:<address>?<query parameters>
// blockchain.info generates URIs of non-BIP compliant form bitcoin://address?....
// We support both until Ben fixes his code.
// Remove the bitcoin scheme.
// (Note: getSchemeSpecificPart() is not used as it unescapes the label and parse then fails.
// For instance with : bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=0.06&label=Tom%20%26%20Jerry
// the & (%26) in Tom and Jerry gets interpreted as a separator and the label then gets parsed
// as 'Tom ' instead of 'Tom & Jerry')
// How to do it if we need to *send* our address to a site for *receiveing* bitcoins from that site?
// Suggestion:
// bitcoin:http(s)://btcexchange.example/giveaddr.php?sid=1234567890
// Wallet would make a http get :
// http(s)://btcexchange.example/giveaddr.php?sid=1234567890&addr=129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha
//
String schemeRequired = params == null ? BITCOIN_SCHEME : params.getURIScheme();
String schemeSpecificPart;
if (input.startsWith(schemeRequired + "http")) {
int startpoint = schemeRequired.length();
String httpAddress = input.substring(startpoint);
putWithValidation(FIELD_URL,httpAddress);
return;
} else if (input.startsWith(schemeRequired + "//")) {
schemeSpecificPart = input.substring((schemeRequired + "//").length());
} else if (input.startsWith(schemeRequired)) {
schemeSpecificPart = input.substring(schemeRequired.length());
} else {
throw new BitcoinURIParseException("Unsupported URI scheme: " + uri.getScheme());
}
// Split off the address from the rest of the query parameters.
String[] addressSplitTokens = schemeSpecificPart.split("\\?");
if (addressSplitTokens.length == 0 || "".equals(addressSplitTokens[0])) {
throw new BitcoinURIParseException("Missing address");
}
String addressToken = addressSplitTokens[0];
String[] nameValuePairTokens;
if (addressSplitTokens.length == 1) {
// Only an address is specified - use an empty '<name>=<value>' token array.
nameValuePairTokens = new String[] {};
} else {
if (addressSplitTokens.length == 2) {
// Split into '<name>=<value>' tokens.
nameValuePairTokens = addressSplitTokens[1].split("&");
} else {
throw new BitcoinURIParseException("Too many question marks in URI '" + uri + "'");
}
}
// Attempt to parse the rest of the URI parameters.
parseParameters(params, addressToken, nameValuePairTokens);
}
/**
* @param params The network parameters or null
* @param nameValuePairTokens The tokens representing the name value pairs (assumed to be
* separated by '=' e.g. 'amount=0.2')
*/
private void parseParameters(@Nullable NetworkParameters params, String addressToken, String[] nameValuePairTokens) throws BitcoinURIParseException {
// Attempt to parse the addressToken as a Bitcoin address for this network
try {
Address address = new Address(params, addressToken);
putWithValidation(FIELD_ADDRESS, address);
} catch (final AddressFormatException e) {
throw new BitcoinURIParseException("Bad address", e);
}
// Attempt to decode the rest of the tokens into a parameter map.
for (String nameValuePairToken : nameValuePairTokens) {
String[] tokens = nameValuePairToken.split("=");
if (tokens.length != 2 || "".equals(tokens[0])) {
throw new BitcoinURIParseException("Malformed Bitcoin URI - cannot parse name value pair '" +
nameValuePairToken + "'");
}
String nameToken = tokens[0].toLowerCase();
String valueToken = tokens[1];
// Parse the amount.
if (FIELD_AMOUNT.equals(nameToken)) {
// Decode the amount (contains an optional decimal component to 8dp).
try {
BigInteger amount = Utils.toNanoCoins(valueToken);
putWithValidation(FIELD_AMOUNT, amount);
} catch (NumberFormatException e) {
throw new OptionalFieldValidationException(String.format("'%s' is not a valid amount", valueToken), e);
} catch (ArithmeticException e) {
throw new OptionalFieldValidationException(String.format("'%s' has too many decimal places", valueToken), e);
}
} else {
if (nameToken.startsWith("req-")) {
// A required parameter that we do not know about.
throw new RequiredFieldValidationException("'" + nameToken + "' is required but not known, this URI is not valid");
} else {
// Known fields and unknown parameters that are optional.
try {
putWithValidation(nameToken, URLDecoder.decode(valueToken, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Unreachable.
throw new RuntimeException(e);
}
}
}
}
// Note to the future: when you want to implement 'req-expires' have a look at commit 410a53791841
// which had it in.
}
/**
* Put the value against the key in the map checking for duplication. This avoids address field overwrite etc.
*
* @param key The key for the map
* @param value The value to store
*/
private void putWithValidation(String key, Object value) throws BitcoinURIParseException {
if (parameterMap.containsKey(key)) {
throw new BitcoinURIParseException(String.format("'%s' is duplicated, URI is invalid", key));
} else {
parameterMap.put(key, value);
}
}
public String getHttpAddress() {
return (String) parameterMap.get(FIELD_URL);
}
/**
* @return The Bitcoin Address from the URI
*/
public Address getAddress() {
return (Address) parameterMap.get(FIELD_ADDRESS);
}
/**
* @return The amount name encoded using a pure integer value based at
* 10,000,000 units is 1 BTC. May be null if no amount is specified
*/
public BigInteger getAmount() {
return (BigInteger) parameterMap.get(FIELD_AMOUNT);
}
/**
* @return The label from the URI.
*/
public String getLabel() {
return (String) parameterMap.get(FIELD_LABEL);
}
/**
* @return The message from the URI.
*/
public String getMessage() {
return (String) parameterMap.get(FIELD_MESSAGE);
}
/**
* @param name The name of the parameter
* @return The parameter value, or null if not present
*/
public Object getParameterByName(String name) {
return parameterMap.get(name);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BitcoinURI[");
boolean first = true;
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
if (first) {
first = false;
} else {
builder.append(",");
}
builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'");
}
builder.append("]");
return builder.toString();
}
// Bitcoin shortcut with old-style params (omits custom network params)
// Takes an address object instead of an address string
public static String convertToBitcoinURI(Address address, BigInteger amount, String label, String message) {
return convertToBitcoinURI(address.toString(), amount, label, message);
}
// Bitcoin shortcut with old-style params (omits custom network params)
// Assumes Bitcoin MainNet, only used for URI scheme.
public static String convertToBitcoinURI(String address, BigInteger amount, String label, String message) {
return convertToBitcoinURI(new MainNetParams(), address, amount, label, message);
}
// New-style (with network params) address object handling
public static String convertToBitcoinURI(NetworkParameters params, Address address, BigInteger amount, String label, String message) {
return convertToBitcoinURI(params, address.toString(), amount, label, message);
}
/**
* Simple Bitcoin URI builder using known good fields.
*
* @param address The Bitcoin address
* @param amount The amount in nanocoins (decimal)
* @param label A label
* @param message A message
* @return A String containing the Bitcoin URI
*/
public static String convertToBitcoinURI(NetworkParameters params, String address, @Nullable BigInteger amount,
@Nullable String label, @Nullable String message) {
checkNotNull(address);
if (amount != null && amount.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Amount must be positive");
}
StringBuilder builder = new StringBuilder();
builder.append(params.getURIScheme()).append(address);
boolean questionMarkHasBeenOutput = false;
if (amount != null) {
builder.append(QUESTION_MARK_SEPARATOR).append(FIELD_AMOUNT).append("=");
builder.append(Utils.bitcoinValueToPlainString(amount));
questionMarkHasBeenOutput = true;
}
if (label != null && !"".equals(label)) {
if (questionMarkHasBeenOutput) {
builder.append(AMPERSAND_SEPARATOR);
} else {
builder.append(QUESTION_MARK_SEPARATOR);
questionMarkHasBeenOutput = true;
}
builder.append(FIELD_LABEL).append("=").append(encodeURLString(label));
}
if (message != null && !"".equals(message)) {
if (questionMarkHasBeenOutput) {
builder.append(AMPERSAND_SEPARATOR);
} else {
builder.append(QUESTION_MARK_SEPARATOR);
}
builder.append(FIELD_MESSAGE).append("=").append(encodeURLString(message));
}
return builder.toString();
}
/**
* Encode a string using URL encoding
*
* @param stringToEncode The string to URL encode
*/
static String encodeURLString(String stringToEncode) {
try {
return java.net.URLEncoder.encode(stringToEncode, "UTF-8").replace("+", ENCODED_SPACE_CHARACTER);
} catch (UnsupportedEncodingException e) {
// should not happen - UTF-8 is a valid encoding
throw new RuntimeException(e);
}
}
}
| |
/*
* Copyright 2013 Cloudera Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.crash.generics;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class CustomData extends GenericData {
public static Schema schemaFromResource(String resource) {
try {
return new Schema.Parser().parse(
Resources.getResource(resource).openStream());
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}
public static final Schema GENERIC_SCHEMA = schemaFromResource("generic.avsc");
protected static final String CONTAINER = "Container";
private final LoadingCache<Schema, List<String>> fieldNamesCache =
CacheBuilder.newBuilder().build(
CacheLoader.from(new Function<Schema, List<String>>() {
@Override
public List<String> apply(@Nullable Schema schema) {
if (schema != null && schema.getType() == Schema.Type.RECORD) {
List<Schema.Field> fields = schema.getFields();
List<String> names = Lists.newArrayListWithCapacity(fields.size());
for (Schema.Field field : fields) {
names.add(field.name());
}
return names;
} else {
return null;
}
}
}));
/*
* Keep a store of the schemas for objects that have been created by this
* CustomData implementation. The keys are weak references so they do not
* keep the created data objects from being garbage collected.
*/
private final Cache<Object, Schema> schemaCache =
CacheBuilder.newBuilder().weakKeys().build();
/*
* record instanceof IndexedRecord
* array instanceof Collection
* map instanceof Map
* fixed instanceof GenericFixed
* string instanceof CharSequence
* bytes instanceof ByteBuffer
* int instanceof Integer
* long instanceof Long
* float instanceof Float
* double instanceof Double
* bool instanceof Boolean
* symbol instanceof GenericEnumSymbol, could be replaced if passed Class<T>
*/
private final DataFactory factory;
private boolean reuseContainers = true;
protected CustomData(DataFactory factory, boolean shouldReuseContainers) {
this.factory = factory;
this.reuseContainers = shouldReuseContainers;
}
@Override
public DatumReader createDatumReader(Schema schema) {
return new CustomDatumReader(schema, this);
}
public <D> DatumWriter<D> createDatumWriter(Schema schema) {
return new CustomDatumWriter<D>(schema, this);
}
public void reuseContainers(boolean shouldReuse) {
this.reuseContainers = shouldReuse;
}
public boolean shouldReuseContainers() {
return this.reuseContainers;
}
@Override
@SuppressWarnings("unchecked")
public Object newRecord(Object old, Schema schema) {
if (shouldReuseContainers() && old != null) {
// GenericData checks schemas via object equality, so do it here
if (isRecord(old) && schema == getRecordSchema(old)) {
// no need to clear the old record; all fields will be replaced
return old;
}
}
final Object record;
try {
record = factory.createRecord(schema.getName(), fieldNamesCache.get(schema));
} catch (ExecutionException ex) {
throw Throwables.propagate(ex);
}
schemaCache.put(record, schema);
return record;
}
@Override
protected Schema getRecordSchema(Object record) {
return schemaCache.getIfPresent(record);
}
@Override
protected Schema getEnumSchema(Object enu) {
return schemaCache.getIfPresent(enu);
}
protected void addEnumSchema(Schema schema) {
for (String enu : schema.getEnumSymbols()) {
schemaCache.put(factory.createSymbol(enu), schema);
}
}
protected boolean hasSchema(Object datum) {
return (schemaCache.getIfPresent(datum) != null);
}
protected boolean isNull(Object datum) {
// no need to check if really null, that is done in super.getSchemaName
return false;
}
@Override
protected String getSchemaName(Object datum) {
if (isNull(datum)) {
return Schema.Type.NULL.getName();
} else {
return super.getSchemaName(datum);
}
}
@Override
public <T> T deepCopy(Schema schema, T value) {
// TODO: eventually replace this with something that hooks object creation
return super.deepCopy(schema, value);
}
public Object newString(String value) {
return factory.createString(value);
}
public Object newString(ByteBuffer utf8) {
return factory.createString(utf8);
}
public Object newMap(Object old, int sizeHint) {
if (shouldReuseContainers() && old != null) {
if (isMap(old)) {
((Map) old).clear();
return old;
}
}
return factory.createMap();
}
public Object newSymbol(String symbol, Schema schema) {
Object sym = factory.createSymbol(symbol);
// make sure the schema is cached for all of the symbols in this enum
if (schema != schemaCache.getIfPresent(sym)) {
addEnumSchema(schema);
}
return sym;
}
public Object newList(Object old, int size, Schema schema) {
if (shouldReuseContainers() && old != null) {
// TODO: add support for GenericArray to reuse contained objects
if (isArray(old) && schema == schemaCache.getIfPresent(old)) {
((Collection) old).clear();
return old;
}
}
Object list = factory.createList(size);
schemaCache.put(list, schema);
return list;
}
public CharSequence makeString(Object datum) {
// By default, coerce non-CharSequence objects with toString()
return datum.toString();
}
}
| |
/**
* Copyright 2012 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dogecoindark.dogecoindarkj.store;
import com.dogecoindark.dogecoindarkj.core.*;
import com.dogecoindark.dogecoindarkj.core.TransactionConfidence.ConfidenceType;
import com.dogecoindark.dogecoindarkj.crypto.KeyCrypter;
import com.dogecoindark.dogecoindarkj.crypto.KeyCrypterScrypt;
import com.dogecoindark.dogecoindarkj.script.Script;
import com.dogecoindark.dogecoindarkj.signers.LocalTransactionSigner;
import com.dogecoindark.dogecoindarkj.signers.TransactionSigner;
import com.dogecoindark.dogecoindarkj.utils.ExchangeRate;
import com.dogecoindark.dogecoindarkj.utils.Fiat;
import com.dogecoindark.dogecoindarkj.wallet.KeyChainGroup;
import com.dogecoindark.dogecoindarkj.wallet.WalletTransaction;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.TextFormat;
import com.google.protobuf.WireFormat;
import com.dogecoindark.dogecoindarkj.wallet.Protos;
import com.dogecoindark.dogecoindarkj.wallet.Protos.Wallet.EncryptionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Serialize and de-serialize a wallet to a byte stream containing a
* <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">protocol buffer</a>. Protocol buffers are
* a data interchange format developed by Google with an efficient binary representation, a type safe specification
* language and compilers that generate code to work with those data structures for many languages. Protocol buffers
* can have their format evolved over time: conceptually they represent data using (tag, length, value) tuples. The
* format is defined by the <tt>wallet.proto</tt> file in the bitcoinj source distribution.<p>
*
* This class is used through its static methods. The most common operations are writeWallet and readWallet, which do
* the obvious operations on Output/InputStreams. You can use a {@link java.io.ByteArrayInputStream} and equivalent
* {@link java.io.ByteArrayOutputStream} if you'd like byte arrays instead. The protocol buffer can also be manipulated
* in its object form if you'd like to modify the flattened data structure before serialization to binary.<p>
*
* You can extend the wallet format with additional fields specific to your application if you want, but make sure
* to either put the extra data in the provided extension areas, or select tag numbers that are unlikely to be used
* by anyone else.<p>
*
* @author Miron Cuperman
* @author Andreas Schildbach
*/
public class WalletProtobufSerializer {
private static final Logger log = LoggerFactory.getLogger(WalletProtobufSerializer.class);
/** Current version used for serializing wallets. A version higher than this is considered from the future. */
public static final int CURRENT_WALLET_VERSION = Protos.Wallet.getDefaultInstance().getVersion();
// Used for de-serialization
protected Map<ByteString, Transaction> txMap;
private boolean requireMandatoryExtensions = true;
public interface WalletFactory {
Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup);
}
private final WalletFactory factory;
public WalletProtobufSerializer() {
this(new WalletFactory() {
@Override
public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup) {
return new Wallet(params, keyChainGroup);
}
});
}
public WalletProtobufSerializer(WalletFactory factory) {
txMap = new HashMap<ByteString, Transaction>();
this.factory = factory;
}
/**
* If this property is set to false, then unknown mandatory extensions will be ignored instead of causing load
* errors. You should only use this if you know exactly what you are doing, as the extension data will NOT be
* round-tripped, possibly resulting in a corrupted wallet if you save it back out again.
*/
public void setRequireMandatoryExtensions(boolean value) {
requireMandatoryExtensions = value;
}
/**
* Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p>
*
* Equivalent to <tt>walletToProto(wallet).writeTo(output);</tt>
*/
public void writeWallet(Wallet wallet, OutputStream output) throws IOException {
Protos.Wallet walletProto = walletToProto(wallet);
walletProto.writeTo(output);
}
/**
* Returns the given wallet formatted as text. The text format is that used by protocol buffers and although it
* can also be parsed using {@link TextFormat#merge(CharSequence, com.google.protobuf.Message.Builder)},
* it is designed more for debugging than storage. It is not well specified and wallets are largely binary data
* structures anyway, consisting as they do of keys (large random numbers) and {@link Transaction}s which also
* mostly contain keys and hashes.
*/
public String walletToText(Wallet wallet) {
Protos.Wallet walletProto = walletToProto(wallet);
return TextFormat.printToString(walletProto);
}
/**
* Converts the given wallet to the object representation of the protocol buffers. This can be modified, or
* additional data fields set, before serialization takes place.
*/
public Protos.Wallet walletToProto(Wallet wallet) {
Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
if (wallet.getDescription() != null) {
walletBuilder.setDescription(wallet.getDescription());
}
for (WalletTransaction wtx : wallet.getWalletTransactions()) {
Protos.Transaction txProto = makeTxProto(wtx);
walletBuilder.addTransaction(txProto);
}
walletBuilder.addAllKey(wallet.serializeKeychainToProtobuf());
for (Script script : wallet.getWatchedScripts()) {
Protos.Script protoScript =
Protos.Script.newBuilder()
.setProgram(ByteString.copyFrom(script.getProgram()))
.setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
.build();
walletBuilder.addWatchedScript(protoScript);
}
// Populate the lastSeenBlockHash field.
Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
if (lastSeenBlockHash != null) {
walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
}
if (wallet.getLastBlockSeenTimeSecs() > 0)
walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());
// Populate the scrypt parameters.
KeyCrypter keyCrypter = wallet.getKeyCrypter();
if (keyCrypter == null) {
// The wallet is unencrypted.
walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
} else {
// The wallet is encrypted.
walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
if (keyCrypter instanceof KeyCrypterScrypt) {
KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
} else {
// Some other form of encryption has been specified that we do not know how to persist.
throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
}
}
if (wallet.getKeyRotationTime() != null) {
long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
walletBuilder.setKeyRotationTime(timeSecs);
}
populateExtensions(wallet, walletBuilder);
for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
walletBuilder.addTags(tag);
}
for (TransactionSigner signer : wallet.getTransactionSigners()) {
// do not serialize LocalTransactionSigner as it's being added implicitly
if (signer instanceof LocalTransactionSigner)
continue;
Protos.TransactionSigner.Builder protoSigner = Protos.TransactionSigner.newBuilder();
protoSigner.setClassName(signer.getClass().getName());
protoSigner.setData(ByteString.copyFrom(signer.serialize()));
walletBuilder.addTransactionSigners(protoSigner);
}
// Populate the wallet version.
walletBuilder.setVersion(wallet.getVersion());
return walletBuilder.build();
}
private static void populateExtensions(Wallet wallet, Protos.Wallet.Builder walletBuilder) {
for (WalletExtension extension : wallet.getExtensions().values()) {
Protos.Extension.Builder proto = Protos.Extension.newBuilder();
proto.setId(extension.getWalletExtensionID());
proto.setMandatory(extension.isWalletExtensionMandatory());
proto.setData(ByteString.copyFrom(extension.serializeWalletExtension()));
walletBuilder.addExtension(proto);
}
}
private static Protos.Transaction makeTxProto(WalletTransaction wtx) {
Transaction tx = wtx.getTransaction();
Protos.Transaction.Builder txBuilder = Protos.Transaction.newBuilder();
txBuilder.setPool(getProtoPool(wtx))
.setHash(hashToByteString(tx.getHash()))
.setVersion((int) tx.getVersion());
if (tx.getUpdateTime() != null) {
txBuilder.setUpdatedAt(tx.getUpdateTime().getTime());
}
if (tx.getLockTime() > 0) {
txBuilder.setLockTime((int)tx.getLockTime());
}
// Handle inputs.
for (TransactionInput input : tx.getInputs()) {
Protos.TransactionInput.Builder inputBuilder = Protos.TransactionInput.newBuilder()
.setScriptBytes(ByteString.copyFrom(input.getScriptBytes()))
.setTransactionOutPointHash(hashToByteString(input.getOutpoint().getHash()))
.setTransactionOutPointIndex((int) input.getOutpoint().getIndex());
if (input.hasSequence())
inputBuilder.setSequence((int) input.getSequenceNumber());
if (input.getValue() != null)
inputBuilder.setValue(input.getValue().value);
txBuilder.addTransactionInput(inputBuilder);
}
// Handle outputs.
for (TransactionOutput output : tx.getOutputs()) {
Protos.TransactionOutput.Builder outputBuilder = Protos.TransactionOutput.newBuilder()
.setScriptBytes(ByteString.copyFrom(output.getScriptBytes()))
.setValue(output.getValue().value);
final TransactionInput spentBy = output.getSpentBy();
if (spentBy != null) {
Sha256Hash spendingHash = spentBy.getParentTransaction().getHash();
int spentByTransactionIndex = spentBy.getParentTransaction().getInputs().indexOf(spentBy);
outputBuilder.setSpentByTransactionHash(hashToByteString(spendingHash))
.setSpentByTransactionIndex(spentByTransactionIndex);
}
txBuilder.addTransactionOutput(outputBuilder);
}
// Handle which blocks tx was seen in.
final Map<Sha256Hash, Integer> appearsInHashes = tx.getAppearsInHashes();
if (appearsInHashes != null) {
for (Map.Entry<Sha256Hash, Integer> entry : appearsInHashes.entrySet()) {
txBuilder.addBlockHash(hashToByteString(entry.getKey()));
txBuilder.addBlockRelativityOffsets(entry.getValue());
}
}
if (tx.hasConfidence()) {
TransactionConfidence confidence = tx.getConfidence();
Protos.TransactionConfidence.Builder confidenceBuilder = Protos.TransactionConfidence.newBuilder();
writeConfidence(txBuilder, confidence, confidenceBuilder);
}
Protos.Transaction.Purpose purpose;
switch (tx.getPurpose()) {
case UNKNOWN: purpose = Protos.Transaction.Purpose.UNKNOWN; break;
case USER_PAYMENT: purpose = Protos.Transaction.Purpose.USER_PAYMENT; break;
case KEY_ROTATION: purpose = Protos.Transaction.Purpose.KEY_ROTATION; break;
case ASSURANCE_CONTRACT_CLAIM: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_CLAIM; break;
case ASSURANCE_CONTRACT_PLEDGE: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_PLEDGE; break;
case ASSURANCE_CONTRACT_STUB: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_STUB; break;
default:
throw new RuntimeException("New tx purpose serialization not implemented.");
}
txBuilder.setPurpose(purpose);
ExchangeRate exchangeRate = tx.getExchangeRate();
if (exchangeRate != null) {
Protos.ExchangeRate.Builder exchangeRateBuilder = Protos.ExchangeRate.newBuilder()
.setCoinValue(exchangeRate.coin.value).setFiatValue(exchangeRate.fiat.value)
.setFiatCurrencyCode(exchangeRate.fiat.currencyCode);
txBuilder.setExchangeRate(exchangeRateBuilder);
}
if (tx.getMemo() != null)
txBuilder.setMemo(tx.getMemo());
return txBuilder.build();
}
private static Protos.Transaction.Pool getProtoPool(WalletTransaction wtx) {
switch (wtx.getPool()) {
case UNSPENT: return Protos.Transaction.Pool.UNSPENT;
case SPENT: return Protos.Transaction.Pool.SPENT;
case DEAD: return Protos.Transaction.Pool.DEAD;
case PENDING: return Protos.Transaction.Pool.PENDING;
default:
throw new RuntimeException("Unreachable");
}
}
private static void writeConfidence(Protos.Transaction.Builder txBuilder,
TransactionConfidence confidence,
Protos.TransactionConfidence.Builder confidenceBuilder) {
synchronized (confidence) {
confidenceBuilder.setType(Protos.TransactionConfidence.Type.valueOf(confidence.getConfidenceType().getValue()));
if (confidence.getConfidenceType() == ConfidenceType.BUILDING) {
confidenceBuilder.setAppearedAtHeight(confidence.getAppearedAtChainHeight());
confidenceBuilder.setDepth(confidence.getDepthInBlocks());
}
if (confidence.getConfidenceType() == ConfidenceType.DEAD) {
// Copy in the overriding transaction, if available.
// (A dead coinbase transaction has no overriding transaction).
if (confidence.getOverridingTransaction() != null) {
Sha256Hash overridingHash = confidence.getOverridingTransaction().getHash();
confidenceBuilder.setOverridingTransaction(hashToByteString(overridingHash));
}
}
TransactionConfidence.Source source = confidence.getSource();
switch (source) {
case SELF: confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_SELF); break;
case NETWORK: confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_NETWORK); break;
case UNKNOWN:
// Fall through.
default:
confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_UNKNOWN); break;
}
}
for (PeerAddress address : confidence.getBroadcastBy()) {
Protos.PeerAddress proto = Protos.PeerAddress.newBuilder()
.setIpAddress(ByteString.copyFrom(address.getAddr().getAddress()))
.setPort(address.getPort())
.setServices(address.getServices().longValue())
.build();
confidenceBuilder.addBroadcastBy(proto);
}
txBuilder.setConfidence(confidenceBuilder);
}
public static ByteString hashToByteString(Sha256Hash hash) {
return ByteString.copyFrom(hash.getBytes());
}
public static Sha256Hash byteStringToHash(ByteString bs) {
return new Sha256Hash(bs.toByteArray());
}
/**
* <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily
* useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object
* may be in an indeterminate state and should be thrown away.</p>
*
* <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally
* inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always
* handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p>
*
* @throws UnreadableWalletException thrown in various error conditions (see description).
*/
public Wallet readWallet(InputStream input, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException {
try {
Protos.Wallet walletProto = parseToProto(input);
final String paramsID = walletProto.getNetworkIdentifier();
NetworkParameters params = NetworkParameters.fromID(paramsID);
if (params == null)
throw new UnreadableWalletException("Unknown network parameters ID " + paramsID);
return readWallet(params, walletExtensions, walletProto);
} catch (IOException e) {
throw new UnreadableWalletException("Could not parse input stream to protobuf", e);
} catch (IllegalStateException e) {
throw new UnreadableWalletException("Could not parse input stream to protobuf", e);
}
}
/**
* <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily
* useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object
* may be in an indeterminate state and should be thrown away.</p>
*
* <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally
* inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always
* handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p>
*
* @throws UnreadableWalletException thrown in various error conditions (see description).
*/
public Wallet readWallet(NetworkParameters params, @Nullable WalletExtension[] extensions,
Protos.Wallet walletProto) throws UnreadableWalletException {
if (walletProto.getVersion() > CURRENT_WALLET_VERSION)
throw new UnreadableWalletException.FutureVersion();
if (!walletProto.getNetworkIdentifier().equals(params.getId()))
throw new UnreadableWalletException.WrongNetwork();
// Read the scrypt parameters that specify how encryption and decryption is performed.
KeyChainGroup chain;
if (walletProto.hasEncryptionParameters()) {
Protos.ScryptParameters encryptionParameters = walletProto.getEncryptionParameters();
final KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(encryptionParameters);
chain = KeyChainGroup.fromProtobufEncrypted(params, walletProto.getKeyList(), keyCrypter);
} else {
chain = KeyChainGroup.fromProtobufUnencrypted(params, walletProto.getKeyList());
}
Wallet wallet = factory.create(params, chain);
List<Script> scripts = Lists.newArrayList();
for (Protos.Script protoScript : walletProto.getWatchedScriptList()) {
try {
Script script =
new Script(protoScript.getProgram().toByteArray(),
protoScript.getCreationTimestamp() / 1000);
scripts.add(script);
} catch (ScriptException e) {
throw new UnreadableWalletException("Unparseable script in wallet");
}
}
wallet.addWatchedScripts(scripts);
if (walletProto.hasDescription()) {
wallet.setDescription(walletProto.getDescription());
}
// Read all transactions and insert into the txMap.
for (Protos.Transaction txProto : walletProto.getTransactionList()) {
readTransaction(txProto, wallet.getParams());
}
// Update transaction outputs to point to inputs that spend them
for (Protos.Transaction txProto : walletProto.getTransactionList()) {
WalletTransaction wtx = connectTransactionOutputs(txProto);
wallet.addWalletTransaction(wtx);
}
// Update the lastBlockSeenHash.
if (!walletProto.hasLastSeenBlockHash()) {
wallet.setLastBlockSeenHash(null);
} else {
wallet.setLastBlockSeenHash(byteStringToHash(walletProto.getLastSeenBlockHash()));
}
if (!walletProto.hasLastSeenBlockHeight()) {
wallet.setLastBlockSeenHeight(-1);
} else {
wallet.setLastBlockSeenHeight(walletProto.getLastSeenBlockHeight());
}
// Will default to zero if not present.
wallet.setLastBlockSeenTimeSecs(walletProto.getLastSeenBlockTimeSecs());
if (walletProto.hasKeyRotationTime()) {
wallet.setKeyRotationTime(new Date(walletProto.getKeyRotationTime() * 1000));
}
loadExtensions(wallet, extensions != null ? extensions : new WalletExtension[0], walletProto);
for (Protos.Tag tag : walletProto.getTagsList()) {
wallet.setTag(tag.getTag(), tag.getData());
}
for (Protos.TransactionSigner signerProto : walletProto.getTransactionSignersList()) {
try {
Class signerClass = Class.forName(signerProto.getClassName());
TransactionSigner signer = (TransactionSigner)signerClass.newInstance();
signer.deserialize(signerProto.getData().toByteArray());
wallet.addTransactionSigner(signer);
} catch (Exception e) {
throw new UnreadableWalletException("Unable to deserialize TransactionSigner instance: " +
signerProto.getClassName(), e);
}
}
if (walletProto.hasVersion()) {
wallet.setVersion(walletProto.getVersion());
}
// Make sure the object can be re-used to read another wallet without corruption.
txMap.clear();
return wallet;
}
private void loadExtensions(Wallet wallet, WalletExtension[] extensionsList, Protos.Wallet walletProto) throws UnreadableWalletException {
final Map<String, WalletExtension> extensions = new HashMap<String, WalletExtension>();
for (WalletExtension e : extensionsList)
extensions.put(e.getWalletExtensionID(), e);
// The Wallet object, if subclassed, might have added some extensions to itself already. In that case, don't
// expect them to be passed in, just fetch them here and don't re-add.
extensions.putAll(wallet.getExtensions());
for (Protos.Extension extProto : walletProto.getExtensionList()) {
String id = extProto.getId();
WalletExtension extension = extensions.get(id);
if (extension == null) {
if (extProto.getMandatory()) {
if (requireMandatoryExtensions)
throw new UnreadableWalletException("Unknown mandatory extension in wallet: " + id);
else
log.error("Unknown extension in wallet {}, ignoring", id);
}
} else {
log.info("Loading wallet extension {}", id);
try {
wallet.deserializeExtension(extension, extProto.getData().toByteArray());
} catch (Exception e) {
if (extProto.getMandatory() && requireMandatoryExtensions) {
log.error("Error whilst reading extension {}, failing to read wallet", id, e);
throw new UnreadableWalletException("Could not parse mandatory extension in wallet: " + id);
} else {
log.error("Error whilst reading extension {}, ignoring", id, e);
}
}
}
}
}
/**
* Returns the loaded protocol buffer from the given byte stream. You normally want
* {@link Wallet#loadFromFile(java.io.File)} instead - this method is designed for low level work involving the
* wallet file format itself.
*/
public static Protos.Wallet parseToProto(InputStream input) throws IOException {
return Protos.Wallet.parseFrom(input);
}
private void readTransaction(Protos.Transaction txProto, NetworkParameters params) throws UnreadableWalletException {
Transaction tx = new Transaction(params);
if (txProto.hasUpdatedAt()) {
tx.setUpdateTime(new Date(txProto.getUpdatedAt()));
}
for (Protos.TransactionOutput outputProto : txProto.getTransactionOutputList()) {
Coin value = Coin.valueOf(outputProto.getValue());
byte[] scriptBytes = outputProto.getScriptBytes().toByteArray();
TransactionOutput output = new TransactionOutput(params, tx, value, scriptBytes);
tx.addOutput(output);
}
for (Protos.TransactionInput inputProto : txProto.getTransactionInputList()) {
byte[] scriptBytes = inputProto.getScriptBytes().toByteArray();
TransactionOutPoint outpoint = new TransactionOutPoint(params,
inputProto.getTransactionOutPointIndex() & 0xFFFFFFFFL,
byteStringToHash(inputProto.getTransactionOutPointHash())
);
Coin value = inputProto.hasValue() ? Coin.valueOf(inputProto.getValue()) : null;
TransactionInput input = new TransactionInput(params, tx, scriptBytes, outpoint, value);
if (inputProto.hasSequence()) {
input.setSequenceNumber(inputProto.getSequence());
}
tx.addInput(input);
}
for (int i = 0; i < txProto.getBlockHashCount(); i++) {
ByteString blockHash = txProto.getBlockHash(i);
int relativityOffset = 0;
if (txProto.getBlockRelativityOffsetsCount() > 0)
relativityOffset = txProto.getBlockRelativityOffsets(i);
tx.addBlockAppearance(byteStringToHash(blockHash), relativityOffset);
}
if (txProto.hasLockTime()) {
tx.setLockTime(0xffffffffL & txProto.getLockTime());
}
if (txProto.hasPurpose()) {
switch (txProto.getPurpose()) {
case UNKNOWN: tx.setPurpose(Transaction.Purpose.UNKNOWN); break;
case USER_PAYMENT: tx.setPurpose(Transaction.Purpose.USER_PAYMENT); break;
case KEY_ROTATION: tx.setPurpose(Transaction.Purpose.KEY_ROTATION); break;
case ASSURANCE_CONTRACT_CLAIM: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_CLAIM); break;
case ASSURANCE_CONTRACT_PLEDGE: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_PLEDGE); break;
case ASSURANCE_CONTRACT_STUB: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_STUB); break;
default: throw new RuntimeException("New purpose serialization not implemented");
}
} else {
// Old wallet: assume a user payment as that's the only reason a new tx would have been created back then.
tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
}
if (txProto.hasExchangeRate()) {
Protos.ExchangeRate exchangeRateProto = txProto.getExchangeRate();
tx.setExchangeRate(new ExchangeRate(Coin.valueOf(exchangeRateProto.getCoinValue()), Fiat.valueOf(
exchangeRateProto.getFiatCurrencyCode(), exchangeRateProto.getFiatValue())));
}
if (txProto.hasMemo())
tx.setMemo(txProto.getMemo());
// Transaction should now be complete.
Sha256Hash protoHash = byteStringToHash(txProto.getHash());
if (!tx.getHash().equals(protoHash))
throw new UnreadableWalletException(String.format("Transaction did not deserialize completely: %s vs %s", tx.getHash(), protoHash));
if (txMap.containsKey(txProto.getHash()))
throw new UnreadableWalletException("Wallet contained duplicate transaction " + byteStringToHash(txProto.getHash()));
txMap.put(txProto.getHash(), tx);
}
private WalletTransaction connectTransactionOutputs(com.dogecoindark.dogecoindarkj.wallet.Protos.Transaction txProto) throws UnreadableWalletException {
Transaction tx = txMap.get(txProto.getHash());
final WalletTransaction.Pool pool;
switch (txProto.getPool()) {
case DEAD: pool = WalletTransaction.Pool.DEAD; break;
case PENDING: pool = WalletTransaction.Pool.PENDING; break;
case SPENT: pool = WalletTransaction.Pool.SPENT; break;
case UNSPENT: pool = WalletTransaction.Pool.UNSPENT; break;
// Upgrade old wallets: inactive pool has been merged with the pending pool.
// Remove this some time after 0.9 is old and everyone has upgraded.
// There should not be any spent outputs in this tx as old wallets would not allow them to be spent
// in this state.
case INACTIVE:
case PENDING_INACTIVE:
pool = WalletTransaction.Pool.PENDING;
break;
default:
throw new UnreadableWalletException("Unknown transaction pool: " + txProto.getPool());
}
for (int i = 0 ; i < tx.getOutputs().size() ; i++) {
TransactionOutput output = tx.getOutputs().get(i);
final Protos.TransactionOutput transactionOutput = txProto.getTransactionOutput(i);
if (transactionOutput.hasSpentByTransactionHash()) {
final ByteString spentByTransactionHash = transactionOutput.getSpentByTransactionHash();
Transaction spendingTx = txMap.get(spentByTransactionHash);
if (spendingTx == null) {
throw new UnreadableWalletException(String.format("Could not connect %s to %s",
tx.getHashAsString(), byteStringToHash(spentByTransactionHash)));
}
final int spendingIndex = transactionOutput.getSpentByTransactionIndex();
TransactionInput input = checkNotNull(spendingTx.getInput(spendingIndex));
input.connect(output);
}
}
if (txProto.hasConfidence()) {
Protos.TransactionConfidence confidenceProto = txProto.getConfidence();
TransactionConfidence confidence = tx.getConfidence();
readConfidence(tx, confidenceProto, confidence);
}
return new WalletTransaction(pool, tx);
}
private void readConfidence(Transaction tx, Protos.TransactionConfidence confidenceProto,
TransactionConfidence confidence) throws UnreadableWalletException {
// We are lenient here because tx confidence is not an essential part of the wallet.
// If the tx has an unknown type of confidence, ignore.
if (!confidenceProto.hasType()) {
log.warn("Unknown confidence type for tx {}", tx.getHashAsString());
return;
}
ConfidenceType confidenceType;
switch (confidenceProto.getType()) {
case BUILDING: confidenceType = ConfidenceType.BUILDING; break;
case DEAD: confidenceType = ConfidenceType.DEAD; break;
// These two are equivalent (must be able to read old wallets).
case NOT_IN_BEST_CHAIN: confidenceType = ConfidenceType.PENDING; break;
case PENDING: confidenceType = ConfidenceType.PENDING; break;
case UNKNOWN:
// Fall through.
default:
confidenceType = ConfidenceType.UNKNOWN; break;
}
confidence.setConfidenceType(confidenceType);
if (confidenceProto.hasAppearedAtHeight()) {
if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {
log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getHashAsString());
return;
}
confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight());
}
if (confidenceProto.hasDepth()) {
if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {
log.warn("Have depth but not BUILDING for tx {}", tx.getHashAsString());
return;
}
confidence.setDepthInBlocks(confidenceProto.getDepth());
}
if (confidenceProto.hasOverridingTransaction()) {
if (confidence.getConfidenceType() != ConfidenceType.DEAD) {
log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getHashAsString());
return;
}
Transaction overridingTransaction =
txMap.get(confidenceProto.getOverridingTransaction());
if (overridingTransaction == null) {
log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getHashAsString());
return;
}
confidence.setOverridingTransaction(overridingTransaction);
}
for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) {
InetAddress ip;
try {
ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray());
} catch (UnknownHostException e) {
throw new UnreadableWalletException("Peer IP address does not have the right length", e);
}
int port = proto.getPort();
PeerAddress address = new PeerAddress(ip, port);
address.setServices(BigInteger.valueOf(proto.getServices()));
confidence.markBroadcastBy(address);
}
switch (confidenceProto.getSource()) {
case SOURCE_SELF: confidence.setSource(TransactionConfidence.Source.SELF); break;
case SOURCE_NETWORK: confidence.setSource(TransactionConfidence.Source.NETWORK); break;
case SOURCE_UNKNOWN:
// Fall through.
default: confidence.setSource(TransactionConfidence.Source.UNKNOWN); break;
}
}
/**
* Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
*
* @param is
* input stream to test
* @return true if input stream is a wallet
*/
public static boolean isWallet(InputStream is) {
try {
final CodedInputStream cis = CodedInputStream.newInstance(is);
final int tag = cis.readTag();
final int field = WireFormat.getTagFieldNumber(tag);
if (field != 1) // network_identifier
return false;
final String network = cis.readString();
return NetworkParameters.fromID(network) != null;
} catch (IOException x) {
return false;
}
}
}
| |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core.position.impl;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.opengamma.DataNotFoundException;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.core.change.DummyChangeManager;
import com.opengamma.core.position.Portfolio;
import com.opengamma.core.position.PortfolioNode;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.PositionSource;
import com.opengamma.core.position.Trade;
import com.opengamma.id.IdUtils;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.id.UniqueIdSupplier;
import com.opengamma.id.VersionCorrection;
import com.opengamma.util.ArgumentChecker;
/**
* A simple mutable implementation of a source of positions.
* <p>
* This class is intended for testing scenarios.
* It is not thread-safe and must not be used in production.
*/
public class MockPositionSource implements PositionSource {
// this is currently public for indirect use by another project via ViewTestUtils
/**
* The portfolios.
*/
private final Map<ObjectId, Portfolio> _portfolios = new ConcurrentHashMap<>();
/**
* A cache of nodes by identifier.
*/
private final Map<ObjectId, PortfolioNode> _nodes = new ConcurrentHashMap<>();
/**
* A cache of positions by identifier.
*/
private final Map<ObjectId, Position> _positions = new ConcurrentHashMap<>();
/**
* A cache of trades by identifier.
*/
private final Map<ObjectId, Trade> _trades = new ConcurrentHashMap<>();
/**
* The suppler of unique identifiers.
*/
private final UniqueIdSupplier _uniqueIdSupplier;
/**
* Creates an instance using the default scheme for each {@link UniqueId} created.
*/
public MockPositionSource() {
_uniqueIdSupplier = new UniqueIdSupplier("Mock");
}
//-------------------------------------------------------------------------
@Override
public Portfolio getPortfolio(final UniqueId uniqueId, final VersionCorrection versionCorrection) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
final Portfolio portfolio = _portfolios.get(uniqueId.getObjectId());
if (portfolio == null) {
throw new DataNotFoundException("Portfolio not found: " + uniqueId);
}
return portfolio;
}
@Override
public Portfolio getPortfolio(final ObjectId objectId, final VersionCorrection versionCorrection) {
ArgumentChecker.notNull(objectId, "objectId");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
final Portfolio portfolio = _portfolios.get(objectId);
if (portfolio == null) {
throw new DataNotFoundException("Portfolio not found: " + objectId);
}
return portfolio;
}
@Override
public PortfolioNode getPortfolioNode(final UniqueId uniqueId, final VersionCorrection versionCorrection) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
final PortfolioNode node = _nodes.get(uniqueId.getObjectId());
if (node == null) {
throw new DataNotFoundException("PortfolioNode not found: " + uniqueId);
}
return node;
}
@Override
public Position getPosition(final UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
final Position position = _positions.get(uniqueId.getObjectId());
if (position == null) {
throw new DataNotFoundException("Position not found: " + uniqueId);
}
return position;
}
@Override
public Position getPosition(final ObjectId objectId, final VersionCorrection versionCorrection) {
ArgumentChecker.notNull(objectId, "objectId");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
final Position position = _positions.get(objectId);
if (position == null) {
throw new DataNotFoundException("Position not found: " + objectId);
}
return position;
}
@Override
public Trade getTrade(final UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
final Trade trade = _trades.get(uniqueId.getObjectId());
if (trade == null) {
throw new DataNotFoundException("Trade not found: " + uniqueId);
}
return trade;
}
//-------------------------------------------------------------------------
@Override
public ChangeManager changeManager() {
return DummyChangeManager.INSTANCE;
}
//-------------------------------------------------------------------------
/**
* Gets the list of all portfolio identifiers.
*
* @return the portfolio identifiers, unmodifiable, not null
*/
public Set<ObjectId> getPortfolioIds() {
return _portfolios.keySet();
}
/**
* Adds a portfolio to the master.
*
* @param portfolio the portfolio to add, not null
*/
public void addPortfolio(final Portfolio portfolio) {
ArgumentChecker.notNull(portfolio, "portfolio");
_portfolios.put(portfolio.getUniqueId().getObjectId(), portfolio);
addToCache(portfolio.getUniqueId().getValue(), null, portfolio.getRootNode());
}
/**
* Adds a node to the cache.
*
* @param portfolioId the id, not null
* @param node the node to add, not null
*/
private void addToCache(final String portfolioId, final UniqueId parentNode, final PortfolioNode node) {
// node
if (node instanceof SimplePortfolioNode) {
final SimplePortfolioNode nodeImpl = (SimplePortfolioNode) node;
nodeImpl.setUniqueId(_uniqueIdSupplier.getWithValuePrefix(portfolioId + "-"));
nodeImpl.setParentNodeId(parentNode);
}
_nodes.put(node.getUniqueId().getObjectId(), node);
// position
for (final Position position : node.getPositions()) {
if (position instanceof SimplePosition) {
final SimplePosition positionImpl = (SimplePosition) position;
positionImpl.setUniqueId(_uniqueIdSupplier.getWithValuePrefix(portfolioId + "-"));
//add trades
for (final Trade trade : positionImpl.getTrades()) {
IdUtils.setInto(trade, _uniqueIdSupplier.getWithValuePrefix(portfolioId + "-"));
_trades.put(trade.getUniqueId().getObjectId(), trade);
}
}
_positions.put(position.getUniqueId().getObjectId(), position);
}
// recurse
for (final PortfolioNode child : node.getChildNodes()) {
addToCache(portfolioId, node.getUniqueId(), child);
}
}
/**
* Removes a portfolio from the master.
*
* @param portfolio the portfolio to remove, not null
*/
public void removePortfolio(final Portfolio portfolio) {
ArgumentChecker.notNull(portfolio, "portfolio");
_portfolios.remove(portfolio.getUniqueId().getObjectId());
removeFromCache(portfolio.getRootNode());
}
/**
* Removes a node from the cache
*
* @param node the node to remove, not null
*/
private void removeFromCache(final PortfolioNode node) {
_nodes.remove(node.getUniqueId().getObjectId());
for (final Position position : node.getPositions()) {
for (final Trade trade : position.getTrades()) {
_trades.remove(trade.getUniqueId().getObjectId());
}
_positions.remove(position.getUniqueId().getObjectId());
}
for (final PortfolioNode child : node.getChildNodes()) {
removeFromCache(child);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.repositories.blobstore;
import org.apache.lucene.store.RateLimiter;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.SnapshotId;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.blobstore.BlobContainer;
import org.elasticsearch.common.blobstore.BlobMetaData;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.BlobStore;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.compress.NotXContentException;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.snapshots.IndexShardRepository;
import org.elasticsearch.index.snapshots.blobstore.BlobStoreIndexShardRepository;
import org.elasticsearch.index.snapshots.blobstore.BlobStoreIndexShardRepository.RateLimiterListener;
import org.elasticsearch.repositories.Repository;
import org.elasticsearch.repositories.RepositoryException;
import org.elasticsearch.repositories.RepositorySettings;
import org.elasticsearch.repositories.RepositoryVerificationException;
import org.elasticsearch.snapshots.InvalidSnapshotNameException;
import org.elasticsearch.snapshots.Snapshot;
import org.elasticsearch.snapshots.SnapshotCreationException;
import org.elasticsearch.snapshots.SnapshotException;
import org.elasticsearch.snapshots.SnapshotMissingException;
import org.elasticsearch.snapshots.SnapshotShardFailure;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* BlobStore - based implementation of Snapshot Repository
* <p>
* This repository works with any {@link BlobStore} implementation. The blobStore should be initialized in the derived
* class before {@link #doStart()} is called.
* <p>
* BlobStoreRepository maintains the following structure in the blob store
* <pre>
* {@code
* STORE_ROOT
* |- index - list of all snapshot name as JSON array
* |- snapshot-20131010 - JSON serialized Snapshot for snapshot "20131010"
* |- meta-20131010.dat - JSON serialized MetaData for snapshot "20131010" (includes only global metadata)
* |- snapshot-20131011 - JSON serialized Snapshot for snapshot "20131011"
* |- meta-20131011.dat - JSON serialized MetaData for snapshot "20131011"
* .....
* |- indices/ - data for all indices
* |- foo/ - data for index "foo"
* | |- meta-20131010.dat - JSON Serialized IndexMetaData for index "foo"
* | |- 0/ - data for shard "0" of index "foo"
* | | |- __1 \
* | | |- __2 |
* | | |- __3 |- files from different segments see snapshot-* for their mappings to real segment files
* | | |- __4 |
* | | |- __5 /
* | | .....
* | | |- snap-20131010.dat - JSON serialized BlobStoreIndexShardSnapshot for snapshot "20131010"
* | | |- snap-20131011.dat - JSON serialized BlobStoreIndexShardSnapshot for snapshot "20131011"
* | | |- list-123 - JSON serialized BlobStoreIndexShardSnapshot for snapshot "20131011"
* | |
* | |- 1/ - data for shard "1" of index "foo"
* | | |- __1
* | | .....
* | |
* | |-2/
* | ......
* |
* |- bar/ - data for index bar
* ......
* }
* </pre>
*/
public abstract class BlobStoreRepository extends AbstractLifecycleComponent<Repository> implements Repository, RateLimiterListener {
private BlobContainer snapshotsBlobContainer;
protected final String repositoryName;
private static final String LEGACY_SNAPSHOT_PREFIX = "snapshot-";
private static final String SNAPSHOT_PREFIX = "snap-";
private static final String SNAPSHOT_SUFFIX = ".dat";
private static final String COMMON_SNAPSHOT_PREFIX = "snap";
private static final String SNAPSHOT_CODEC = "snapshot";
private static final String SNAPSHOTS_FILE = "index";
private static final String TESTS_FILE = "tests-";
private static final String METADATA_NAME_FORMAT = "meta-%s.dat";
private static final String LEGACY_METADATA_NAME_FORMAT = "metadata-%s";
private static final String METADATA_CODEC = "metadata";
private static final String INDEX_METADATA_CODEC = "index-metadata";
private static final String SNAPSHOT_NAME_FORMAT = SNAPSHOT_PREFIX + "%s" + SNAPSHOT_SUFFIX;
private static final String LEGACY_SNAPSHOT_NAME_FORMAT = LEGACY_SNAPSHOT_PREFIX + "%s";
private final BlobStoreIndexShardRepository indexShardRepository;
private final RateLimiter snapshotRateLimiter;
private final RateLimiter restoreRateLimiter;
private final CounterMetric snapshotRateLimitingTimeInNanos = new CounterMetric();
private final CounterMetric restoreRateLimitingTimeInNanos = new CounterMetric();
private ChecksumBlobStoreFormat<MetaData> globalMetaDataFormat;
private LegacyBlobStoreFormat<MetaData> globalMetaDataLegacyFormat;
private ChecksumBlobStoreFormat<IndexMetaData> indexMetaDataFormat;
private LegacyBlobStoreFormat<IndexMetaData> indexMetaDataLegacyFormat;
private ChecksumBlobStoreFormat<Snapshot> snapshotFormat;
private LegacyBlobStoreFormat<Snapshot> snapshotLegacyFormat;
private final boolean readOnly;
/**
* Constructs new BlobStoreRepository
*
* @param repositoryName repository name
* @param repositorySettings repository settings
* @param indexShardRepository an instance of IndexShardRepository
*/
protected BlobStoreRepository(String repositoryName, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) {
super(repositorySettings.globalSettings());
this.repositoryName = repositoryName;
this.indexShardRepository = (BlobStoreIndexShardRepository) indexShardRepository;
snapshotRateLimiter = getRateLimiter(repositorySettings, "max_snapshot_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB));
restoreRateLimiter = getRateLimiter(repositorySettings, "max_restore_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB));
readOnly = repositorySettings.settings().getAsBoolean("readonly", false);
}
/**
* {@inheritDoc}
*/
@Override
protected void doStart() {
this.snapshotsBlobContainer = blobStore().blobContainer(basePath());
indexShardRepository.initialize(blobStore(), basePath(), chunkSize(), snapshotRateLimiter, restoreRateLimiter, this, isCompress());
ParseFieldMatcher parseFieldMatcher = new ParseFieldMatcher(settings);
globalMetaDataFormat = new ChecksumBlobStoreFormat<>(METADATA_CODEC, METADATA_NAME_FORMAT, MetaData.PROTO, parseFieldMatcher, isCompress());
globalMetaDataLegacyFormat = new LegacyBlobStoreFormat<>(LEGACY_METADATA_NAME_FORMAT, MetaData.PROTO, parseFieldMatcher);
indexMetaDataFormat = new ChecksumBlobStoreFormat<>(INDEX_METADATA_CODEC, METADATA_NAME_FORMAT, IndexMetaData.PROTO, parseFieldMatcher, isCompress());
indexMetaDataLegacyFormat = new LegacyBlobStoreFormat<>(LEGACY_SNAPSHOT_NAME_FORMAT, IndexMetaData.PROTO, parseFieldMatcher);
snapshotFormat = new ChecksumBlobStoreFormat<>(SNAPSHOT_CODEC, SNAPSHOT_NAME_FORMAT, Snapshot.PROTO, parseFieldMatcher, isCompress());
snapshotLegacyFormat = new LegacyBlobStoreFormat<>(LEGACY_SNAPSHOT_NAME_FORMAT, Snapshot.PROTO, parseFieldMatcher);
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() {
}
/**
* {@inheritDoc}
*/
@Override
protected void doClose() {
try {
blobStore().close();
} catch (Throwable t) {
logger.warn("cannot close blob store", t);
}
}
/**
* Returns initialized and ready to use BlobStore
* <p>
* This method is first called in the {@link #doStart()} method.
*
* @return blob store
*/
abstract protected BlobStore blobStore();
/**
* Returns base path of the repository
*/
abstract protected BlobPath basePath();
/**
* Returns true if metadata and snapshot files should be compressed
*
* @return true if compression is needed
*/
protected boolean isCompress() {
return false;
}
/**
* Returns data file chunk size.
* <p>
* This method should return null if no chunking is needed.
*
* @return chunk size
*/
protected ByteSizeValue chunkSize() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void initializeSnapshot(SnapshotId snapshotId, List<String> indices, MetaData metaData) {
if (readOnly()) {
throw new RepositoryException(this.repositoryName, "cannot create snapshot in a readonly repository");
}
try {
if (snapshotFormat.exists(snapshotsBlobContainer, snapshotId.getSnapshot()) ||
snapshotLegacyFormat.exists(snapshotsBlobContainer, snapshotId.getSnapshot())) {
throw new InvalidSnapshotNameException(snapshotId, "snapshot with such name already exists");
}
// Write Global MetaData
globalMetaDataFormat.write(metaData, snapshotsBlobContainer, snapshotId.getSnapshot());
for (String index : indices) {
final IndexMetaData indexMetaData = metaData.index(index);
final BlobPath indexPath = basePath().add("indices").add(index);
final BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
indexMetaDataFormat.write(indexMetaData, indexMetaDataBlobContainer, snapshotId.getSnapshot());
}
} catch (IOException ex) {
throw new SnapshotCreationException(snapshotId, ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public void deleteSnapshot(SnapshotId snapshotId) {
if (readOnly()) {
throw new RepositoryException(this.repositoryName, "cannot delete snapshot from a readonly repository");
}
List<String> indices = Collections.emptyList();
Snapshot snapshot = null;
try {
snapshot = readSnapshot(snapshotId);
indices = snapshot.indices();
} catch (SnapshotMissingException ex) {
throw ex;
} catch (IllegalStateException | SnapshotException | ElasticsearchParseException ex) {
logger.warn("cannot read snapshot file [{}]", ex, snapshotId);
}
MetaData metaData = null;
try {
if (snapshot != null) {
metaData = readSnapshotMetaData(snapshotId, snapshot.version(), indices, true);
} else {
metaData = readSnapshotMetaData(snapshotId, null, indices, true);
}
} catch (IOException | SnapshotException ex) {
logger.warn("cannot read metadata for snapshot [{}]", ex, snapshotId);
}
try {
// Delete snapshot file first so we wouldn't end up with partially deleted snapshot that looks OK
if (snapshot != null) {
snapshotFormat(snapshot.version()).delete(snapshotsBlobContainer, snapshotId.getSnapshot());
globalMetaDataFormat(snapshot.version()).delete(snapshotsBlobContainer, snapshotId.getSnapshot());
} else {
// We don't know which version was the snapshot created with - try deleting both current and legacy formats
snapshotFormat.delete(snapshotsBlobContainer, snapshotId.getSnapshot());
snapshotLegacyFormat.delete(snapshotsBlobContainer, snapshotId.getSnapshot());
globalMetaDataLegacyFormat.delete(snapshotsBlobContainer, snapshotId.getSnapshot());
globalMetaDataFormat.delete(snapshotsBlobContainer, snapshotId.getSnapshot());
}
// Delete snapshot from the snapshot list
List<SnapshotId> snapshotIds = snapshots();
if (snapshotIds.contains(snapshotId)) {
List<SnapshotId> builder = new ArrayList<>();
for (SnapshotId id : snapshotIds) {
if (!snapshotId.equals(id)) {
builder.add(id);
}
}
snapshotIds = Collections.unmodifiableList(builder);
}
writeSnapshotList(snapshotIds);
// Now delete all indices
for (String index : indices) {
BlobPath indexPath = basePath().add("indices").add(index);
BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
try {
indexMetaDataFormat(snapshot.version()).delete(indexMetaDataBlobContainer, snapshotId.getSnapshot());
} catch (IOException ex) {
logger.warn("[{}] failed to delete metadata for index [{}]", ex, snapshotId, index);
}
if (metaData != null) {
IndexMetaData indexMetaData = metaData.index(index);
if (indexMetaData != null) {
for (int shardId = 0; shardId < indexMetaData.getNumberOfShards(); shardId++) {
try {
indexShardRepository.delete(snapshotId, snapshot.version(), new ShardId(indexMetaData.getIndex(), shardId));
} catch (SnapshotException ex) {
logger.warn("[{}] failed to delete shard data for shard [{}][{}]", ex, snapshotId, index, shardId);
}
}
}
}
}
} catch (IOException ex) {
throw new RepositoryException(this.repositoryName, "failed to update snapshot in repository", ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public Snapshot finalizeSnapshot(SnapshotId snapshotId, List<String> indices, long startTime, String failure, int totalShards, List<SnapshotShardFailure> shardFailures) {
try {
Snapshot blobStoreSnapshot = new Snapshot(snapshotId.getSnapshot(), indices, startTime, failure, System.currentTimeMillis(), totalShards, shardFailures);
snapshotFormat.write(blobStoreSnapshot, snapshotsBlobContainer, snapshotId.getSnapshot());
List<SnapshotId> snapshotIds = snapshots();
if (!snapshotIds.contains(snapshotId)) {
snapshotIds = new ArrayList<>(snapshotIds);
snapshotIds.add(snapshotId);
snapshotIds = Collections.unmodifiableList(snapshotIds);
}
writeSnapshotList(snapshotIds);
return blobStoreSnapshot;
} catch (IOException ex) {
throw new RepositoryException(this.repositoryName, "failed to update snapshot in repository", ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<SnapshotId> snapshots() {
try {
List<SnapshotId> snapshots = new ArrayList<>();
Map<String, BlobMetaData> blobs;
try {
blobs = snapshotsBlobContainer.listBlobsByPrefix(COMMON_SNAPSHOT_PREFIX);
} catch (UnsupportedOperationException ex) {
// Fall back in case listBlobsByPrefix isn't supported by the blob store
return readSnapshotList();
}
int prefixLength = SNAPSHOT_PREFIX.length();
int suffixLength = SNAPSHOT_SUFFIX.length();
int legacyPrefixLength = LEGACY_SNAPSHOT_PREFIX.length();
for (BlobMetaData md : blobs.values()) {
String blobName = md.name();
final String name;
if (blobName.startsWith(SNAPSHOT_PREFIX) && blobName.length() > legacyPrefixLength) {
name = blobName.substring(prefixLength, blobName.length() - suffixLength);
} else if (blobName.startsWith(LEGACY_SNAPSHOT_PREFIX) && blobName.length() > suffixLength + prefixLength) {
name = blobName.substring(legacyPrefixLength);
} else {
// not sure what it was - ignore
continue;
}
snapshots.add(new SnapshotId(repositoryName, name));
}
return Collections.unmodifiableList(snapshots);
} catch (IOException ex) {
throw new RepositoryException(repositoryName, "failed to list snapshots in repository", ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public MetaData readSnapshotMetaData(SnapshotId snapshotId, Snapshot snapshot, List<String> indices) throws IOException {
return readSnapshotMetaData(snapshotId, snapshot.version(), indices, false);
}
/**
* {@inheritDoc}
*/
@Override
public Snapshot readSnapshot(SnapshotId snapshotId) {
try {
return snapshotFormat.read(snapshotsBlobContainer, snapshotId.getSnapshot());
} catch (FileNotFoundException | NoSuchFileException ex) {
// File is missing - let's try legacy format instead
try {
return snapshotLegacyFormat.read(snapshotsBlobContainer, snapshotId.getSnapshot());
} catch (FileNotFoundException | NoSuchFileException ex1) {
throw new SnapshotMissingException(snapshotId, ex);
} catch (IOException | NotXContentException ex1) {
throw new SnapshotException(snapshotId, "failed to get snapshots", ex1);
}
} catch (IOException | NotXContentException ex) {
throw new SnapshotException(snapshotId, "failed to get snapshots", ex);
}
}
private MetaData readSnapshotMetaData(SnapshotId snapshotId, Version snapshotVersion, List<String> indices, boolean ignoreIndexErrors) throws IOException {
MetaData metaData;
if (snapshotVersion == null) {
// When we delete corrupted snapshots we might not know which version we are dealing with
// We can try detecting the version based on the metadata file format
assert ignoreIndexErrors;
if (globalMetaDataFormat.exists(snapshotsBlobContainer, snapshotId.getSnapshot())) {
snapshotVersion = Version.CURRENT;
} else if (globalMetaDataLegacyFormat.exists(snapshotsBlobContainer, snapshotId.getSnapshot())) {
throw new SnapshotException(snapshotId, "snapshot is too old");
} else {
throw new SnapshotMissingException(snapshotId);
}
}
try {
metaData = globalMetaDataFormat(snapshotVersion).read(snapshotsBlobContainer, snapshotId.getSnapshot());
} catch (FileNotFoundException | NoSuchFileException ex) {
throw new SnapshotMissingException(snapshotId, ex);
} catch (IOException ex) {
throw new SnapshotException(snapshotId, "failed to get snapshots", ex);
}
MetaData.Builder metaDataBuilder = MetaData.builder(metaData);
for (String index : indices) {
BlobPath indexPath = basePath().add("indices").add(index);
BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
try {
metaDataBuilder.put(indexMetaDataFormat(snapshotVersion).read(indexMetaDataBlobContainer, snapshotId.getSnapshot()), false);
} catch (ElasticsearchParseException | IOException ex) {
if (ignoreIndexErrors) {
logger.warn("[{}] [{}] failed to read metadata for index", ex, snapshotId, index);
} else {
throw ex;
}
}
}
return metaDataBuilder.build();
}
/**
* Configures RateLimiter based on repository and global settings
*
* @param repositorySettings repository settings
* @param setting setting to use to configure rate limiter
* @param defaultRate default limiting rate
* @return rate limiter or null of no throttling is needed
*/
private RateLimiter getRateLimiter(RepositorySettings repositorySettings, String setting, ByteSizeValue defaultRate) {
ByteSizeValue maxSnapshotBytesPerSec = repositorySettings.settings().getAsBytesSize(setting,
settings.getAsBytesSize(setting, defaultRate));
if (maxSnapshotBytesPerSec.bytes() <= 0) {
return null;
} else {
return new RateLimiter.SimpleRateLimiter(maxSnapshotBytesPerSec.mbFrac());
}
}
/**
* Returns appropriate global metadata format based on the provided version of the snapshot
*/
private BlobStoreFormat<MetaData> globalMetaDataFormat(Version version) {
if(legacyMetaData(version)) {
return globalMetaDataLegacyFormat;
} else {
return globalMetaDataFormat;
}
}
/**
* Returns appropriate snapshot format based on the provided version of the snapshot
*/
private BlobStoreFormat<Snapshot> snapshotFormat(Version version) {
if(legacyMetaData(version)) {
return snapshotLegacyFormat;
} else {
return snapshotFormat;
}
}
/**
* In v2.0.0 we changed the metadata file format
* @return true if legacy version should be used false otherwise
*/
public static boolean legacyMetaData(Version version) {
return version.before(Version.V_2_0_0_beta1);
}
/**
* Returns appropriate index metadata format based on the provided version of the snapshot
*/
private BlobStoreFormat<IndexMetaData> indexMetaDataFormat(Version version) {
if(legacyMetaData(version)) {
return indexMetaDataLegacyFormat;
} else {
return indexMetaDataFormat;
}
}
/**
* Writes snapshot index file
* <p>
* This file can be used by read-only repositories that are unable to list files in the repository
*
* @param snapshots list of snapshot ids
* @throws IOException I/O errors
*/
protected void writeSnapshotList(List<SnapshotId> snapshots) throws IOException {
final BytesReference bRef;
try(BytesStreamOutput bStream = new BytesStreamOutput()) {
try(StreamOutput stream = new OutputStreamStreamOutput(bStream)) {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
builder.startObject();
builder.startArray("snapshots");
for (SnapshotId snapshot : snapshots) {
builder.value(snapshot.getSnapshot());
}
builder.endArray();
builder.endObject();
builder.close();
}
bRef = bStream.bytes();
}
if (snapshotsBlobContainer.blobExists(SNAPSHOTS_FILE)) {
snapshotsBlobContainer.deleteBlob(SNAPSHOTS_FILE);
}
snapshotsBlobContainer.writeBlob(SNAPSHOTS_FILE, bRef);
}
/**
* Reads snapshot index file
* <p>
* This file can be used by read-only repositories that are unable to list files in the repository
*
* @return list of snapshots in the repository
* @throws IOException I/O errors
*/
protected List<SnapshotId> readSnapshotList() throws IOException {
try (InputStream blob = snapshotsBlobContainer.readBlob(SNAPSHOTS_FILE)) {
BytesStreamOutput out = new BytesStreamOutput();
Streams.copy(blob, out);
ArrayList<SnapshotId> snapshots = new ArrayList<>();
try (XContentParser parser = XContentHelper.createParser(out.bytes())) {
if (parser.nextToken() == XContentParser.Token.START_OBJECT) {
if (parser.nextToken() == XContentParser.Token.FIELD_NAME) {
String currentFieldName = parser.currentName();
if ("snapshots".equals(currentFieldName)) {
if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
snapshots.add(new SnapshotId(repositoryName, parser.text()));
}
}
}
}
}
}
return Collections.unmodifiableList(snapshots);
}
}
@Override
public void onRestorePause(long nanos) {
restoreRateLimitingTimeInNanos.inc(nanos);
}
@Override
public void onSnapshotPause(long nanos) {
snapshotRateLimitingTimeInNanos.inc(nanos);
}
@Override
public long snapshotThrottleTimeInNanos() {
return snapshotRateLimitingTimeInNanos.count();
}
@Override
public long restoreThrottleTimeInNanos() {
return restoreRateLimitingTimeInNanos.count();
}
@Override
public String startVerification() {
try {
if (readOnly()) {
// It's readonly - so there is not much we can do here to verify it
return null;
} else {
String seed = Strings.randomBase64UUID();
byte[] testBytes = Strings.toUTF8Bytes(seed);
BlobContainer testContainer = blobStore().blobContainer(basePath().add(testBlobPrefix(seed)));
String blobName = "master.dat";
testContainer.writeBlob(blobName + "-temp", new BytesArray(testBytes));
// Make sure that move is supported
testContainer.move(blobName + "-temp", blobName);
return seed;
}
} catch (IOException exp) {
throw new RepositoryVerificationException(repositoryName, "path " + basePath() + " is not accessible on master node", exp);
}
}
@Override
public void endVerification(String seed) {
if (readOnly()) {
throw new UnsupportedOperationException("shouldn't be called");
}
try {
blobStore().delete(basePath().add(testBlobPrefix(seed)));
} catch (IOException exp) {
throw new RepositoryVerificationException(repositoryName, "cannot delete test data at " + basePath(), exp);
}
}
public static String testBlobPrefix(String seed) {
return TESTS_FILE + seed;
}
@Override
public boolean readOnly() {
return readOnly;
}
}
| |
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.app.Notification;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;
import android.widget.RemoteViews;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.TestOnly;
import static com.squareup.picasso.BitmapHunter.forRequest;
import static com.squareup.picasso.MemoryPolicy.NO_CACHE;
import static com.squareup.picasso.MemoryPolicy.NO_STORE;
import static com.squareup.picasso.MemoryPolicy.shouldReadFromMemoryCache;
import static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;
import static com.squareup.picasso.Picasso.Priority;
import static com.squareup.picasso.PicassoDrawable.setBitmap;
import static com.squareup.picasso.PicassoDrawable.setPlaceholder;
import static com.squareup.picasso.RemoteViewsAction.AppWidgetAction;
import static com.squareup.picasso.RemoteViewsAction.NotificationAction;
import static com.squareup.picasso.Utils.OWNER_MAIN;
import static com.squareup.picasso.Utils.VERB_CHANGED;
import static com.squareup.picasso.Utils.VERB_COMPLETED;
import static com.squareup.picasso.Utils.VERB_CREATED;
import static com.squareup.picasso.Utils.checkMain;
import static com.squareup.picasso.Utils.checkNotMain;
import static com.squareup.picasso.Utils.createKey;
import static com.squareup.picasso.Utils.log;
/** Fluent API for building an image download request. */
@SuppressWarnings("UnusedDeclaration") // Public API.
public class RequestCreator {
private static final AtomicInteger nextId = new AtomicInteger();
private final Picasso picasso;
private final Request.Builder data;
private boolean noFade;
private boolean deferred;
private boolean setPlaceholder = true;
private int placeholderResId;
private int errorResId;
private int memoryPolicy;
private int networkPolicy;
private Drawable placeholderDrawable;
private Drawable errorDrawable;
private Object tag;
RequestCreator(Picasso picasso, Uri uri, int resourceId) {
if (picasso.shutdown) {
throw new IllegalStateException(
"Picasso instance already shut down. Cannot submit new requests.");
}
this.picasso = picasso;
this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
}
@TestOnly RequestCreator() {
this.picasso = null;
this.data = new Request.Builder(null, 0, null);
}
/**
* Explicitly opt-out to having a placeholder set when calling {@code into}.
* <p>
* By default, Picasso will either set a supplied placeholder or clear the target
* {@link ImageView} in order to ensure behavior in situations where views are recycled. This
* method will prevent that behavior and retain any already set image.
*/
public RequestCreator noPlaceholder() {
if (placeholderResId != 0) {
throw new IllegalStateException("Placeholder resource already set.");
}
if (placeholderDrawable != null) {
throw new IllegalStateException("Placeholder image already set.");
}
setPlaceholder = false;
return this;
}
/**
* A placeholder drawable to be used while the image is being loaded. If the requested image is
* not immediately available in the memory cache then this resource will be set on the target
* {@link ImageView}.
*/
public RequestCreator placeholder(int placeholderResId) {
if (!setPlaceholder) {
throw new IllegalStateException("Already explicitly declared as no placeholder.");
}
if (placeholderResId == 0) {
throw new IllegalArgumentException("Placeholder image resource invalid.");
}
if (placeholderDrawable != null) {
throw new IllegalStateException("Placeholder image already set.");
}
this.placeholderResId = placeholderResId;
return this;
}
/**
* A placeholder drawable to be used while the image is being loaded. If the requested image is
* not immediately available in the memory cache then this resource will be set on the target
* {@link ImageView}.
* <p>
* If you are not using a placeholder image but want to clear an existing image (such as when
* used in an {@link android.widget.Adapter adapter}), pass in {@code null}.
*/
public RequestCreator placeholder(Drawable placeholderDrawable) {
if (!setPlaceholder) {
throw new IllegalStateException("Already explicitly declared as no placeholder.");
}
if (placeholderResId != 0) {
throw new IllegalStateException("Placeholder image already set.");
}
this.placeholderDrawable = placeholderDrawable;
return this;
}
/** An error drawable to be used if the request image could not be loaded. */
public RequestCreator error(int errorResId) {
if (errorResId == 0) {
throw new IllegalArgumentException("Error image resource invalid.");
}
if (errorDrawable != null) {
throw new IllegalStateException("Error image already set.");
}
this.errorResId = errorResId;
return this;
}
/** An error drawable to be used if the request image could not be loaded. */
public RequestCreator error(Drawable errorDrawable) {
if (errorDrawable == null) {
throw new IllegalArgumentException("Error image may not be null.");
}
if (errorResId != 0) {
throw new IllegalStateException("Error image already set.");
}
this.errorDrawable = errorDrawable;
return this;
}
/**
* Assign a tag to this request. Tags are an easy way to logically associate
* related requests that can be managed together e.g. paused, resumed,
* or canceled.
* <p>
* You can either use simple {@link String} tags or objects that naturally
* define the scope of your requests within your app such as a
* {@link android.content.Context}, an {@link android.app.Activity}, or a
* {@link android.app.Fragment}.
*
* <strong>WARNING:</strong>: Picasso will keep a reference to the tag for
* as long as this tag is paused and/or has active requests. Look out for
* potential leaks.
*
* @see Picasso#cancelTag(Object)
* @see Picasso#pauseTag(Object)
* @see Picasso#resumeTag(Object)
*/
public RequestCreator tag(Object tag) {
if (tag == null) {
throw new IllegalArgumentException("Tag invalid.");
}
if (this.tag != null) {
throw new IllegalStateException("Tag already set.");
}
this.tag = tag;
return this;
}
/**
* Attempt to resize the image to fit exactly into the target {@link ImageView}'s bounds. This
* will result in delayed execution of the request until the {@link ImageView} has been laid out.
* <p>
* <em>Note:</em> This method works only when your target is an {@link ImageView}.
*/
public RequestCreator fit() {
deferred = true;
return this;
}
/** Internal use only. Used by {@link DeferredRequestCreator}. */
RequestCreator unfit() {
deferred = false;
return this;
}
/** Resize the image to the specified dimension size. */
public RequestCreator resizeDimen(int targetWidthResId, int targetHeightResId) {
Resources resources = picasso.context.getResources();
int targetWidth = resources.getDimensionPixelSize(targetWidthResId);
int targetHeight = resources.getDimensionPixelSize(targetHeightResId);
return resize(targetWidth, targetHeight);
}
/** Resize the image to the specified size in pixels. */
public RequestCreator resize(int targetWidth, int targetHeight) {
data.resize(targetWidth, targetHeight);
return this;
}
/**
* Crops an image inside of the bounds specified by {@link #resize(int, int)} rather than
* distorting the aspect ratio. This cropping technique scales the image so that it fills the
* requested bounds and then crops the extra.
*/
public RequestCreator centerCrop() {
data.centerCrop();
return this;
}
/**
* Centers an image inside of the bounds specified by {@link #resize(int, int)}. This scales
* the image so that both dimensions are equal to or less than the requested bounds.
*/
public RequestCreator centerInside() {
data.centerInside();
return this;
}
/**
* Only resize an image if the original image size is bigger than the target size
* specified by {@link #resize(int, int)}.
*/
public RequestCreator onlyScaleDown() {
data.onlyScaleDown();
return this;
}
/** Rotate the image by the specified degrees. */
public RequestCreator rotate(float degrees) {
data.rotate(degrees);
return this;
}
/** Rotate the image by the specified degrees around a pivot point. */
public RequestCreator rotate(float degrees, float pivotX, float pivotY) {
data.rotate(degrees, pivotX, pivotY);
return this;
}
/**
* Attempt to decode the image using the specified config.
* <p>
* Note: This value may be ignored by {@link BitmapFactory}. See
* {@link BitmapFactory.Options#inPreferredConfig its documentation} for more details.
*/
public RequestCreator config(Bitmap.Config config) {
data.config(config);
return this;
}
/**
* Sets the stable key for this request to be used instead of the URI or resource ID when
* caching. Two requests with the same value are considered to be for the same resource.
*/
public RequestCreator stableKey(String stableKey) {
data.stableKey(stableKey);
return this;
}
/**
* Set the priority of this request.
* <p>
* This will affect the order in which the requests execute but does not guarantee it.
* By default, all requests have {@link Priority#NORMAL} priority, except for
* {@link #fetch()} requests, which have {@link Priority#LOW} priority by default.
*/
public RequestCreator priority(Priority priority) {
data.priority(priority);
return this;
}
/**
* Add a custom transformation to be applied to the image.
* <p>
* Custom transformations will always be run after the built-in transformations.
*/
// TODO show example of calling resize after a transform in the javadoc
public RequestCreator transform(Transformation transformation) {
data.transform(transformation);
return this;
}
/**
* Add a list of custom transformations to be applied to the image.
* <p>
* Custom transformations will always be run after the built-in transformations.
*/
public RequestCreator transform(List<? extends Transformation> transformations) {
data.transform(transformations);
return this;
}
/**
* @deprecated Use {@link #memoryPolicy(MemoryPolicy, MemoryPolicy...)} instead.
*/
@Deprecated public RequestCreator skipMemoryCache() {
return memoryPolicy(NO_CACHE, NO_STORE);
}
/**
* Specifies the {@link MemoryPolicy} to use for this request. You may specify additional policy
* options using the varargs parameter.
*/
public RequestCreator memoryPolicy(MemoryPolicy policy, MemoryPolicy... additional) {
if (policy == null) {
throw new IllegalArgumentException("Memory policy cannot be null.");
}
this.memoryPolicy |= policy.index;
if (additional == null) {
throw new IllegalArgumentException("Memory policy cannot be null.");
}
if (additional.length > 0) {
for (MemoryPolicy memoryPolicy : additional) {
if (memoryPolicy == null) {
throw new IllegalArgumentException("Memory policy cannot be null.");
}
this.memoryPolicy |= memoryPolicy.index;
}
}
return this;
}
/**
* Specifies the {@link NetworkPolicy} to use for this request. You may specify additional policy
* options using the varargs parameter.
*/
public RequestCreator networkPolicy(NetworkPolicy policy, NetworkPolicy... additional) {
if (policy == null) {
throw new IllegalArgumentException("Network policy cannot be null.");
}
this.networkPolicy |= policy.index;
if (additional == null) {
throw new IllegalArgumentException("Network policy cannot be null.");
}
if (additional.length > 0) {
for (NetworkPolicy networkPolicy : additional) {
if (networkPolicy == null) {
throw new IllegalArgumentException("Network policy cannot be null.");
}
this.networkPolicy |= networkPolicy.index;
}
}
return this;
}
/** Disable brief fade in of images loaded from the disk cache or network. */
public RequestCreator noFade() {
noFade = true;
return this;
}
/**
* Synchronously fulfill this request. Must not be called from the main thread.
* <p>
* <em>Note</em>: The result of this operation is not cached in memory because the underlying
* {@link Cache} implementation is not guaranteed to be thread-safe.
*/
public Bitmap get() throws IOException {
long started = System.nanoTime();
checkNotMain();
if (deferred) {
throw new IllegalStateException("Fit cannot be used with get.");
}
if (!data.hasImage()) {
return null;
}
Request finalData = createRequest(started);
String key = createKey(finalData, new StringBuilder());
Action action = new GetAction(picasso, finalData, memoryPolicy, networkPolicy, tag, key);
return forRequest(picasso, picasso.dispatcher, picasso.cache, picasso.stats, action).hunt();
}
/**
* Asynchronously fulfills the request without a {@link ImageView} or {@link Target}. This is
* useful when you want to warm up the cache with an image.
* <p>
* <em>Note:</em> It is safe to invoke this method from any thread.
*/
public void fetch() {
fetch(null);
}
/**
* Asynchronously fulfills the request without a {@link ImageView} or {@link Target},
* and invokes the target {@link Callback} with the result. This is useful when you want to warm
* up the cache with an image.
* <p>
* <em>Note:</em> The {@link Callback} param is a strong reference and will prevent your
* {@link android.app.Activity} or {@link android.app.Fragment} from being garbage collected
* until the request is completed.
*/
public void fetch(Callback callback) {
long started = System.nanoTime();
if (deferred) {
throw new IllegalStateException("Fit cannot be used with fetch.");
}
if (data.hasImage()) {
// Fetch requests have lower priority by default.
if (!data.hasPriority()) {
data.priority(Priority.LOW);
}
Request request = createRequest(started);
String key = createKey(request, new StringBuilder());
Bitmap bitmap = picasso.quickMemoryCacheCheck(key);
if (bitmap != null) {
if (picasso.loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
}
if (callback != null) {
callback.onSuccess();
}
} else {
Action action =
new FetchAction(picasso, request, memoryPolicy, networkPolicy, tag, key, callback);
picasso.submit(action);
}
}
}
/**
* Asynchronously fulfills the request into the specified {@link Target}. In most cases, you
* should use this when you are dealing with a custom {@link android.view.View View} or view
* holder which should implement the {@link Target} interface.
* <p>
* Implementing on a {@link android.view.View View}:
* <blockquote><pre>
* public class ProfileView extends FrameLayout implements Target {
* {@literal @}Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
* setBackgroundDrawable(new BitmapDrawable(bitmap));
* }
*
* {@literal @}Override public void onBitmapFailed() {
* setBackgroundResource(R.drawable.profile_error);
* }
*
* {@literal @}Override public void onPrepareLoad(Drawable placeHolderDrawable) {
* frame.setBackgroundDrawable(placeHolderDrawable);
* }
* }
* </pre></blockquote>
* Implementing on a view holder object for use inside of an adapter:
* <blockquote><pre>
* public class ViewHolder implements Target {
* public FrameLayout frame;
* public TextView name;
*
* {@literal @}Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
* frame.setBackgroundDrawable(new BitmapDrawable(bitmap));
* }
*
* {@literal @}Override public void onBitmapFailed() {
* frame.setBackgroundResource(R.drawable.profile_error);
* }
*
* {@literal @}Override public void onPrepareLoad(Drawable placeHolderDrawable) {
* frame.setBackgroundDrawable(placeHolderDrawable);
* }
* }
* </pre></blockquote>
* <p>
* <em>Note:</em> This method keeps a weak reference to the {@link Target} instance and will be
* garbage collected if you do not keep a strong reference to it. To receive callbacks when an
* image is loaded use {@link #into(android.widget.ImageView, Callback)}.
*/
public void into(Target target) {
long started = System.nanoTime();
checkMain();
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
if (deferred) {
throw new IllegalStateException("Fit cannot be used with a Target.");
}
if (!data.hasImage()) {
picasso.cancelRequest(target);
target.onPrepareLoad(setPlaceholder ? getPlaceholderDrawable() : null);
return;
}
Request request = createRequest(started);
String requestKey = createKey(request);
if (shouldReadFromMemoryCache(memoryPolicy)) {
Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
if (bitmap != null) {
picasso.cancelRequest(target);
target.onBitmapLoaded(bitmap, MEMORY);
return;
}
}
target.onPrepareLoad(setPlaceholder ? getPlaceholderDrawable() : null);
Action action =
new TargetAction(picasso, target, request, memoryPolicy, networkPolicy, errorDrawable,
requestKey, tag, errorResId);
picasso.enqueueAndSubmit(action);
}
/**
* Asynchronously fulfills the request into the specified {@link RemoteViews} object with the
* given {@code viewId}. This is used for loading bitmaps into a {@link Notification}.
*/
public void into(RemoteViews remoteViews, int viewId, int notificationId,
Notification notification) {
into(remoteViews, viewId, notificationId, notification, null);
}
/**
* Asynchronously fulfills the request into the specified {@link RemoteViews} object with the
* given {@code viewId}. This is used for loading bitmaps into a {@link Notification}.
*/
public void into(RemoteViews remoteViews, int viewId, int notificationId,
Notification notification, String notificationTag) {
long started = System.nanoTime();
if (remoteViews == null) {
throw new IllegalArgumentException("RemoteViews must not be null.");
}
if (notification == null) {
throw new IllegalArgumentException("Notification must not be null.");
}
if (deferred) {
throw new IllegalStateException("Fit cannot be used with RemoteViews.");
}
if (placeholderDrawable != null || placeholderResId != 0 || errorDrawable != null) {
throw new IllegalArgumentException(
"Cannot use placeholder or error drawables with remote views.");
}
Request request = createRequest(started);
String key = createKey(request, new StringBuilder()); // Non-main thread needs own builder.
RemoteViewsAction action =
new NotificationAction(picasso, request, remoteViews, viewId, notificationId, notification,
notificationTag, memoryPolicy, networkPolicy, key, tag, errorResId);
performRemoteViewInto(action);
}
/**
* Asynchronously fulfills the request into the specified {@link RemoteViews} object with the
* given {@code viewId}. This is used for loading bitmaps into all instances of a widget.
*/
public void into(RemoteViews remoteViews, int viewId, int[] appWidgetIds) {
long started = System.nanoTime();
if (remoteViews == null) {
throw new IllegalArgumentException("remoteViews must not be null.");
}
if (appWidgetIds == null) {
throw new IllegalArgumentException("appWidgetIds must not be null.");
}
if (deferred) {
throw new IllegalStateException("Fit cannot be used with remote views.");
}
if (placeholderDrawable != null || placeholderResId != 0 || errorDrawable != null) {
throw new IllegalArgumentException(
"Cannot use placeholder or error drawables with remote views.");
}
Request request = createRequest(started);
String key = createKey(request, new StringBuilder()); // Non-main thread needs own builder.
RemoteViewsAction action =
new AppWidgetAction(picasso, request, remoteViews, viewId, appWidgetIds, memoryPolicy,
networkPolicy, key, tag, errorResId);
performRemoteViewInto(action);
}
/**
* Asynchronously fulfills the request into the specified {@link ImageView}.
* <p>
* <em>Note:</em> This method keeps a weak reference to the {@link ImageView} instance and will
* automatically support object recycling.
*/
public void into(ImageView target) {
into(target, null);
}
/**
* Asynchronously fulfills the request into the specified {@link ImageView} and invokes the
* target {@link Callback} if it's not {@code null}.
* <p>
* <em>Note:</em> The {@link Callback} param is a strong reference and will prevent your
* {@link android.app.Activity} or {@link android.app.Fragment} from being garbage collected. If
* you use this method, it is <b>strongly</b> recommended you invoke an adjacent
* {@link Picasso#cancelRequest(android.widget.ImageView)} call to prevent temporary leaking.
*/
public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
checkMain();
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
if (!data.hasImage()) {
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
if (deferred) {
if (data.hasSize()) {
throw new IllegalStateException("Fit cannot be used with resize.");
}
int width = target.getWidth();
int height = target.getHeight();
if (width == 0 || height == 0) {
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
picasso.defer(target, new DeferredRequestCreator(this, target, callback));
return;
}
data.resize(width, height);
}
Request request = createRequest(started);
String requestKey = createKey(request);
if (shouldReadFromMemoryCache(memoryPolicy)) {
Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
if (bitmap != null) {
picasso.cancelRequest(target);
setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
if (picasso.loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
}
if (callback != null) {
callback.onSuccess();
}
return;
}
}
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action);
}
private Drawable getPlaceholderDrawable() {
if (placeholderResId != 0) {
return picasso.context.getResources().getDrawable(placeholderResId);
} else {
return placeholderDrawable; // This may be null which is expected and desired behavior.
}
}
/** Create the request optionally passing it through the request transformer. */
private Request createRequest(long started) {
int id = nextId.getAndIncrement();
Request request = data.build();
request.id = id;
request.started = started;
boolean loggingEnabled = picasso.loggingEnabled;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
}
Request transformed = picasso.transformRequest(request);
if (transformed != request) {
// If the request was changed, copy over the id and timestamp from the original.
transformed.id = id;
transformed.started = started;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
}
}
return transformed;
}
private void performRemoteViewInto(RemoteViewsAction action) {
if (shouldReadFromMemoryCache(memoryPolicy)) {
Bitmap bitmap = picasso.quickMemoryCacheCheck(action.getKey());
if (bitmap != null) {
action.complete(bitmap, MEMORY);
return;
}
}
if (placeholderResId != 0) {
action.setImageResource(placeholderResId);
}
picasso.enqueueAndSubmit(action);
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* def
*/
package com.microsoft.azure.management.servicebus.v2015_08_01.implementation;
import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl;
import com.microsoft.azure.management.servicebus.v2015_08_01.Namespaces;
import com.microsoft.azure.management.servicebus.v2015_08_01.NamespaceResource;
import rx.Observable;
import rx.Completable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import com.microsoft.azure.arm.resources.ResourceUtilsCore;
import com.microsoft.azure.arm.utils.RXMapper;
import rx.functions.Func1;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.servicebus.v2015_08_01.CheckNameAvailabilityResult;
import com.microsoft.azure.management.servicebus.v2015_08_01.NamespaceSharedAccessAuthorizationRuleResource;
import com.microsoft.azure.management.servicebus.v2015_08_01.ResourceListKeys;
class NamespacesImpl extends GroupableResourcesCoreImpl<NamespaceResource, NamespaceResourceImpl, NamespaceResourceInner, NamespacesInner, ServiceBusManager> implements Namespaces {
protected NamespacesImpl(ServiceBusManager manager) {
super(manager.inner().namespaces(), manager);
}
@Override
protected Observable<NamespaceResourceInner> getInnerAsync(String resourceGroupName, String name) {
NamespacesInner client = this.inner();
return client.getByResourceGroupAsync(resourceGroupName, name);
}
@Override
protected Completable deleteInnerAsync(String resourceGroupName, String name) {
NamespacesInner client = this.inner();
return client.deleteAsync(resourceGroupName, name).toCompletable();
}
@Override
public Observable<String> deleteByIdsAsync(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return Observable.empty();
}
Collection<Observable<String>> observables = new ArrayList<>();
for (String id : ids) {
final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id);
final String name = ResourceUtilsCore.nameFromResourceId(id);
Observable<String> o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id);
observables.add(o);
}
return Observable.mergeDelayError(observables);
}
@Override
public Observable<String> deleteByIdsAsync(String...ids) {
return this.deleteByIdsAsync(new ArrayList<String>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).toBlocking().last();
}
}
@Override
public void deleteByIds(String...ids) {
this.deleteByIds(new ArrayList<String>(Arrays.asList(ids)));
}
@Override
public PagedList<NamespaceResource> listByResourceGroup(String resourceGroupName) {
NamespacesInner client = this.inner();
return this.wrapList(client.listByResourceGroup(resourceGroupName));
}
@Override
public Observable<NamespaceResource> listByResourceGroupAsync(String resourceGroupName) {
NamespacesInner client = this.inner();
return client.listByResourceGroupAsync(resourceGroupName)
.flatMapIterable(new Func1<Page<NamespaceResourceInner>, Iterable<NamespaceResourceInner>>() {
@Override
public Iterable<NamespaceResourceInner> call(Page<NamespaceResourceInner> page) {
return page.items();
}
})
.map(new Func1<NamespaceResourceInner, NamespaceResource>() {
@Override
public NamespaceResource call(NamespaceResourceInner inner) {
return wrapModel(inner);
}
});
}
@Override
public PagedList<NamespaceResource> list() {
NamespacesInner client = this.inner();
return this.wrapList(client.list());
}
@Override
public Observable<NamespaceResource> listAsync() {
NamespacesInner client = this.inner();
return client.listAsync()
.flatMapIterable(new Func1<Page<NamespaceResourceInner>, Iterable<NamespaceResourceInner>>() {
@Override
public Iterable<NamespaceResourceInner> call(Page<NamespaceResourceInner> page) {
return page.items();
}
})
.map(new Func1<NamespaceResourceInner, NamespaceResource>() {
@Override
public NamespaceResource call(NamespaceResourceInner inner) {
return wrapModel(inner);
}
});
}
@Override
public NamespaceResourceImpl define(String name) {
return wrapModel(name);
}
@Override
public Observable<CheckNameAvailabilityResult> checkNameAvailabilityMethodAsync(String name) {
NamespacesInner client = this.inner();
return client.checkNameAvailabilityMethodAsync(name)
.map(new Func1<CheckNameAvailabilityResultInner, CheckNameAvailabilityResult>() {
@Override
public CheckNameAvailabilityResult call(CheckNameAvailabilityResultInner inner) {
return new CheckNameAvailabilityResultImpl(inner, manager());
}
});
}
@Override
protected NamespaceResourceImpl wrapModel(NamespaceResourceInner inner) {
return new NamespaceResourceImpl(inner.name(), inner, manager());
}
@Override
protected NamespaceResourceImpl wrapModel(String name) {
return new NamespaceResourceImpl(name, new NamespaceResourceInner(), this.manager());
}
@Override
public NamespaceSharedAccessAuthorizationRuleResourceImpl defineAuthorizationRule(String name) {
return wrapAuthorizationRuleModel(name);
}
private NamespaceSharedAccessAuthorizationRuleResourceImpl wrapAuthorizationRuleModel(String name) {
return new NamespaceSharedAccessAuthorizationRuleResourceImpl(name, this.manager());
}
private NamespaceSharedAccessAuthorizationRuleResourceImpl wrapNamespaceSharedAccessAuthorizationRuleResourceModel(SharedAccessAuthorizationRuleResourceInner inner) {
return new NamespaceSharedAccessAuthorizationRuleResourceImpl(inner, manager());
}
private Observable<SharedAccessAuthorizationRuleResourceInner> getSharedAccessAuthorizationRuleResourceInnerUsingNamespacesInnerAsync(String id) {
String resourceGroupName = IdParsingUtils.getValueFromIdByName(id, "resourceGroups");
String namespaceName = IdParsingUtils.getValueFromIdByName(id, "namespaces");
String authorizationRuleName = IdParsingUtils.getValueFromIdByName(id, "AuthorizationRules");
NamespacesInner client = this.inner();
return client.getAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName);
}
@Override
public Observable<NamespaceSharedAccessAuthorizationRuleResource> getAuthorizationRuleAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
NamespacesInner client = this.inner();
return client.getAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName)
.map(new Func1<SharedAccessAuthorizationRuleResourceInner, NamespaceSharedAccessAuthorizationRuleResource>() {
@Override
public NamespaceSharedAccessAuthorizationRuleResource call(SharedAccessAuthorizationRuleResourceInner inner) {
return wrapNamespaceSharedAccessAuthorizationRuleResourceModel(inner);
}
});
}
@Override
public Observable<NamespaceSharedAccessAuthorizationRuleResource> listAuthorizationRulesAsync(final String resourceGroupName, final String namespaceName) {
NamespacesInner client = this.inner();
return client.listAuthorizationRulesAsync(resourceGroupName, namespaceName)
.flatMapIterable(new Func1<Page<SharedAccessAuthorizationRuleResourceInner>, Iterable<SharedAccessAuthorizationRuleResourceInner>>() {
@Override
public Iterable<SharedAccessAuthorizationRuleResourceInner> call(Page<SharedAccessAuthorizationRuleResourceInner> page) {
return page.items();
}
})
.map(new Func1<SharedAccessAuthorizationRuleResourceInner, NamespaceSharedAccessAuthorizationRuleResource>() {
@Override
public NamespaceSharedAccessAuthorizationRuleResource call(SharedAccessAuthorizationRuleResourceInner inner) {
return wrapNamespaceSharedAccessAuthorizationRuleResourceModel(inner);
}
});
}
@Override
public Completable deleteAuthorizationRuleAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
NamespacesInner client = this.inner();
return client.deleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName).toCompletable();
}
@Override
public Observable<ResourceListKeys> listKeysAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
NamespacesInner client = this.inner();
return client.listKeysAsync(resourceGroupName, namespaceName, authorizationRuleName)
.map(new Func1<ResourceListKeysInner, ResourceListKeys>() {
@Override
public ResourceListKeys call(ResourceListKeysInner inner) {
return new ResourceListKeysImpl(inner, manager());
}
});
}
@Override
public Observable<ResourceListKeys> regenerateKeysAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
NamespacesInner client = this.inner();
return client.regenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName)
.map(new Func1<ResourceListKeysInner, ResourceListKeys>() {
@Override
public ResourceListKeys call(ResourceListKeysInner inner) {
return new ResourceListKeysImpl(inner, manager());
}
});
}
}
| |
/**
* Copyright (C) 2015 - present McLeod Moores Software Limited, All rights reserved.
*
* Please see distribution for license.
*/
package com.mcleodmoores.starling.client.component;
import com.mcleodmoores.starling.client.config.ConfigManager;
import com.mcleodmoores.starling.client.stateless.StatelessAnalyticService;
import com.opengamma.component.ComponentInfo;
import com.opengamma.component.ComponentRepository;
import com.opengamma.component.factory.AbstractComponentFactory;
import com.opengamma.component.factory.ComponentInfoAttributes;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.core.position.PositionSource;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.view.ViewProcessor;
import com.opengamma.master.config.ConfigMaster;
import com.opengamma.master.portfolio.PortfolioMaster;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.master.security.SecurityMaster;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A component factory for a MarketDataManager.
*/
@BeanDefinition
public class ConfigManagerComponentFactory extends AbstractComponentFactory {
/**
* The classifier that the factory should publish under.
*/
@PropertyDefinition(validate = "notNull")
private String _classifier;
/**
* The config master.
*/
@PropertyDefinition(validate = "notNull")
private ConfigMaster _configMaster;
/**
* The config source.
*/
@PropertyDefinition(validate = "notNull")
private ConfigSource _configSource;
@Override
public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) {
ComponentInfo info = new ComponentInfo(ConfigManager.class, getClassifier());
info.addAttribute(ComponentInfoAttributes.LEVEL, 1);
ConfigManager configManager =
new ConfigManager(getConfigMaster(), getConfigSource());
repo.registerComponent(info, configManager);
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code ConfigManagerComponentFactory}.
* @return the meta-bean, not null
*/
public static ConfigManagerComponentFactory.Meta meta() {
return ConfigManagerComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(ConfigManagerComponentFactory.Meta.INSTANCE);
}
@Override
public ConfigManagerComponentFactory.Meta metaBean() {
return ConfigManagerComponentFactory.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the classifier that the factory should publish under.
* @return the value of the property, not null
*/
public String getClassifier() {
return _classifier;
}
/**
* Sets the classifier that the factory should publish under.
* @param classifier the new value of the property, not null
*/
public void setClassifier(String classifier) {
JodaBeanUtils.notNull(classifier, "classifier");
this._classifier = classifier;
}
/**
* Gets the the {@code classifier} property.
* @return the property, not null
*/
public final Property<String> classifier() {
return metaBean().classifier().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the config master.
* @return the value of the property, not null
*/
public ConfigMaster getConfigMaster() {
return _configMaster;
}
/**
* Sets the config master.
* @param configMaster the new value of the property, not null
*/
public void setConfigMaster(ConfigMaster configMaster) {
JodaBeanUtils.notNull(configMaster, "configMaster");
this._configMaster = configMaster;
}
/**
* Gets the the {@code configMaster} property.
* @return the property, not null
*/
public final Property<ConfigMaster> configMaster() {
return metaBean().configMaster().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the config source.
* @return the value of the property, not null
*/
public ConfigSource getConfigSource() {
return _configSource;
}
/**
* Sets the config source.
* @param configSource the new value of the property, not null
*/
public void setConfigSource(ConfigSource configSource) {
JodaBeanUtils.notNull(configSource, "configSource");
this._configSource = configSource;
}
/**
* Gets the the {@code configSource} property.
* @return the property, not null
*/
public final Property<ConfigSource> configSource() {
return metaBean().configSource().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public ConfigManagerComponentFactory clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
ConfigManagerComponentFactory other = (ConfigManagerComponentFactory) obj;
return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) &&
JodaBeanUtils.equal(getConfigMaster(), other.getConfigMaster()) &&
JodaBeanUtils.equal(getConfigSource(), other.getConfigSource()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash * 31 + JodaBeanUtils.hashCode(getClassifier());
hash = hash * 31 + JodaBeanUtils.hashCode(getConfigMaster());
hash = hash * 31 + JodaBeanUtils.hashCode(getConfigSource());
return hash ^ super.hashCode();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("ConfigManagerComponentFactory{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
@Override
protected void toString(StringBuilder buf) {
super.toString(buf);
buf.append("classifier").append('=').append(JodaBeanUtils.toString(getClassifier())).append(',').append(' ');
buf.append("configMaster").append('=').append(JodaBeanUtils.toString(getConfigMaster())).append(',').append(' ');
buf.append("configSource").append('=').append(JodaBeanUtils.toString(getConfigSource())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code ConfigManagerComponentFactory}.
*/
public static class Meta extends AbstractComponentFactory.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code classifier} property.
*/
private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite(
this, "classifier", ConfigManagerComponentFactory.class, String.class);
/**
* The meta-property for the {@code configMaster} property.
*/
private final MetaProperty<ConfigMaster> _configMaster = DirectMetaProperty.ofReadWrite(
this, "configMaster", ConfigManagerComponentFactory.class, ConfigMaster.class);
/**
* The meta-property for the {@code configSource} property.
*/
private final MetaProperty<ConfigSource> _configSource = DirectMetaProperty.ofReadWrite(
this, "configSource", ConfigManagerComponentFactory.class, ConfigSource.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"classifier",
"configMaster",
"configSource");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return _classifier;
case 10395716: // configMaster
return _configMaster;
case 195157501: // configSource
return _configSource;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends ConfigManagerComponentFactory> builder() {
return new DirectBeanBuilder<ConfigManagerComponentFactory>(new ConfigManagerComponentFactory());
}
@Override
public Class<? extends ConfigManagerComponentFactory> beanType() {
return ConfigManagerComponentFactory.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code classifier} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> classifier() {
return _classifier;
}
/**
* The meta-property for the {@code configMaster} property.
* @return the meta-property, not null
*/
public final MetaProperty<ConfigMaster> configMaster() {
return _configMaster;
}
/**
* The meta-property for the {@code configSource} property.
* @return the meta-property, not null
*/
public final MetaProperty<ConfigSource> configSource() {
return _configSource;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return ((ConfigManagerComponentFactory) bean).getClassifier();
case 10395716: // configMaster
return ((ConfigManagerComponentFactory) bean).getConfigMaster();
case 195157501: // configSource
return ((ConfigManagerComponentFactory) bean).getConfigSource();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
((ConfigManagerComponentFactory) bean).setClassifier((String) newValue);
return;
case 10395716: // configMaster
((ConfigManagerComponentFactory) bean).setConfigMaster((ConfigMaster) newValue);
return;
case 195157501: // configSource
((ConfigManagerComponentFactory) bean).setConfigSource((ConfigSource) newValue);
return;
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((ConfigManagerComponentFactory) bean)._classifier, "classifier");
JodaBeanUtils.notNull(((ConfigManagerComponentFactory) bean)._configMaster, "configMaster");
JodaBeanUtils.notNull(((ConfigManagerComponentFactory) bean)._configSource, "configSource");
super.validate(bean);
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gdata.client;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.annotations.Beta;
import com.google.gdata.client.AuthTokenFactory.AuthToken;
import com.google.gdata.client.AuthTokenFactory.TokenListener;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthSigner;
import com.google.gdata.client.batch.BatchInterruptedException;
import com.google.gdata.client.http.GoogleGDataRequest;
import com.google.gdata.client.http.GoogleGDataRequest.GoogleCookie;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.IEntry;
import com.google.gdata.data.IFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.RedirectRequiredException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.PrivateKey;
import java.util.Map;
import java.util.Set;
/**
* The GoogleService class extends the basic GData {@link Service}
* abstraction to add support for authentication and cookies.
*
*
*/
public class GoogleService extends Service implements TokenListener {
// Authentication token factory used to access Google services
private AuthTokenFactory authTokenFactory;
// Cookie manager.
private CookieManager cookieManager;
/**
* Authentication failed, invalid credentials presented to server.
*/
public static class InvalidCredentialsException
extends AuthenticationException {
public InvalidCredentialsException(String message) {
super(message);
}
}
/**
* Authentication failed, account has been deleted.
*/
public static class AccountDeletedException extends AuthenticationException {
public AccountDeletedException(String message) {
super(message);
}
}
/**
* Authentication failed, account has been disabled.
*/
public static class AccountDisabledException extends AuthenticationException {
public AccountDisabledException(String message) {
super(message);
}
}
/**
* Authentication failed, account has not been verified.
*/
public static class NotVerifiedException extends AuthenticationException {
public NotVerifiedException(String message) {
super(message);
}
}
/**
* Authentication failed, user did not agree to the terms of service.
*/
public static class TermsNotAgreedException extends AuthenticationException {
public TermsNotAgreedException(String message) {
super(message);
}
}
/**
* Authentication failed, authentication service not available.
*/
public static class ServiceUnavailableException extends
AuthenticationException {
public ServiceUnavailableException(String message) {
super(message);
}
}
/**
* Authentication failed, CAPTCHA requires answering.
*/
public static class CaptchaRequiredException extends AuthenticationException {
private String captchaUrl;
private String captchaToken;
public CaptchaRequiredException(String message,
String captchaUrl,
String captchaToken) {
super(message);
this.captchaToken = captchaToken;
this.captchaUrl = captchaUrl;
}
public String getCaptchaToken() { return captchaToken; }
public String getCaptchaUrl() { return captchaUrl; }
}
/**
* Authentication failed, the token's session has expired.
*/
public static class SessionExpiredException extends AuthenticationException {
public SessionExpiredException(String message) {
super(message);
}
}
/**
* Constructs a GoogleService instance connecting to the service with name
* {@code serviceName} for an application with the name
* {@code applicationName}. The default domain (www.google.com) and the
* default Google authentication methods will be used to authenticate.
* A simple cookie manager is used.
*
* @param serviceName the name of the Google service to which we are
* connecting. Sample names of services might include
* "cl" (Calendar), "mail" (GMail), or
* "blogger" (Blogger)
* @param applicationName the name of the client application accessing the
* service. Application names should preferably have
* the format [company-id]-[app-name]-[app-version].
* The name will be used by the Google servers to
* monitor the source of authentication.
*/
public GoogleService(String serviceName,
String applicationName) {
this(serviceName, applicationName, "https", "www.google.com");
}
/**
* Constructs a GoogleService instance connecting to the service with name
* {@code serviceName} for an application with the name
* {@code applicationName}. The service will authenticate at the provided
* {@code domainName}. The default Google authentication methods will be
* used to authenticate. A simple cookie manager is used.
*
* @param serviceName the name of the Google service to which we are
* connecting. Sample names of services might include
* "cl" (Calendar), "mail" (GMail), or
* "blogger" (Blogger)
* @param applicationName the name of the client application accessing the
* service. Application names should preferably have
* the format [company-id]-[app-name]-[app-version].
* The name will be used by the Google servers to
* monitor the source of authentication.
* @param protocol name of protocol to use for authentication
* ("http"/"https")
* @param domainName the name of the domain hosting the login handler
*/
public GoogleService(String serviceName,
String applicationName,
String protocol,
String domainName) {
requestFactory = new GoogleGDataRequest.Factory();
authTokenFactory =
new GoogleAuthTokenFactory(serviceName, applicationName,
protocol, domainName, this);
cookieManager = new SimpleCookieManager();
initRequestFactory(applicationName);
}
/**
* Constructs a GoogleService instance connecting to the service for an
* application with the name {@code applicationName}. The provided
* {@code GDataRequestFactory} will create requests, and the given
* {@code AuthTokenFactory} will be used to generate auth tokens.
* A simple cookie manager is used.
*
* @param applicationName the name of the client application accessing the
* service. Application names should preferably have
* the format [company-id]-[app-name]-[app-version].
* The name will be used by the Google servers to
* monitor the source of authentication.
* @param requestFactory the request factory that generates gdata requests
* @param authTokenFactory the auth token factory that generates auth tokens
*/
public GoogleService(String applicationName,
GDataRequestFactory requestFactory,
AuthTokenFactory authTokenFactory) {
this.requestFactory = requestFactory;
this.authTokenFactory = authTokenFactory;
cookieManager = new SimpleCookieManager();
initRequestFactory(applicationName);
}
/**
* Sets the headers in the request factory with the appropriate user agent
* settings.
*/
private void initRequestFactory(String applicationName) {
if (applicationName != null) {
requestFactory.setHeader("User-Agent",
applicationName + " " + getServiceVersion());
} else {
requestFactory.setHeader("User-Agent", getServiceVersion());
}
}
/**
* Returns the {@link AuthTokenFactory} currently associated with the service.
*/
public AuthTokenFactory getAuthTokenFactory() {
return authTokenFactory;
}
/**
* Sets the {@link AuthTokenFactory} currently associated with the service.
*
* @param authTokenFactory Authentication factory
*/
public void setAuthTokenFactory(AuthTokenFactory authTokenFactory) {
this.authTokenFactory = authTokenFactory;
}
/**
* Returns the {@link CookieManager} currently associated with the service.
*/
public CookieManager getCookieManager() {
return cookieManager;
}
/**
* Sets the {@link CookieManager} currently associated with the service.
*
* @param cookieManager Cookie manager
*/
public void setCookieManager(CookieManager cookieManager) {
this.cookieManager = cookieManager;
}
public void tokenChanged(AuthToken newToken) {
if (cookieManager != null) {
// Flush any cookies that might contain session info for the
// previous user.
cookieManager.clearCookies();
}
requestFactory.setAuthToken(newToken);
}
/**
* Sets the credentials of the user to authenticate requests to the server.
*
* @param username the name of the user (an email address)
* @param password the password of the user
* @throws AuthenticationException if authentication failed.
*/
public void setUserCredentials(String username, String password)
throws AuthenticationException {
setUserCredentials(username, password,
ClientLoginAccountType.HOSTED_OR_GOOGLE);
}
/**
* Sets the credentials of the user to authenticate requests to the server.
*
* @param username the name of the user (an email address)
* @param password the password of the user
* @param accountType the account type: HOSTED, GOOGLE, or HOSTED_OR_GOOGLE
* @throws AuthenticationException if authentication failed.
*/
public void setUserCredentials(String username,
String password,
ClientLoginAccountType accountType)
throws AuthenticationException {
setUserCredentials(username, password, null, null, accountType);
}
/**
* Sets the credentials of the user to authenticate requests to the server.
* A CAPTCHA token and a CAPTCHA answer can also be optionally provided
* to authenticate when the authentication server requires that a
* CAPTCHA be answered.
*
* @param username the name of the user (an email id)
* @param password the password of the user
* @param captchaToken the CAPTCHA token issued by the server
* @param captchaAnswer the answer to the respective CAPTCHA token
* @throws AuthenticationException if authentication failed
*/
public void setUserCredentials(String username,
String password,
String captchaToken,
String captchaAnswer)
throws AuthenticationException {
setUserCredentials(username, password, captchaToken, captchaAnswer,
ClientLoginAccountType.HOSTED_OR_GOOGLE);
}
/**
* Sets the credentials of the user to authenticate requests to the server.
* A CAPTCHA token and a CAPTCHA answer can also be optionally provided
* to authenticate when the authentication server requires that a
* CAPTCHA be answered.
*
* @param username the name of the user (an email id)
* @param password the password of the user
* @param captchaToken the CAPTCHA token issued by the server
* @param captchaAnswer the answer to the respective CAPTCHA token
* @param accountType the account type: HOSTED, GOOGLE, or HOSTED_OR_GOOGLE
* @throws AuthenticationException if authentication failed
*/
public void setUserCredentials(String username,
String password,
String captchaToken,
String captchaAnswer,
ClientLoginAccountType accountType)
throws AuthenticationException {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setUserCredentials(username, password,
captchaToken, captchaAnswer,
accountType);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
/**
* Sets the AuthToken that should be used to authenticate requests to the
* server. This is useful if the caller has some other way of accessing the
* AuthToken, versus calling getAuthToken with credentials to request the
* AuthToken using ClientLogin.
*
* @param token the AuthToken in ascii form
*/
public void setUserToken(String token) {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setUserToken(token);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
/**
* Sets the OAuth credentials used to generate the authorization header.
* This header needs to be set per request, as it depends on the request url.
* The following OAuth parameters are required:
* <ul>
* <li>oauth_consumer_key
* <li>oauth_token
* </ul>
*
* @param parameters the OAuth parameters to use to generate the header
* @param signer the signing method to use for signing the header
*/
public void setOAuthCredentials(OAuthParameters parameters,
OAuthSigner signer) throws OAuthException {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setOAuthCredentials(parameters, signer);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
/**
* Sets the OAuth 2.0 credentials used to generate the authorization header.
*
* @param credential the OAuth 2.0 credentials to use to generate the header
*/
@Beta
public void setOAuth2Credentials(Credential credential) {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setOAuth2Credentials(credential);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
/**
* Sets the AuthSub token to be used to authenticate a user.
*
* @param token the AuthSub token retrieved from Google
*/
public void setAuthSubToken(String token) {
setAuthSubToken(token, null);
}
/**
* Sets the AuthSub token to be used to authenticate a user. The token
* will be used in secure-mode, and the provided private key will be used
* to sign all requests.
*
* @param token the AuthSub token retrieved from Google
* @param key the private key to be used to sign all requests
*/
public void setAuthSubToken(String token,
PrivateKey key) {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setAuthSubToken(token, key);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
/**
* Retrieves the authentication token for the provided set of credentials.
*
* @param username the name of the user (an email address)
* @param password the password of the user
* @param captchaToken the CAPTCHA token if CAPTCHA is required (Optional)
* @param captchaAnswer the respective answer of the CAPTCHA token (Optional)
* @param serviceName the name of the service to which a token is required
* @param applicationName the application requesting the token
* @return the token
* @throws AuthenticationException if authentication failed
*/
public String getAuthToken(String username,
String password,
String captchaToken,
String captchaAnswer,
String serviceName,
String applicationName)
throws AuthenticationException {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
return googleAuthTokenFactory.getAuthToken(username, password, captchaToken,
captchaAnswer, serviceName,
applicationName);
}
/**
* Makes a HTTP POST request to the provided {@code url} given the
* provided {@code parameters}. It returns the output from the POST
* handler as a String object.
*
* @param url the URL to post the request
* @param parameters the parameters to post to the handler
* @return the output from the handler
* @throws IOException if an I/O exception occurs while creating, writing,
* or reading the request
*/
public static String makePostRequest(URL url,
Map<String, String> parameters)
throws IOException {
return GoogleAuthTokenFactory.makePostRequest(url, parameters);
}
/**
* Enables or disables cookie handling.
*/
public void setHandlesCookies(boolean handlesCookies) {
if (cookieManager == null) {
if (handlesCookies) {
throw new IllegalArgumentException("No cookie manager defined");
}
return;
}
cookieManager.setCookiesEnabled(handlesCookies);
}
/**
* Returns {@code true} if the GoogleService is handling cookies.
*/
public boolean handlesCookies() {
if (cookieManager == null) {
return false;
}
return cookieManager.cookiesEnabled();
}
/**
* Adds a new GoogleCookie instance to the cache.
*/
public void addCookie(GoogleCookie cookie) {
if (cookieManager != null) {
cookieManager.addCookie(cookie);
}
}
/**
* Returns the set of associated cookies returned by previous requests.
*/
public Set<GoogleCookie> getCookies() {
if (cookieManager == null) {
throw new IllegalArgumentException("No cookie manager defined");
}
return cookieManager.getCookies();
}
@Override
public GDataRequest createRequest(GDataRequest.RequestType type,
URL requestUrl,
ContentType contentType)
throws IOException, ServiceException {
GDataRequest request = super.createRequest(type, requestUrl, contentType);
if (request instanceof GoogleGDataRequest) {
((GoogleGDataRequest) request).setService(this);
}
return request;
}
@Override
protected GDataRequest createRequest(Query query, ContentType contentType)
throws IOException, ServiceException {
GDataRequest request = super.createRequest(query, contentType);
if (request instanceof GoogleGDataRequest) {
((GoogleGDataRequest) request).setService(this);
}
return request;
}
@Override
public <E extends IEntry> E getEntry(URL entryUrl,
Class<E> entryClass,
DateTime ifModifiedSince)
throws IOException, ServiceException {
try {
return super.getEntry(entryUrl, entryClass, ifModifiedSince);
} catch (RedirectRequiredException e) {
entryUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getEntry(entryUrl, entryClass, ifModifiedSince);
}
@Override
public <E extends IEntry> E getEntry(URL entryUrl,
Class<E> entryClass,
String etag)
throws IOException, ServiceException {
try {
return super.getEntry(entryUrl, entryClass, etag);
} catch (RedirectRequiredException e) {
entryUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getEntry(entryUrl, entryClass, etag);
}
@Override
public <E extends IEntry> E update(URL entryUrl, E entry)
throws IOException, ServiceException {
try {
return super.update(entryUrl, entry);
} catch (RedirectRequiredException e) {
entryUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.update(entryUrl, entry);
}
@Override
public <E extends IEntry> E insert(URL feedUrl, E entry)
throws IOException, ServiceException {
try {
return super.insert(feedUrl, entry);
} catch (RedirectRequiredException e) {
feedUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.insert(feedUrl, entry);
}
@Override
public <F extends IFeed> F getFeed(URL feedUrl,
Class<F> feedClass,
DateTime ifModifiedSince)
throws IOException, ServiceException {
try {
return super.getFeed(feedUrl, feedClass, ifModifiedSince);
} catch (RedirectRequiredException e) {
feedUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getFeed(feedUrl, feedClass, ifModifiedSince);
}
@Override
public <F extends IFeed> F getFeed(URL feedUrl, Class<F> feedClass,
String etag) throws IOException, ServiceException {
try {
return super.getFeed(feedUrl, feedClass, etag);
} catch (RedirectRequiredException e) {
feedUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getFeed(feedUrl, feedClass, etag);
}
@Override
public <F extends IFeed> F getFeed(Query query,
Class<F> feedClass,
DateTime ifModifiedSince)
throws IOException, ServiceException {
try {
return super.getFeed(query, feedClass, ifModifiedSince);
} catch (RedirectRequiredException e) {
query = new Query(handleRedirectException(e));
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getFeed(query, feedClass, ifModifiedSince);
}
@Override
public <F extends IFeed> F getFeed(Query query, Class<F> feedClass,
String etag) throws IOException, ServiceException {
try {
return super.getFeed(query, feedClass, etag);
} catch (RedirectRequiredException e) {
query = new Query(handleRedirectException(e));
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.getFeed(query, feedClass, etag);
}
@Override
public void delete(URL entryUrl) throws IOException, ServiceException {
try {
super.delete(entryUrl);
return;
} catch (RedirectRequiredException e) {
entryUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
super.delete(entryUrl);
}
@Override
public void delete(URL entryUrl, String etag)
throws IOException, ServiceException {
try {
super.delete(entryUrl, etag);
return;
} catch (RedirectRequiredException e) {
entryUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
super.delete(entryUrl, etag);
}
/**
* Handles a redirect exception by generating the new URL to use for the
* redirect.
*/
protected URL handleRedirectException(RedirectRequiredException redirect)
throws ServiceException {
try {
return new URL(redirect.getRedirectLocation());
} catch (MalformedURLException e) {
ServiceException se = new ServiceException(
CoreErrorDomain.ERR.invalidRedirectedToUrl);
se.setInternalReason("Invalid redirected-to URL - "
+ redirect.getRedirectLocation());
throw se;
}
}
/**
* Delegates session expired exception to {@link AuthTokenFactory}.
*/
protected void handleSessionExpiredException(SessionExpiredException e)
throws ServiceException {
authTokenFactory.handleSessionExpiredException(e);
}
/**
* Executes several operations (insert, update or delete) on the entries that
* are part of the input {@link IFeed}. It will return another feed that
* describes what was done while executing these operations.
*
* It is possible for one batch operation to fail even though other operations
* have worked, so this method won't throw a ServiceException unless something
* really wrong is going on. You need to check the entries in the returned
* feed to know which operations succeeded and which operations failed (see
* {@link com.google.gdata.data.batch.BatchStatus} and
* {@link com.google.gdata.data.batch.BatchInterrupted} extensions.)
*
* @param feedUrl the POST URI associated with the target feed.
* @param inputFeed a description of the operations to execute, described
* using tags in the batch: namespace
* @return a feed with the result of each operation in a separate entry
* @throws IOException error communicating with the GData service.
* @throws com.google.gdata.util.ParseException error parsing the return entry
* data.
* @throws ServiceException insert request failed due to system error.
* @throws BatchInterruptedException if something really wrong was detected by
* the server while parsing the request, like invalid XML data. Some
* operations might have succeeded when this exception is thrown.
* Check {@link BatchInterruptedException#getIFeed()}.
*/
@Override
public <F extends IFeed> F batch(URL feedUrl, F inputFeed)
throws IOException, ServiceException, BatchInterruptedException {
try {
return super.batch(feedUrl, inputFeed);
} catch (RedirectRequiredException e) {
feedUrl = handleRedirectException(e);
} catch (SessionExpiredException e) {
handleSessionExpiredException(e);
}
return super.batch(feedUrl, inputFeed);
}
/**
* Get the {@link GoogleAuthTokenFactory} current associated with this
* service. If an auth token factory of a different type is configured,
* an {@link IllegalStateException} is thrown.
*
* @return Google authentication token factory.
*/
private GoogleAuthTokenFactory getGoogleAuthTokenFactory() {
if (!(authTokenFactory instanceof GoogleAuthTokenFactory)) {
throw new IllegalStateException("Invalid authentication token factory");
}
return (GoogleAuthTokenFactory) authTokenFactory;
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.newvfs;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.impl.ArchiveHandler;
import com.intellij.openapi.vfs.newvfs.events.*;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class VfsImplUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.VfsImplUtil");
private static final String FILE_SEPARATORS = "/" + File.separator;
private VfsImplUtil() { }
@Nullable
public static NewVirtualFile findFileByPath(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
Pair<NewVirtualFile, Iterable<String>> data = prepare(vfs, path);
if (data == null) return null;
NewVirtualFile file = data.first;
for (String pathElement : data.second) {
if (pathElement.isEmpty() || ".".equals(pathElement)) continue;
if ("..".equals(pathElement)) {
if (file.is(VFileProperty.SYMLINK)) {
final NewVirtualFile canonicalFile = file.getCanonicalFile();
file = canonicalFile != null ? canonicalFile.getParent() : null;
}
else {
file = file.getParent();
}
}
else {
file = file.findChild(pathElement);
}
if (file == null) return null;
}
return file;
}
@Nullable
public static NewVirtualFile findFileByPathIfCached(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
return findCachedFileByPath(vfs, path).first;
}
@NotNull
public static Pair<NewVirtualFile, NewVirtualFile> findCachedFileByPath(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
Pair<NewVirtualFile, Iterable<String>> data = prepare(vfs, path);
if (data == null) return Pair.empty();
NewVirtualFile file = data.first;
for (String pathElement : data.second) {
if (pathElement.isEmpty() || ".".equals(pathElement)) continue;
NewVirtualFile last = file;
if ("..".equals(pathElement)) {
if (file.is(VFileProperty.SYMLINK)) {
String canonicalPath = file.getCanonicalPath();
NewVirtualFile canonicalFile = canonicalPath != null ? findCachedFileByPath(vfs, canonicalPath).first : null;
file = canonicalFile != null ? canonicalFile.getParent() : null;
}
else {
file = file.getParent();
}
}
else {
file = file.findChildIfCached(pathElement);
}
if (file == null) return Pair.pair(null, last);
}
return Pair.pair(file, null);
}
@Nullable
public static NewVirtualFile refreshAndFindFileByPath(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
Pair<NewVirtualFile, Iterable<String>> data = prepare(vfs, path);
if (data == null) return null;
NewVirtualFile file = data.first;
for (String pathElement : data.second) {
if (pathElement.isEmpty() || ".".equals(pathElement)) continue;
if ("..".equals(pathElement)) {
if (file.is(VFileProperty.SYMLINK)) {
final String canonicalPath = file.getCanonicalPath();
final NewVirtualFile canonicalFile = canonicalPath != null ? refreshAndFindFileByPath(vfs, canonicalPath) : null;
file = canonicalFile != null ? canonicalFile.getParent() : null;
}
else {
file = file.getParent();
}
}
else {
file = file.refreshAndFindChild(pathElement);
}
if (file == null) return null;
}
return file;
}
@Nullable
private static Pair<NewVirtualFile, Iterable<String>> prepare(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
String normalizedPath = normalize(vfs, path);
if (StringUtil.isEmptyOrSpaces(normalizedPath)) {
return null;
}
String basePath = vfs.extractRootPath(normalizedPath);
if (basePath.length() > normalizedPath.length() || basePath.isEmpty()) {
LOG.warn(vfs + " failed to extract root path '" + basePath + "' from '" + normalizedPath + "' (original '" + path + "')");
return null;
}
NewVirtualFile root = ManagingFS.getInstance().findRoot(basePath, vfs);
if (root == null || !root.exists()) {
return null;
}
Iterable<String> parts = StringUtil.tokenize(normalizedPath.substring(basePath.length()), FILE_SEPARATORS);
return Pair.create(root, parts);
}
public static void refresh(@NotNull NewVirtualFileSystem vfs, boolean asynchronous) {
VirtualFile[] roots = ManagingFS.getInstance().getRoots(vfs);
if (roots.length > 0) {
RefreshQueue.getInstance().refresh(asynchronous, true, null, roots);
}
}
public static String normalize(@NotNull NewVirtualFileSystem vfs, @NotNull String path) {
return vfs.normalize(path);
}
/**
* Guru method for force synchronous file refresh.
*
* Refreshing files via {@link #refresh(NewVirtualFileSystem, boolean)} doesn't work well if the file was changed
* twice in short time and content length wasn't changed (for example file modification timestamp for HFS+ works per seconds).
*
* If you're sure that a file is changed twice in a second and you have to get the latest file's state - use this method.
*
* Likely you need this method if you have following code:
*
* <code>
* FileDocumentManager.getInstance().saveDocument(document);
* runExternalToolToChangeFile(virtualFile.getPath()) // changes file externally in milliseconds, probably without changing file's length
* VfsUtil.markDirtyAndRefresh(true, true, true, virtualFile); // might be replace with {@link #forceSyncRefresh(VirtualFile)}
* </code>
*/
public static void forceSyncRefresh(@NotNull VirtualFile file) {
RefreshQueue.getInstance().processSingleEvent(new VFileContentChangeEvent(null, file, file.getModificationStamp(), -1, true));
}
private static final AtomicBoolean ourSubscribed = new AtomicBoolean(false);
private static final Object ourLock = new Object();
private static final Map<String, Pair<ArchiveFileSystem, ArchiveHandler>> ourHandlers = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
private static final Map<String, Set<String>> ourDominatorsMap = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
@NotNull
public static <T extends ArchiveHandler> T getHandler(@NotNull ArchiveFileSystem vfs,
@NotNull VirtualFile entryFile,
@NotNull Function<String, T> producer) {
String localPath = vfs.extractLocalPath(vfs.extractRootPath(entryFile.getPath()));
return getHandler(vfs, localPath, producer);
}
@NotNull
private static <T extends ArchiveHandler> T getHandler(@NotNull ArchiveFileSystem vfs,
@NotNull String localPath,
@NotNull Function<String, T> producer) {
checkSubscription();
ArchiveHandler handler;
synchronized (ourLock) {
Pair<ArchiveFileSystem, ArchiveHandler> record = ourHandlers.get(localPath);
if (record == null) {
handler = producer.fun(localPath);
record = Pair.create(vfs, handler);
ourHandlers.put(localPath, record);
forEachDirectoryComponent(localPath, containingDirectoryPath -> {
Set<String> handlers = ourDominatorsMap.computeIfAbsent(containingDirectoryPath, __ -> ContainerUtil.newTroveSet());
handlers.add(localPath);
});
}
handler = record.second;
}
//noinspection unchecked
return (T)handler;
}
private static void forEachDirectoryComponent(String rootPath, Consumer<String> consumer) {
int index = rootPath.lastIndexOf('/');
while (index > 0) {
String containingDirectoryPath = rootPath.substring(0, index);
consumer.consume(containingDirectoryPath);
index = rootPath.lastIndexOf('/', index - 1);
}
}
private static void checkSubscription() {
if (ourSubscribed.getAndSet(true)) return;
Application app = ApplicationManager.getApplication();
if (app.isDisposeInProgress()) return; // IDEA-181620 we might perform shutdown activity that includes visiting zip files
app.getMessageBus().connect(app).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
InvalidationState state = null;
synchronized (ourLock) {
for (VFileEvent event : events) {
if (!(event.getFileSystem() instanceof LocalFileSystem)) continue;
if (event instanceof VFileCreateEvent) continue; // created file should not invalidate + getFile is costly
if (event instanceof VFilePropertyChangeEvent &&
!VirtualFile.PROP_NAME.equals(((VFilePropertyChangeEvent)event).getPropertyName())) {
continue;
}
String path = event.getPath();
if (event instanceof VFilePropertyChangeEvent) {
path = ((VFilePropertyChangeEvent)event).getOldPath();
}
else if (event instanceof VFileMoveEvent) {
path = ((VFileMoveEvent)event).getOldPath();
}
VirtualFile file = event.getFile();
if (file == null || !file.isDirectory()) {
state = InvalidationState.invalidate(state, path);
}
else {
Collection<String> affectedPaths = ourDominatorsMap.get(path);
if (affectedPaths != null) {
affectedPaths = ContainerUtil.newArrayList(affectedPaths); // defensive copying; original may be updated on invalidation
for (String affectedPath : affectedPaths) {
state = InvalidationState.invalidate(state, affectedPath);
}
}
}
}
}
if (state != null) state.scheduleRefresh();
}
});
}
private static class InvalidationState {
private Set<NewVirtualFile> myRootsToRefresh;
@Nullable
static InvalidationState invalidate(@Nullable InvalidationState state, final String path) {
Pair<ArchiveFileSystem, ArchiveHandler> handlerPair = ourHandlers.remove(path);
if (handlerPair != null) {
handlerPair.second.dispose();
forEachDirectoryComponent(path, containingDirectoryPath -> {
Set<String> handlers = ourDominatorsMap.get(containingDirectoryPath);
if (handlers != null && handlers.remove(path) && handlers.isEmpty()) {
ourDominatorsMap.remove(containingDirectoryPath);
}
});
if (state == null) state = new InvalidationState();
state.registerPathToRefresh(path, handlerPair.first);
}
return state;
}
private void registerPathToRefresh(String path, ArchiveFileSystem vfs) {
NewVirtualFile root = ManagingFS.getInstance().findRoot(vfs.composeRootPath(path), vfs);
if (root != null) {
if (myRootsToRefresh == null) myRootsToRefresh = ContainerUtil.newHashSet();
myRootsToRefresh.add(root);
}
}
void scheduleRefresh() {
if (myRootsToRefresh != null) {
for (NewVirtualFile root : myRootsToRefresh) {
root.markDirtyRecursively();
}
boolean async = !ApplicationManager.getApplication().isUnitTestMode();
RefreshQueue.getInstance().refresh(async, true, null, myRootsToRefresh);
}
}
}
}
| |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.testutil;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.PlayerMessage;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.testutil.ActionSchedule.ActionNode;
import com.google.android.exoplayer2.testutil.ActionSchedule.PlayerRunnable;
import com.google.android.exoplayer2.testutil.ActionSchedule.PlayerTarget;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.util.HandlerWrapper;
/**
* Base class for actions to perform during playback tests.
*/
public abstract class Action {
private final String tag;
private final @Nullable String description;
/**
* @param tag A tag to use for logging.
* @param description A description to be logged when the action is executed, or null if no
* logging is required.
*/
public Action(String tag, @Nullable String description) {
this.tag = tag;
this.description = description;
}
/**
* Executes the action and schedules the next.
*
* @param player The player to which the action should be applied.
* @param trackSelector The track selector to which the action should be applied.
* @param surface The surface to use when applying actions.
* @param handler The handler to use to pass to the next action.
* @param nextAction The next action to schedule immediately after this action finished.
*/
public final void doActionAndScheduleNext(
SimpleExoPlayer player,
MappingTrackSelector trackSelector,
Surface surface,
HandlerWrapper handler,
ActionNode nextAction) {
if (description != null) {
Log.i(tag, description);
}
doActionAndScheduleNextImpl(player, trackSelector, surface, handler, nextAction);
}
/**
* Called by {@link #doActionAndScheduleNext(SimpleExoPlayer, MappingTrackSelector, Surface,
* HandlerWrapper, ActionNode)} to perform the action and to schedule the next action node.
*
* @param player The player to which the action should be applied.
* @param trackSelector The track selector to which the action should be applied.
* @param surface The surface to use when applying actions.
* @param handler The handler to use to pass to the next action.
* @param nextAction The next action to schedule immediately after this action finished.
*/
protected void doActionAndScheduleNextImpl(
SimpleExoPlayer player,
MappingTrackSelector trackSelector,
Surface surface,
HandlerWrapper handler,
ActionNode nextAction) {
doActionImpl(player, trackSelector, surface);
if (nextAction != null) {
nextAction.schedule(player, trackSelector, surface, handler);
}
}
/**
* Called by {@link #doActionAndScheduleNextImpl(SimpleExoPlayer, MappingTrackSelector, Surface,
* HandlerWrapper, ActionNode)} to perform the action.
*
* @param player The player to which the action should be applied.
* @param trackSelector The track selector to which the action should be applied.
* @param surface The surface to use when applying actions.
*/
protected abstract void doActionImpl(
SimpleExoPlayer player, MappingTrackSelector trackSelector, Surface surface);
/**
* Calls {@link Player#seekTo(long)} or {@link Player#seekTo(int, long)}.
*/
public static final class Seek extends Action {
private final Integer windowIndex;
private final long positionMs;
/**
* Action calls {@link Player#seekTo(long)}.
*
* @param tag A tag to use for logging.
* @param positionMs The seek position.
*/
public Seek(String tag, long positionMs) {
super(tag, "Seek:" + positionMs);
this.windowIndex = null;
this.positionMs = positionMs;
}
/**
* Action calls {@link Player#seekTo(int, long)}.
*
* @param tag A tag to use for logging.
* @param windowIndex The window to seek to.
* @param positionMs The seek position.
*/
public Seek(String tag, int windowIndex, long positionMs) {
super(tag, "Seek:" + positionMs);
this.windowIndex = windowIndex;
this.positionMs = positionMs;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
if (windowIndex == null) {
player.seekTo(positionMs);
} else {
player.seekTo(windowIndex, positionMs);
}
}
}
/**
* Calls {@link Player#stop()} or {@link Player#stop(boolean)}.
*/
public static final class Stop extends Action {
private static final String STOP_ACTION_TAG = "Stop";
private final Boolean reset;
/**
* Action will call {@link Player#stop()}.
*
* @param tag A tag to use for logging.
*/
public Stop(String tag) {
super(tag, STOP_ACTION_TAG);
this.reset = null;
}
/**
* Action will call {@link Player#stop(boolean)}.
*
* @param tag A tag to use for logging.
* @param reset The value to pass to {@link Player#stop(boolean)}.
*/
public Stop(String tag, boolean reset) {
super(tag, STOP_ACTION_TAG);
this.reset = reset;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
if (reset == null) {
player.stop();
} else {
player.stop(reset);
}
}
}
/**
* Calls {@link Player#setPlayWhenReady(boolean)}.
*/
public static final class SetPlayWhenReady extends Action {
private final boolean playWhenReady;
/**
* @param tag A tag to use for logging.
* @param playWhenReady The value to pass.
*/
public SetPlayWhenReady(String tag, boolean playWhenReady) {
super(tag, playWhenReady ? "Play" : "Pause");
this.playWhenReady = playWhenReady;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.setPlayWhenReady(playWhenReady);
}
}
/**
* Calls {@link MappingTrackSelector#setRendererDisabled(int, boolean)}.
*/
public static final class SetRendererDisabled extends Action {
private final int rendererIndex;
private final boolean disabled;
/**
* @param tag A tag to use for logging.
* @param rendererIndex The index of the renderer.
* @param disabled Whether the renderer should be disabled.
*/
public SetRendererDisabled(String tag, int rendererIndex, boolean disabled) {
super(tag, "SetRendererDisabled:" + rendererIndex + ":" + disabled);
this.rendererIndex = rendererIndex;
this.disabled = disabled;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
trackSelector.setRendererDisabled(rendererIndex, disabled);
}
}
/**
* Calls {@link SimpleExoPlayer#clearVideoSurface()}.
*/
public static final class ClearVideoSurface extends Action {
/**
* @param tag A tag to use for logging.
*/
public ClearVideoSurface(String tag) {
super(tag, "ClearVideoSurface");
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.clearVideoSurface();
}
}
/**
* Calls {@link SimpleExoPlayer#setVideoSurface(Surface)}.
*/
public static final class SetVideoSurface extends Action {
/**
* @param tag A tag to use for logging.
*/
public SetVideoSurface(String tag) {
super(tag, "SetVideoSurface");
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.setVideoSurface(surface);
}
}
/**
* Calls {@link ExoPlayer#prepare(MediaSource)}.
*/
public static final class PrepareSource extends Action {
private final MediaSource mediaSource;
private final boolean resetPosition;
private final boolean resetState;
/**
* @param tag A tag to use for logging.
*/
public PrepareSource(String tag, MediaSource mediaSource) {
this(tag, mediaSource, true, true);
}
/**
* @param tag A tag to use for logging.
*/
public PrepareSource(String tag, MediaSource mediaSource, boolean resetPosition,
boolean resetState) {
super(tag, "PrepareSource");
this.mediaSource = mediaSource;
this.resetPosition = resetPosition;
this.resetState = resetState;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.prepare(mediaSource, resetPosition, resetState);
}
}
/**
* Calls {@link Player#setRepeatMode(int)}.
*/
public static final class SetRepeatMode extends Action {
private final @Player.RepeatMode int repeatMode;
/**
* @param tag A tag to use for logging.
*/
public SetRepeatMode(String tag, @Player.RepeatMode int repeatMode) {
super(tag, "SetRepeatMode:" + repeatMode);
this.repeatMode = repeatMode;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.setRepeatMode(repeatMode);
}
}
/**
* Calls {@link Player#setShuffleModeEnabled(boolean)}.
*/
public static final class SetShuffleModeEnabled extends Action {
private final boolean shuffleModeEnabled;
/**
* @param tag A tag to use for logging.
*/
public SetShuffleModeEnabled(String tag, boolean shuffleModeEnabled) {
super(tag, "SetShuffleModeEnabled:" + shuffleModeEnabled);
this.shuffleModeEnabled = shuffleModeEnabled;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.setShuffleModeEnabled(shuffleModeEnabled);
}
}
/** Calls {@link ExoPlayer#createMessage(Target)} and {@link PlayerMessage#send()}. */
public static final class SendMessages extends Action {
private final Target target;
private final int windowIndex;
private final long positionMs;
private final boolean deleteAfterDelivery;
/**
* @param tag A tag to use for logging.
* @param target A message target.
* @param positionMs The position at which the message should be sent, in milliseconds.
*/
public SendMessages(String tag, Target target, long positionMs) {
this(
tag,
target,
/* windowIndex= */ C.INDEX_UNSET,
positionMs,
/* deleteAfterDelivery= */ true);
}
/**
* @param tag A tag to use for logging.
* @param target A message target.
* @param windowIndex The window index at which the message should be sent, or {@link
* C#INDEX_UNSET} for the current window.
* @param positionMs The position at which the message should be sent, in milliseconds.
* @param deleteAfterDelivery Whether the message will be deleted after delivery.
*/
public SendMessages(
String tag, Target target, int windowIndex, long positionMs, boolean deleteAfterDelivery) {
super(tag, "SendMessages");
this.target = target;
this.windowIndex = windowIndex;
this.positionMs = positionMs;
this.deleteAfterDelivery = deleteAfterDelivery;
}
@Override
protected void doActionImpl(
final SimpleExoPlayer player, MappingTrackSelector trackSelector, Surface surface) {
if (target instanceof PlayerTarget) {
((PlayerTarget) target).setPlayer(player);
}
PlayerMessage message = player.createMessage(target);
if (windowIndex != C.INDEX_UNSET) {
message.setPosition(windowIndex, positionMs);
} else {
message.setPosition(positionMs);
}
message.setHandler(new Handler());
message.setDeleteAfterDelivery(deleteAfterDelivery);
message.send();
}
}
/**
* Calls {@link Player#setPlaybackParameters(PlaybackParameters)}.
*/
public static final class SetPlaybackParameters extends Action {
private final PlaybackParameters playbackParameters;
/**
* @param tag A tag to use for logging.
* @param playbackParameters The playback parameters.
*/
public SetPlaybackParameters(String tag, PlaybackParameters playbackParameters) {
super(tag, "SetPlaybackParameters:" + playbackParameters);
this.playbackParameters = playbackParameters;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
player.setPlaybackParameters(playbackParameters);
}
}
/** Throws a playback exception on the playback thread. */
public static final class ThrowPlaybackException extends Action {
private final ExoPlaybackException exception;
/**
* @param tag A tag to use for logging.
* @param exception The exception to throw.
*/
public ThrowPlaybackException(String tag, ExoPlaybackException exception) {
super(tag, "ThrowPlaybackException:" + exception);
this.exception = exception;
}
@Override
protected void doActionImpl(
SimpleExoPlayer player, MappingTrackSelector trackSelector, Surface surface) {
player
.createMessage(
new Target() {
@Override
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
throw exception;
}
})
.send();
}
}
/**
* Schedules a play action to be executed, waits until the player reaches the specified position,
* and pauses the player again.
*/
public static final class PlayUntilPosition extends Action {
private final int windowIndex;
private final long positionMs;
/**
* @param tag A tag to use for logging.
* @param windowIndex The window index at which the player should be paused again.
* @param positionMs The position in that window at which the player should be paused again.
*/
public PlayUntilPosition(String tag, int windowIndex, long positionMs) {
super(tag, "PlayUntilPosition:" + windowIndex + "," + positionMs);
this.windowIndex = windowIndex;
this.positionMs = positionMs;
}
@Override
protected void doActionAndScheduleNextImpl(
final SimpleExoPlayer player,
final MappingTrackSelector trackSelector,
final Surface surface,
final HandlerWrapper handler,
final ActionNode nextAction) {
// Schedule one message on the playback thread to pause the player immediately.
player
.createMessage(
new Target() {
@Override
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
player.setPlayWhenReady(/* playWhenReady= */ false);
}
})
.setPosition(windowIndex, positionMs)
.send();
// Schedule another message on this test thread to continue action schedule.
player
.createMessage(
new Target() {
@Override
public void handleMessage(int messageType, Object payload)
throws ExoPlaybackException {
nextAction.schedule(player, trackSelector, surface, handler);
}
})
.setPosition(windowIndex, positionMs)
.setHandler(new Handler())
.send();
player.setPlayWhenReady(true);
}
@Override
protected void doActionImpl(
SimpleExoPlayer player, MappingTrackSelector trackSelector, Surface surface) {
// Not triggered.
}
}
/**
* Waits for {@link Player.EventListener#onTimelineChanged(Timeline, Object, int)}.
*/
public static final class WaitForTimelineChanged extends Action {
private final Timeline expectedTimeline;
/**
* @param tag A tag to use for logging.
*/
public WaitForTimelineChanged(String tag, Timeline expectedTimeline) {
super(tag, "WaitForTimelineChanged");
this.expectedTimeline = expectedTimeline;
}
@Override
protected void doActionAndScheduleNextImpl(
final SimpleExoPlayer player,
final MappingTrackSelector trackSelector,
final Surface surface,
final HandlerWrapper handler,
final ActionNode nextAction) {
if (nextAction == null) {
return;
}
Player.EventListener listener = new Player.DefaultEventListener() {
@Override
public void onTimelineChanged(Timeline timeline, Object manifest,
@Player.TimelineChangeReason int reason) {
if (timeline.equals(expectedTimeline)) {
player.removeListener(this);
nextAction.schedule(player, trackSelector, surface, handler);
}
}
};
player.addListener(listener);
if (player.getCurrentTimeline().equals(expectedTimeline)) {
player.removeListener(listener);
nextAction.schedule(player, trackSelector, surface, handler);
}
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
// Not triggered.
}
}
/**
* Waits for {@link Player.EventListener#onPositionDiscontinuity(int)}.
*/
public static final class WaitForPositionDiscontinuity extends Action {
/**
* @param tag A tag to use for logging.
*/
public WaitForPositionDiscontinuity(String tag) {
super(tag, "WaitForPositionDiscontinuity");
}
@Override
protected void doActionAndScheduleNextImpl(
final SimpleExoPlayer player,
final MappingTrackSelector trackSelector,
final Surface surface,
final HandlerWrapper handler,
final ActionNode nextAction) {
if (nextAction == null) {
return;
}
player.addListener(new Player.DefaultEventListener() {
@Override
public void onPositionDiscontinuity(@Player.DiscontinuityReason int reason) {
player.removeListener(this);
nextAction.schedule(player, trackSelector, surface, handler);
}
});
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
// Not triggered.
}
}
/**
* Waits for a specified playback state, returning either immediately or after a call to
* {@link Player.EventListener#onPlayerStateChanged(boolean, int)}.
*/
public static final class WaitForPlaybackState extends Action {
private final int targetPlaybackState;
/**
* @param tag A tag to use for logging.
*/
public WaitForPlaybackState(String tag, int targetPlaybackState) {
super(tag, "WaitForPlaybackState");
this.targetPlaybackState = targetPlaybackState;
}
@Override
protected void doActionAndScheduleNextImpl(
final SimpleExoPlayer player,
final MappingTrackSelector trackSelector,
final Surface surface,
final HandlerWrapper handler,
final ActionNode nextAction) {
if (nextAction == null) {
return;
}
if (targetPlaybackState == player.getPlaybackState()) {
nextAction.schedule(player, trackSelector, surface, handler);
} else {
player.addListener(new Player.DefaultEventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (targetPlaybackState == playbackState) {
player.removeListener(this);
nextAction.schedule(player, trackSelector, surface, handler);
}
}
});
}
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
// Not triggered.
}
}
/**
* Waits for {@link Player.EventListener#onSeekProcessed()}.
*/
public static final class WaitForSeekProcessed extends Action {
/**
* @param tag A tag to use for logging.
*/
public WaitForSeekProcessed(String tag) {
super(tag, "WaitForSeekProcessed");
}
@Override
protected void doActionAndScheduleNextImpl(
final SimpleExoPlayer player,
final MappingTrackSelector trackSelector,
final Surface surface,
final HandlerWrapper handler,
final ActionNode nextAction) {
if (nextAction == null) {
return;
}
player.addListener(new Player.DefaultEventListener() {
@Override
public void onSeekProcessed() {
player.removeListener(this);
nextAction.schedule(player, trackSelector, surface, handler);
}
});
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
// Not triggered.
}
}
/**
* Calls {@link Runnable#run()}.
*/
public static final class ExecuteRunnable extends Action {
private final Runnable runnable;
/**
* @param tag A tag to use for logging.
*/
public ExecuteRunnable(String tag, Runnable runnable) {
super(tag, "ExecuteRunnable");
this.runnable = runnable;
}
@Override
protected void doActionImpl(SimpleExoPlayer player, MappingTrackSelector trackSelector,
Surface surface) {
if (runnable instanceof PlayerRunnable) {
((PlayerRunnable) runnable).setPlayer(player);
}
runnable.run();
}
}
}
| |
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
*/
package org.olat.course.nodes.iq;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.dom4j.Document;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.fullWebApp.LayoutMain3ColsController;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.htmlsite.HtmlStaticPageComponent;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.link.LinkFactory;
import org.olat.core.gui.components.panel.Panel;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.dtabs.Activateable2;
import org.olat.core.gui.control.generic.iframe.IFrameDisplayController;
import org.olat.core.id.Identity;
import org.olat.core.id.OLATResourceable;
import org.olat.core.id.Roles;
import org.olat.core.id.context.ContextEntry;
import org.olat.core.id.context.StateEntry;
import org.olat.core.logging.AssertException;
import org.olat.core.logging.OLATRuntimeException;
import org.olat.core.logging.activity.ThreadLocalUserActivityLogger;
import org.olat.core.util.Formatter;
import org.olat.core.util.StringHelper;
import org.olat.core.util.UserSession;
import org.olat.core.util.event.EventBus;
import org.olat.core.util.event.GenericEventListener;
import org.olat.core.util.resource.OresHelper;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.course.CourseFactory;
import org.olat.course.ICourse;
import org.olat.course.assessment.AssessmentHelper;
import org.olat.course.assessment.AssessmentManager;
import org.olat.course.assessment.AssessmentNotificationsHandler;
import org.olat.course.auditing.UserNodeAuditManager;
import org.olat.course.nodes.AssessableCourseNode;
import org.olat.course.nodes.CourseNode;
import org.olat.course.nodes.IQSELFCourseNode;
import org.olat.course.nodes.IQSURVCourseNode;
import org.olat.course.nodes.IQTESTCourseNode;
import org.olat.course.nodes.ObjectivesHelper;
import org.olat.course.nodes.SelfAssessableCourseNode;
import org.olat.course.run.scoring.ScoreEvaluation;
import org.olat.course.run.userview.UserCourseEnvironment;
import org.olat.ims.qti.QTIChangeLogMessage;
import org.olat.ims.qti.container.AssessmentContext;
import org.olat.ims.qti.navigator.NavigatorDelegate;
import org.olat.ims.qti.process.AssessmentInstance;
import org.olat.ims.qti.process.ImsRepositoryResolver;
import org.olat.instantMessaging.InstantMessagingService;
import org.olat.modules.ModuleConfiguration;
import org.olat.modules.iq.IQDisplayController;
import org.olat.modules.iq.IQManager;
import org.olat.modules.iq.IQSecurityCallback;
import org.olat.modules.iq.IQSubmittedEvent;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.olat.util.logging.activity.LoggingResourceable;
/**
* Description:<BR>
* Run controller for the qti test, selftest and survey course node.
* Call assessmentStopped if test is finished, closed or at dispose (e.g. course tab gets closed).
*
* Initial Date: Oct 13, 2004
* @author Felix Jost
*/
public class IQRunController extends BasicController implements GenericEventListener, Activateable2, NavigatorDelegate {
private VelocityContainer myContent;
private IQSecurityCallback secCallback;
private ModuleConfiguration modConfig;
private LayoutMain3ColsController displayContainerController;
private IQDisplayController displayController;
private CourseNode courseNode;
private String type;
private UserCourseEnvironment userCourseEnv;
private Link startButton;
private Link showResultsButton;
private Link hideResultsButton;
private IFrameDisplayController iFrameCtr;
private Panel mainPanel;
private boolean assessmentStopped = true; //default: true
private EventBus singleUserEventCenter;
private OLATResourceable assessmentEventOres;
private UserSession userSession;
private OLATResourceable assessmentInstanceOres;
private final IQManager iqManager;
/**
* Constructor for a test run controller
* @param userCourseEnv
* @param moduleConfiguration
* @param secCallback
* @param ureq
* @param wControl
* @param testCourseNode
*/
IQRunController(UserCourseEnvironment userCourseEnv, ModuleConfiguration moduleConfiguration, IQSecurityCallback secCallback, UserRequest ureq, WindowControl wControl, IQTESTCourseNode testCourseNode) {
super(ureq, wControl);
this.modConfig = moduleConfiguration;
this.secCallback = secCallback;
this.userCourseEnv = userCourseEnv;
this.courseNode = testCourseNode;
this.type = AssessmentInstance.QMD_ENTRY_TYPE_ASSESS;
this.singleUserEventCenter = ureq.getUserSession().getSingleUserEventCenter();
this.assessmentEventOres = OresHelper.createOLATResourceableType(AssessmentEvent.class);
this.assessmentInstanceOres = OresHelper.createOLATResourceableType(AssessmentInstance.class);
this.userSession = ureq.getUserSession();
iqManager = CoreSpringFactory.getImpl(IQManager.class);
addLoggingResourceable(LoggingResourceable.wrap(courseNode));
myContent = createVelocityContainer("testrun");
mainPanel = putInitialPanel(myContent);
if (!modConfig.get(IQEditController.CONFIG_KEY_TYPE).equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
throw new OLATRuntimeException("IQRunController launched with Test constructor but module configuration not configured as test" ,null);
}
init(ureq);
exposeUserTestDataToVC(ureq);
StringBuilder qtiChangelog = createChangelogMsg(ureq);
// decide about changelog in VC
if(qtiChangelog.length()>0){
//there is some message
myContent.contextPut("changeLog", qtiChangelog);
}
//if show results on test home page configured - show log
Boolean showResultOnHomePage = (Boolean) testCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_RESULT_ON_HOME_PAGE);
myContent.contextPut("showChangelog", showResultOnHomePage);
}
/**
* @param ureq
* @return
*/
private StringBuilder createChangelogMsg(UserRequest ureq) {
/*
* TODO:pb:is ImsRepositoryResolver the right place for getting the change log?
*/
RepositoryEntry re = courseNode.getReferencedRepositoryEntry();
//re could be null, but if we are here it should not be null!
Roles userRoles = ureq.getUserSession().getRoles();
boolean showAll = userRoles.isAuthor() || userRoles.isOLATAdmin();
//get changelog
Formatter formatter = Formatter.getInstance(ureq.getLocale());
ImsRepositoryResolver resolver = new ImsRepositoryResolver(re);
QTIChangeLogMessage[] qtiChangeLog = resolver.getDocumentChangeLog();
StringBuilder qtiChangelog = new StringBuilder();
if(qtiChangeLog.length>0){
//there are resource changes
Arrays.sort(qtiChangeLog);
for (int i = qtiChangeLog.length-1; i >= 0 ; i--) {
//show latest change first
if(!showAll && qtiChangeLog[i].isPublic()){
//logged in person is a normal user, hence public messages only
Date msgDate = new Date(qtiChangeLog[i].getTimestmp());
qtiChangelog.append("\nChange date: ").append(formatter.formatDateAndTime(msgDate)).append("\n");
String msg = StringHelper.escapeHtml(qtiChangeLog[i].getLogMessage());
qtiChangelog.append(msg);
qtiChangelog.append("\n********************************\n");
}else if (showAll){
//logged in person is an author, olat admin, owner, show all messages
Date msgDate = new Date(qtiChangeLog[i].getTimestmp());
qtiChangelog.append("\nChange date: ").append(formatter.formatDateAndTime(msgDate)).append("\n");
String msg = StringHelper.escapeHtml(qtiChangeLog[i].getLogMessage());
qtiChangelog.append(msg);
qtiChangelog.append("\n********************************\n");
}//else non public messages are not shown to normal user
}
}
return qtiChangelog;
}
/**
* Constructor for a self-test run controller
* @param userCourseEnv
* @param moduleConfiguration
* @param secCallback
* @param ureq
* @param wControl
* @param selftestCourseNode
*/
IQRunController(UserCourseEnvironment userCourseEnv, ModuleConfiguration moduleConfiguration, IQSecurityCallback secCallback, UserRequest ureq, WindowControl wControl, IQSELFCourseNode selftestCourseNode) {
super(ureq, wControl);
this.modConfig = moduleConfiguration;
this.secCallback = secCallback;
this.userCourseEnv = userCourseEnv;
this.courseNode = selftestCourseNode;
this.type = AssessmentInstance.QMD_ENTRY_TYPE_SELF;
iqManager = CoreSpringFactory.getImpl(IQManager.class);
addLoggingResourceable(LoggingResourceable.wrap(courseNode));
myContent = createVelocityContainer("selftestrun");
mainPanel = putInitialPanel(myContent);
if (!modConfig.get(IQEditController.CONFIG_KEY_TYPE).equals(AssessmentInstance.QMD_ENTRY_TYPE_SELF)) {
throw new OLATRuntimeException("IQRunController launched with Selftest constructor but module configuration not configured as selftest" ,null);
}
init(ureq);
exposeUserSelfTestDataToVC(ureq);
StringBuilder qtiChangelog = createChangelogMsg(ureq);
// decide about changelog in VC
if(qtiChangelog.length()>0){
//there is some message
myContent.contextPut("changeLog", qtiChangelog);
}
//per default change log is not open
myContent.contextPut("showChangelog", Boolean.FALSE);
}
/**
* Constructor for a survey run controller
* @param userCourseEnv
* @param moduleConfiguration
* @param secCallback
* @param ureq
* @param wControl
* @param surveyCourseNode
*/
IQRunController(UserCourseEnvironment userCourseEnv, ModuleConfiguration moduleConfiguration, IQSecurityCallback secCallback, UserRequest ureq, WindowControl wControl, IQSURVCourseNode surveyCourseNode) {
super(ureq, wControl);
this.modConfig = moduleConfiguration;
this.secCallback = secCallback;
this.userCourseEnv = userCourseEnv;
this.courseNode = surveyCourseNode;
this.type = AssessmentInstance.QMD_ENTRY_TYPE_SURVEY;
iqManager = CoreSpringFactory.getImpl(IQManager.class);
addLoggingResourceable(LoggingResourceable.wrap(courseNode));
myContent = createVelocityContainer("surveyrun");
mainPanel = putInitialPanel(myContent);
if (!modConfig.get(IQEditController.CONFIG_KEY_TYPE).equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY)) {
throw new OLATRuntimeException("IQRunController launched with Survey constructor but module configuration not configured as survey" ,null);
}
init(ureq);
exposeUserQuestionnaireDataToVC();
StringBuilder qtiChangelog = createChangelogMsg(ureq);
// decide about changelog in VC
if(qtiChangelog.length()>0){
//there is some message
myContent.contextPut("changeLog", qtiChangelog);
}
//per default change log is not open
myContent.contextPut("showChangelog", Boolean.FALSE);
}
private void init(UserRequest ureq) {
startButton = LinkFactory.createButton("start", myContent, this);
// fetch disclaimer file
String sDisclaimer = (String)modConfig.get(IQEditController.CONFIG_KEY_DISCLAIMER);
if (sDisclaimer != null) {
VFSContainer baseContainer = userCourseEnv.getCourseEnvironment().getCourseFolderContainer();
int lastSlash = sDisclaimer.lastIndexOf('/');
if (lastSlash != -1) {
baseContainer = (VFSContainer)baseContainer.resolve(sDisclaimer.substring(0, lastSlash));
sDisclaimer = sDisclaimer.substring(lastSlash);
// first check if disclaimer exists on filesystem
if (baseContainer == null || baseContainer.resolve(sDisclaimer) == null) {
showWarning("disclaimer.file.invalid", sDisclaimer);
} else {
//screenreader do not like iframes, display inline
if (getWindowControl().getWindowBackOffice().getWindowManager().isForScreenReader()) {
HtmlStaticPageComponent disclaimerComp = new HtmlStaticPageComponent("disc", baseContainer);
myContent.put("disc", disclaimerComp);
disclaimerComp.setCurrentURI(sDisclaimer);
myContent.contextPut("hasDisc", Boolean.TRUE);
} else {
iFrameCtr = new IFrameDisplayController(ureq, getWindowControl(), baseContainer);
listenTo(iFrameCtr);//dispose automatically
myContent.put("disc", iFrameCtr.getInitialComponent());
iFrameCtr.setCurrentURI(sDisclaimer);
myContent.contextPut("hasDisc", Boolean.TRUE);
}
}
}
}
// push title and learning objectives, only visible on intro page
myContent.contextPut("menuTitle", courseNode.getShortTitle());
myContent.contextPut("displayTitle", courseNode.getLongTitle());
// Adding learning objectives
String learningObj = courseNode.getLearningObjectives();
if (learningObj != null) {
Component learningObjectives = ObjectivesHelper.createLearningObjectivesComponent(learningObj, ureq);
myContent.put("learningObjectives", learningObjectives);
myContent.contextPut("hasObjectives", learningObj); // dummy value, just an exists operator
}
if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
checkChats(ureq);
singleUserEventCenter.registerFor(this, getIdentity(), InstantMessagingService.TOWER_EVENT_ORES);
}
}
private void checkChats (UserRequest ureq) {
List<?> allChats = null;
if (ureq != null) {
allChats = ureq.getUserSession().getChats();
}
if (allChats == null || allChats.size() == 0) {
startButton.setEnabled (true);
myContent.contextPut("hasChatWindowOpen", false);
} else {
startButton.setEnabled (false);
myContent.contextPut("hasChatWindowOpen", true);
}
}
@Override
public void event(Event event) {
if (type == AssessmentInstance.QMD_ENTRY_TYPE_ASSESS) {
if (event.getCommand().startsWith("ChatWindow")) {
checkChats(null);
}
}
}
/**
* @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, org.olat.core.gui.components.Component, org.olat.core.gui.control.Event)
*/
public void event(UserRequest ureq, Component source, Event event) {
if (source == startButton && startButton.isEnabled()){
long callingResId = userCourseEnv.getCourseEnvironment().getCourseResourceableId().longValue();
String callingResDetail = courseNode.getIdent();
removeAsListenerAndDispose(displayController);
//fxdiff BAKS-7 Resume function
OLATResourceable ores = OresHelper.createOLATResourceableTypeWithoutCheck("test");
ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrapBusinessPath(ores));
WindowControl bwControl = addToHistory(ureq, ores, null);
Controller returnController = iqManager.createIQDisplayController(modConfig, secCallback, ureq, bwControl, callingResId, callingResDetail, this);
/*
* either returnController is a MessageController or it is a IQDisplayController
* this should not serve as pattern to be copy&pasted.
* FIXME:2008-11-21:pb INTRODUCED because of read/write QTI Lock solution for scalability II, 6.1.x Release
*/
if(returnController instanceof IQDisplayController){
displayController = (IQDisplayController)returnController;
listenTo(displayController);
if(displayController.isClosed()) {
//do nothing
} else if (displayController.isReady()) {
// in case displayController was unable to initialize, a message was set by displayController
// this is the case if no more attempts or security check was unsuccessfull
displayContainerController = new LayoutMain3ColsController(ureq, getWindowControl(), null, null, displayController.getInitialComponent(), null);
listenTo(displayContainerController); // autodispose
//need to wrap a course restart controller again, because IQDisplay
//runs on top of GUIStack
ICourse course = CourseFactory.loadCourse(callingResId);
RepositoryEntry courseRepositoryEntry = RepositoryManager.getInstance().lookupRepositoryEntry(course, true);
Panel empty = new Panel("empty");//empty panel set as "menu" and "tool"
Controller courseCloser = CourseFactory.createDisposedCourseRestartController(ureq, getWindowControl(), courseRepositoryEntry);
Controller disposedRestartController = new LayoutMain3ColsController(ureq, getWindowControl(), empty, empty, courseCloser.getInitialComponent(), "disposed course whily in iqRun" + callingResId);
displayContainerController.setDisposedMessageController(disposedRestartController);
final Boolean fullWindow = (Boolean)modConfig.getBooleanSafe(IQEditController.CONFIG_FULLWINDOW, true);
if(fullWindow.booleanValue()) {
displayContainerController.setAsFullscreen(ureq);
}
displayContainerController.activate();
if (modConfig.get(IQEditController.CONFIG_KEY_TYPE).equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
assessmentStopped = false;
singleUserEventCenter.registerFor(this, getIdentity(), assessmentInstanceOres);
singleUserEventCenter.fireEventToListenersOf(new AssessmentEvent(AssessmentEvent.TYPE.STARTED, ureq.getUserSession()), assessmentEventOres);
}
}//endif isReady
}else{
// -> qti file was locked -> show info message
// user must click again on course node to activate
mainPanel.pushContent(returnController.getInitialComponent());
}
} else if(source == showResultsButton) {
AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
Long assessmentID = am.getAssessmentID(courseNode, ureq.getIdentity());
if(assessmentID==null) {
//fallback solution: if the assessmentID is not available via AssessmentManager than try to get it via IQManager
long callingResId = userCourseEnv.getCourseEnvironment().getCourseResourceableId().longValue();
String callingResDetail = courseNode.getIdent();
assessmentID = iqManager.getLastAssessmentID(ureq.getIdentity(), callingResId, callingResDetail);
}
if(assessmentID!=null && !assessmentID.equals("")) {
Document doc = iqManager.getResultsReportingFromFile(ureq.getIdentity(), type, assessmentID);
//StringBuilder resultsHTML = LocalizedXSLTransformer.getInstance(ureq.getLocale()).renderResults(doc);
String summaryConfig = (String)modConfig.get(IQEditController.CONFIG_KEY_SUMMARY);
int summaryType = AssessmentInstance.getSummaryType(summaryConfig);
String resultsHTML = iqManager.transformResultsReporting(doc, ureq.getLocale(), summaryType);
myContent.contextPut("displayreporting", resultsHTML);
myContent.contextPut("resreporting", resultsHTML);
myContent.contextPut("showResults", Boolean.TRUE);
}
} else if (source == hideResultsButton) {
myContent.contextPut("showResults", Boolean.FALSE);
}
}
@Override
public void submitAssessment(AssessmentInstance ai) {
if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
AssessmentContext ac = ai.getAssessmentContext();
AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
Float score = new Float(ac.getScore());
Boolean passed = new Boolean(ac.isPassed());
ScoreEvaluation sceval = new ScoreEvaluation(score, passed, am.getNodeFullyAssessed(courseNode,
getIdentity()), new Long(ai.getAssessID()));
AssessableCourseNode acn = (AssessableCourseNode)courseNode; // assessment nodes are assesable
boolean incrementUserAttempts = true;
acn.updateUserScoreEvaluation(sceval, userCourseEnv, getIdentity(), incrementUserAttempts);
// Mark publisher for notifications
AssessmentNotificationsHandler anh = AssessmentNotificationsHandler.getInstance();
Long courseId = userCourseEnv.getCourseEnvironment().getCourseResourceableId();
anh.markPublisherNews(getIdentity(), courseId);
if(!assessmentStopped) {
assessmentStopped = true;
AssessmentEvent assessmentStoppedEvent = new AssessmentEvent(AssessmentEvent.TYPE.STOPPED, userSession);
singleUserEventCenter.deregisterFor(this, assessmentInstanceOres);
singleUserEventCenter.fireEventToListenersOf(assessmentStoppedEvent, assessmentEventOres);
}
} else if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY)) {
// save number of attempts
// although this is not an assessable node we still use the assessment
// manager since this one uses caching
AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
am.incrementNodeAttempts(courseNode, getIdentity(), userCourseEnv);
} else if(type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SELF)){
AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
am.incrementNodeAttempts(courseNode, getIdentity(), userCourseEnv);
}
}
@Override
public void cancelAssessment(AssessmentInstance ai) {
//
}
/**
* @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event)
*/
public void event(UserRequest urequest, Controller source, Event event) {
if (source == displayController) {
if (event instanceof IQSubmittedEvent) {
// Save results in case of test
if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
exposeUserTestDataToVC(urequest);
}
// Save results in case of questionnaire
else if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY)) {
exposeUserQuestionnaireDataToVC();
if(displayContainerController != null) {
displayContainerController.deactivate(urequest);
} else {
getWindowControl().pop();
}
OLATResourceable ores = OresHelper.createOLATResourceableInstance("test", -1l);
addToHistory(urequest, ores, null);
}
// Don't save results in case of self-test
// but do safe attempts !
else if(type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SELF)){
//am.incrementNodeAttempts(courseNode, urequest.getIdentity(), userCourseEnv);
}
} else if (event.equals(Event.DONE_EVENT)) {
stopAssessment(urequest, event);
} else if ("test_stopped".equals(event.getCommand())) {
stopAssessment(urequest, event);
showWarning("error.assessment.stopped");
}
}
}
private void stopAssessment(UserRequest ureq, Event event) {
if(displayContainerController != null) {
displayContainerController.deactivate(ureq);
} else {
getWindowControl().pop();
}
removeHistory(ureq);
OLATResourceable ores = OresHelper.createOLATResourceableInstance("test", -1l);
addToHistory(ureq, ores, null);
if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS) && !assessmentStopped ) {
assessmentStopped = true;
AssessmentEvent assessmentStoppedEvent = new AssessmentEvent(AssessmentEvent.TYPE.STOPPED, userSession);
singleUserEventCenter.deregisterFor(this, assessmentInstanceOres);
singleUserEventCenter.fireEventToListenersOf(assessmentStoppedEvent, assessmentEventOres);
}
fireEvent(ureq, event);
}
private void exposeUserTestDataToVC(UserRequest ureq) {
// config : show score info
Object enableScoreInfoObject = modConfig.get(IQEditController.CONFIG_KEY_ENABLESCOREINFO);
if (enableScoreInfoObject != null) {
myContent.contextPut("enableScoreInfo", enableScoreInfoObject );
} else {
myContent.contextPut("enableScoreInfo", Boolean.TRUE );
}
// configuration data
myContent.contextPut("attemptsConfig", modConfig.get(IQEditController.CONFIG_KEY_ATTEMPTS));
// user data
if ( !(courseNode instanceof AssessableCourseNode))
throw new AssertException("exposeUserTestDataToVC can only be called for test nodes, not for selftest or questionnaire");
AssessableCourseNode acn = (AssessableCourseNode)courseNode; // assessment nodes are assesable
ScoreEvaluation scoreEval = acn.getUserScoreEvaluation(userCourseEnv);
//block if test passed (and config set to check it)
Boolean blockAfterSuccess = (Boolean)modConfig.get(IQEditController.CONFIG_KEY_BLOCK_AFTER_SUCCESS);
Boolean blocked = Boolean.FALSE;
if(blockAfterSuccess != null && blockAfterSuccess.booleanValue()) {
Boolean passed = scoreEval.getPassed();
if(passed != null && passed.booleanValue()) {
blocked = Boolean.TRUE;
}
}
myContent.contextPut("blockAfterSuccess", blocked );
Identity identity = userCourseEnv.getIdentityEnvironment().getIdentity();
myContent.contextPut("score", AssessmentHelper.getRoundedScore(scoreEval.getScore()));
myContent.contextPut("hasPassedValue", (scoreEval.getPassed() == null ? Boolean.FALSE : Boolean.TRUE));
myContent.contextPut("passed", scoreEval.getPassed());
StringBuilder comment = Formatter.stripTabsAndReturns(acn.getUserUserComment(userCourseEnv));
myContent.contextPut("comment", StringHelper.xssScan(comment));
myContent.contextPut("attempts", acn.getUserAttempts(userCourseEnv));
UserNodeAuditManager am = userCourseEnv.getCourseEnvironment().getAuditManager();
myContent.contextPut("log", am.getUserNodeLog(courseNode, identity));
exposeResults(ureq);
}
/**
* Provides the self test score and results, if any, to the velocity container.
* @param ureq
*/
private void exposeUserSelfTestDataToVC(UserRequest ureq) {
// config : show score info
Object enableScoreInfoObject = modConfig.get(IQEditController.CONFIG_KEY_ENABLESCOREINFO);
if (enableScoreInfoObject != null) {
myContent.contextPut("enableScoreInfo", enableScoreInfoObject );
} else {
myContent.contextPut("enableScoreInfo", Boolean.TRUE );
}
if ( !(courseNode instanceof SelfAssessableCourseNode))
throw new AssertException("exposeUserSelfTestDataToVC can only be called for selftest nodes, not for test or questionnaire");
SelfAssessableCourseNode acn = (SelfAssessableCourseNode)courseNode;
ScoreEvaluation scoreEval = acn.getUserScoreEvaluation(userCourseEnv);
if (scoreEval != null) {
myContent.contextPut("hasResults", Boolean.TRUE);
myContent.contextPut("score", AssessmentHelper.getRoundedScore(scoreEval.getScore()));
myContent.contextPut("hasPassedValue", (scoreEval.getPassed() == null ? Boolean.FALSE : Boolean.TRUE));
myContent.contextPut("passed", scoreEval.getPassed());
myContent.contextPut("attempts", new Integer(1)); //at least one attempt
exposeResults(ureq);
}
}
/**
* Provides the show results button if results available or a message with the visibility period.
* @param ureq
*/
private void exposeResults(UserRequest ureq) {
//migration: check if old tests have no summary configured
String configuredSummary = (String) modConfig.get(IQEditController.CONFIG_KEY_SUMMARY);
boolean noSummary = configuredSummary==null || (configuredSummary!=null && configuredSummary.equals(AssessmentInstance.QMD_ENTRY_SUMMARY_NONE));
if(!noSummary) {
Boolean showResultsObj = (Boolean)modConfig.get(IQEditController.CONFIG_KEY_RESULT_ON_HOME_PAGE);
boolean showResultsOnHomePage = (showResultsObj!=null && showResultsObj.booleanValue());
myContent.contextPut("showResultsOnHomePage",new Boolean(showResultsOnHomePage));
boolean dateRelatedVisibility = AssessmentHelper.isResultVisible(modConfig);
if(showResultsOnHomePage && dateRelatedVisibility) {
myContent.contextPut("showResultsVisible",Boolean.TRUE);
showResultsButton = LinkFactory.createButton("command.showResults", myContent, this);
hideResultsButton = LinkFactory.createButton("command.hideResults", myContent, this);
} else if(showResultsOnHomePage) {
Date startDate = (Date)modConfig.get(IQEditController.CONFIG_KEY_RESULTS_START_DATE);
Date endDate = (Date)modConfig.get(IQEditController.CONFIG_KEY_RESULTS_END_DATE);
String visibilityStartDate = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale()).format(startDate);
String visibilityEndDate = "-";
if(endDate!=null) {
visibilityEndDate = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale()).format(endDate);
}
String visibilityPeriod = getTranslator().translate("showResults.visibility", new String[] { visibilityStartDate, visibilityEndDate});
myContent.contextPut("visibilityPeriod",visibilityPeriod);
myContent.contextPut("showResultsVisible",Boolean.FALSE);
}
}
}
private void exposeUserQuestionnaireDataToVC() {
AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
Identity identity = userCourseEnv.getIdentityEnvironment().getIdentity();
// although this is not an assessable node we still use the assessment
// manager since this one uses caching
myContent.contextPut("attempts", am.getNodeAttempts(courseNode, identity));
}
/**
*
* @see org.olat.core.gui.control.DefaultController#doDisspose(boolean)
*/
protected void doDispose() {
// child controllers disposed by basic controller
if (!type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
return;
}
singleUserEventCenter.deregisterFor(this, assessmentInstanceOres);
singleUserEventCenter.deregisterFor(this, InstantMessagingService.TOWER_EVENT_ORES);
if (!assessmentStopped) {
AssessmentEvent assessmentStoppedEvent = new AssessmentEvent(AssessmentEvent.TYPE.STOPPED, userSession);
singleUserEventCenter.fireEventToListenersOf(assessmentStoppedEvent, assessmentEventOres);
}
}
@Override
//fxdiff BAKS-7 Resume function
public void activate(UserRequest ureq, List<ContextEntry> entries, StateEntry state) {
if(entries == null || entries.isEmpty()) return;
ContextEntry ce = entries.remove(0);
if("test".equals(ce.getOLATResourceable().getResourceableTypeName())) {
Long resourceId = ce.getOLATResourceable().getResourceableId();
if(resourceId != null && resourceId.longValue() >= 0) {
event(ureq, startButton, Event.CHANGED_EVENT);
}
}
}
}
| |
package desmoj.extensions.visualization2d.engine.model;
import java.awt.Dimension;
import java.awt.Point;
import java.util.Hashtable;
import desmoj.extensions.visualization2d.engine.modelGrafic.Grafic;
import desmoj.extensions.visualization2d.engine.modelGrafic.ResourceGrafic;
/**
* Resource-station with waiting queue and process station.
* Every resource station has a total no of available resources.
* A entity needs a specified no of resources.
* The entities are waiting in a waiting-queue until the required
* resources are free.
*
* @version DESMO-J, Ver. 2.4.1 copyright (c) 2014
* @author christian.mueller@th-wildau.de
* For information about subproject: desmoj.extensions.visualization2d
* please have a look at:
* http://www.th-wildau.de/cmueller/Desmo-J/Visualization2d/
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
public class Resource implements Basic {
private String id;
private String name;
private List list;
private ProcessNew process;
private Hashtable<String, Integer> neededRes;
private Grafic grafic;
private Model model;
/**
* Constructor, a Resource contains a List and a ProcessNew instance.
* The id's of this instances have a prefix "res".
* @param model used animation.model.Model
* @param id resourceId
* @param resourceType resourceTypeName (only for information, its no Id)
* @param resourceTotal total number of resources (only for information)
*/
public Resource(Model model, String id, String resourceType, int resourceTotal){
this.model = model;
this.id = id;
this.name = null;
this.list = new List(model, List.PREFIX_RESOURCE, this.id);
this.process = new ProcessNew(model, ProcessNew.PREFIX_RESOURCE, this.id, resourceType, resourceTotal, null);
this.neededRes = new Hashtable<String, Integer>();
if(this.id != null) model.getResources().add(this);
}
public Model getModel(){
return this.model;
}
/**
* get id of resource
*/
public String getId() {
return this.id;
}
/**
* set name of resource
* @param name
*/
public void setName(String name){
this.name = name;
this.list.setName(name);
this.process.setName(name);
}
/**
* get name of resource
*/
public String getName(){
return this.name;
}
/**
* get resource Type (only for information)
* @return
*/
public String getResourceType(){
return this.process.getResourceType();
}
/**
* total no. of available resources
* @return
*/
public int getResourceTotal(){
return this.process.getResourceTotal();
}
/**
* no of actual used resources
* @return
*/
public int getResourceUsed(){
return this.process.getResourceUsed();
}
/**
* actual no of free resources
* @return
*/
public int getResourceFree(){
return this.process.getResourceTotal()-this.process.getResourceUsed() ;
}
/**
* actual no. of entities (sets with process-entities) in process-part
* @return
*/
public int getProcessEntriesAnz(){
return this.process.getEntriesAnz();
}
/**
* get id of entity in position index in process
* @param index
* @return
* @throws ModelException, when a internal error occurred
*/
public String getProcessEntry(int index) throws ModelException{
String out = "";
String[] pe = this.process.getProcessEntries(index);
if(pe != null && pe.length == 1) out = pe[0];
else throw new ModelException("ProcessEntry must have exact one Process");
return out;
}
/**
* get actual no. of resources, used by entity in position index
* @param index
* @return
*/
public int getResourceEntriesAnz(int index){
return this.process.getResourceEntriesAnz(index);
}
/**
* get content of waiting queue
* @return (index)(id, rank, resources needed)
*/
public String[][] getWaitingQueueContent(){
String[][] content = this.list.getContent();
int queueLength = content.length;
String[][] out = new String[queueLength][3];
for(int i=0; i<queueLength; i++){
out[i][0] = content[i][0];
out[i][1] = content[i][1];
out[i][2] = this.neededRes.get(content[i][0]).toString();
}
return out;
}
/**
* put a processEntity, that require resourceEntityAnz resources, into
* waiting queue
* @param processEntityId id of processEntity
* @param resourceEntityAnz required no. of resources
* @param time simulation time
* @throws ModelException, when processEntity isn't free
*/
public void provide(String processEntityId, int priority, int resourceEntityAnz,
String priorityAttribute, long time) throws ModelException{
Entity entity = model.getEntities().get(processEntityId);
if(entity != null && entity.isFree()){
this.list.addToContainer(processEntityId, priority, priorityAttribute, time);
this.neededRes.put(processEntityId, new Integer(resourceEntityAnz));
}else{
throw new ModelException("Entity does not exist or isn't free Id: "+processEntityId);
}
if(this.grafic != null) ((ResourceGrafic)(this.grafic)).update();
}
/**
* move processEntity from waiting queue to process
* @param processEntityId id of processEntity
* @param time simulation time
* @throws ModelException, when entity isn't in waiting queue
*/
public void takeProcess(String processEntityId, long time) throws ModelException{
if(this.list.containsInContainer(processEntityId)){
this.list.removeFromContainer(processEntityId, time);
String[] processEntityIds = new String[1];
processEntityIds[0] = processEntityId;
Integer resourceEntityAnz = this.neededRes.get(processEntityId);
if(resourceEntityAnz != null)
this.process.addEntry(processEntityIds, resourceEntityAnz, time);
else throw new ModelException("Missing processEntry "+processEntityId+" in Resource.neededRes");
}else{
throw new ModelException("Entity isn't in waiting queue of resource EntityId: "+processEntityId);
}
if(this.grafic != null) ((ResourceGrafic)(this.grafic)).update();
}
/**
* removes processEntity from process
* @param processEntityId id of processEntity
* @param time simulation time
* @throws ModelException, when entity isn't in process
*/
public void takeBack(String processEntityId, int resourceGiveBackAnz, long time) throws ModelException{
Integer anzRes = this.neededRes.get(processEntityId);
if(anzRes != null){
if(resourceGiveBackAnz < anzRes.intValue()){
// reduce no of needed resources
this.neededRes.put(processEntityId, new Integer(anzRes.intValue()-resourceGiveBackAnz));
}else{
// remove entity
if(this.process.contains(processEntityId)){
this.process.removeEntry(processEntityId, time);
this.neededRes.remove(processEntityId);
}else{
throw new ModelException("Entity isn't in process of resource EntityId: "+processEntityId);
}
}
}else{
throw new ModelException("Entity is in resource "+this.getId()+" unknown EntityId: "+processEntityId);
}
if(this.grafic != null) ((ResourceGrafic)(this.grafic)).update();
}
/**
* create a ProcessGrafic
* @param viewId Id of view
* @param x middlepoint x-coordinate
* @param y middlepoint y-coordinate
* @param defaultEntityTypeId for sizing
* @return ProcessGrafic
* @throws ModelException
*/
public Grafic createGrafic(String viewId, int x, int y, String defaultEntityTypeId,
int anzVisible, boolean horizontal, Dimension deltaSize) throws ModelException{
this.grafic = new ResourceGrafic(this, viewId, new Point(x, y), defaultEntityTypeId, anzVisible, horizontal, deltaSize);
return this.grafic;
}
/**
* get ProcessGrafic, created before
*/
public Grafic getGrafic() {
return grafic;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.lib.output;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** An {@link OutputCommitter} that commits files specified
* in job output directory i.e. ${mapreduce.output.fileoutputformat.outputdir}.
**/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class FileOutputCommitter extends PathOutputCommitter {
private static final Logger LOG =
LoggerFactory.getLogger(FileOutputCommitter.class);
/**
* Name of directory where pending data is placed. Data that has not been
* committed yet.
*/
public static final String PENDING_DIR_NAME = "_temporary";
/**
* Temporary directory name
*
* The static variable to be compatible with M/R 1.x
*/
@Deprecated
protected static final String TEMP_DIR_NAME = PENDING_DIR_NAME;
public static final String SUCCEEDED_FILE_NAME = "_SUCCESS";
public static final String SUCCESSFUL_JOB_OUTPUT_DIR_MARKER =
"mapreduce.fileoutputcommitter.marksuccessfuljobs";
public static final String FILEOUTPUTCOMMITTER_ALGORITHM_VERSION =
"mapreduce.fileoutputcommitter.algorithm.version";
public static final int FILEOUTPUTCOMMITTER_ALGORITHM_VERSION_DEFAULT = 2;
// Skip cleanup _temporary folders under job's output directory
public static final String FILEOUTPUTCOMMITTER_CLEANUP_SKIPPED =
"mapreduce.fileoutputcommitter.cleanup.skipped";
public static final boolean
FILEOUTPUTCOMMITTER_CLEANUP_SKIPPED_DEFAULT = false;
// Ignore exceptions in cleanup _temporary folder under job's output directory
public static final String FILEOUTPUTCOMMITTER_CLEANUP_FAILURES_IGNORED =
"mapreduce.fileoutputcommitter.cleanup-failures.ignored";
public static final boolean
FILEOUTPUTCOMMITTER_CLEANUP_FAILURES_IGNORED_DEFAULT = false;
// Number of attempts when failure happens in commit job
public static final String FILEOUTPUTCOMMITTER_FAILURE_ATTEMPTS =
"mapreduce.fileoutputcommitter.failures.attempts";
// default value to be 1 to keep consistent with previous behavior
public static final int FILEOUTPUTCOMMITTER_FAILURE_ATTEMPTS_DEFAULT = 1;
private Path outputPath = null;
private Path workPath = null;
private final int algorithmVersion;
private final boolean skipCleanup;
private final boolean ignoreCleanupFailures;
/**
* Create a file output committer
* @param outputPath the job's output path, or null if you want the output
* committer to act as a noop.
* @param context the task's context
* @throws IOException
*/
public FileOutputCommitter(Path outputPath,
TaskAttemptContext context) throws IOException {
this(outputPath, (JobContext)context);
if (getOutputPath() != null) {
workPath = Preconditions.checkNotNull(
getTaskAttemptPath(context, getOutputPath()),
"Null task attempt path in %s and output path %s",
context, outputPath);
}
}
/**
* Create a file output committer
* @param outputPath the job's output path, or null if you want the output
* committer to act as a noop.
* @param context the task's context
* @throws IOException
*/
@Private
public FileOutputCommitter(Path outputPath,
JobContext context) throws IOException {
super(outputPath, context);
Configuration conf = context.getConfiguration();
algorithmVersion =
conf.getInt(FILEOUTPUTCOMMITTER_ALGORITHM_VERSION,
FILEOUTPUTCOMMITTER_ALGORITHM_VERSION_DEFAULT);
LOG.info("File Output Committer Algorithm version is " + algorithmVersion);
if (algorithmVersion != 1 && algorithmVersion != 2) {
throw new IOException("Only 1 or 2 algorithm version is supported");
}
// if skip cleanup
skipCleanup = conf.getBoolean(
FILEOUTPUTCOMMITTER_CLEANUP_SKIPPED,
FILEOUTPUTCOMMITTER_CLEANUP_SKIPPED_DEFAULT);
// if ignore failures in cleanup
ignoreCleanupFailures = conf.getBoolean(
FILEOUTPUTCOMMITTER_CLEANUP_FAILURES_IGNORED,
FILEOUTPUTCOMMITTER_CLEANUP_FAILURES_IGNORED_DEFAULT);
LOG.info("FileOutputCommitter skip cleanup _temporary folders under " +
"output directory:" + skipCleanup + ", ignore cleanup failures: " +
ignoreCleanupFailures);
if (outputPath != null) {
FileSystem fs = outputPath.getFileSystem(context.getConfiguration());
this.outputPath = fs.makeQualified(outputPath);
}
}
/**
* @return the path where final output of the job should be placed. This
* could also be considered the committed application attempt path.
*/
private Path getOutputPath() {
return this.outputPath;
}
/**
* @return true if we have an output path set, else false.
*/
private boolean hasOutputPath() {
return this.outputPath != null;
}
/**
* @return the path where the output of pending job attempts are
* stored.
*/
private Path getPendingJobAttemptsPath() {
return getPendingJobAttemptsPath(getOutputPath());
}
/**
* Get the location of pending job attempts.
* @param out the base output directory.
* @return the location of pending job attempts.
*/
private static Path getPendingJobAttemptsPath(Path out) {
return new Path(out, PENDING_DIR_NAME);
}
/**
* Get the Application Attempt Id for this job
* @param context the context to look in
* @return the Application Attempt Id for a given job.
*/
private static int getAppAttemptId(JobContext context) {
return context.getConfiguration().getInt(
MRJobConfig.APPLICATION_ATTEMPT_ID, 0);
}
/**
* Compute the path where the output of a given job attempt will be placed.
* @param context the context of the job. This is used to get the
* application attempt id.
* @return the path to store job attempt data.
*/
public Path getJobAttemptPath(JobContext context) {
return getJobAttemptPath(context, getOutputPath());
}
/**
* Compute the path where the output of a given job attempt will be placed.
* @param context the context of the job. This is used to get the
* application attempt id.
* @param out the output path to place these in.
* @return the path to store job attempt data.
*/
public static Path getJobAttemptPath(JobContext context, Path out) {
return getJobAttemptPath(getAppAttemptId(context), out);
}
/**
* Compute the path where the output of a given job attempt will be placed.
* @param appAttemptId the ID of the application attempt for this job.
* @return the path to store job attempt data.
*/
protected Path getJobAttemptPath(int appAttemptId) {
return getJobAttemptPath(appAttemptId, getOutputPath());
}
/**
* Compute the path where the output of a given job attempt will be placed.
* @param appAttemptId the ID of the application attempt for this job.
* @return the path to store job attempt data.
*/
private static Path getJobAttemptPath(int appAttemptId, Path out) {
return new Path(getPendingJobAttemptsPath(out), String.valueOf(appAttemptId));
}
/**
* Compute the path where the output of pending task attempts are stored.
* @param context the context of the job with pending tasks.
* @return the path where the output of pending task attempts are stored.
*/
private Path getPendingTaskAttemptsPath(JobContext context) {
return getPendingTaskAttemptsPath(context, getOutputPath());
}
/**
* Compute the path where the output of pending task attempts are stored.
* @param context the context of the job with pending tasks.
* @return the path where the output of pending task attempts are stored.
*/
private static Path getPendingTaskAttemptsPath(JobContext context, Path out) {
return new Path(getJobAttemptPath(context, out), PENDING_DIR_NAME);
}
/**
* Compute the path where the output of a task attempt is stored until
* that task is committed.
*
* @param context the context of the task attempt.
* @return the path where a task attempt should be stored.
*/
public Path getTaskAttemptPath(TaskAttemptContext context) {
return new Path(getPendingTaskAttemptsPath(context),
String.valueOf(context.getTaskAttemptID()));
}
/**
* Compute the path where the output of a task attempt is stored until
* that task is committed.
*
* @param context the context of the task attempt.
* @param out The output path to put things in.
* @return the path where a task attempt should be stored.
*/
public static Path getTaskAttemptPath(TaskAttemptContext context, Path out) {
return new Path(getPendingTaskAttemptsPath(context, out),
String.valueOf(context.getTaskAttemptID()));
}
/**
* Compute the path where the output of a committed task is stored until
* the entire job is committed.
* @param context the context of the task attempt
* @return the path where the output of a committed task is stored until
* the entire job is committed.
*/
public Path getCommittedTaskPath(TaskAttemptContext context) {
return getCommittedTaskPath(getAppAttemptId(context), context);
}
public static Path getCommittedTaskPath(TaskAttemptContext context, Path out) {
return getCommittedTaskPath(getAppAttemptId(context), context, out);
}
/**
* Compute the path where the output of a committed task is stored until the
* entire job is committed for a specific application attempt.
* @param appAttemptId the id of the application attempt to use
* @param context the context of any task.
* @return the path where the output of a committed task is stored.
*/
protected Path getCommittedTaskPath(int appAttemptId, TaskAttemptContext context) {
return new Path(getJobAttemptPath(appAttemptId),
String.valueOf(context.getTaskAttemptID().getTaskID()));
}
private static Path getCommittedTaskPath(int appAttemptId, TaskAttemptContext context, Path out) {
return new Path(getJobAttemptPath(appAttemptId, out),
String.valueOf(context.getTaskAttemptID().getTaskID()));
}
private static class CommittedTaskFilter implements PathFilter {
@Override
public boolean accept(Path path) {
return !PENDING_DIR_NAME.equals(path.getName());
}
}
/**
* Get a list of all paths where output from committed tasks are stored.
* @param context the context of the current job
* @return the list of these Paths/FileStatuses.
* @throws IOException
*/
private FileStatus[] getAllCommittedTaskPaths(JobContext context)
throws IOException {
Path jobAttemptPath = getJobAttemptPath(context);
FileSystem fs = jobAttemptPath.getFileSystem(context.getConfiguration());
return fs.listStatus(jobAttemptPath, new CommittedTaskFilter());
}
/**
* Get the directory that the task should write results into.
* @return the work directory
* @throws IOException
*/
public Path getWorkPath() throws IOException {
return workPath;
}
/**
* Create the temporary directory that is the root of all of the task
* work directories.
* @param context the job's context
*/
public void setupJob(JobContext context) throws IOException {
if (hasOutputPath()) {
Path jobAttemptPath = getJobAttemptPath(context);
FileSystem fs = jobAttemptPath.getFileSystem(
context.getConfiguration());
if (!fs.mkdirs(jobAttemptPath)) {
LOG.error("Mkdirs failed to create " + jobAttemptPath);
}
} else {
LOG.warn("Output Path is null in setupJob()");
}
}
/**
* The job has completed, so do works in commitJobInternal().
* Could retry on failure if using algorithm 2.
* @param context the job's context
*/
public void commitJob(JobContext context) throws IOException {
int maxAttemptsOnFailure = isCommitJobRepeatable(context) ?
context.getConfiguration().getInt(FILEOUTPUTCOMMITTER_FAILURE_ATTEMPTS,
FILEOUTPUTCOMMITTER_FAILURE_ATTEMPTS_DEFAULT) : 1;
int attempt = 0;
boolean jobCommitNotFinished = true;
while (jobCommitNotFinished) {
try {
commitJobInternal(context);
jobCommitNotFinished = false;
} catch (Exception e) {
if (++attempt >= maxAttemptsOnFailure) {
throw e;
} else {
LOG.warn("Exception get thrown in job commit, retry (" + attempt +
") time.", e);
}
}
}
}
/**
* The job has completed, so do following commit job, include:
* Move all committed tasks to the final output dir (algorithm 1 only).
* Delete the temporary directory, including all of the work directories.
* Create a _SUCCESS file to make it as successful.
* @param context the job's context
*/
@VisibleForTesting
protected void commitJobInternal(JobContext context) throws IOException {
if (hasOutputPath()) {
Path finalOutput = getOutputPath();
FileSystem fs = finalOutput.getFileSystem(context.getConfiguration());
if (algorithmVersion == 1) {
for (FileStatus stat: getAllCommittedTaskPaths(context)) {
mergePaths(fs, stat, finalOutput);
}
}
if (skipCleanup) {
LOG.info("Skip cleanup the _temporary folders under job's output " +
"directory in commitJob.");
} else {
// delete the _temporary folder and create a _done file in the o/p
// folder
try {
cleanupJob(context);
} catch (IOException e) {
if (ignoreCleanupFailures) {
// swallow exceptions in cleanup as user configure to make sure
// commitJob could be success even when cleanup get failure.
LOG.error("Error in cleanup job, manually cleanup is needed.", e);
} else {
// throw back exception to fail commitJob.
throw e;
}
}
}
// True if the job requires output.dir marked on successful job.
// Note that by default it is set to true.
if (context.getConfiguration().getBoolean(
SUCCESSFUL_JOB_OUTPUT_DIR_MARKER, true)) {
Path markerPath = new Path(outputPath, SUCCEEDED_FILE_NAME);
// If job commit is repeatable and previous/another AM could write
// mark file already, we need to set overwritten to be true explicitly
// in case other FS implementations don't overwritten by default.
if (isCommitJobRepeatable(context)) {
fs.create(markerPath, true).close();
} else {
fs.create(markerPath).close();
}
}
} else {
LOG.warn("Output Path is null in commitJob()");
}
}
/**
* Merge two paths together. Anything in from will be moved into to, if there
* are any name conflicts while merging the files or directories in from win.
* @param fs the File System to use
* @param from the path data is coming from.
* @param to the path data is going to.
* @throws IOException on any error
*/
private void mergePaths(FileSystem fs, final FileStatus from,
final Path to) throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Merging data from " + from + " to " + to);
}
FileStatus toStat;
try {
toStat = fs.getFileStatus(to);
} catch (FileNotFoundException fnfe) {
toStat = null;
}
if (from.isFile()) {
if (toStat != null) {
if (!fs.delete(to, true)) {
throw new IOException("Failed to delete " + to);
}
}
if (!fs.rename(from.getPath(), to)) {
throw new IOException("Failed to rename " + from + " to " + to);
}
} else if (from.isDirectory()) {
if (toStat != null) {
if (!toStat.isDirectory()) {
if (!fs.delete(to, true)) {
throw new IOException("Failed to delete " + to);
}
renameOrMerge(fs, from, to);
} else {
//It is a directory so merge everything in the directories
for (FileStatus subFrom : fs.listStatus(from.getPath())) {
Path subTo = new Path(to, subFrom.getPath().getName());
mergePaths(fs, subFrom, subTo);
}
}
} else {
renameOrMerge(fs, from, to);
}
}
}
private void renameOrMerge(FileSystem fs, FileStatus from, Path to)
throws IOException {
if (algorithmVersion == 1) {
if (!fs.rename(from.getPath(), to)) {
throw new IOException("Failed to rename " + from + " to " + to);
}
} else {
fs.mkdirs(to);
for (FileStatus subFrom : fs.listStatus(from.getPath())) {
Path subTo = new Path(to, subFrom.getPath().getName());
mergePaths(fs, subFrom, subTo);
}
}
}
@Override
@Deprecated
public void cleanupJob(JobContext context) throws IOException {
if (hasOutputPath()) {
Path pendingJobAttemptsPath = getPendingJobAttemptsPath();
FileSystem fs = pendingJobAttemptsPath
.getFileSystem(context.getConfiguration());
// if job allow repeatable commit and pendingJobAttemptsPath could be
// deleted by previous AM, we should tolerate FileNotFoundException in
// this case.
try {
fs.delete(pendingJobAttemptsPath, true);
} catch (FileNotFoundException e) {
if (!isCommitJobRepeatable(context)) {
throw e;
}
}
} else {
LOG.warn("Output Path is null in cleanupJob()");
}
}
/**
* Delete the temporary directory, including all of the work directories.
* @param context the job's context
*/
@Override
public void abortJob(JobContext context, JobStatus.State state)
throws IOException {
// delete the _temporary folder
cleanupJob(context);
}
/**
* No task setup required.
*/
@Override
public void setupTask(TaskAttemptContext context) throws IOException {
// FileOutputCommitter's setupTask doesn't do anything. Because the
// temporary task directory is created on demand when the
// task is writing.
}
/**
* Move the files from the work directory to the job output directory
* @param context the task context
*/
@Override
public void commitTask(TaskAttemptContext context)
throws IOException {
commitTask(context, null);
}
@Private
public void commitTask(TaskAttemptContext context, Path taskAttemptPath)
throws IOException {
TaskAttemptID attemptId = context.getTaskAttemptID();
if (hasOutputPath()) {
context.progress();
if(taskAttemptPath == null) {
taskAttemptPath = getTaskAttemptPath(context);
}
FileSystem fs = taskAttemptPath.getFileSystem(context.getConfiguration());
FileStatus taskAttemptDirStatus;
try {
taskAttemptDirStatus = fs.getFileStatus(taskAttemptPath);
} catch (FileNotFoundException e) {
taskAttemptDirStatus = null;
}
if (taskAttemptDirStatus != null) {
if (algorithmVersion == 1) {
Path committedTaskPath = getCommittedTaskPath(context);
if (fs.exists(committedTaskPath)) {
if (!fs.delete(committedTaskPath, true)) {
throw new IOException("Could not delete " + committedTaskPath);
}
}
if (!fs.rename(taskAttemptPath, committedTaskPath)) {
throw new IOException("Could not rename " + taskAttemptPath + " to "
+ committedTaskPath);
}
LOG.info("Saved output of task '" + attemptId + "' to " +
committedTaskPath);
} else {
// directly merge everything from taskAttemptPath to output directory
mergePaths(fs, taskAttemptDirStatus, outputPath);
LOG.info("Saved output of task '" + attemptId + "' to " +
outputPath);
}
} else {
LOG.warn("No Output found for " + attemptId);
}
} else {
LOG.warn("Output Path is null in commitTask()");
}
}
/**
* Delete the work directory
* @throws IOException
*/
@Override
public void abortTask(TaskAttemptContext context) throws IOException {
abortTask(context, null);
}
@Private
public void abortTask(TaskAttemptContext context, Path taskAttemptPath) throws IOException {
if (hasOutputPath()) {
context.progress();
if(taskAttemptPath == null) {
taskAttemptPath = getTaskAttemptPath(context);
}
FileSystem fs = taskAttemptPath.getFileSystem(context.getConfiguration());
if(!fs.delete(taskAttemptPath, true)) {
LOG.warn("Could not delete "+taskAttemptPath);
}
} else {
LOG.warn("Output Path is null in abortTask()");
}
}
/**
* Did this task write any files in the work directory?
* @param context the task's context
*/
@Override
public boolean needsTaskCommit(TaskAttemptContext context
) throws IOException {
return needsTaskCommit(context, null);
}
@Private
public boolean needsTaskCommit(TaskAttemptContext context, Path taskAttemptPath
) throws IOException {
if(hasOutputPath()) {
if(taskAttemptPath == null) {
taskAttemptPath = getTaskAttemptPath(context);
}
FileSystem fs = taskAttemptPath.getFileSystem(context.getConfiguration());
return fs.exists(taskAttemptPath);
}
return false;
}
@Override
@Deprecated
public boolean isRecoverySupported() {
return true;
}
@Override
public boolean isCommitJobRepeatable(JobContext context) throws IOException {
return algorithmVersion == 2;
}
@Override
public void recoverTask(TaskAttemptContext context)
throws IOException {
if(hasOutputPath()) {
context.progress();
TaskAttemptID attemptId = context.getTaskAttemptID();
int previousAttempt = getAppAttemptId(context) - 1;
if (previousAttempt < 0) {
throw new IOException ("Cannot recover task output for first attempt...");
}
Path previousCommittedTaskPath = getCommittedTaskPath(
previousAttempt, context);
FileSystem fs = previousCommittedTaskPath.getFileSystem(context.getConfiguration());
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to recover task from " + previousCommittedTaskPath);
}
if (algorithmVersion == 1) {
if (fs.exists(previousCommittedTaskPath)) {
Path committedTaskPath = getCommittedTaskPath(context);
if (!fs.delete(committedTaskPath, true) &&
fs.exists(committedTaskPath)) {
throw new IOException("Could not delete " + committedTaskPath);
}
//Rename can fail if the parent directory does not yet exist.
Path committedParent = committedTaskPath.getParent();
fs.mkdirs(committedParent);
if (!fs.rename(previousCommittedTaskPath, committedTaskPath)) {
throw new IOException("Could not rename " + previousCommittedTaskPath +
" to " + committedTaskPath);
}
} else {
LOG.warn(attemptId+" had no output to recover.");
}
} else {
// essentially a no-op, but for backwards compatibility
// after upgrade to the new fileOutputCommitter,
// check if there are any output left in committedTaskPath
try {
FileStatus from = fs.getFileStatus(previousCommittedTaskPath);
LOG.info("Recovering task for upgrading scenario, moving files from "
+ previousCommittedTaskPath + " to " + outputPath);
mergePaths(fs, from, outputPath);
} catch (FileNotFoundException ignored) {
}
LOG.info("Done recovering task " + attemptId);
}
} else {
LOG.warn("Output Path is null in recoverTask()");
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(
"FileOutputCommitter{");
sb.append(super.toString()).append("; ");
sb.append("outputPath=").append(outputPath);
sb.append(", workPath=").append(workPath);
sb.append(", algorithmVersion=").append(algorithmVersion);
sb.append(", skipCleanup=").append(skipCleanup);
sb.append(", ignoreCleanupFailures=").append(ignoreCleanupFailures);
sb.append('}');
return sb.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.net;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Uninterruptibles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.Channel;
import net.openhft.chronicle.core.util.ThrowingBiConsumer;
import net.openhft.chronicle.core.util.ThrowingRunnable;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.net.MessageGenerator.UniformPayloadGenerator;
import org.apache.cassandra.utils.ExecutorUtils;
import org.apache.cassandra.utils.MonotonicClock;
import org.apache.cassandra.utils.memory.BufferPool;
import static java.lang.Math.min;
import static org.apache.cassandra.net.MessagingService.current_version;
import static org.apache.cassandra.net.ConnectionType.LARGE_MESSAGES;
import static org.apache.cassandra.utils.MonotonicClock.approxTime;
import static org.apache.cassandra.utils.MonotonicClock.preciseTime;
public class ConnectionBurnTest
{
private static final Logger logger = LoggerFactory.getLogger(ConnectionBurnTest.class);
static
{
// stop updating ALMOST_SAME_TIME so that we get consistent message expiration times
((MonotonicClock.AbstractEpochSamplingClock) preciseTime).pauseEpochSampling();
DatabaseDescriptor.daemonInitialization();
DatabaseDescriptor.setCrossNodeTimeout(true);
}
static class NoGlobalInboundMetrics implements InboundMessageHandlers.GlobalMetricCallbacks
{
static final NoGlobalInboundMetrics instance = new NoGlobalInboundMetrics();
public LatencyConsumer internodeLatencyRecorder(InetAddressAndPort to)
{
return (timeElapsed, timeUnit) -> {};
}
public void recordInternalLatency(Verb verb, long timeElapsed, TimeUnit timeUnit) {}
public void recordInternodeDroppedMessage(Verb verb, long timeElapsed, TimeUnit timeUnit) {}
}
static class Inbound
{
final Map<InetAddressAndPort, Map<InetAddressAndPort, InboundMessageHandlers>> handlersByRecipientThenSender;
final InboundSockets sockets;
Inbound(List<InetAddressAndPort> endpoints, GlobalInboundSettings settings, Test test)
{
final InboundMessageHandlers.GlobalResourceLimits globalInboundLimits = new InboundMessageHandlers.GlobalResourceLimits(new ResourceLimits.Concurrent(settings.globalReserveLimit));
Map<InetAddressAndPort, Map<InetAddressAndPort, InboundMessageHandlers>> handlersByRecipientThenSender = new HashMap<>();
List<InboundConnectionSettings> bind = new ArrayList<>();
for (InetAddressAndPort recipient : endpoints)
{
Map<InetAddressAndPort, InboundMessageHandlers> handlersBySender = new HashMap<>();
for (InetAddressAndPort sender : endpoints)
handlersBySender.put(sender, new InboundMessageHandlers(recipient, sender, settings.queueCapacity, settings.endpointReserveLimit, globalInboundLimits, NoGlobalInboundMetrics.instance, test, test));
handlersByRecipientThenSender.put(recipient, handlersBySender);
bind.add(settings.template.withHandlers(handlersBySender::get).withBindAddress(recipient));
}
this.sockets = new InboundSockets(bind);
this.handlersByRecipientThenSender = handlersByRecipientThenSender;
}
}
private static class ConnectionKey
{
final InetAddressAndPort from;
final InetAddressAndPort to;
final ConnectionType type;
private ConnectionKey(InetAddressAndPort from, InetAddressAndPort to, ConnectionType type)
{
this.from = from;
this.to = to;
this.type = type;
}
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConnectionKey that = (ConnectionKey) o;
return Objects.equals(from, that.from) &&
Objects.equals(to, that.to) &&
type == that.type;
}
public int hashCode()
{
return Objects.hash(from, to, type);
}
}
private static class Test implements InboundMessageHandlers.HandlerProvider, InboundMessageHandlers.MessageConsumer
{
private final IVersionedSerializer<byte[]> serializer = new IVersionedSerializer<byte[]>()
{
public void serialize(byte[] payload, DataOutputPlus out, int version) throws IOException
{
long id = MessageGenerator.getId(payload);
forId(id).serialize(id, payload, out, version);
}
public byte[] deserialize(DataInputPlus in, int version) throws IOException
{
MessageGenerator.Header header = MessageGenerator.readHeader(in, version);
return forId(header.id).deserialize(header, in, version);
}
public long serializedSize(byte[] payload, int version)
{
return MessageGenerator.serializedSize(payload, version);
}
};
static class Builder
{
long time;
TimeUnit timeUnit;
int endpoints;
MessageGenerators generators;
OutboundConnectionSettings outbound;
GlobalInboundSettings inbound;
public Builder time(long time, TimeUnit timeUnit) { this.time = time; this.timeUnit = timeUnit; return this; }
public Builder endpoints(int endpoints) { this.endpoints = endpoints; return this; }
public Builder inbound(GlobalInboundSettings inbound) { this.inbound = inbound; return this; }
public Builder outbound(OutboundConnectionSettings outbound) { this.outbound = outbound; return this; }
public Builder generators(MessageGenerators generators) { this.generators = generators; return this; }
Test build() { return new Test(endpoints, generators, inbound, outbound, timeUnit.toNanos(time)); }
}
static Builder builder() { return new Builder(); }
private static final int messageIdsPerConnection = 1 << 20;
final long runForNanos;
final int version;
final List<InetAddressAndPort> endpoints;
final Inbound inbound;
final Connection[] connections;
final long[] connectionMessageIds;
final ExecutorService executor = Executors.newCachedThreadPool();
final Map<ConnectionKey, Connection> connectionLookup = new HashMap<>();
private Test(int simulateEndpoints, MessageGenerators messageGenerators, GlobalInboundSettings inboundSettings, OutboundConnectionSettings outboundTemplate, long runForNanos)
{
this.endpoints = endpoints(simulateEndpoints);
this.inbound = new Inbound(endpoints, inboundSettings, this);
this.connections = new Connection[endpoints.size() * endpoints.size() * 3];
this.connectionMessageIds = new long[connections.length];
this.version = outboundTemplate.acceptVersions == null ? current_version : outboundTemplate.acceptVersions.max;
this.runForNanos = runForNanos;
int i = 0;
long minId = 0, maxId = messageIdsPerConnection - 1;
for (InetAddressAndPort recipient : endpoints)
{
for (InetAddressAndPort sender : endpoints)
{
InboundMessageHandlers inboundHandlers = inbound.handlersByRecipientThenSender.get(recipient).get(sender);
OutboundConnectionSettings template = outboundTemplate.withDefaultReserveLimits();
ResourceLimits.Limit reserveEndpointCapacityInBytes = new ResourceLimits.Concurrent(template.applicationSendQueueReserveEndpointCapacityInBytes);
ResourceLimits.EndpointAndGlobal reserveCapacityInBytes = new ResourceLimits.EndpointAndGlobal(reserveEndpointCapacityInBytes, template.applicationSendQueueReserveGlobalCapacityInBytes);
for (ConnectionType type : ConnectionType.MESSAGING_TYPES)
{
Connection connection = new Connection(sender, recipient, type, inboundHandlers, template, reserveCapacityInBytes, messageGenerators.get(type), minId, maxId);
this.connections[i] = connection;
this.connectionMessageIds[i] = minId;
connectionLookup.put(new ConnectionKey(sender, recipient, type), connection);
minId = maxId + 1;
maxId += messageIdsPerConnection;
++i;
}
}
}
}
Connection forId(long messageId)
{
int i = Arrays.binarySearch(connectionMessageIds, messageId);
if (i < 0) i = -2 -i;
Connection connection = connections[i];
assert connection.minId <= messageId && connection.maxId >= messageId;
return connection;
}
List<Connection> getConnections(InetAddressAndPort endpoint, boolean inbound)
{
List<Connection> result = new ArrayList<>();
for (ConnectionType type : ConnectionType.MESSAGING_TYPES)
{
for (InetAddressAndPort other : endpoints)
{
result.add(connectionLookup.get(inbound ? new ConnectionKey(other, endpoint, type)
: new ConnectionKey(endpoint, other, type)));
}
}
result.forEach(c -> {assert endpoint.equals(inbound ? c.recipient : c.sender); });
return result;
}
public void run() throws ExecutionException, InterruptedException, NoSuchFieldException, IllegalAccessException, TimeoutException
{
Reporters reporters = new Reporters(endpoints, connections);
try
{
long deadline = System.nanoTime() + runForNanos;
Verb._TEST_2.unsafeSetHandler(() -> message -> {});
Verb._TEST_2.unsafeSetSerializer(() -> serializer);
inbound.sockets.open().get();
CountDownLatch failed = new CountDownLatch(1);
for (Connection connection : connections)
connection.startVerifier(failed::countDown, executor, deadline);
for (int i = 0 ; i < 2 * connections.length ; ++i)
{
executor.execute(() -> {
String threadName = Thread.currentThread().getName();
try
{
ThreadLocalRandom random = ThreadLocalRandom.current();
while (approxTime.now() < deadline && !Thread.currentThread().isInterrupted())
{
Connection connection = connections[random.nextInt(connections.length)];
if (!connection.registerSender())
continue;
try
{
Thread.currentThread().setName("Generate-" + connection.linkId);
int count = 0;
switch (random.nextInt() & 3)
{
case 0: count = random.nextInt(100, 200); break;
case 1: count = random.nextInt(200, 1000); break;
case 2: count = random.nextInt(1000, 2000); break;
case 3: count = random.nextInt(2000, 10000); break;
}
if (connection.outbound.type() == LARGE_MESSAGES)
count /= 2;
while (connection.isSending()
&& count-- > 0
&& approxTime.now() < deadline
&& !Thread.currentThread().isInterrupted())
connection.sendOne();
}
finally
{
Thread.currentThread().setName(threadName);
connection.unregisterSender();
}
}
}
catch (Throwable t)
{
if (t instanceof InterruptedException)
return;
logger.error("Unexpected exception", t);
failed.countDown();
}
});
}
executor.execute(() -> {
Thread.currentThread().setName("Test-SetInFlight");
ThreadLocalRandom random = ThreadLocalRandom.current();
List<Connection> connections = new ArrayList<>(Arrays.asList(this.connections));
while (!Thread.currentThread().isInterrupted())
{
Collections.shuffle(connections);
int total = random.nextInt(1 << 20, 128 << 20);
for (int i = connections.size() - 1; i >= 1 ; --i)
{
int average = total / (i + 1);
int max = random.nextInt(1, min(2 * average, total - 2));
int min = random.nextInt(0, max);
connections.get(i).setInFlightByteBounds(min, max);
total -= max;
}
// note that setInFlightByteBounds might not
connections.get(0).setInFlightByteBounds(random.nextInt(0, total), total);
Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS);
}
});
// TODO: slowly modify the pattern of interrupts, from often to infrequent
executor.execute(() -> {
Thread.currentThread().setName("Test-Reconnect");
ThreadLocalRandom random = ThreadLocalRandom.current();
while (deadline > System.nanoTime())
{
try
{
Thread.sleep(random.nextInt(60000));
}
catch (InterruptedException e)
{
break;
}
Connection connection = connections[random.nextInt(connections.length)];
OutboundConnectionSettings template = connection.outboundTemplate;
template = ConnectionTest.SETTINGS.get(random.nextInt(ConnectionTest.SETTINGS.size()))
.outbound.apply(template);
connection.reconnectWith(template);
}
});
executor.execute(() -> {
Thread.currentThread().setName("Test-Sync");
ThreadLocalRandom random = ThreadLocalRandom.current();
BiConsumer<InetAddressAndPort, List<Connection>> checkStoppedTo = (to, from) -> {
InboundMessageHandlers handlers = from.get(0).inbound;
long using = handlers.usingCapacity();
long usingReserve = handlers.usingEndpointReserveCapacity();
if (using != 0 || usingReserve != 0)
{
String message = to + " inbound using %d capacity and %d reserve; should be zero";
from.get(0).verifier.logFailure(message, using, usingReserve);
}
};
BiConsumer<InetAddressAndPort, List<Connection>> checkStoppedFrom = (from, to) -> {
long using = to.stream().map(c -> c.outbound).mapToLong(OutboundConnection::pendingBytes).sum();
long usingReserve = to.get(0).outbound.unsafeGetEndpointReserveLimits().using();
if (using != 0 || usingReserve != 0)
{
String message = from + " outbound using %d capacity and %d reserve; should be zero";
to.get(0).verifier.logFailure(message, using, usingReserve);
}
};
ThrowingBiConsumer<List<Connection>, ThrowingRunnable<InterruptedException>, InterruptedException> sync =
(connections, exec) -> {
logger.info("Syncing connections: {}", connections);
final CountDownLatch ready = new CountDownLatch(connections.size());
final CountDownLatch done = new CountDownLatch(1);
for (Connection connection : connections)
{
connection.sync(() -> {
ready.countDown();
try { done.await(); }
catch (InterruptedException e) { Thread.interrupted(); }
});
}
ready.await();
try
{
exec.run();
}
finally
{
done.countDown();
}
logger.info("Sync'd connections: {}", connections);
};
int count = 0;
while (deadline > System.nanoTime())
{
try
{
Thread.sleep(random.nextInt(10000));
if (++count % 10 == 0)
// {
// boolean checkInbound = random.nextBoolean();
// BiConsumer<InetAddressAndPort, List<Connection>> verifier = checkInbound ? checkStoppedTo : checkStoppedFrom;
// InetAddressAndPort endpoint = endpoints.get(random.nextInt(endpoints.size()));
// List<Connection> connections = getConnections(endpoint, checkInbound);
// sync.accept(connections, () -> verifier.accept(endpoint, connections));
// }
// else if (count % 100 == 0)
{
sync.accept(ImmutableList.copyOf(connections), () -> {
for (InetAddressAndPort endpoint : endpoints)
{
checkStoppedTo .accept(endpoint, getConnections(endpoint, true ));
checkStoppedFrom.accept(endpoint, getConnections(endpoint, false));
}
long inUse = BufferPool.unsafeGetBytesInUse();
if (inUse > 0)
{
// try
// {
// ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class).dumpHeap("/Users/belliottsmith/code/cassandra/cassandra/leak.hprof", true);
// }
// catch (IOException e)
// {
// throw new RuntimeException(e);
// }
connections[0].verifier.logFailure("Using %d bytes of BufferPool, but all connections are idle", inUse);
}
});
}
else
{
CountDownLatch latch = new CountDownLatch(1);
Connection connection = connections[random.nextInt(connections.length)];
connection.sync(latch::countDown);
latch.await();
}
}
catch (InterruptedException e)
{
break;
}
}
});
while (deadline > System.nanoTime() && failed.getCount() > 0)
{
reporters.update();
reporters.print();
Uninterruptibles.awaitUninterruptibly(failed, 30L, TimeUnit.SECONDS);
}
executor.shutdownNow();
ExecutorUtils.awaitTermination(1L, TimeUnit.MINUTES, executor);
}
finally
{
reporters.update();
reporters.print();
inbound.sockets.close().get();
new FutureCombiner(Arrays.stream(connections)
.map(c -> c.outbound.close(false))
.collect(Collectors.toList()))
.get();
}
}
class WrappedInboundCallbacks implements InboundMessageCallbacks
{
private final InboundMessageCallbacks wrapped;
WrappedInboundCallbacks(InboundMessageCallbacks wrapped)
{
this.wrapped = wrapped;
}
public void onHeaderArrived(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onHeaderArrived(messageSize, header, timeElapsed, unit);
wrapped.onHeaderArrived(messageSize, header, timeElapsed, unit);
}
public void onArrived(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onArrived(messageSize, header, timeElapsed, unit);
wrapped.onArrived(messageSize, header, timeElapsed, unit);
}
public void onArrivedExpired(int messageSize, Message.Header header, boolean wasCorrupt, long timeElapsed, TimeUnit unit)
{
forId(header.id).onArrivedExpired(messageSize, header, wasCorrupt, timeElapsed, unit);
wrapped.onArrivedExpired(messageSize, header, wasCorrupt, timeElapsed, unit);
}
public void onArrivedCorrupt(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onArrivedCorrupt(messageSize, header, timeElapsed, unit);
wrapped.onArrivedCorrupt(messageSize, header, timeElapsed, unit);
}
public void onClosedBeforeArrival(int messageSize, Message.Header header, int bytesReceived, boolean wasCorrupt, boolean wasExpired)
{
forId(header.id).onClosedBeforeArrival(messageSize, header, bytesReceived, wasCorrupt, wasExpired);
wrapped.onClosedBeforeArrival(messageSize, header, bytesReceived, wasCorrupt, wasExpired);
}
public void onFailedDeserialize(int messageSize, Message.Header header, Throwable t)
{
forId(header.id).onFailedDeserialize(messageSize, header, t);
wrapped.onFailedDeserialize(messageSize, header, t);
}
public void onDispatched(int messageSize, Message.Header header)
{
forId(header.id).onDispatched(messageSize, header);
wrapped.onDispatched(messageSize, header);
}
public void onExecuting(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onExecuting(messageSize, header, timeElapsed, unit);
wrapped.onExecuting(messageSize, header, timeElapsed, unit);
}
public void onProcessed(int messageSize, Message.Header header)
{
forId(header.id).onProcessed(messageSize, header);
wrapped.onProcessed(messageSize, header);
}
public void onExpired(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onExpired(messageSize, header, timeElapsed, unit);
wrapped.onExpired(messageSize, header, timeElapsed, unit);
}
public void onExecuted(int messageSize, Message.Header header, long timeElapsed, TimeUnit unit)
{
forId(header.id).onExecuted(messageSize, header, timeElapsed, unit);
wrapped.onExecuted(messageSize, header, timeElapsed, unit);
}
}
public void fail(Message.Header header, Throwable failure)
{
// forId(header.id).verifier.logFailure("Unexpected failure", failure);
}
public void accept(Message<?> message)
{
forId(message.id()).process(message);
}
public InboundMessageCallbacks wrap(InboundMessageCallbacks wrap)
{
return new WrappedInboundCallbacks(wrap);
}
public InboundMessageHandler provide(
FrameDecoder decoder,
ConnectionType type,
Channel channel,
InetAddressAndPort self,
InetAddressAndPort peer,
int version,
int largeMessageThreshold,
int queueCapacity,
ResourceLimits.Limit endpointReserveCapacity,
ResourceLimits.Limit globalReserveCapacity,
InboundMessageHandler.WaitQueue endpointWaitQueue,
InboundMessageHandler.WaitQueue globalWaitQueue,
InboundMessageHandler.OnHandlerClosed onClosed,
InboundMessageCallbacks callbacks,
Consumer<Message<?>> messageSink
)
{
return new InboundMessageHandler(decoder, type, channel, self, peer, version, largeMessageThreshold, queueCapacity, endpointReserveCapacity, globalReserveCapacity, endpointWaitQueue, globalWaitQueue, onClosed, wrap(callbacks), messageSink)
{
final IntConsumer releaseCapacity = size -> super.releaseProcessedCapacity(size, null);
protected void releaseProcessedCapacity(int bytes, Message.Header header)
{
forId(header.id).controller.process(bytes, releaseCapacity);
}
};
}
}
static List<InetAddressAndPort> endpoints(int count)
{
return IntStream.rangeClosed(1, count)
.mapToObj(ConnectionBurnTest::endpoint)
.collect(Collectors.toList());
}
private static InetAddressAndPort endpoint(int i)
{
try
{
return InetAddressAndPort.getByName("127.0.0." + i);
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
}
private void test(GlobalInboundSettings inbound, OutboundConnectionSettings outbound) throws ExecutionException, InterruptedException, NoSuchFieldException, IllegalAccessException, TimeoutException
{
MessageGenerator small = new UniformPayloadGenerator(0, 1, (1 << 15));
MessageGenerator large = new UniformPayloadGenerator(0, 1, (1 << 16) + (1 << 15));
MessageGenerators generators = new MessageGenerators(small, large);
outbound = outbound.withApplicationSendQueueCapacityInBytes(1 << 18)
.withApplicationReserveSendQueueCapacityInBytes(1 << 30, new ResourceLimits.Concurrent(Integer.MAX_VALUE));
Test.builder()
.generators(generators)
.endpoints(4)
.inbound(inbound)
.outbound(outbound)
// change the following for a longer burn
.time(2L, TimeUnit.MINUTES)
.build().run();
}
public static void main(String[] args) throws ExecutionException, InterruptedException, NoSuchFieldException, IllegalAccessException, TimeoutException
{
new ConnectionBurnTest().test();
}
@org.junit.Test
public void test() throws ExecutionException, InterruptedException, NoSuchFieldException, IllegalAccessException, TimeoutException
{
GlobalInboundSettings inboundSettings = new GlobalInboundSettings()
.withQueueCapacity(1 << 18)
.withEndpointReserveLimit(1 << 20)
.withGlobalReserveLimit(1 << 21)
.withTemplate(new InboundConnectionSettings()
.withEncryption(ConnectionTest.encryptionOptions));
test(inboundSettings, new OutboundConnectionSettings(null)
.withTcpUserTimeoutInMS(0));
MessagingService.instance().socketFactory.shutdownNow();
}
}
| |
package org.taskdistribution;
import org.jgroups.*;
import org.jgroups.util.Promise;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Bela Ban
* todo: make submit() non-blocking, e.g. with a CompletableFuture (JDK 8)
*/
public class Server extends ReceiverAdapter implements Master, Slave {
private String props="udp.xml";
private JChannel ch;
/** Maps task IDs to Tasks */
private final ConcurrentMap<ClusterID,Entry> tasks=new ConcurrentHashMap<>();
/** Used to handle received tasks */
private final ExecutorService thread_pool=Executors.newCachedThreadPool();
private View view;
private int rank=-1;
private int cluster_size=-1;
public Server(String props) {
this.props=props;
}
public void start(String name) throws Exception {
ch=new JChannel(props).name(name);
ch.setReceiver(this);
ch.connect("dzone-demo");
}
public void stop() {
thread_pool.shutdown();
ch.close();
}
public String info() {
StringBuilder sb=new StringBuilder();
sb.append("local_addr=" + ch.getAddress() + "\nview=" + view).append("\n");
sb.append("rank=" + rank + "\n");
sb.append("(" + tasks.size() + " entries in tasks cache)");
return sb.toString();
}
public Object submit(Task task, long timeout) throws Exception {
ClusterID id=ClusterID.create(ch.getAddress());
try {
Request req=new Request(Request.Type.EXECUTE, task, id, null);
byte[] buf=Util.streamableToByteBuffer(req);
Entry entry=new Entry(task, ch.getAddress());
tasks.put(id, entry);
log("==> submitting " + id);
ch.send(new Message(null, buf));
// wait on entry for result
return entry.promise.getResultWithTimeout(timeout);
}
catch(Exception ex) {
tasks.remove(id); // remove it again
throw ex;
}
}
public Object handle(Task task) {
return task.execute();
}
/** All we receive is Requests */
public void receive(Message msg) {
try {
Request req=Util.streamableFromByteBuffer(Request.class, msg.getRawBuffer(), msg.getOffset(), msg.getLength());
switch(req.type) {
case EXECUTE:
handleExecute(req.id, msg.getSrc(), req.task);
break;
case RESULT:
Entry entry=tasks.get(req.id);
if(entry == null) {
err("found no entry for request " + req.id);
}
else {
entry.promise.setResult(req.result);
}
multicastRemoveRequest(req.id);
break;
case REMOVE:
tasks.remove(req.id);
break;
default:
throw new IllegalArgumentException("type " + req.type + " is not recognized");
}
}
catch(Exception e) {
err("exception receiving message from " + msg.getSrc(), e);
}
}
private void multicastRemoveRequest(ClusterID id) {
Request remove_req=new Request(Request.Type.REMOVE, null, id, null);
try {
byte[] buf=Util.streamableToByteBuffer(remove_req);
ch.send(new Message(null, buf));
}
catch(Exception e) {
err("failed multicasting REMOVE request", e);
}
}
private void handleExecute(ClusterID id, Address sender, Task task) {
tasks.putIfAbsent(id, new Entry(task, sender));
int index=id.getId() % cluster_size;
if(index != rank) {
return;
}
// System.out.println("ID=" + id + ", index=" + index + ", my rank=" + rank);
execute(id, sender, task);
}
private void execute(ClusterID id, Address sender, Task task) {
Handler handler=new Handler(id, sender, task);
thread_pool.execute(handler);
}
public void viewAccepted(View view) {
List<Address> left_members=this.view != null && view != null?
Util.leftMembers(this.view.getMembers(), view.getMembers()) : null;
this.view=view;
Address local_addr=ch.getAddress();
System.out.println("view: " + view);
cluster_size=view.size();
List<Address> mbrs=view.getMembers();
int old_rank=rank;
for(int i=0; i < mbrs.size(); i++) {
Address tmp=mbrs.get(i);
if(tmp.equals(local_addr)) {
rank=i;
break;
}
}
if(old_rank == -1 || old_rank != rank)
log("my rank is " + rank);
// process tasks by left members
if(left_members != null && !left_members.isEmpty()) {
for(Address mbr: left_members) {
handleLeftMember(mbr);
}
}
}
/** Take over the tasks previously assigned to this member *if* the ID matches my (new rank) */
private void handleLeftMember(Address mbr) {
for(Map.Entry<ClusterID,Entry> entry: tasks.entrySet()) {
ClusterID id=entry.getKey();
int index=id.getId() % cluster_size;
if(index != rank)
continue;
Entry val=entry.getValue();
if(mbr.equals(val.submitter)) {
err("will not take over tasks submitted by " + mbr + " because it left the cluster");
continue;
}
log("**** taking over task " + id + " from " + mbr + " (submitted by " + val.submitter + ")");
execute(id, val.submitter, val.task);
}
}
public static void main(String[] args) throws Exception {
String props="udp.xml";
String name=null;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-props")) {
props=args[++i];
continue;
}
if(args[i].equals("-name")) {
name=args[++i];
continue;
}
help();
return;
}
Server server=new Server(props);
server.start(name);
loop(server);
}
private static void loop(Server server) {
boolean looping=true;
while(looping) {
int key=Util.keyPress("[1] Submit [2] Submit long running task [3] Info [q] Quit");
switch(key) {
case '1':
Task task=new Task() {
private static final long serialVersionUID=5102426397394071700L;
public Object execute() {
return new Date();
}
};
_submit(task, server);
break;
case '2':
task=new Task() {
private static final long serialVersionUID=5102426397394071700L;
public Object execute() {
System.out.println("sleeping for 15 secs...");
Util.sleep(15000);
System.out.println("done");
return new Date();
}
};
_submit(task, server);
break;
case '3':
System.out.println(server.info());
break;
case 'q':
case -1:
looping=false;
break;
case 'r':
case '\n':
break;
}
}
server.stop();
}
private static void _submit(Task task, Server server) {
try {
Object result=server.submit(task, 30000);
log("<== result = " + result);
}
catch(Exception e) {
e.printStackTrace();
}
}
private static void help() {
System.out.println("Server [-props <XML config file>] [-name <name>]");
}
private static void log(String msg) {
System.out.println(msg);
}
private static void err(String msg) {
System.err.println(msg);
}
private static void err(String msg, Throwable t) {
System.err.println(msg + ", ex=" + t);
}
private static class Entry {
private final Task task;
private final Address submitter;
private final Promise<Object> promise=new Promise<>();
public Entry(Task task, Address submitter) {
this.task=task;
this.submitter=submitter;
}
}
private class Handler implements Runnable {
final ClusterID id;
final Address sender;
final Task task;
public Handler(ClusterID id, Address sender, Task task) {
this.id=id;
this.sender=sender;
this.task=task;
}
public void run() {
Object result=null;
if(task != null) {
try {
log("executing " + id);
result=handle(task);
}
catch(Throwable t) {
err("failed executing " + id, t);
result=t;
}
}
Request response=new Request(Request.Type.RESULT, null, id, result);
try {
byte[] buf=Util.streamableToByteBuffer(response);
Message rsp=new Message(sender, buf);
ch.send(rsp);
}
catch(Exception e) {
err("failed executing task " + id, e);
}
}
}
public static class Request implements Streamable {
enum Type {EXECUTE, RESULT, REMOVE};
private Type type;
private Task task;
private ClusterID id;
private Object result;
public Request() {
}
public Request(Type type, Task task, ClusterID id, Object result) {
this.type=type;
this.task=task;
this.id=id;
this.result=result;
}
public void writeTo(DataOutput out) throws IOException {
out.writeInt(type.ordinal());
Util.objectToStream(task, out);
Util.writeStreamable(id, out);
Util.objectToStream(result, out);
}
public void readFrom(DataInput in) throws IOException, ClassNotFoundException {
int tmp=in.readInt();
switch(tmp) {
case 0:
type=Type.EXECUTE;
break;
case 1:
type=Type.RESULT;
break;
case 2:
type=Type.REMOVE;
break;
default:
throw new IllegalArgumentException("ordinal " + tmp + " cannot be mapped to enum");
}
task=Util.objectFromStream(in);
id=Util.readStreamable(ClusterID::new, in);
result=Util.objectFromStream(in);
}
}
}
| |
/**
* The MIT License
* Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ee.ria.xroad.common.ocsp;
import ee.ria.xroad.common.CodedException;
import ee.ria.xroad.common.SystemProperties;
import ee.ria.xroad.common.conf.globalconf.GlobalConf;
import ee.ria.xroad.common.conf.globalconf.TimeBasedObjectCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.ocsp.ResponderID;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.CertificateStatus;
import org.bouncycastle.cert.ocsp.OCSPException;
import org.bouncycastle.cert.ocsp.OCSPResp;
import org.bouncycastle.cert.ocsp.RevokedStatus;
import org.bouncycastle.cert.ocsp.SingleResp;
import org.bouncycastle.cert.ocsp.UnknownStatus;
import org.bouncycastle.operator.ContentVerifierProvider;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.OperatorCreationException;
import org.joda.time.DateTime;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static ee.ria.xroad.common.ErrorCodes.X_CERT_VALIDATION;
import static ee.ria.xroad.common.ErrorCodes.X_INCORRECT_VALIDATION_INFO;
import static ee.ria.xroad.common.util.CryptoUtils.SHA1_ID;
import static ee.ria.xroad.common.util.CryptoUtils.calculateDigest;
import static ee.ria.xroad.common.util.CryptoUtils.createCertId;
import static ee.ria.xroad.common.util.CryptoUtils.createDefaultContentVerifier;
import static ee.ria.xroad.common.util.CryptoUtils.createDigestCalculator;
import static ee.ria.xroad.common.util.CryptoUtils.readCertificate;
/** Helper class for verifying OCSP responses. */
@Slf4j
public final class OcspVerifier {
private static final String ID_KP_OCSPSIGNING = "1.3.6.1.5.5.7.3.9";
private static final String SINGLE_RESP = "single_resp";
private static final String SIGNATURE = "signature";
private static final String CERTIFICATE = "certificate";
private final int ocspFreshnessSeconds;
private final OcspVerifierOptions options;
private static final TimeBasedObjectCache CACHE = new TimeBasedObjectCache(SystemProperties
.getOcspVerifierCachePeriod());;
/**
* Constructor
*/
public OcspVerifier(int ocspFreshnessSeconds, OcspVerifierOptions options) {
this.ocspFreshnessSeconds = ocspFreshnessSeconds;
if (options == null) {
this.options = new OcspVerifierOptions(true);
} else {
this.options = options;
}
}
/**
* Verifies certificate with respect to OCSP response.
* @param response the OCSP response
* @param subject the certificate to verify
* @param issuer the issuer of the subject certificate
* @throws Exception CodedException with appropriate error code
* if verification fails or the status of OCSP is not good.
*/
public void verifyValidityAndStatus(OCSPResp response,
X509Certificate subject, X509Certificate issuer) throws Exception {
verifyValidityAndStatus(response, subject, issuer, new Date());
}
/**
* Verifies certificate with respect to OCSP response at a specified date
* and checks the OCSP status
* @param response the OCSP response
* @param subject the certificate to verify
* @param issuer the issuer of the subject certificate
* @param atDate the date
* @throws Exception CodedException with appropriate error code
* if verification fails or the status of OCSP is not good.
*/
public void verifyValidityAndStatus(OCSPResp response,
X509Certificate subject, X509Certificate issuer, Date atDate)
throws Exception {
verifyValidity(response, subject, issuer, atDate);
verifyStatus(response);
}
/**
* Verifies certificate with respect to OCSP response but does not
* check the status of the OCSP response.
* @param response the OCSP response
* @param subject the certificate to verify
* @param issuer the issuer of the subject certificate
* @throws Exception CodedException with appropriate error code
* if verification fails.
*/
public void verifyValidity(OCSPResp response, X509Certificate subject,
X509Certificate issuer) throws Exception {
verifyValidity(response, subject, issuer, new Date());
}
/**
* Verifies certificate with respect to OCSP response but does not
* check the status of the OCSP response.
* @param response the OCSP response
* @param subject the certificate to getOcspCertverify
* @param issuer the issuer of the subject certificate
* @param atDate the date
* @throws Exception CodedException with appropriate error code
* if verification fails.
*/
public void verifyValidity(OCSPResp response, X509Certificate subject,
X509Certificate issuer, Date atDate) throws Exception {
log.debug("verifyValidity(subject: {}, issuer: {}, atDate: {})",
new Object[] {subject.getSubjectX500Principal().getName(),
issuer.getSubjectX500Principal().getName(), atDate});
SingleResp singleResp = verifyResponseValidityCached(response, subject, issuer);
verifyValidityAt(atDate, singleResp);
}
private void verifyValidityAt(Date atDate, SingleResp singleResp) {
// 5. The time at which the status being indicated is known
// to be correct (thisUpdate) is sufficiently recent.
if (isExpired(singleResp, atDate)) {
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
"OCSP response is too old (thisUpdate: %s)",
singleResp.getThisUpdate());
}
if (options.isVerifyNextUpdate()) {
// 6. When available, the time at or before which newer information will
// be available about the status of the certificate (nextUpdate) is
// greater than the current time.
log.debug("Verify OCSP nextUpdate, atDate: {} nextUpdate: {}", atDate, singleResp.getNextUpdate());
if (singleResp.getNextUpdate() != null
&& singleResp.getNextUpdate().before(atDate)) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
String.format("OCSP nextUpdate is too old, atDate: %s nextUpdate: %s", fmt.format(atDate),
fmt.format(singleResp.getNextUpdate())));
}
} else {
log.debug("OCSP nextUpdate verification is turned off");
}
}
private synchronized SingleResp verifyResponseValidityCached(OCSPResp response, X509Certificate subject,
X509Certificate issuer)
throws Exception {
String key = SINGLE_RESP + response.hashCode() + subject.hashCode() + issuer.hashCode();
if (!CACHE.isValid(key)) {
CACHE.setValue(key, verifyResponseValidity(response, subject, issuer));
}
return (SingleResp) CACHE.getValue(key);
}
private SingleResp verifyResponseValidity(OCSPResp response, X509Certificate subject, X509Certificate issuer)
throws Exception {
BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
SingleResp singleResp = basicResp.getResponses()[0];
CertificateID requestCertId = createCertId(subject, issuer);
// http://www.ietf.org/rfc/rfc2560.txt -- 3.2:
// Prior to accepting a signed response as valid, OCSP clients
// SHALL confirm that:
// 1. The certificate identified in a received response corresponds to
// that which was identified in the corresponding request;
if (!singleResp.getCertID().equals(requestCertId)) {
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
"OCSP response does not apply to certificate (sn = %s)",
subject.getSerialNumber());
}
X509Certificate ocspCert = getOcspCert(basicResp);
if (ocspCert == null) {
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
"Could not find OCSP certificate for responder ID");
}
if (!verifySignature(basicResp, ocspCert)) {
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
"Signature on OCSP response is not valid");
}
// 3. The identity of the signer matches the intended
// recipient of the request.
// -- Not important here because the original request is not available.
// 4. The signer is currently authorized to sign the response.
if (!isAuthorizedOcspSigner(ocspCert, issuer)) {
throw new CodedException(X_INCORRECT_VALIDATION_INFO,
"OCSP responder is not authorized for given CA");
}
return singleResp;
}
private boolean verifySignature(BasicOCSPResp basicResp, X509Certificate ocspCert) throws OperatorCreationException,
OCSPException {
ContentVerifierProvider verifier =
createDefaultContentVerifier(ocspCert.getPublicKey());
return basicResp.isSignatureValid(verifier);
}
/**
* Verifies the status of the OCSP response.
* @param response the OCSP response
* @throws Exception CodedException with error code X_CERT_VALIDATION
* if status is not good.
*/
public static void verifyStatus(OCSPResp response) throws Exception {
BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
SingleResp singleResp = basicResp.getResponses()[0];
CertificateStatus status = singleResp.getCertStatus();
if (status != null) { // null indicates GOOD.
throw new CodedException(X_CERT_VALIDATION,
"OCSP response indicates certificate status is %s",
getStatusString(status));
}
}
/**
* Returns true if the OCSP response is about to expire at the given date.
* @param singleResp the response
* @param atDate the date
* @return true, if the OCSP response is expired
*/
public boolean isExpired(SingleResp singleResp, Date atDate) {
Date allowedThisUpdate = new DateTime(atDate)
.minusSeconds(ocspFreshnessSeconds).toDate();
log.trace("isExpired(thisUpdate: {}, allowedThisUpdate: {}, "
+ "atDate: {})", new Object[] {singleResp.getThisUpdate(),
allowedThisUpdate, atDate });
return singleResp.getThisUpdate().before(allowedThisUpdate);
}
/**
* Returns true if the OCSP response is about to expire at the current date.
* @param response the response
* @return true, if the OCSP response is expired
* @throws Exception if an error occurs
*/
public boolean isExpired(OCSPResp response) throws Exception {
BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
SingleResp singleResp = basicResp.getResponses()[0];
return isExpired(singleResp, new Date());
}
/**
* Returns true if the OCSP response is about to expire at the
* specified date.
* @param response the response
* @param atDate the date
* @return true, if the OCSP response is expired at the specified date.
* @throws Exception if an error occurs
*/
public boolean isExpired(OCSPResp response, Date atDate) throws Exception {
BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
SingleResp singleResp = basicResp.getResponses()[0];
return isExpired(singleResp, atDate);
}
/**
* @param response the OCSP response
* @return certificate that was used to sign the given OCSP response.
* @throws Exception if an error occurs
*/
public static X509Certificate getOcspCert(BasicOCSPResp response)
throws Exception {
List<X509Certificate> knownCerts = getOcspCerts(response);
ResponderID respId = response.getResponderId().toASN1Primitive();
// We can search either by key hash or by name, depending which
// one is provided in the responder ID.
if (respId.getName() != null) {
for (X509Certificate cert : knownCerts) {
X509CertificateHolder certHolder =
new X509CertificateHolder(cert.getEncoded());
if (certHolder.getSubject().equals(respId.getName())) {
return cert;
}
}
} else if (respId.getKeyHash() != null) {
DigestCalculator dc = createDigestCalculator(SHA1_ID);
for (X509Certificate cert : knownCerts) {
X509CertificateHolder certHolder =
new X509CertificateHolder(cert.getEncoded());
DERBitString keyData =
certHolder.getSubjectPublicKeyInfo().getPublicKeyData();
byte[] d = calculateDigest(dc, keyData.getBytes());
if (MessageDigestAlgorithm.isEqual(respId.getKeyHash(), d)) {
return cert;
}
}
}
return null;
}
private static List<X509Certificate> getOcspCerts(BasicOCSPResp response)
throws Exception {
List<X509Certificate> certs = new ArrayList<>();
certs.addAll(GlobalConf.getOcspResponderCertificates());
certs.addAll(GlobalConf.getAllCaCerts());
for (X509CertificateHolder cert : response.getCerts()) {
certs.add(readCertificate(cert.getEncoded()));
}
return certs;
}
private static String getStatusString(CertificateStatus status) {
if (status instanceof UnknownStatus) {
return "UNKNOWN";
} else if (status instanceof RevokedStatus) {
RevokedStatus rs = (RevokedStatus) status;
return String.format("REVOKED (date: %tF %tT)",
rs.getRevocationTime(), rs.getRevocationTime());
} else {
return "INVALID";
}
}
private static boolean isAuthorizedOcspSigner(X509Certificate ocspCert,
X509Certificate issuer) throws Exception {
// 1. Matches a local configuration of OCSP signing authority for the
// certificate in question; or
if (GlobalConf.isOcspResponderCert(issuer, ocspCert)) {
return true;
}
// 2. Is the certificate of the CA that issued the certificate in
// question; or
if (ocspCert.equals(issuer)) {
return true;
}
// 3. Includes a value of id-ad-ocspSigning in an ExtendedKeyUsage
// extension and is issued by the CA that issued the certificate in
// question.
if (ocspCert.getIssuerX500Principal().equals(
issuer.getSubjectX500Principal())) {
List<String> keyUsage = ocspCert.getExtendedKeyUsage();
if (keyUsage == null) {
return false;
}
for (String key : keyUsage) {
if (key.equals(ID_KP_OCSPSIGNING)) {
return true;
}
}
}
return false;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.security.authorization.composite;
import java.lang.reflect.Field;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Session;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.oak.api.ContentSession;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.AggregatedPermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.RepositoryPermission;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.TreePermission;
import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Test the effect of the combination of
*
* - default permission provider
* - custom provider that doesn't support any permissions nowhere
*
* The tests are executed both for the set of principals associated with the test
* user and with the admin session.
* The expected outcome is that the composite provider behaves exactly like the
* default provider (i.e. the {@code NotSupportingProvider} is never respected
* during evaluation).
*
* While there is no real use in such a {@link AggregatedPermissionProvider}, that
* is never called, is is used here to verify that the composite provider doesn't
* introduce any regressions compared to the default provider implementation.
*/
public class CompositeProviderNoScopeTest extends AbstractCompositeProviderTest {
private CompositePermissionProvider cppTestUser;
private PermissionProvider defTestUser;
private CompositePermissionProvider cppAdminUser;
private PermissionProvider defAdminUser;
@Override
public void before() throws Exception {
super.before();
ContentSession cs = root.getContentSession();
Set<Principal> testPrincipals = ImmutableSet.of(getTestUser().getPrincipal(), EveryonePrincipal.getInstance());
cppTestUser = createPermissionProvider(testPrincipals);
defTestUser = getConfig(AuthorizationConfiguration.class).getPermissionProvider(root, cs.getWorkspaceName(), testPrincipals);
Set<Principal> adminPrincipals = cs.getAuthInfo().getPrincipals();
cppAdminUser = createPermissionProvider(adminPrincipals);
defAdminUser = getConfig(AuthorizationConfiguration.class).getPermissionProvider(root, cs.getWorkspaceName(), adminPrincipals);
}
@Override
protected AggregatedPermissionProvider getTestPermissionProvider() {
return new NoScopeProvider(root);
}
@Override
@Test
public void testGetTreePermissionInstance() {
PermissionProvider pp = createPermissionProviderOR();
TreePermission parentPermission = TreePermission.EMPTY;
for (String path : TP_PATHS) {
Tree t = readOnlyRoot.getTree(path);
TreePermission tp = pp.getTreePermission(t, parentPermission);
assertCompositeTreePermission(t.isRoot(), tp);
parentPermission = tp;
}
}
@Override
@Test
public void testGetTreePermissionInstanceOR() {
PermissionProvider pp = createPermissionProviderOR();
TreePermission parentPermission = TreePermission.EMPTY;
for (String path : TP_PATHS) {
Tree t = readOnlyRoot.getTree(path);
TreePermission tp = pp.getTreePermission(t, parentPermission);
assertCompositeTreePermission(t.isRoot(), tp);
parentPermission = tp;
}
}
@Override
@Test
public void testTreePermissionGetChild() {
List<String> childNames = ImmutableList.of("test", "a", "b", "c", "nonexisting");
Tree rootTree = readOnlyRoot.getTree(ROOT_PATH);
NodeState ns = getTreeProvider().asNodeState(rootTree);
TreePermission tp = createPermissionProvider().getTreePermission(rootTree, TreePermission.EMPTY);
assertCompositeTreePermission(tp);
for (String cName : childNames) {
ns = ns.getChildNode(cName);
tp = tp.getChildPermission(cName, ns);
assertCompositeTreePermission(false, tp);
}
}
@Override
@Test
public void testTreePermissionGetChildOR() {
List<String> childNames = ImmutableList.of("test", "a", "b", "c", "nonexisting");
Tree rootTree = readOnlyRoot.getTree(ROOT_PATH);
NodeState ns = getTreeProvider().asNodeState(rootTree);
TreePermission tp = createPermissionProviderOR().getTreePermission(rootTree, TreePermission.EMPTY);
assertCompositeTreePermission(tp);
for (String cName : childNames) {
ns = ns.getChildNode(cName);
tp = tp.getChildPermission(cName, ns);
assertCompositeTreePermission(false, tp);
}
}
@Test
public void testGetPrivileges() {
for (String p : defPrivileges.keySet()) {
Set<String> expected = defPrivileges.get(p);
Tree tree = readOnlyRoot.getTree(p);
assertEquals(p, expected, cppTestUser.getPrivileges(tree));
assertEquals(p, defTestUser.getPrivileges(tree), cppTestUser.getPrivileges(tree));
}
}
@Test
public void testGetPrivilegesOr() throws Exception {
Set<Principal> testPrincipals = ImmutableSet.of(getTestUser().getPrincipal(), EveryonePrincipal.getInstance());
CompositePermissionProvider ccpTestUserOR = createPermissionProviderOR(testPrincipals);
PermissionProvider defTestUserOR = getConfig(AuthorizationConfiguration.class).getPermissionProvider(root, root.getContentSession().getWorkspaceName(), testPrincipals);
for (String p : defPrivileges.keySet()) {
Set<String> expected = defPrivileges.get(p);
Tree tree = readOnlyRoot.getTree(p);
assertEquals(p, expected, ccpTestUserOR.getPrivileges(tree));
assertEquals(p, defTestUserOR.getPrivileges(tree), ccpTestUserOR.getPrivileges(tree));
}
}
@Test
public void testGetPrivilegesAdmin() {
Set<String> expected = ImmutableSet.of(JCR_ALL);
for (String p : NODE_PATHS) {
Tree tree = readOnlyRoot.getTree(p);
assertEquals(p, expected, cppAdminUser.getPrivileges(tree));
assertEquals(p, defAdminUser.getPrivileges(tree), cppAdminUser.getPrivileges(tree));
}
}
@Test
public void testGetPrivilegesOnRepo() {
Set<String> expected = ImmutableSet.of(JCR_NAMESPACE_MANAGEMENT, JCR_NODE_TYPE_DEFINITION_MANAGEMENT);
assertEquals(expected, cppTestUser.getPrivileges(null));
assertEquals(defTestUser.getPrivileges(null), cppTestUser.getPrivileges(null));
}
@Test
public void testGetPrivilegesOnRepoAdmin() {
Set<String> expected = ImmutableSet.of(JCR_ALL);
assertEquals(expected, cppAdminUser.getPrivileges(null));
assertEquals(defAdminUser.getPrivileges(null), cppAdminUser.getPrivileges(null));
}
@Test
public void testHasPrivileges() {
for (String p : defPrivileges.keySet()) {
Set<String> expected = defPrivileges.get(p);
Tree tree = readOnlyRoot.getTree(p);
String[] privNames = expected.toArray(new String[expected.size()]);
assertTrue(p, cppTestUser.hasPrivileges(tree, privNames));
assertEquals(p, defTestUser.hasPrivileges(tree, privNames), cppTestUser.hasPrivileges(tree, privNames));
}
}
@Test
public void testHasPrivilegesAdmin() {
for (String p : NODE_PATHS) {
Tree tree = readOnlyRoot.getTree(p);
assertTrue(p, cppAdminUser.hasPrivileges(tree, JCR_ALL));
assertTrue(p, defAdminUser.hasPrivileges(tree, JCR_ALL));
}
}
@Test
public void testHasPrivilegesOnRepo() {
assertTrue(cppTestUser.hasPrivileges(null, JCR_NAMESPACE_MANAGEMENT, JCR_NODE_TYPE_DEFINITION_MANAGEMENT));
assertTrue(defTestUser.hasPrivileges(null, JCR_NAMESPACE_MANAGEMENT, JCR_NODE_TYPE_DEFINITION_MANAGEMENT));
assertTrue(cppTestUser.hasPrivileges(null));
assertTrue(defTestUser.hasPrivileges(null));
}
@Test
public void testHasPrivilegeOnRepoAdminUser() {
assertTrue(cppAdminUser.hasPrivileges(null, JCR_ALL));
assertTrue(defAdminUser.hasPrivileges(null, JCR_ALL));
assertTrue(cppAdminUser.hasPrivileges(null));
assertTrue(defAdminUser.hasPrivileges(null));
}
@Test
public void testIsGranted() {
for (String p : defPermissions.keySet()) {
long expected = defPermissions.get(p);
Tree tree = readOnlyRoot.getTree(p);
assertTrue(p, cppTestUser.isGranted(tree, null, expected));
assertTrue(p, defTestUser.isGranted(tree, null, expected));
}
}
@Test
public void testIsGrantedAdmin() {
for (String p : defPermissions.keySet()) {
Tree tree = readOnlyRoot.getTree(p);
assertTrue(p, cppAdminUser.isGranted(tree, null, Permissions.ALL));
assertTrue(p, defAdminUser.isGranted(tree, null, Permissions.ALL));
}
}
@Test
public void testIsGrantedProperty() {
for (String p : defPermissions.keySet()) {
long expected = defPermissions.get(p);
Tree tree = readOnlyRoot.getTree(p);
assertTrue(p, cppTestUser.isGranted(tree, PROPERTY_STATE, expected));
assertTrue(p, defTestUser.isGranted(tree, PROPERTY_STATE, expected));
}
}
@Test
public void testIsGrantedPropertyAdmin() {
for (String p : defPermissions.keySet()) {
Tree tree = readOnlyRoot.getTree(p);
assertTrue(p, cppAdminUser.isGranted(tree, PROPERTY_STATE, Permissions.ALL));
assertTrue(p, defAdminUser.isGranted(tree, PROPERTY_STATE, Permissions.ALL));
}
}
@Test
public void testIsGrantedAction() {
for (String p : defActionsGranted.keySet()) {
String actions = getActionString(defActionsGranted.get(p));
assertTrue(p + " : " + actions, cppTestUser.isGranted(p, actions));
assertTrue(p + " : " + actions, defTestUser.isGranted(p, actions));
}
}
@Test
public void testIsGrantedAction2() {
Map<String, String[]> noAccess = ImmutableMap.<String, String[]>builder().
put(ROOT_PATH, new String[] {Session.ACTION_READ}).
put(ROOT_PATH + "jcr:primaryType", new String[] {Session.ACTION_READ, Session.ACTION_SET_PROPERTY}).
put("/nonexisting", new String[] {Session.ACTION_READ, Session.ACTION_ADD_NODE}).
put(TEST_PATH_2, new String[] {Session.ACTION_READ, Session.ACTION_REMOVE}).
put(TEST_PATH_2 + "/jcr:primaryType", new String[] {Session.ACTION_READ, Session.ACTION_SET_PROPERTY}).
put(TEST_A_B_C_PATH, new String[] {Session.ACTION_READ, Session.ACTION_REMOVE}).
put(TEST_A_B_C_PATH + "/noneExisting", new String[] {Session.ACTION_READ, JackrabbitSession.ACTION_REMOVE_NODE}).
put(TEST_A_B_C_PATH + "/jcr:primaryType", new String[] {JackrabbitSession.ACTION_REMOVE_PROPERTY}).build();
for (String p : noAccess.keySet()) {
String actions = getActionString(noAccess.get(p));
assertFalse(p, cppTestUser.isGranted(p, actions));
assertFalse(p, defTestUser.isGranted(p, actions));
}
}
@Test
public void testIsGrantedActionAdmin() {
String allActions = getActionString(ALL_ACTIONS);
for (String p : defActionsGranted.keySet()) {
assertTrue(p + " : " + allActions, cppAdminUser.isGranted(p, allActions));
assertTrue(p + " : " + allActions, defAdminUser.isGranted(p, allActions));
}
}
@Test
public void testRepositoryPermissionIsGranted() {
RepositoryPermission rp = cppTestUser.getRepositoryPermission();
assertTrue(rp.isGranted(Permissions.NAMESPACE_MANAGEMENT));
assertTrue(rp.isGranted(Permissions.NODE_TYPE_DEFINITION_MANAGEMENT));
assertTrue(rp.isGranted(Permissions.NAMESPACE_MANAGEMENT | Permissions.NODE_TYPE_DEFINITION_MANAGEMENT));
}
@Test
public void testRepositoryPermissionIsGrantedAdminUser() {
RepositoryPermission rp = cppAdminUser.getRepositoryPermission();
assertTrue(rp.isGranted(Permissions.ALL));
}
@Test
public void testTreePermissionIsGranted() {
TreePermission parentPermission = TreePermission.EMPTY;
for (String path : TP_PATHS) {
TreePermission tp = cppTestUser.getTreePermission(readOnlyRoot.getTree(path), parentPermission);
Long toTest = (defPermissions.containsKey(path)) ? defPermissions.get(path) : defPermissions.get(PathUtils.getAncestorPath(path, 1));
if (toTest != null) {
assertTrue(tp.isGranted(toTest));
}
parentPermission = tp;
}
}
@Test
public void testTreePermissionIsGrantedProperty() {
TreePermission parentPermission = TreePermission.EMPTY;
for (String path : TP_PATHS) {
TreePermission tp = cppTestUser.getTreePermission(readOnlyRoot.getTree(path), parentPermission);
Long toTest = (defPermissions.containsKey(path)) ? defPermissions.get(path) : defPermissions.get(PathUtils.getAncestorPath(path, 1));
if (toTest != null) {
assertTrue(tp.isGranted(toTest, PROPERTY_STATE));
}
parentPermission = tp;
}
}
@Test
public void testTreePermissionCanRead() {
Map<String, Boolean> readMap = ImmutableMap.<String, Boolean>builder().
put(ROOT_PATH, false).
put(TEST_PATH, true).
put(TEST_A_PATH, true).
put(TEST_A_B_PATH, true).
put(TEST_A_B_C_PATH, false).
put(TEST_A_B_C_PATH + "/nonexisting", false).
build();
TreePermission parentPermission = TreePermission.EMPTY;
TreePermission parentPermission2 = TreePermission.EMPTY;
for (String nodePath : readMap.keySet()) {
Tree tree = readOnlyRoot.getTree(nodePath);
TreePermission tp = cppTestUser.getTreePermission(tree, parentPermission);
TreePermission tp2 = defTestUser.getTreePermission(tree, parentPermission2);
boolean expectedResult = readMap.get(nodePath);
assertEquals(nodePath, expectedResult, tp.canRead());
assertEquals(nodePath + "(default)", expectedResult, tp2.canRead());
parentPermission = tp;
parentPermission2 = tp2;
}
}
@Test
public void testTreePermissionCanReadProperty() {
Map<String, Boolean> readMap = ImmutableMap.<String, Boolean>builder().
put(ROOT_PATH, false).
put(TEST_PATH, true).
put(TEST_A_PATH, true).
put(TEST_A_B_PATH, true).
put(TEST_A_B_C_PATH, true).
put(TEST_A_B_C_PATH + "/nonexisting", true).
build();
TreePermission parentPermission = TreePermission.EMPTY;
TreePermission parentPermission2 = TreePermission.EMPTY;
for (String nodePath : readMap.keySet()) {
Tree tree = readOnlyRoot.getTree(nodePath);
TreePermission tp = cppTestUser.getTreePermission(tree, parentPermission);
TreePermission tp2 = defTestUser.getTreePermission(tree, parentPermission2);
boolean expectedResult = readMap.get(nodePath);
assertEquals(nodePath, expectedResult, tp.canRead(PROPERTY_STATE));
assertEquals(nodePath + "(default)", expectedResult, tp2.canRead(PROPERTY_STATE));
parentPermission = tp;
parentPermission2 = tp2;
}
}
@Test
public void testTreePermissionCanReadAdmin() {
TreePermission parentPermission = TreePermission.EMPTY;
TreePermission parentPermission2 = TreePermission.EMPTY;
for (String nodePath : TP_PATHS) {
Tree tree = readOnlyRoot.getTree(nodePath);
TreePermission tp = cppAdminUser.getTreePermission(tree, parentPermission);
TreePermission tp2 = defAdminUser.getTreePermission(tree, parentPermission2);
assertTrue(nodePath, tp.canRead());
assertTrue(nodePath, tp.canRead(PROPERTY_STATE));
assertTrue(nodePath + "(default)", tp2.canRead());
assertTrue(nodePath + "(default)", tp2.canRead(PROPERTY_STATE));
parentPermission = tp;
parentPermission2 = tp2;
}
}
@Test
public void testTreePermissionSize() throws Exception {
Field tpField = CompositeTreePermission.class.getDeclaredField("treePermissions");
tpField.setAccessible(true);
Tree rootTree = readOnlyRoot.getTree(ROOT_PATH);
NodeState ns = getTreeProvider().asNodeState(rootTree);
TreePermission tp = cppTestUser.getTreePermission(rootTree, TreePermission.EMPTY);
assertEquals(2, ((TreePermission[]) tpField.get(tp)).length);
List<String> childNames = ImmutableList.of("test", "a", "b", "c", "nonexisting");
for (String cName : childNames) {
ns = ns.getChildNode(cName);
tp = tp.getChildPermission(cName, ns);
assertCompositeTreePermission(false, tp);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.schema;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.search.*;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.CachingTokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.common.SolrException;
import org.apache.solr.response.TextResponseWriter;
import org.apache.solr.search.QParser;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.io.StringReader;
/** <code>TextField</code> is the basic type for configurable text analysis.
* Analyzers for field types using this implementation should be defined in the schema.
*
*/
public class TextField extends FieldType {
protected boolean autoGeneratePhraseQueries;
/**
* Analyzer set by schema for text types to use when searching fields
* of this type, subclasses can set analyzer themselves or override
* getAnalyzer()
* This analyzer is used to process wildcard, prefix, regex and other multiterm queries. It
* assembles a list of tokenizer +filters that "make sense" for this, primarily accent folding and
* lowercasing filters, and charfilters.
*
* @see #getMultiTermAnalyzer
* @see #setMultiTermAnalyzer
*/
protected Analyzer multiTermAnalyzer=null;
private boolean isExplicitMultiTermAnalyzer = false;
@Override
protected void init(IndexSchema schema, Map<String,String> args) {
properties |= TOKENIZED;
if (schema.getVersion() > 1.1F &&
// only override if it's not explicitly true
0 == (trueProperties & OMIT_TF_POSITIONS)) {
properties &= ~OMIT_TF_POSITIONS;
}
if (schema.getVersion() > 1.3F) {
autoGeneratePhraseQueries = false;
} else {
autoGeneratePhraseQueries = true;
}
String autoGeneratePhraseQueriesStr = args.remove("autoGeneratePhraseQueries");
if (autoGeneratePhraseQueriesStr != null)
autoGeneratePhraseQueries = Boolean.parseBoolean(autoGeneratePhraseQueriesStr);
super.init(schema, args);
}
/**
* Returns the Analyzer to be used when searching fields of this type when mult-term queries are specified.
* <p>
* This method may be called many times, at any time.
* </p>
* @see #getAnalyzer
*/
public Analyzer getMultiTermAnalyzer() {
return multiTermAnalyzer;
}
public void setMultiTermAnalyzer(Analyzer analyzer) {
this.multiTermAnalyzer = analyzer;
}
public boolean getAutoGeneratePhraseQueries() {
return autoGeneratePhraseQueries;
}
@Override
public SortField getSortField(SchemaField field, boolean reverse) {
/* :TODO: maybe warn if isTokenized(), but doesn't use LimitTokenCountFilter in it's chain? */
return getStringSort(field, reverse);
}
@Override
public void write(TextResponseWriter writer, String name, IndexableField f) throws IOException {
writer.writeStr(name, f.stringValue(), true);
}
@Override
public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) {
return parseFieldQuery(parser, getQueryAnalyzer(), field.getName(), externalVal);
}
@Override
public Object toObject(SchemaField sf, BytesRef term) {
return term.utf8ToString();
}
@Override
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
}
@Override
public void setQueryAnalyzer(Analyzer analyzer) {
this.queryAnalyzer = analyzer;
}
@Override
public Query getRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {
Analyzer multiAnalyzer = getMultiTermAnalyzer();
BytesRef lower = analyzeMultiTerm(field.getName(), part1, multiAnalyzer);
BytesRef upper = analyzeMultiTerm(field.getName(), part2, multiAnalyzer);
return new TermRangeQuery(field.getName(), lower, upper, minInclusive, maxInclusive);
}
public static BytesRef analyzeMultiTerm(String field, String part, Analyzer analyzerIn) {
if (part == null || analyzerIn == null) return null;
TokenStream source;
try {
source = analyzerIn.tokenStream(field, new StringReader(part));
source.reset();
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unable to initialize TokenStream to analyze multiTerm term: " + part, e);
}
TermToBytesRefAttribute termAtt = source.getAttribute(TermToBytesRefAttribute.class);
BytesRef bytes = termAtt.getBytesRef();
try {
if (!source.incrementToken())
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"analyzer returned no terms for multiTerm term: " + part);
termAtt.fillBytesRef();
if (source.incrementToken())
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"analyzer returned too many terms for multiTerm term: " + part);
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"error analyzing range part: " + part, e);
}
try {
source.end();
source.close();
} catch (IOException e) {
throw new RuntimeException("Unable to end & close TokenStream after analyzing multiTerm term: " + part, e);
}
return BytesRef.deepCopyOf(bytes);
}
static Query parseFieldQuery(QParser parser, Analyzer analyzer, String field, String queryText) {
int phraseSlop = 0;
// most of the following code is taken from the Lucene QueryParser
// Use the analyzer to get all the tokens, and then build a TermQuery,
// PhraseQuery, or nothing based on the term count
TokenStream source;
try {
source = analyzer.tokenStream(field, new StringReader(queryText));
source.reset();
} catch (IOException e) {
throw new RuntimeException("Unable to initialize TokenStream to analyze query text", e);
}
CachingTokenFilter buffer = new CachingTokenFilter(source);
CharTermAttribute termAtt = null;
PositionIncrementAttribute posIncrAtt = null;
int numTokens = 0;
buffer.reset();
if (buffer.hasAttribute(CharTermAttribute.class)) {
termAtt = buffer.getAttribute(CharTermAttribute.class);
}
if (buffer.hasAttribute(PositionIncrementAttribute.class)) {
posIncrAtt = buffer.getAttribute(PositionIncrementAttribute.class);
}
int positionCount = 0;
boolean severalTokensAtSamePosition = false;
boolean hasMoreTokens = false;
if (termAtt != null) {
try {
hasMoreTokens = buffer.incrementToken();
while (hasMoreTokens) {
numTokens++;
int positionIncrement = (posIncrAtt != null) ? posIncrAtt.getPositionIncrement() : 1;
if (positionIncrement != 0) {
positionCount += positionIncrement;
} else {
severalTokensAtSamePosition = true;
}
hasMoreTokens = buffer.incrementToken();
}
} catch (IOException e) {
// ignore
}
}
try {
// rewind the buffer stream
buffer.reset();
// close original stream - all tokens buffered
source.close();
}
catch (IOException e) {
// ignore
}
if (numTokens == 0)
return null;
else if (numTokens == 1) {
String term = null;
try {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
term = termAtt.toString();
} catch (IOException e) {
// safe to ignore, because we know the number of tokens
}
// return newTermQuery(new Term(field, term));
return new TermQuery(new Term(field, term));
} else {
if (severalTokensAtSamePosition) {
if (positionCount == 1) {
// no phrase query:
// BooleanQuery q = newBooleanQuery(true);
BooleanQuery q = new BooleanQuery(true);
for (int i = 0; i < numTokens; i++) {
String term = null;
try {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
term = termAtt.toString();
} catch (IOException e) {
// safe to ignore, because we know the number of tokens
}
// Query currentQuery = newTermQuery(new Term(field, term));
Query currentQuery = new TermQuery(new Term(field, term));
q.add(currentQuery, BooleanClause.Occur.SHOULD);
}
return q;
}
else {
// phrase query:
// MultiPhraseQuery mpq = newMultiPhraseQuery();
MultiPhraseQuery mpq = new MultiPhraseQuery();
mpq.setSlop(phraseSlop);
List multiTerms = new ArrayList();
int position = -1;
for (int i = 0; i < numTokens; i++) {
String term = null;
int positionIncrement = 1;
try {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
term = termAtt.toString();
if (posIncrAtt != null) {
positionIncrement = posIncrAtt.getPositionIncrement();
}
} catch (IOException e) {
// safe to ignore, because we know the number of tokens
}
if (positionIncrement > 0 && multiTerms.size() > 0) {
mpq.add((Term[])multiTerms.toArray(new Term[multiTerms.size()]),position);
multiTerms.clear();
}
position += positionIncrement;
multiTerms.add(new Term(field, term));
}
mpq.add((Term[])multiTerms.toArray(new Term[multiTerms.size()]),position);
return mpq;
}
}
else {
// PhraseQuery pq = newPhraseQuery();
PhraseQuery pq = new PhraseQuery();
pq.setSlop(phraseSlop);
int position = -1;
for (int i = 0; i < numTokens; i++) {
String term = null;
int positionIncrement = 1;
try {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
term = termAtt.toString();
if (posIncrAtt != null) {
positionIncrement = posIncrAtt.getPositionIncrement();
}
} catch (IOException e) {
// safe to ignore, because we know the number of tokens
}
position += positionIncrement;
pq.add(new Term(field, term),position);
}
return pq;
}
}
}
public void setIsExplicitMultiTermAnalyzer(boolean isExplicitMultiTermAnalyzer) {
this.isExplicitMultiTermAnalyzer = isExplicitMultiTermAnalyzer;
}
public boolean isExplicitMultiTermAnalyzer() {
return isExplicitMultiTermAnalyzer;
}
}
| |
package ca.utoronto.civ.its.lightgrid.dispatcher;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import ca.utoronto.civ.its.lightgrid.ClientHandle;
import ca.utoronto.civ.its.lightgrid.Job;
import ca.utoronto.civ.its.lightgrid.ResourceHandle;
public class Dispatcher
{
private Hashtable clientIdToClientHandle;
private String localHostname;
private Hashtable clientIdToSentJobIdVector;
private Hashtable jobIdToSentJob;
private Hashtable resourceIdToResourceHandle;
private Vector resourceQueue;
private Vector unsentJobQueue;
private Vector reassignableSentJobQueue;
private Hashtable clientIdToJobQueueNum;
private int nextClientId;
private int nextResourceId;
public Dispatcher()
{
resourceQueue = new Vector();
unsentJobQueue = new Vector();
reassignableSentJobQueue = new Vector();
clientIdToJobQueueNum = new Hashtable();
jobIdToSentJob = new Hashtable();
clientIdToClientHandle = new Hashtable();
resourceIdToResourceHandle = new Hashtable();
clientIdToSentJobIdVector = new Hashtable();
nextResourceId = 0;
nextClientId = 0;
(new ResourceListener(this)).start();
(new ClientListener(this)).start();
(new UserInputListener(this)).start();
try
{
localHostname = InetAddress.getLocalHost().getCanonicalHostName();
}
catch(UnknownHostException uhe)
{
System.err.println("Cannot find host: " + uhe.getMessage());
localHostname = null;
}
try
{
FileWriter theFile = new FileWriter("dispatcher.txt");
theFile.write(localHostname + "\n");
theFile.close();
}
catch(IOException ioe)
{
System.err.println("can't access dispatcher file");
System.exit(1);
}
System.out.println("\nLightGrid Dispatcher booted ok.\n");
try
{
StreamTokenizer resourceFileStream = new StreamTokenizer(new FileReader("resources.txt"));
resourceFileStream.resetSyntax();
resourceFileStream.whitespaceChars(0, ' ');
resourceFileStream.wordChars(33, 255);
resourceFileStream.eolIsSignificant(false);
while(resourceFileStream.nextToken() == StreamTokenizer.TT_WORD)
{
(new ResourceTalker(new ResourceHandle(resourceFileStream.sval, "none"), "sayhello " + localHostname, "")).start();
}
}
catch(IOException ioe)
{
System.err.println("can't access resources file, waiting for hello");
}
}
public synchronized String addClient(String hostname) throws UnknownHostException
{
ClientHandle c = new ClientHandle(hostname, (new Integer(nextClientId).toString()));
nextClientId++;
clientIdToClientHandle.put(c.getId(), c);
clientIdToSentJobIdVector.put(c.getId(), new Vector());
System.out.println("Registered client " + (nextClientId - 1) + " at " + hostname);
return c.getId();
}
public void addJobs(Job[] theJobs)
{
for(int i = 0; i < theJobs.length; i++)
{
if(!clientIdToJobQueueNum.containsKey(theJobs[i].getClient().getId()))
{
clientIdToJobQueueNum.put(theJobs[i].getClient().getId(), (new Integer(unsentJobQueue.size())));
unsentJobQueue.addElement(new Vector());
reassignableSentJobQueue.addElement(new Vector());
}
((Vector)unsentJobQueue.elementAt(((Integer)clientIdToJobQueueNum.get(theJobs[i].getClient().getId())).intValue())).addElement(theJobs[i]);
}
synchronized(this)
{
this.notifyAll();
}
}
public synchronized String addResource(String hostname) throws UnknownHostException
{
ResourceHandle r = new ResourceHandle(hostname, (new Integer(nextResourceId).toString()));
nextResourceId++;
resourceIdToResourceHandle.put(r.getId(), r);
System.out.println("Registered resource " + (nextResourceId - 1) + " at " + hostname);
enqueueResource(r);
return r.getId();
}
public void enqueueResource(ResourceHandle s)
{
resourceQueue.addElement(s);
synchronized(this)
{
this.notifyAll();
}
}
public void enqueueResource(String resourceId)
{
enqueueResource((ResourceHandle)resourceIdToResourceHandle.get(resourceId));
}
public void processReset(String resourceId, String jobId)
{
ResourceHandle r = (ResourceHandle)resourceIdToResourceHandle.get(resourceId);
Job j = (Job)jobIdToSentJob.get(jobId);
if(j != null)
{
j.deAssignResource(r);
if(!j.hasAssignedResources())
{
jobIdToSentJob.remove(jobId);
((Vector)clientIdToSentJobIdVector.get(j.getClient().getId())).remove(jobId);
}
}
enqueueResource(r);
}
public void processResult(String resourceId, String jobId, Object result)
{
ResourceHandle r = (ResourceHandle)resourceIdToResourceHandle.get(resourceId);
Job j = (Job)jobIdToSentJob.get(jobId);
if(j != null)
{
j.deAssignResource(r);
if(!j.isResultSent())
{
j.setResultSent(true);
(new ClientTalker(j.getClient(), "result " + j.getJobId(), result)).start();
}
if(j.hasAssignedResources())
{
Enumeration assignedResources = j.getAssignedResources();
while(assignedResources.hasMoreElements())
{
ResourceHandle theResource = (ResourceHandle)assignedResources.nextElement();
(new ResourceTalker(theResource, "reset " + j.getJobId(), "")).start();
}
}
else
{
jobIdToSentJob.remove(jobId);
((Vector)clientIdToSentJobIdVector.get(j.getClient().getId())).remove(jobId);
}
}
enqueueResource(r);
}
private void dispatch()
{
Job job = null;
int lastQueueNum = 0;
while(true)
{
synchronized(unsentJobQueue)
{
synchronized(reassignableSentJobQueue)
{
while((!jobQueuesEmpty()) && (resourceQueue.size() > 0))
{
job = null;
for(int i = 0; i < unsentJobQueue.size(); i++)
{
lastQueueNum = (lastQueueNum + 1) % unsentJobQueue.size();
if(((Vector)unsentJobQueue.elementAt(lastQueueNum)).size() != 0)
{
job = (Job)((Vector)unsentJobQueue.elementAt(lastQueueNum)).elementAt(0);
((Vector)unsentJobQueue.elementAt(lastQueueNum)).removeElementAt(0);
jobIdToSentJob.put(job.getJobId(), job);
((Vector)clientIdToSentJobIdVector.get(job.getClient().getId())).addElement(job.getJobId());
break;
}
else if(((Vector)reassignableSentJobQueue.elementAt(lastQueueNum)).size() != 0)
{
do
{
job = (Job)((Vector)reassignableSentJobQueue.elementAt(lastQueueNum)).elementAt(0);
((Vector)reassignableSentJobQueue.elementAt(lastQueueNum)).removeElementAt(0);
}
while(((!jobIdToSentJob.containsKey(job.getJobId())) || (job.isResultSent())) && (((Vector)reassignableSentJobQueue.elementAt(lastQueueNum)).size() != 0));
if((jobIdToSentJob.containsKey(job.getJobId())) || (!job.isResultSent()))
{
break;
}
}
}
if((job != null) && (jobIdToSentJob.containsKey(job.getJobId())) && (!job.isResultSent()))
{
job.assignResource(((ResourceHandle)resourceQueue.elementAt(0)));
(new ResourceTalker((ResourceHandle)resourceQueue.elementAt(0), "job " + job.getJobId() + " " + job.getJobProcessorClass(), job.getParameters())).start();
resourceQueue.removeElementAt(0);
if(job.getPriority() > 0)
{
((Vector)reassignableSentJobQueue.elementAt(((Integer)clientIdToJobQueueNum.get(job.getClient().getId())).intValue())).addElement(job);
}
}
}
}
}
try
{
synchronized(this)
{
this.wait();
}
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
public boolean jobQueuesEmpty()
{
for(int i = 0; i < unsentJobQueue.size(); i++)
{
if((((Vector)unsentJobQueue.elementAt(i)).size() != 0) || (((Vector)reassignableSentJobQueue.elementAt(i)).size() != 0))
{
return false;
}
}
return true;
}
public void resetAll()
{
Enumeration clientIds = clientIdToClientHandle.keys();
while(clientIds.hasMoreElements())
{
resetClientById((String)clientIds.nextElement());
}
jobIdToSentJob = new Hashtable();
clientIdToJobQueueNum = new Hashtable();
unsentJobQueue = new Vector();
reassignableSentJobQueue = new Vector();
}
public void resetClientById(String clientId)
{
synchronized(unsentJobQueue)
{
synchronized(reassignableSentJobQueue)
{
System.out.println("resetting clientId" + clientId);
Enumeration sentJobIdList = ((Vector)clientIdToSentJobIdVector.get(clientId)).elements();
Enumeration assignedResources = null;
Job theJob = null;
while(sentJobIdList.hasMoreElements())
{
theJob = ((Job)jobIdToSentJob.get((String)sentJobIdList.nextElement()));
theJob.setResultSent(true);
assignedResources = theJob.getAssignedResources();
while(assignedResources.hasMoreElements())
{
(new ResourceTalker((ResourceHandle)assignedResources.nextElement(), "reset " + theJob.getJobId(), "")).start();
}
}
if(clientIdToJobQueueNum.containsKey(clientId))
{
((Vector)unsentJobQueue.elementAt(((Integer)clientIdToJobQueueNum.get(clientId)).intValue())).removeAllElements();
((Vector)reassignableSentJobQueue.elementAt(((Integer)clientIdToJobQueueNum.get(clientId)).intValue())).removeAllElements();
}
}
}
}
public void killAllResources()
{
Enumeration allResourceIds = resourceIdToResourceHandle.keys();
while(allResourceIds.hasMoreElements())
{
(new ResourceTalker((ResourceHandle)resourceIdToResourceHandle.get(allResourceIds.nextElement()), "die", "")).start();
}
}
public static void main(String[] args) throws Throwable
{
(new Dispatcher()).dispatch();
}
public ClientHandle getClientHandle(String clientid)
{
return (ClientHandle)clientIdToClientHandle.get(clientid);
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.relational.optimizer;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.scalar.ScalarFunctionImplementation;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.LambdaDefinitionExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.facebook.presto.sql.relational.VariableReferenceExpression;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.List;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.sql.relational.Expressions.call;
import static com.facebook.presto.sql.relational.Expressions.constant;
import static com.facebook.presto.sql.relational.Expressions.constantNull;
import static com.facebook.presto.sql.relational.Signatures.BIND;
import static com.facebook.presto.sql.relational.Signatures.CAST;
import static com.facebook.presto.sql.relational.Signatures.COALESCE;
import static com.facebook.presto.sql.relational.Signatures.DEREFERENCE;
import static com.facebook.presto.sql.relational.Signatures.IF;
import static com.facebook.presto.sql.relational.Signatures.IN;
import static com.facebook.presto.sql.relational.Signatures.IS_NULL;
import static com.facebook.presto.sql.relational.Signatures.NULL_IF;
import static com.facebook.presto.sql.relational.Signatures.ROW_CONSTRUCTOR;
import static com.facebook.presto.sql.relational.Signatures.SWITCH;
import static com.facebook.presto.sql.relational.Signatures.TRY;
import static com.facebook.presto.sql.relational.Signatures.TRY_CAST;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.collect.ImmutableList.toImmutableList;
public class ExpressionOptimizer
{
private final FunctionRegistry registry;
private final TypeManager typeManager;
private final ConnectorSession session;
public ExpressionOptimizer(FunctionRegistry registry, TypeManager typeManager, Session session)
{
this.registry = registry;
this.typeManager = typeManager;
this.session = session.toConnectorSession();
}
public RowExpression optimize(RowExpression expression)
{
return expression.accept(new Visitor(), null);
}
private class Visitor
implements RowExpressionVisitor<Void, RowExpression>
{
@Override
public RowExpression visitInputReference(InputReferenceExpression reference, Void context)
{
return reference;
}
@Override
public RowExpression visitConstant(ConstantExpression literal, Void context)
{
return literal;
}
@Override
public RowExpression visitCall(CallExpression call, Void context)
{
ScalarFunctionImplementation function;
Signature signature = call.getSignature();
if (signature.getName().equals(CAST)) {
Signature functionSignature = registry.getCoercion(call.getArguments().get(0).getType(), call.getType());
function = registry.getScalarFunctionImplementation(functionSignature);
}
else {
switch (signature.getName()) {
// TODO: optimize these special forms
case IF: {
checkState(call.getArguments().size() == 3, "IF function should have 3 arguments. Get " + call.getArguments().size());
RowExpression optimizedOperand = call.getArguments().get(0).accept(this, context);
if (optimizedOperand instanceof ConstantExpression) {
ConstantExpression constantOperand = (ConstantExpression) optimizedOperand;
checkState(constantOperand.getType().equals(BOOLEAN), "Operand of IF function should be BOOLEAN type. Get type " + constantOperand.getType().getDisplayName());
if (Boolean.TRUE.equals(constantOperand.getValue())) {
return call.getArguments().get(1).accept(this, context);
}
// FALSE and NULL
else {
return call.getArguments().get(2).accept(this, context);
}
}
List<RowExpression> arguments = call.getArguments().stream()
.map(argument -> argument.accept(this, null))
.collect(toImmutableList());
return call(signature, call.getType(), arguments);
}
case TRY: {
checkState(call.getArguments().size() == 1, "try call expressions must have a single argument");
if (!(Iterables.getOnlyElement(call.getArguments()) instanceof CallExpression)) {
return Iterables.getOnlyElement(call.getArguments()).accept(this, null);
}
List<RowExpression> arguments = call.getArguments().stream()
.map(argument -> argument.accept(this, null))
.collect(toImmutableList());
return call(signature, call.getType(), arguments);
}
case BIND: {
checkState(call.getArguments().size() == 2, BIND + " function should have 2 arguments. Got " + call.getArguments().size());
RowExpression optimizedValue = call.getArguments().get(0).accept(this, context);
RowExpression optimizedFunction = call.getArguments().get(1).accept(this, context);
if (optimizedValue instanceof ConstantExpression && optimizedFunction instanceof ConstantExpression) {
// Here, optimizedValue and optimizedFunction should be merged together into a new ConstantExpression.
// It's not implemented because it would be dead code anyways because visitLambda does not produce ConstantExpression.
throw new UnsupportedOperationException();
}
return call(signature, call.getType(), ImmutableList.of(optimizedValue, optimizedFunction));
}
case NULL_IF:
case SWITCH:
case "WHEN":
case TRY_CAST:
case IS_NULL:
case COALESCE:
case "AND":
case "OR":
case IN:
case DEREFERENCE:
case ROW_CONSTRUCTOR: {
List<RowExpression> arguments = call.getArguments().stream()
.map(argument -> argument.accept(this, null))
.collect(toImmutableList());
return call(signature, call.getType(), arguments);
}
default:
function = registry.getScalarFunctionImplementation(signature);
}
}
List<RowExpression> arguments = call.getArguments().stream()
.map(argument -> argument.accept(this, context))
.collect(toImmutableList());
// TODO: optimize function calls with lambda arguments. For example, apply(x -> x + 2, 1)
if (Iterables.all(arguments, instanceOf(ConstantExpression.class)) && function.isDeterministic()) {
MethodHandle method = function.getMethodHandle();
if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) {
method = method.bindTo(session);
}
int index = 0;
List<Object> constantArguments = new ArrayList<>();
for (RowExpression argument : arguments) {
Object value = ((ConstantExpression) argument).getValue();
// if any argument is null, return null
if (value == null && !function.getNullableArguments().get(index)) {
return constantNull(call.getType());
}
constantArguments.add(value);
index++;
}
try {
return constant(method.invokeWithArguments(constantArguments), call.getType());
}
catch (Throwable e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
// Do nothing. As a result, this specific tree will be left untouched. But irrelevant expressions will continue to get evaluated and optimized.
}
}
return call(signature, typeManager.getType(signature.getReturnType()), arguments);
}
@Override
public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context)
{
return new LambdaDefinitionExpression(lambda.getArgumentTypes(), lambda.getArguments(), lambda.getBody().accept(this, context));
}
@Override
public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context)
{
return reference;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tez.mapreduce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.URL;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.tez.client.TezClientUtils;
import org.apache.tez.client.TezClient;
import org.apache.tez.client.TezAppMasterStatus;
import org.apache.tez.common.ReflectionUtils;
import org.apache.tez.common.TezUtils;
import org.apache.tez.common.counters.FileSystemCounter;
import org.apache.tez.common.counters.TaskCounter;
import org.apache.tez.dag.api.DAG;
import org.apache.tez.dag.api.DataSinkDescriptor;
import org.apache.tez.dag.api.DataSourceDescriptor;
import org.apache.tez.dag.api.Edge;
import org.apache.tez.dag.api.EdgeProperty;
import org.apache.tez.dag.api.EdgeProperty.DataMovementType;
import org.apache.tez.dag.api.EdgeProperty.DataSourceType;
import org.apache.tez.dag.api.EdgeProperty.SchedulingType;
import org.apache.tez.dag.api.InputDescriptor;
import org.apache.tez.dag.api.InputInitializerDescriptor;
import org.apache.tez.dag.api.OutputDescriptor;
import org.apache.tez.dag.api.ProcessorDescriptor;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezException;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.api.UserPayload;
import org.apache.tez.dag.api.Vertex;
import org.apache.tez.dag.api.client.DAGClient;
import org.apache.tez.dag.api.client.DAGStatus;
import org.apache.tez.dag.api.client.StatusGetOpts;
import org.apache.tez.dag.api.client.DAGStatus.State;
import org.apache.tez.dag.history.logging.impl.SimpleHistoryLoggingService;
import org.apache.tez.mapreduce.common.MRInputAMSplitGenerator;
import org.apache.tez.mapreduce.examples.BroadcastAndOneToOneExample;
import org.apache.tez.mapreduce.examples.ExampleDriver;
import org.apache.tez.mapreduce.examples.MRRSleepJob;
import org.apache.tez.mapreduce.examples.MRRSleepJob.ISleepReducer;
import org.apache.tez.mapreduce.examples.MRRSleepJob.MRRSleepJobPartitioner;
import org.apache.tez.mapreduce.examples.MRRSleepJob.SleepInputFormat;
import org.apache.tez.mapreduce.examples.MRRSleepJob.SleepMapper;
import org.apache.tez.mapreduce.examples.MRRSleepJob.SleepReducer;
import org.apache.tez.mapreduce.examples.UnionExample;
import org.apache.tez.mapreduce.hadoop.MRHelpers;
import org.apache.tez.mapreduce.hadoop.MRInputHelpers;
import org.apache.tez.mapreduce.hadoop.MRJobConfig;
import org.apache.tez.mapreduce.input.MRInputLegacy;
import org.apache.tez.mapreduce.output.MROutputLegacy;
import org.apache.tez.mapreduce.processor.map.MapProcessor;
import org.apache.tez.mapreduce.processor.reduce.ReduceProcessor;
import org.apache.tez.mapreduce.protos.MRRuntimeProtos.MRInputUserPayloadProto;
import org.apache.tez.runtime.api.Event;
import org.apache.tez.runtime.api.InputInitializer;
import org.apache.tez.runtime.api.InputInitializerContext;
import org.apache.tez.runtime.library.api.TezRuntimeConfiguration;
import org.apache.tez.runtime.library.input.OrderedGroupedInputLegacy;
import org.apache.tez.runtime.library.output.OrderedPartitionedKVOutput;
import org.apache.tez.runtime.library.processor.SleepProcessor;
import org.apache.tez.runtime.library.processor.SleepProcessor.SleepProcessorConfig;
import org.apache.tez.test.MiniTezCluster;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
public class TestMRRJobsDAGApi {
private static final Log LOG = LogFactory.getLog(TestMRRJobsDAGApi.class);
protected static MiniTezCluster mrrTezCluster;
protected static MiniDFSCluster dfsCluster;
private static Configuration conf = new Configuration();
private static FileSystem remoteFs;
private Random random = new Random();
private static String TEST_ROOT_DIR = "target" + Path.SEPARATOR
+ TestMRRJobsDAGApi.class.getName() + "-tmpDir";
@BeforeClass
public static void setup() throws IOException {
try {
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, TEST_ROOT_DIR);
dfsCluster = new MiniDFSCluster.Builder(conf).numDataNodes(2)
.format(true).racks(null).build();
remoteFs = dfsCluster.getFileSystem();
} catch (IOException io) {
throw new RuntimeException("problem starting mini dfs cluster", io);
}
if (mrrTezCluster == null) {
mrrTezCluster = new MiniTezCluster(TestMRRJobsDAGApi.class.getName(),
1, 1, 1);
Configuration conf = new Configuration();
conf.set("fs.defaultFS", remoteFs.getUri().toString()); // use HDFS
conf.setInt("yarn.nodemanager.delete.debug-delay-sec", 20000);
mrrTezCluster.init(conf);
mrrTezCluster.start();
}
}
@AfterClass
public static void tearDown() {
if (mrrTezCluster != null) {
mrrTezCluster.stop();
mrrTezCluster = null;
}
if (dfsCluster != null) {
dfsCluster.shutdown();
dfsCluster = null;
}
// TODO Add cleanup code.
}
@Test(timeout = 60000)
public void testSleepJob() throws TezException, IOException, InterruptedException {
SleepProcessorConfig spConf = new SleepProcessorConfig(1);
DAG dag = DAG.create("TezSleepProcessor");
Vertex vertex = Vertex.create("SleepVertex", ProcessorDescriptor.create(
SleepProcessor.class.getName()).setUserPayload(spConf.toUserPayload()), 1,
Resource.newInstance(1024, 1));
dag.addVertex(vertex);
TezConfiguration tezConf = new TezConfiguration(mrrTezCluster.getConfig());
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String.valueOf(random
.nextInt(100000))));
remoteFs.mkdirs(remoteStagingDir);
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, remoteStagingDir.toString());
TezClient tezSession = TezClient.create("TezSleepProcessor", tezConf, false);
tezSession.start();
DAGClient dagClient = tezSession.submitDAG(dag);
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.info("Waiting for job to complete. Sleeping for 500ms." + " Current state: "
+ dagStatus.getState());
Thread.sleep(500l);
dagStatus = dagClient.getDAGStatus(null);
}
dagStatus = dagClient.getDAGStatus(Sets.newHashSet(StatusGetOpts.GET_COUNTERS));
assertEquals(DAGStatus.State.SUCCEEDED, dagStatus.getState());
assertNotNull(dagStatus.getDAGCounters());
assertNotNull(dagStatus.getDAGCounters().getGroup(FileSystemCounter.class.getName()));
assertNotNull(dagStatus.getDAGCounters().findCounter(TaskCounter.GC_TIME_MILLIS));
ExampleDriver.printDAGStatus(dagClient, new String[] { "SleepVertex" }, true, true);
tezSession.stop();
}
@Test(timeout = 100000)
public void testMultipleDAGsWithDuplicateName() throws TezException, IOException,
InterruptedException {
TezClient tezSession = null;
try {
TezConfiguration tezConf = new TezConfiguration(mrrTezCluster.getConfig());
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String.valueOf(random
.nextInt(100000))));
remoteFs.mkdirs(remoteStagingDir);
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, remoteStagingDir.toString());
tezSession = TezClient.create("OrderedWordCountSession", tezConf, true);
tezSession.start();
SleepProcessorConfig spConf = new SleepProcessorConfig(1);
for (int dagIndex = 1; dagIndex <= 2; dagIndex++) {
DAG dag = DAG.create("TezSleepProcessor");
Vertex vertex = Vertex.create("SleepVertex", ProcessorDescriptor.create(
SleepProcessor.class.getName()).setUserPayload(spConf.toUserPayload()), 1,
Resource.newInstance(1024, 1));
dag.addVertex(vertex);
DAGClient dagClient = null;
try {
dagClient = tezSession.submitDAG(dag);
if (dagIndex > 1) {
fail("Should fail due to duplicate dag name for dagIndex: " + dagIndex);
}
} catch (TezException tex) {
if (dagIndex > 1) {
assertTrue(tex.getMessage().contains("Duplicate dag name "));
continue;
}
fail("DuplicateDAGName exception thrown for 1st DAG submission");
}
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.debug("Waiting for job to complete. Sleeping for 500ms." + " Current state: "
+ dagStatus.getState());
Thread.sleep(500l);
dagStatus = dagClient.getDAGStatus(null);
}
}
} finally {
if (tezSession != null) {
tezSession.stop();
}
}
}
@Test
public void testNonDefaultFSStagingDir() throws Exception {
SleepProcessorConfig spConf = new SleepProcessorConfig(1);
DAG dag = DAG.create("TezSleepProcessor");
Vertex vertex = Vertex.create("SleepVertex", ProcessorDescriptor.create(
SleepProcessor.class.getName()).setUserPayload(spConf.toUserPayload()), 1,
Resource.newInstance(1024, 1));
dag.addVertex(vertex);
TezConfiguration tezConf = new TezConfiguration(mrrTezCluster.getConfig());
Path stagingDir = new Path(TEST_ROOT_DIR, "testNonDefaultFSStagingDir"
+ String.valueOf(random.nextInt(100000)));
FileSystem localFs = FileSystem.getLocal(tezConf);
stagingDir = localFs.makeQualified(stagingDir);
localFs.mkdirs(stagingDir);
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, stagingDir.toString());
TezClient tezSession = TezClient.create("TezSleepProcessor", tezConf, false);
tezSession.start();
DAGClient dagClient = tezSession.submitDAG(dag);
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.info("Waiting for job to complete. Sleeping for 500ms." + " Current state: "
+ dagStatus.getState());
Thread.sleep(500l);
dagStatus = dagClient.getDAGStatus(null);
}
dagStatus = dagClient.getDAGStatus(Sets.newHashSet(StatusGetOpts.GET_COUNTERS));
assertEquals(DAGStatus.State.SUCCEEDED, dagStatus.getState());
assertNotNull(dagStatus.getDAGCounters());
assertNotNull(dagStatus.getDAGCounters().getGroup(FileSystemCounter.class.getName()));
assertNotNull(dagStatus.getDAGCounters().findCounter(TaskCounter.GC_TIME_MILLIS));
ExampleDriver.printDAGStatus(dagClient, new String[] { "SleepVertex" }, true, true);
tezSession.stop();
}
// Submits a simple 5 stage sleep job using tez session. Then kills it.
@Test(timeout = 60000)
public void testHistoryLogging() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
SleepProcessorConfig spConf = new SleepProcessorConfig(1);
DAG dag = DAG.create("TezSleepProcessorHistoryLogging");
Vertex vertex = Vertex.create("SleepVertex", ProcessorDescriptor.create(
SleepProcessor.class.getName()).setUserPayload(spConf.toUserPayload()), 2,
Resource.newInstance(1024, 1));
dag.addVertex(vertex);
TezConfiguration tezConf = new TezConfiguration(mrrTezCluster.getConfig());
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String.valueOf(random
.nextInt(100000))));
remoteFs.mkdirs(remoteStagingDir);
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, remoteStagingDir.toString());
FileSystem localFs = FileSystem.getLocal(tezConf);
Path historyLogDir = new Path(TEST_ROOT_DIR, "testHistoryLogging");
localFs.mkdirs(historyLogDir);
tezConf.set(TezConfiguration.TEZ_SIMPLE_HISTORY_LOGGING_DIR,
localFs.makeQualified(historyLogDir).toString());
tezConf.setBoolean(TezConfiguration.TEZ_AM_SESSION_MODE, false);
TezClient tezSession = TezClient.create("TezSleepProcessorHistoryLogging", tezConf);
tezSession.start();
DAGClient dagClient = tezSession.submitDAG(dag);
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.info("Waiting for job to complete. Sleeping for 500ms." + " Current state: "
+ dagStatus.getState());
Thread.sleep(500l);
dagStatus = dagClient.getDAGStatus(null);
}
assertEquals(DAGStatus.State.SUCCEEDED, dagStatus.getState());
FileStatus historyLogFileStatus = null;
for (FileStatus fileStatus : localFs.listStatus(historyLogDir)) {
if (fileStatus.isDirectory()) {
continue;
}
Path p = fileStatus.getPath();
if (p.getName().startsWith(SimpleHistoryLoggingService.LOG_FILE_NAME_PREFIX)) {
historyLogFileStatus = fileStatus;
break;
}
}
Assert.assertNotNull(historyLogFileStatus);
Assert.assertTrue(historyLogFileStatus.getLen() > 0);
tezSession.stop();
}
// Submits a simple 5 stage sleep job using the DAG submit API instead of job
// client.
@Test(timeout = 60000)
public void testMRRSleepJobDagSubmit() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
State finalState = testMRRSleepJobDagSubmitCore(false, false, false, false);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
// TODO Add additional checks for tracking URL etc. - once it's exposed by
// the DAG API.
}
// Submits a simple 5 stage sleep job using the DAG submit API. Then kills it.
@Test(timeout = 60000)
public void testMRRSleepJobDagSubmitAndKill() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
State finalState = testMRRSleepJobDagSubmitCore(false, true, false, false);
Assert.assertEquals(DAGStatus.State.KILLED, finalState);
// TODO Add additional checks for tracking URL etc. - once it's exposed by
// the DAG API.
}
// Submits a DAG to AM via RPC after AM has started
@Test(timeout = 60000)
public void testMRRSleepJobViaSession() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
State finalState = testMRRSleepJobDagSubmitCore(true, false, false, false);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
}
// Submit 2 jobs via RPC using a custom initializer. The second job is submitted with an
// additional local resource, which is verified by the initializer.
@Test(timeout = 120000)
public void testAMRelocalization() throws Exception {
Path relocPath = new Path("/tmp/relocalizationfilefound");
if (remoteFs.exists(relocPath)) {
remoteFs.delete(relocPath, true);
}
TezClient tezSession = createTezSession();
State finalState = testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, true, MRInputAMSplitGeneratorRelocalizationTest.class, null);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
Assert.assertFalse(remoteFs.exists(new Path("/tmp/relocalizationfilefound")));
// Start the second job with some additional resources.
// Create a test jar directly to HDFS
LOG.info("Creating jar for relocalization test");
Path relocFilePath = new Path("/tmp/test.jar");
relocFilePath = remoteFs.makeQualified(relocFilePath);
OutputStream os = remoteFs.create(relocFilePath, true);
createTestJar(os, RELOCALIZATION_TEST_CLASS_NAME);
// Also upload one of Tez's own JARs to HDFS and add as resource; should be ignored
Path tezAppJar = new Path(MiniTezCluster.APPJAR);
Path tezAppJarRemote = remoteFs.makeQualified(new Path("/tmp/" + tezAppJar.getName()));
remoteFs.copyFromLocalFile(tezAppJar, tezAppJarRemote);
Map<String, LocalResource> additionalResources = new HashMap<String, LocalResource>();
additionalResources.put("test.jar", createLrObjFromPath(relocFilePath));
additionalResources.put("TezAppJar.jar", createLrObjFromPath(tezAppJarRemote));
Assert.assertEquals(TezAppMasterStatus.READY,
tezSession.getAppMasterStatus());
finalState = testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, true, MRInputAMSplitGeneratorRelocalizationTest.class, additionalResources);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
Assert.assertEquals(TezAppMasterStatus.READY,
tezSession.getAppMasterStatus());
Assert.assertTrue(remoteFs.exists(new Path("/tmp/relocalizationfilefound")));
stopAndVerifyYarnApp(tezSession);
}
private void stopAndVerifyYarnApp(TezClient tezSession) throws TezException,
IOException, YarnException {
ApplicationId appId = tezSession.getAppMasterApplicationId();
tezSession.stop();
Assert.assertEquals(TezAppMasterStatus.SHUTDOWN,
tezSession.getAppMasterStatus());
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(mrrTezCluster.getConfig());
yarnClient.start();
while (true) {
ApplicationReport appReport = yarnClient.getApplicationReport(appId);
if (appReport.getYarnApplicationState().equals(
YarnApplicationState.FINISHED)
|| appReport.getYarnApplicationState().equals(
YarnApplicationState.FAILED)
|| appReport.getYarnApplicationState().equals(
YarnApplicationState.KILLED)) {
break;
}
}
ApplicationReport appReport = yarnClient.getApplicationReport(appId);
Assert.assertEquals(YarnApplicationState.FINISHED,
appReport.getYarnApplicationState());
Assert.assertEquals(FinalApplicationStatus.SUCCEEDED,
appReport.getFinalApplicationStatus());
}
@Test(timeout = 120000)
public void testAMRelocalizationConflict() throws Exception {
Path relocPath = new Path("/tmp/relocalizationfilefound");
if (remoteFs.exists(relocPath)) {
remoteFs.delete(relocPath, true);
}
// Run a DAG w/o a file.
TezClient tezSession = createTezSession();
State finalState = testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, true, MRInputAMSplitGeneratorRelocalizationTest.class, null);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
Assert.assertFalse(remoteFs.exists(relocPath));
// Create a bogus TezAppJar directly to HDFS
LOG.info("Creating jar for relocalization test");
Path tezAppJar = new Path(MiniTezCluster.APPJAR);
Path tezAppJarRemote = remoteFs.makeQualified(new Path("/tmp/" + tezAppJar.getName()));
OutputStream os = remoteFs.create(tezAppJarRemote, true);
createTestJar(os, RELOCALIZATION_TEST_CLASS_NAME);
Map<String, LocalResource> additionalResources = new HashMap<String, LocalResource>();
additionalResources.put("TezAppJar.jar", createLrObjFromPath(tezAppJarRemote));
try {
testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, true, MRInputAMSplitGeneratorRelocalizationTest.class, additionalResources);
Assert.fail("should have failed");
} catch (Exception ex) {
// expected
}
stopAndVerifyYarnApp(tezSession);
}
private LocalResource createLrObjFromPath(Path filePath) {
return LocalResource.newInstance(ConverterUtils.getYarnUrlFromPath(filePath),
LocalResourceType.FILE, LocalResourceVisibility.PRIVATE, 0, 0);
}
private TezClient createTezSession() throws IOException, TezException {
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String
.valueOf(new Random().nextInt(100000))));
remoteFs.mkdirs(remoteStagingDir);
TezConfiguration tezConf = new TezConfiguration(mrrTezCluster.getConfig());
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, remoteStagingDir.toString());
TezClient tezSession = TezClient.create("testrelocalizationsession", tezConf, true);
tezSession.start();
Assert.assertEquals(TezAppMasterStatus.INITIALIZING, tezSession.getAppMasterStatus());
return tezSession;
}
// Submits a DAG to AM via RPC after AM has started
@Test(timeout = 120000)
public void testMultipleMRRSleepJobViaSession() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String
.valueOf(new Random().nextInt(100000))));
remoteFs.mkdirs(remoteStagingDir);
TezConfiguration tezConf = new TezConfiguration(
mrrTezCluster.getConfig());
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR,
remoteStagingDir.toString());
TezClient tezSession = TezClient.create("testsession", tezConf, true);
tezSession.start();
Assert.assertEquals(TezAppMasterStatus.INITIALIZING,
tezSession.getAppMasterStatus());
State finalState = testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, false, null, null);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
Assert.assertEquals(TezAppMasterStatus.READY,
tezSession.getAppMasterStatus());
finalState = testMRRSleepJobDagSubmitCore(true, false, false,
tezSession, false, null, null);
Assert.assertEquals(DAGStatus.State.SUCCEEDED, finalState);
Assert.assertEquals(TezAppMasterStatus.READY,
tezSession.getAppMasterStatus());
stopAndVerifyYarnApp(tezSession);
}
// Submits a simple 5 stage sleep job using tez session. Then kills it.
@Test(timeout = 60000)
public void testMRRSleepJobDagSubmitAndKillViaRPC() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
State finalState = testMRRSleepJobDagSubmitCore(true, true, false, false);
Assert.assertEquals(DAGStatus.State.KILLED, finalState);
// TODO Add additional checks for tracking URL etc. - once it's exposed by
// the DAG API.
}
// Create and close a tez session without submitting a job
@Test(timeout = 60000)
public void testTezSessionShutdown() throws IOException,
InterruptedException, TezException, ClassNotFoundException, YarnException {
testMRRSleepJobDagSubmitCore(true, false, true, false);
}
@Test(timeout = 60000)
public void testAMSplitGeneration() throws IOException, InterruptedException,
TezException, ClassNotFoundException, YarnException {
testMRRSleepJobDagSubmitCore(true, false, false, true);
}
public State testMRRSleepJobDagSubmitCore(
boolean dagViaRPC,
boolean killDagWhileRunning,
boolean closeSessionBeforeSubmit,
boolean genSplitsInAM) throws IOException,
InterruptedException, TezException, ClassNotFoundException,
YarnException {
return testMRRSleepJobDagSubmitCore(dagViaRPC, killDagWhileRunning,
closeSessionBeforeSubmit, null, genSplitsInAM, null, null);
}
public State testMRRSleepJobDagSubmitCore(
boolean dagViaRPC,
boolean killDagWhileRunning,
boolean closeSessionBeforeSubmit,
TezClient reUseTezSession,
boolean genSplitsInAM,
Class<? extends InputInitializer> initializerClass,
Map<String, LocalResource> additionalLocalResources) throws IOException,
InterruptedException, TezException, ClassNotFoundException,
YarnException {
LOG.info("\n\n\nStarting testMRRSleepJobDagSubmit().");
JobConf stage1Conf = new JobConf(mrrTezCluster.getConfig());
JobConf stage2Conf = new JobConf(mrrTezCluster.getConfig());
JobConf stage3Conf = new JobConf(mrrTezCluster.getConfig());
stage1Conf.setLong(MRRSleepJob.MAP_SLEEP_TIME, 1);
stage1Conf.setInt(MRRSleepJob.MAP_SLEEP_COUNT, 1);
stage1Conf.setInt(MRJobConfig.NUM_MAPS, 1);
stage1Conf.set(MRJobConfig.MAP_CLASS_ATTR, SleepMapper.class.getName());
stage1Conf.set(MRJobConfig.MAP_OUTPUT_KEY_CLASS,
IntWritable.class.getName());
stage1Conf.set(MRJobConfig.MAP_OUTPUT_VALUE_CLASS,
IntWritable.class.getName());
stage1Conf.set(MRJobConfig.INPUT_FORMAT_CLASS_ATTR,
SleepInputFormat.class.getName());
stage1Conf.set(MRJobConfig.PARTITIONER_CLASS_ATTR,
MRRSleepJobPartitioner.class.getName());
stage2Conf.setLong(MRRSleepJob.REDUCE_SLEEP_TIME, 1);
stage2Conf.setInt(MRRSleepJob.REDUCE_SLEEP_COUNT, 1);
stage2Conf.setInt(MRJobConfig.NUM_REDUCES, 1);
stage2Conf
.set(MRJobConfig.REDUCE_CLASS_ATTR, ISleepReducer.class.getName());
stage2Conf.set(MRJobConfig.MAP_OUTPUT_KEY_CLASS,
IntWritable.class.getName());
stage2Conf.set(MRJobConfig.MAP_OUTPUT_VALUE_CLASS,
IntWritable.class.getName());
stage2Conf.set(MRJobConfig.PARTITIONER_CLASS_ATTR,
MRRSleepJobPartitioner.class.getName());
stage3Conf.setLong(MRRSleepJob.REDUCE_SLEEP_TIME, 1);
stage3Conf.setInt(MRRSleepJob.REDUCE_SLEEP_COUNT, 1);
stage3Conf.setInt(MRJobConfig.NUM_REDUCES, 1);
stage3Conf.set(MRJobConfig.REDUCE_CLASS_ATTR, SleepReducer.class.getName());
stage3Conf.set(MRJobConfig.MAP_OUTPUT_KEY_CLASS,
IntWritable.class.getName());
stage3Conf.set(MRJobConfig.MAP_OUTPUT_VALUE_CLASS,
IntWritable.class.getName());
MRHelpers.translateMRConfToTez(stage1Conf);
MRHelpers.translateMRConfToTez(stage2Conf);
MRHelpers.translateMRConfToTez(stage3Conf);
MRHelpers.configureMRApiUsage(stage1Conf);
MRHelpers.configureMRApiUsage(stage2Conf);
MRHelpers.configureMRApiUsage(stage3Conf);
Path remoteStagingDir = remoteFs.makeQualified(new Path("/tmp", String
.valueOf(new Random().nextInt(100000))));
TezClientUtils.ensureStagingDirExists(conf, remoteStagingDir);
UserPayload stage1Payload = TezUtils.createUserPayloadFromConf(stage1Conf);
UserPayload stage2Payload = TezUtils.createUserPayloadFromConf(stage2Conf);
UserPayload stage3Payload = TezUtils.createUserPayloadFromConf(stage3Conf);
DAG dag = DAG.create("testMRRSleepJobDagSubmit-" + random.nextInt(1000));
Class<? extends InputInitializer> inputInitializerClazz =
genSplitsInAM ?
(initializerClass == null ? MRInputAMSplitGenerator.class : initializerClass)
: null;
LOG.info("Using initializer class: " + initializerClass);
DataSourceDescriptor dsd;
if (!genSplitsInAM) {
dsd = MRInputHelpers
.configureMRInputWithLegacySplitGeneration(stage1Conf, remoteStagingDir, true);
} else {
if (initializerClass == null) {
dsd = MRInputLegacy.createConfigBuilder(stage1Conf, SleepInputFormat.class).build();
} else {
InputInitializerDescriptor iid =
InputInitializerDescriptor.create(inputInitializerClazz.getName());
dsd = MRInputLegacy.createConfigBuilder(stage1Conf, SleepInputFormat.class)
.setCustomInitializerDescriptor(iid).build();
}
}
Vertex stage1Vertex = Vertex.create("map", ProcessorDescriptor.create(
MapProcessor.class.getName()).setUserPayload(stage1Payload),
dsd.getNumberOfShards(), Resource.newInstance(256, 1));
stage1Vertex.addDataSource("MRInput", dsd);
Vertex stage2Vertex = Vertex.create("ireduce", ProcessorDescriptor.create(
ReduceProcessor.class.getName()).setUserPayload(stage2Payload),
1, Resource.newInstance(256, 1));
Vertex stage3Vertex = Vertex.create("reduce", ProcessorDescriptor.create(
ReduceProcessor.class.getName()).setUserPayload(stage3Payload),
1, Resource.newInstance(256, 1));
stage3Conf.setBoolean(TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT,
true);
DataSinkDescriptor dataSinkDescriptor =
MROutputLegacy.createConfigBuilder(stage3Conf, NullOutputFormat.class).build();
Assert.assertFalse(dataSinkDescriptor.getOutputDescriptor().getHistoryText().isEmpty());
stage3Vertex.addDataSink("MROutput", dataSinkDescriptor);
// TODO env, resources
dag.addVertex(stage1Vertex);
dag.addVertex(stage2Vertex);
dag.addVertex(stage3Vertex);
Edge edge1 = Edge.create(stage1Vertex, stage2Vertex, EdgeProperty.create(
DataMovementType.SCATTER_GATHER, DataSourceType.PERSISTED,
SchedulingType.SEQUENTIAL, OutputDescriptor.create(
OrderedPartitionedKVOutput.class.getName()).setUserPayload(stage2Payload),
InputDescriptor.create(
OrderedGroupedInputLegacy.class.getName()).setUserPayload(stage2Payload)));
Edge edge2 = Edge.create(stage2Vertex, stage3Vertex, EdgeProperty.create(
DataMovementType.SCATTER_GATHER, DataSourceType.PERSISTED,
SchedulingType.SEQUENTIAL, OutputDescriptor.create(
OrderedPartitionedKVOutput.class.getName()).setUserPayload(stage3Payload),
InputDescriptor.create(
OrderedGroupedInputLegacy.class.getName()).setUserPayload(stage3Payload)));
dag.addEdge(edge1);
dag.addEdge(edge2);
TezConfiguration tezConf = new TezConfiguration(
mrrTezCluster.getConfig());
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR,
remoteStagingDir.toString());
DAGClient dagClient = null;
boolean reuseSession = reUseTezSession != null;
TezClient tezSession = null;
if (!dagViaRPC) {
Preconditions.checkArgument(reuseSession == false);
}
if (!reuseSession) {
TezConfiguration tempTezconf = new TezConfiguration(tezConf);
if (!dagViaRPC) {
tempTezconf.setBoolean(TezConfiguration.TEZ_AM_SESSION_MODE, false);
} else {
tempTezconf.setBoolean(TezConfiguration.TEZ_AM_SESSION_MODE, true);
}
tezSession = TezClient.create("testsession", tempTezconf);
tezSession.start();
} else {
tezSession = reUseTezSession;
}
if(!dagViaRPC) {
// TODO Use utility method post TEZ-205 to figure out AM arguments etc.
dagClient = tezSession.submitDAG(dag);
}
if (dagViaRPC && closeSessionBeforeSubmit) {
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(mrrTezCluster.getConfig());
yarnClient.start();
boolean sentKillSession = false;
while(true) {
Thread.sleep(500l);
ApplicationReport appReport =
yarnClient.getApplicationReport(tezSession.getAppMasterApplicationId());
if (appReport == null) {
continue;
}
YarnApplicationState appState = appReport.getYarnApplicationState();
if (!sentKillSession) {
if (appState == YarnApplicationState.RUNNING) {
tezSession.stop();
sentKillSession = true;
}
} else {
if (appState == YarnApplicationState.FINISHED
|| appState == YarnApplicationState.KILLED
|| appState == YarnApplicationState.FAILED) {
LOG.info("Application completed after sending session shutdown"
+ ", yarnApplicationState=" + appState
+ ", finalAppStatus=" + appReport.getFinalApplicationStatus());
Assert.assertEquals(YarnApplicationState.FINISHED,
appState);
Assert.assertEquals(FinalApplicationStatus.SUCCEEDED,
appReport.getFinalApplicationStatus());
break;
}
}
}
yarnClient.stop();
return null;
}
if(dagViaRPC) {
LOG.info("Submitting dag to tez session with appId=" + tezSession.getAppMasterApplicationId()
+ " and Dag Name=" + dag.getName());
if (additionalLocalResources != null) {
tezSession.addAppMasterLocalFiles(additionalLocalResources);
}
dagClient = tezSession.submitDAG(dag);
Assert.assertEquals(TezAppMasterStatus.RUNNING,
tezSession.getAppMasterStatus());
}
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.info("Waiting for job to complete. Sleeping for 500ms."
+ " Current state: " + dagStatus.getState());
Thread.sleep(500l);
if(killDagWhileRunning
&& dagStatus.getState() == DAGStatus.State.RUNNING) {
LOG.info("Killing running dag/session");
if (dagViaRPC) {
tezSession.stop();
} else {
dagClient.tryKillDAG();
}
}
dagStatus = dagClient.getDAGStatus(null);
}
if (!reuseSession) {
tezSession.stop();
}
return dagStatus.getState();
}
private static LocalResource createLocalResource(FileSystem fc, Path file,
LocalResourceType type, LocalResourceVisibility visibility)
throws IOException {
FileStatus fstat = fc.getFileStatus(file);
URL resourceURL = ConverterUtils.getYarnUrlFromPath(fc.resolvePath(fstat
.getPath()));
long resourceSize = fstat.getLen();
long resourceModificationTime = fstat.getModificationTime();
return LocalResource.newInstance(resourceURL, type, visibility,
resourceSize, resourceModificationTime);
}
@Test(timeout = 60000)
public void testVertexGroups() throws Exception {
LOG.info("Running Group Test");
Path inPath = new Path(TEST_ROOT_DIR, "in-groups");
Path outPath = new Path(TEST_ROOT_DIR, "out-groups");
FSDataOutputStream out = remoteFs.create(inPath);
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write("abcd ");
writer.write("efgh ");
writer.write("abcd ");
writer.write("efgh ");
writer.close();
out.close();
UnionExample job = new UnionExample();
if (job.run(inPath.toString(), outPath.toString(), mrrTezCluster.getConfig())) {
LOG.info("Success VertexGroups Test");
} else {
throw new TezUncheckedException("VertexGroups Test Failed");
}
}
@Test(timeout = 60000)
public void testBroadcastAndOneToOne() throws Exception {
LOG.info("Running BroadcastAndOneToOne Test");
BroadcastAndOneToOneExample job = new BroadcastAndOneToOneExample();
if (job.run(mrrTezCluster.getConfig(), true)) {
LOG.info("Success BroadcastAndOneToOne Test");
} else {
throw new TezUncheckedException("BroadcastAndOneToOne Test Failed");
}
}
// This class should not be used by more than one test in a single run, since
// the path it writes to is not dynamic.
private static String RELOCALIZATION_TEST_CLASS_NAME = "AMClassloadTestDummyClass";
public static class MRInputAMSplitGeneratorRelocalizationTest extends MRInputAMSplitGenerator {
public MRInputAMSplitGeneratorRelocalizationTest(
InputInitializerContext initializerContext) {
super(initializerContext);
}
@Override
public List<Event> initialize() throws Exception {
MRInputUserPayloadProto userPayloadProto = MRInputHelpers
.parseMRInputPayload(getContext().getInputUserPayload());
Configuration conf = TezUtils.createConfFromByteString(userPayloadProto
.getConfigurationBytes());
try {
ReflectionUtils.getClazz(RELOCALIZATION_TEST_CLASS_NAME);
LOG.info("Class found");
FileSystem fs = FileSystem.get(conf);
fs.mkdirs(new Path("/tmp/relocalizationfilefound"));
} catch (TezUncheckedException e) {
LOG.info("Class not found");
}
return super.initialize();
}
}
private static void createTestJar(OutputStream outStream, String dummyClassName)
throws URISyntaxException, IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileObject srcFileObject = new SimpleJavaFileObjectImpl(
URI.create("string:///" + dummyClassName + Kind.SOURCE.extension), Kind.SOURCE);
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, Collections.singletonList(srcFileObject))
.call();
JavaFileObject javaFileObject = fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT,
dummyClassName, Kind.CLASS, null);
File classFile = new File(dummyClassName + Kind.CLASS.extension);
JarOutputStream jarOutputStream = new JarOutputStream(outStream);
JarEntry jarEntry = new JarEntry(classFile.getName());
jarEntry.setTime(classFile.lastModified());
jarOutputStream.putNextEntry(jarEntry);
InputStream in = javaFileObject.openInputStream();
byte buffer[] = new byte[4096];
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
jarOutputStream.write(buffer, 0, nRead);
}
in.close();
jarOutputStream.close();
javaFileObject.delete();
}
private static class SimpleJavaFileObjectImpl extends SimpleJavaFileObject {
static final String code = "public class AMClassloadTestDummyClass {}";
SimpleJavaFileObjectImpl(URI uri, Kind kind) {
super(uri, kind);
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
}
| |
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.HealthContributorAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.HealthEndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.web.servlet.ServletManagementContextAutoConfiguration;
import org.springframework.boot.actuate.endpoint.ApiVersion;
import org.springframework.boot.actuate.endpoint.EndpointId;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
import org.springframework.boot.actuate.endpoint.web.WebOperation;
import org.springframework.boot.actuate.endpoint.web.WebOperationRequestPredicate;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.config.BeanIds;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
/**
* Tests for {@link CloudFoundryActuatorAutoConfiguration}.
*
* @author Madhura Bhave
*/
class CloudFoundryActuatorAutoConfigurationTests {
private static final String V3_JSON = ApiVersion.V3.getProducedMimeType().toString();
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class,
JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class,
ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class,
WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class));
@Test
void cloudFoundryPlatformActive() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping,
"endpointMapping");
assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication");
CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils
.getField(handlerMapping, "corsConfiguration");
assertThat(corsConfiguration.getAllowedOrigins()).contains("*");
assertThat(corsConfiguration.getAllowedMethods())
.containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name()));
assertThat(corsConfiguration.getAllowedHeaders())
.containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type"));
});
}
@Test
void cloudfoundryapplicationProducesActuatorMediaType() throws Exception {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
mockMvc.perform(get("/cloudfoundryapplication"))
.andExpect(header().string("Content-Type", V3_JSON));
});
}
@Test
void cloudFoundryPlatformActiveSetsApplicationId() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor");
String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId");
assertThat(applicationId).isEqualTo("my-app-id");
});
}
@Test
void cloudFoundryPlatformActiveSetsCloudControllerUrl() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor");
Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor,
"cloudFoundrySecurityService");
String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService,
"cloudControllerUrl");
assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com");
});
}
@Test
void skipSslValidation() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com",
"management.cloudfoundry.skip-ssl-validation:true").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor");
Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor,
"cloudFoundrySecurityService");
RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService,
"restTemplate");
assertThat(restTemplate.getRequestFactory())
.isInstanceOf(SkipSslVerificationHttpRequestFactory.class);
});
}
@Test
void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id")
.run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor");
Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor,
"cloudFoundrySecurityService");
assertThat(interceptorSecurityService).isNull();
});
}
@Test
void cloudFoundryPathsIgnoredBySpringSecurity() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id")
.run((context) -> {
FilterChainProxy securityFilterChain = (FilterChainProxy) context
.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/cloudfoundryapplication/my-path");
assertThat(chain.getFilters()).isEmpty();
assertThat(chain.matches(request)).isTrue();
request.setServletPath("/some-other-path");
assertThat(chain.matches(request)).isFalse();
});
}
@Test
void cloudFoundryPlatformInactive() {
this.contextRunner.withPropertyValues()
.run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping"))
.isFalse());
}
@Test
void cloudFoundryManagementEndpointsDisabled() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false")
.run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse());
}
@Test
void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() {
this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---",
"vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com")
.run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Collection<ExposableWebEndpoint> endpoints = handlerMapping.getEndpoints();
assertThat(endpoints.stream()
.filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst())
.isNotEmpty();
});
}
@Test
void endpointPathCustomizationIsNotApplied() {
this.contextRunner
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com",
"management.endpoints.web.path-mapping.test=custom")
.withBean(TestEndpoint.class, TestEndpoint::new).run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
Collection<ExposableWebEndpoint> endpoints = handlerMapping.getEndpoints();
ExposableWebEndpoint endpoint = endpoints.stream()
.filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst()
.get();
Collection<WebOperation> operations = endpoint.getOperations();
assertThat(operations).hasSize(1);
assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test");
});
}
@Test
void healthEndpointInvokerShouldBeCloudFoundryWebExtension() {
this.contextRunner
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com")
.withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class,
HealthEndpointAutoConfiguration.class))
.run((context) -> {
Collection<ExposableWebEndpoint> endpoints = context
.getBean("cloudFoundryWebEndpointServletHandlerMapping",
CloudFoundryWebEndpointServletHandlerMapping.class)
.getEndpoints();
ExposableWebEndpoint endpoint = endpoints.iterator().next();
assertThat(endpoint.getOperations()).hasSize(2);
WebOperation webOperation = findOperationWithRequestPath(endpoint, "health");
assertThat(webOperation).extracting("invoker").extracting("target")
.isInstanceOf(CloudFoundryHealthEndpointWebExtension.class);
});
}
private CloudFoundryWebEndpointServletHandlerMapping getHandlerMapping(ApplicationContext context) {
return context.getBean("cloudFoundryWebEndpointServletHandlerMapping",
CloudFoundryWebEndpointServletHandlerMapping.class);
}
private WebOperation findOperationWithRequestPath(ExposableWebEndpoint endpoint, String requestPath) {
for (WebOperation operation : endpoint.getOperations()) {
WebOperationRequestPredicate predicate = operation.getRequestPredicate();
if (predicate.getPath().equals(requestPath) && predicate.getProduces().contains(V3_JSON)) {
return operation;
}
}
throw new IllegalStateException(
"No operation found with request path " + requestPath + " from " + endpoint.getOperations());
}
@Endpoint(id = "test")
static class TestEndpoint {
@ReadOperation
String hello() {
return "hello world";
}
}
}
| |
package apoc.load;
import org.neo4j.procedure.Description;
import apoc.result.RowResult;
import apoc.ApocConfiguration;
import apoc.util.MapUtil;
import org.neo4j.logging.Log;
import org.neo4j.procedure.Context;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.Procedure;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* @author mh
* @since 26.02.16
*/
public class Jdbc {
static {
ApocConfiguration.get("jdbc").forEach((k, v) -> {
if (k.endsWith("driver")) loadDriver(v.toString());
});
}
@Context
public Log log;
@Procedure
@Description("apoc.load.driver('org.apache.derby.jdbc.EmbeddedDriver') register JDBC driver of source database")
public void driver(@Name("driverClass") String driverClass) {
loadDriver(driverClass);
}
private static void loadDriver(@Name("driverClass") String driverClass) {
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not load driver class "+driverClass+" "+e.getMessage());
}
}
@Procedure
@Description("apoc.load.jdbc('key or url','table or statement') YIELD row - load from relational database, from a full table or a sql statement")
public Stream<RowResult> jdbc(@Name("jdbc") String urlOrKey, @Name("tableOrSql") String tableOrSelect, @Name
(value = "params", defaultValue = "[]") List<Object> params) {
return executeQuery(urlOrKey, tableOrSelect, params.toArray(new Object[params.size()]));
}
@Procedure
@Deprecated
@Description("deprecated - please use: apoc.load.jdbc('key or url','statement',[params]) YIELD row - load from relational database, from a sql statement with parameters")
public Stream<RowResult> jdbcParams(@Name("jdbc") String urlOrKey, @Name("sql") String select, @Name("params") List<Object> params) {
return executeQuery(urlOrKey, select,params.toArray(new Object[params.size()]));
}
private Stream<RowResult> executeQuery(String urlOrKey, String tableOrSelect, Object...params) {
String url = urlOrKey.contains(":") ? urlOrKey : getJdbcUrl(urlOrKey);
String query = tableOrSelect.indexOf(' ') == -1 ? "SELECT * FROM " + tableOrSelect : tableOrSelect;
try {
Connection connection = DriverManager.getConnection(url);
PreparedStatement stmt = connection.prepareStatement(query);
for (int i = 0; i < params.length; i++) stmt.setObject(i+1, params[i]);
ResultSet rs = stmt.executeQuery();
rs.setFetchSize(5000);
Iterator<Map<String, Object>> supplier = new ResultSetIterator(log, rs,true);
Spliterator<Map<String, Object>> spliterator = Spliterators.spliteratorUnknownSize(supplier, Spliterator.ORDERED);
return StreamSupport.stream(spliterator, false)
.map(RowResult::new)
.onClose( () -> closeIt(log, stmt, connection));
} catch (SQLException e) {
log.error(String.format("Cannot execute SQL statement `%s`.%nError:%n%s", query, e.getMessage()),e);
String errorMessage = "Cannot execute SQL statement `%s`.%nError:%n%s";
if(e.getMessage().contains("No suitable driver")) errorMessage="Cannot execute SQL statement `%s`.%nError:%n%s%n%s";
throw new RuntimeException(String.format(errorMessage, query, e.getMessage(), "Please download and copy the JDBC driver into $NEO4J_HOME/plugins,more details at https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_load_jdbc_resources"), e);
}
}
@Procedure
@Description("apoc.load.jdbcUpdate('key or url','statement',[params]) YIELD row - update relational database, from a SQL statement with optional parameters")
public Stream<RowResult> jdbcUpdate(@Name("jdbc") String urlOrKey, @Name("query") String query, @Name(value = "params", defaultValue = "[]") List<Object> params) {
log.info( String.format( "Executing SQL update: %s", query ) );
return executeUpdate(urlOrKey, query, params.toArray(new Object[params.size()]));
}
private Stream<RowResult> executeUpdate(String urlOrKey, String query, Object...params) {
String url = urlOrKey.contains(":") ? urlOrKey : getJdbcUrl(urlOrKey);
try {
Connection connection = DriverManager.getConnection(url);
PreparedStatement stmt = connection.prepareStatement(query);
for (int i = 0; i < params.length; i++) stmt.setObject(i+1, params[i]);
int updateCount = stmt.executeUpdate();
closeIt(log, stmt, connection);
Map<String,Object> result = MapUtil.map( "count", updateCount );
return Stream.of( result )
.map( RowResult::new );
} catch (SQLException e) {
log.error(String.format("Cannot execute SQL statement `%s`.%nError:%n%s", query, e.getMessage()),e);
String errorMessage = "Cannot execute SQL statement `%s`.%nError:%n%s";
if(e.getMessage().contains("No suitable driver")) errorMessage="Cannot execute SQL statement `%s`.%nError:%n%s%n%s";
throw new RuntimeException(String.format(errorMessage, query, e.getMessage(), "Please download and copy the JDBC driver into $NEO4J_HOME/plugins,more details at https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_load_jdbc_resources"), e);
}
}
static void closeIt(Log log, AutoCloseable...closeables) {
for (AutoCloseable c : closeables) {
try {
if (c!=null) {
c.close();
}
} catch (Exception e) {
log.warn(String.format("Error closing %s: %s", c.getClass().getSimpleName(), c),e);
// ignore
}
}
}
private static String getJdbcUrl(String key) {
Object value = ApocConfiguration.get("jdbc").get(key + ".url");
if (value == null) throw new RuntimeException("No apoc.jdbc."+key+".url jdbc url specified");
return value.toString();
}
private static class ResultSetIterator implements Iterator<Map<String, Object>> {
private final Log log;
private final ResultSet rs;
private final String[] columns;
private final boolean closeConnection;
private Map<String, Object> map;
public ResultSetIterator(Log log, ResultSet rs, boolean closeConnection) throws SQLException {
this.log = log;
this.rs = rs;
this.columns = getMetaData(rs);
this.closeConnection = closeConnection;
this.map = get();
}
private String[] getMetaData(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
String[] columns = new String[cols + 1];
for (int col = 1; col <= cols; col++) {
columns[col] = meta.getColumnLabel(col);
}
return columns;
}
@Override
public boolean hasNext() {
return this.map != null;
}
@Override
public Map<String, Object> next() {
Map<String, Object> current = this.map;
this.map = get();
return current;
}
public Map<String, Object> get() {
try {
if (handleEndOfResults()) return null;
Map<String, Object> row = new LinkedHashMap<>(columns.length);
for (int col = 1; col < columns.length; col++) {
row.put(columns[col], convert(rs.getObject(col)));
}
return row;
} catch (SQLException e) {
throw new RuntimeException("Cannot execute read result-set.", e);
}
}
private Object convert(Object value) {
if (value instanceof UUID || value instanceof BigInteger || value instanceof BigDecimal) {
return value.toString();
}
if (value instanceof java.util.Date) {
return ((java.util.Date) value).getTime();
}
return value;
}
private boolean handleEndOfResults() throws SQLException {
if (rs.isClosed()) {
return true;
}
if (!rs.next()) {
if (!rs.isClosed()) {
// rs.close();
closeIt(log, rs.getStatement(), closeConnection ? rs.getStatement().getConnection() : null);
}
return true;
}
return false;
}
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.facet.impl.ui.libraries;
import com.intellij.facet.ui.libraries.LibraryDownloadInfo;
import com.intellij.facet.ui.libraries.LibraryInfo;
import com.intellij.facet.ui.libraries.RemoteRepositoryInfo;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.MutualMap;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
/**
* @author nik
*/
public class LibraryCompositionOptionsPanel {
private final MutualMap<LibrariesContainer.LibraryLevel, String> myLibraryLevels = new MutualMap<LibrariesContainer.LibraryLevel, String>(true);
private JPanel myMainPanel;
private JButton myAddLibraryButton;
private JButton myAddJarsButton;
private JCheckBox myDownloadMissingJarsCheckBox;
private TextFieldWithBrowseButton myDirectoryField;
private JComboBox myLibraryLevelComboBox;
private JTextField myLibraryNameField;
private JPanel myMissingLibrariesPanel;
private JPanel myNewLibraryPanel;
private JPanel myLibraryPropertiesPanel;
private JPanel myMirrorsPanel;
private JLabel myMissingLibrariesLabel;
private JLabel myHiddenLabel;
private final List<VirtualFile> myAddedJars = new ArrayList<VirtualFile>();
private final List<Library> myUsedLibraries = new ArrayList<Library>();
private final LibrariesContainer myLibrariesContainer;
private final LibraryCompositionSettings myLibraryCompositionSettings;
private final List<Library> mySuitableLibraries;
private final LibraryDownloadingMirrorsMap myMirrorsMap;
private List<RemoteRepositoryMirrorPanel> myMirrorPanelsList;
public LibraryCompositionOptionsPanel(final @NotNull LibrariesContainer librariesContainer, final @NotNull LibraryCompositionSettings libraryCompositionSettings,
final @NotNull LibraryDownloadingMirrorsMap mirrorsMap) {
myLibrariesContainer = librariesContainer;
myLibraryCompositionSettings = libraryCompositionSettings;
myMirrorsMap = mirrorsMap;
addMirrorsPanels();
myMainPanel.setBorder(BorderFactory.createCompoundBorder(IdeBorderFactory.createTitledBorder(libraryCompositionSettings.getTitle()), IdeBorderFactory.createEmptyBorder(5,5,5,5)));
myDirectoryField.addBrowseFolderListener(ProjectBundle.message("file.chooser.directory.for.downloaded.libraries.title"),
ProjectBundle.message("file.chooser.directory.for.downloaded.libraries.description"), null,
FileChooserDescriptorFactory.createSingleFolderDescriptor());
myAddedJars.addAll(myLibraryCompositionSettings.getAddedJars());
myUsedLibraries.addAll(myLibraryCompositionSettings.getUsedLibraries());
myAddJarsButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
showFileChooser();
}
});
myAddLibraryButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
showLibrariesChooser();
}
});
myDownloadMissingJarsCheckBox.setSelected(myLibraryCompositionSettings.isDownloadLibraries());
myDownloadMissingJarsCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
updateAll();
}
});
mySuitableLibraries = calculateSuitableLibraries();
myAddLibraryButton.setEnabled(!mySuitableLibraries.isEmpty());
myLibraryLevels.put(LibrariesContainer.LibraryLevel.GLOBAL, ProjectBundle.message("combobox.item.global.library"));
myLibraryLevels.put(LibrariesContainer.LibraryLevel.PROJECT, ProjectBundle.message("combobox.item.project.library"));
myLibraryLevels.put(LibrariesContainer.LibraryLevel.MODULE, ProjectBundle.message("combobox.item.module.library"));
for (String level : myLibraryLevels.getValues()) {
myLibraryLevelComboBox.addItem(level);
}
myLibraryLevelComboBox.setSelectedItem(myLibraryLevels.getValue(myLibraryCompositionSettings.getLibraryLevel()));
myLibraryNameField.setText(myLibraryCompositionSettings.getLibraryName());
myDirectoryField.setText(FileUtil.toSystemDependentName(myLibraryCompositionSettings.getDirectoryForDownloadedLibrariesPath()));
String jars = RequiredLibrariesInfo.getLibrariesPresentableText(myLibraryCompositionSettings.getLibraryInfos());
myHiddenLabel.setText(UIUtil.toHtml(ProjectBundle.message("label.text.libraries.are.missing", jars)));
updateAll();
myMissingLibrariesPanel.getPreferredSize();
myMainPanel.validate();
}
public LibraryCompositionSettings getLibraryCompositionSettings() {
return myLibraryCompositionSettings;
}
private void addMirrorsPanels() {
myMirrorsPanel.setLayout(new VerticalFlowLayout());
myMirrorPanelsList = new ArrayList<RemoteRepositoryMirrorPanel>();
Set<String> repositories = new HashSet<String>();
LibraryInfo[] libraryInfos = myLibraryCompositionSettings.getLibraryInfos();
for (LibraryInfo libraryInfo : libraryInfos) {
LibraryDownloadInfo downloadingInfo = libraryInfo.getDownloadingInfo();
if (downloadingInfo != null) {
RemoteRepositoryInfo repositoryInfo = downloadingInfo.getRemoteRepository();
if (repositoryInfo != null && repositories.add(repositoryInfo.getId())) {
RemoteRepositoryMirrorPanel mirrorPanel = new RemoteRepositoryMirrorPanel(repositoryInfo, myMirrorsMap);
myMirrorPanelsList.add(mirrorPanel);
myMirrorsPanel.add(mirrorPanel.getPanel());
}
}
}
}
private List<Library> calculateSuitableLibraries() {
LibraryInfo[] libraryInfos = myLibraryCompositionSettings.getLibraryInfos();
RequiredLibrariesInfo requiredLibraries = new RequiredLibrariesInfo(libraryInfos);
List<Library> suitableLibraries = new ArrayList<Library>();
Library[] libraries = myLibrariesContainer.getAllLibraries();
for (Library library : libraries) {
RequiredLibrariesInfo.RequiredClassesNotFoundInfo info =
requiredLibraries.checkLibraries(myLibrariesContainer.getLibraryFiles(library, OrderRootType.CLASSES));
if (info == null || info.getLibraryInfos().length < libraryInfos.length) {
suitableLibraries.add(library);
}
}
return suitableLibraries;
}
private void showLibrariesChooser() {
ChooseLibrariesDialog dialog = new ChooseLibrariesDialog(myMainPanel, mySuitableLibraries);
dialog.markElements(myUsedLibraries);
dialog.show();
if (dialog.isOK()) {
myUsedLibraries.clear();
myUsedLibraries.addAll(dialog.getMarkedLibraries());
updateAll();
}
}
private void showFileChooser() {
final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, false, true, false, false, true);
descriptor.setTitle(IdeBundle.message("file.chooser.select.paths.title"));
descriptor.setDescription(IdeBundle.message("file.chooser.multiselect.description"));
final VirtualFile[] files = FileChooser.chooseFiles(myAddJarsButton, descriptor, getBaseDirectory());
myAddedJars.addAll(Arrays.asList(files));
updateAll();
}
@Nullable
private VirtualFile getBaseDirectory() {
String path = myLibraryCompositionSettings.getBaseDirectoryForDownloadedFiles();
VirtualFile dir = LocalFileSystem.getInstance().findFileByPath(path);
if (dir == null) {
path = path.substring(0, path.lastIndexOf('/'));
dir = LocalFileSystem.getInstance().findFileByPath(path);
}
return dir;
}
private void updateAll() {
String missingJarsText = "";
List<VirtualFile> roots = new ArrayList<VirtualFile>();
roots.addAll(myAddedJars);
for (Library library : myUsedLibraries) {
roots.addAll(Arrays.asList(myLibrariesContainer.getLibraryFiles(library, OrderRootType.CLASSES)));
}
RequiredLibrariesInfo.RequiredClassesNotFoundInfo info = new RequiredLibrariesInfo(myLibraryCompositionSettings.getLibraryInfos()).checkLibraries(
roots.toArray(new VirtualFile[roots.size()]));
if (info != null) {
missingJarsText = ProjectBundle.message("label.text.libraries.are.missing", info.getMissingJarsText());
}
else {
missingJarsText = ProjectBundle.message("label.text.all.library.files.found");
}
myMissingLibrariesLabel.setText(UIUtil.toHtml(missingJarsText));
((CardLayout)myMissingLibrariesPanel.getLayout()).show(myMissingLibrariesPanel, "shown");
if (info == null) {
myDownloadMissingJarsCheckBox.setSelected(false);
}
myNewLibraryPanel.setVisible(info != null || !myAddedJars.isEmpty());
myLibraryPropertiesPanel.setVisible(!myAddedJars.isEmpty() || myDownloadMissingJarsCheckBox.isSelected());
myDownloadMissingJarsCheckBox.setEnabled(info != null);
myDirectoryField.setEnabled(myDownloadMissingJarsCheckBox.isSelected());
UIUtil.setEnabled(myMirrorsPanel, myDownloadMissingJarsCheckBox.isSelected(), true);
}
public void updateRepositoriesMirrors(final LibraryDownloadingMirrorsMap mirrorsMap) {
for (RemoteRepositoryMirrorPanel mirrorPanel : myMirrorPanelsList) {
mirrorPanel.updateComboBox(mirrorsMap);
}
}
public void saveSelectedRepositoriesMirrors(final LibraryDownloadingMirrorsMap mirrorsMap) {
for (RemoteRepositoryMirrorPanel mirrorPanel : myMirrorPanelsList) {
mirrorsMap.setMirror(mirrorPanel.getRemoteRepository(), mirrorPanel.getSelectedMirror());
}
}
public void apply() {
saveSelectedRepositoriesMirrors(myMirrorsMap);
if (myDownloadMissingJarsCheckBox.isSelected()) {
myLibraryCompositionSettings.setDownloadLibraries(true);
myLibraryCompositionSettings.setDirectoryForDownloadedLibrariesPath(FileUtil.toSystemIndependentName(myDirectoryField.getText()));
}
else {
myLibraryCompositionSettings.setDownloadLibraries(false);
}
myLibraryCompositionSettings.setUsedLibraries(myUsedLibraries);
myLibraryCompositionSettings.setAddedJars(myAddedJars);
myLibraryCompositionSettings.setLibraryLevel(myLibraryLevels.getKey((String)myLibraryLevelComboBox.getSelectedItem()));
myLibraryCompositionSettings.setLibraryName(myLibraryNameField.getText());
}
public JPanel getMainPanel() {
return myMainPanel;
}
}
| |
package fi.csc.chipster.sessiondb;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import fi.csc.chipster.auth.model.Role;
import fi.csc.chipster.comp.JobState;
import fi.csc.chipster.rest.Config;
import fi.csc.chipster.rest.RestUtils;
import fi.csc.chipster.rest.TestServerLauncher;
import fi.csc.chipster.sessiondb.model.Input;
import fi.csc.chipster.sessiondb.model.Job;
public class SessionJobResourceTest {
@SuppressWarnings("unused")
private final Logger logger = LogManager.getLogger();
private static TestServerLauncher launcher;
private static SessionDbClient user1Client;
private static SessionDbClient user2Client;
private static SessionDbClient compClient;
private static UUID sessionId1;
private static UUID sessionId2;
@BeforeClass
public static void setUp() throws Exception {
Config config = new Config();
launcher = new TestServerLauncher(config);
user1Client = new SessionDbClient(launcher.getServiceLocator(), launcher.getUser1Token(), Role.CLIENT);
user2Client = new SessionDbClient(launcher.getServiceLocator(), launcher.getUser2Token(), Role.CLIENT);
compClient = new SessionDbClient(launcher.getServiceLocator(), launcher.getCompToken(), Role.CLIENT);
sessionId1 = user1Client.createSession(RestUtils.getRandomSession());
sessionId2 = user2Client.createSession(RestUtils.getRandomSession());
}
@AfterClass
public static void tearDown() throws Exception {
launcher.stop();
}
@Test
public void post() throws RestException {
user1Client.createJob(sessionId1, RestUtils.getRandomJob());
}
public static void testCreateJob(int expected, UUID sessionId, Job job, SessionDbClient client) {
try {
client.createJob(sessionId, job);
assertEquals(true, false);
} catch (RestException e) {
assertEquals(expected, e.getResponse().getStatus());
}
}
@Test
public void postWithId() throws RestException {
Job job = RestUtils.getRandomJob();
job.setJobIdPair(sessionId1, RestUtils.createUUID());
user1Client.createJob(sessionId1, job);
}
@Test
public void postWrongUser() throws RestException {
Job job = RestUtils.getRandomJob();
job.setJobIdPair(sessionId2, RestUtils.createUUID());
testCreateJob(403, sessionId2, job, user1Client);
}
@Test
public void postWithWrongId() throws RestException {
Job job = RestUtils.getRandomJob();
job.setJobIdPair(sessionId2, RestUtils.createUUID());
testCreateJob(400, sessionId1, job, user1Client);
}
@Test
public void postWithSameJobId() throws RestException {
Job job1 = RestUtils.getRandomJob();
Job job2 = RestUtils.getRandomJob();
UUID jobId = RestUtils.createUUID();
job1.setJobIdPair(sessionId1, jobId);
job2.setJobIdPair(sessionId2, jobId);
String name1 = "name1";
String name2 = "name2";
job1.setToolId(name1);
job2.setToolId(name2);
user1Client.createJob(sessionId1, job1);
user2Client.createJob(sessionId2, job2);
// check that there are really to different jobs on the server
assertEquals(name1, user1Client.getJob(sessionId1, jobId).getToolId());
assertEquals(name2, user2Client.getJob(sessionId2, jobId).getToolId());
}
@Test
public void get() throws IOException, RestException {
UUID jobId = user1Client.createJob(sessionId1, RestUtils.getRandomJob());
assertEquals(true, user1Client.getJob(sessionId1, jobId) != null);
assertEquals(true, compClient.getJob(sessionId1, jobId) != null);
// wrong user
testGetJob(403, sessionId1, jobId, user2Client);
// wrong session
testGetJob(403, sessionId2, jobId, user1Client);
testGetJob(404, sessionId2, jobId, user2Client);
}
public static void testGetJob(int expected, UUID sessionId, UUID jobId, SessionDbClient client) {
try {
client.getJob(sessionId, jobId);
assertEquals(true, false);
} catch (RestException e) {
assertEquals(expected, e.getResponse().getStatus());
}
}
@Test
public void getAll() throws RestException {
UUID id1 = user1Client.createJob(sessionId1, RestUtils.getRandomJob());
UUID id2 = user1Client.createJob(sessionId1, RestUtils.getRandomJob());
assertEquals(true, user1Client.getJobs(sessionId1).containsKey(id1));
assertEquals(true, user1Client.getJobs(sessionId1).containsKey(id2));
// wrong user
testGetJobs(403, sessionId1, user2Client);
// wrong session
assertEquals(false, user2Client.getJobs(sessionId2).containsKey(id1));
}
public static void testGetJobs(int expected, UUID sessionId, SessionDbClient client) {
try {
client.getJobs(sessionId);
assertEquals(true, false);
} catch (RestException e) {
assertEquals(expected, e.getResponse().getStatus());
}
}
@Test
public void put() throws RestException {
Job job = RestUtils.getRandomJob();
UUID jobId = user1Client.createJob(sessionId1, job);
// client
job.setToolName("new name");
user1Client.updateJob(sessionId1, job);
assertEquals("new name", user1Client.getJob(sessionId1, jobId).getToolName());
// comp
job.setToolName("new name2");
user1Client.updateJob(sessionId1, job);
assertEquals("new name2", compClient.getJob(sessionId1, jobId).getToolName());
// wrong user
testUpdateJob(403, sessionId1, job, user2Client);
// wrong session
testUpdateJob(403, sessionId2, job, user1Client);
testUpdateJob(404, sessionId2, job, user2Client);
}
@Test
public void createJobWithInputs() throws RestException {
Job job = RestUtils.getRandomJob();
UUID datasetId = user1Client.createDataset(sessionId1, RestUtils.getRandomDataset());
ArrayList<Input> i = new ArrayList<>();
i.add(RestUtils.getRandomInput(datasetId));
job.setInputs(i);
UUID jobId = user1Client.createJob(sessionId1, job);
Assert.assertNotNull(jobId);
}
/**
* Creating a job isn't allowed if we don't have access rights to its inputs
*
* @throws RestException
*/
@Test
public void createJobWithWrongInputs() throws RestException {
Job job = RestUtils.getRandomJob();
UUID datasetId = user2Client.createDataset(sessionId2, RestUtils.getRandomDataset());
ArrayList<Input> i = new ArrayList<>();
i.add(RestUtils.getRandomInput(datasetId));
job.setInputs(i);
testCreateJob(403, sessionId1, job, user1Client);
}
/**
* Updating a job must be allowed (for example to cancel it) even if the inputs have been deleted
*
* @throws RestException
*/
@Test
public void updateJobWitMissingInputs() throws RestException {
Job job = RestUtils.getRandomJob();
UUID datasetId = user1Client.createDataset(sessionId1, RestUtils.getRandomDataset());
ArrayList<Input> i = new ArrayList<>();
i.add(RestUtils.getRandomInput(datasetId));
job.setInputs(i);
user1Client.createJob(sessionId1, job);
user1Client.deleteDataset(sessionId1, datasetId);
job.setState(JobState.CANCELLED);
user1Client.updateJob(sessionId1, job);
}
/**
* Updating a job isn't allowed if we don't have access rights to its inputs
*
* @throws RestException
*/
@Test
public void updateJobWithWrongInputs() throws RestException {
Job job = RestUtils.getRandomJob();
user1Client.createJob(sessionId1, job);
UUID datasetId = user2Client.createDataset(sessionId2, RestUtils.getRandomDataset());
ArrayList<Input> i = new ArrayList<>();
i.add(RestUtils.getRandomInput(datasetId));
job.setInputs(i);
testUpdateJob(403, sessionId1, job, user1Client);
}
public static void testUpdateJob(int expected, UUID sessionId, Job job, SessionDbClient client) {
try {
client.updateJob(sessionId, job);
assertEquals(true, false);
} catch (RestException e) {
assertEquals(expected, e.getResponse().getStatus());
}
}
@Test
public void delete() throws RestException, InterruptedException {
UUID jobId = user1Client.createJob(sessionId1, RestUtils.getRandomJob());
// wrong user
testDeleteJob(403, sessionId1, jobId, user2Client);
// wrong session
testDeleteJob(403, sessionId2, jobId, user1Client);
testDeleteJob(404, sessionId2, jobId, user2Client);
// wait a minute so that scheduler can process the job creation event
// otherwise it will complain in a log
Thread.sleep(500);
// delete
user1Client.deleteJob(sessionId1, jobId);
// doesn't exist anymore
testDeleteJob(404, sessionId1, jobId, user1Client);
}
public static void testDeleteJob(int expected, UUID sessionId, UUID jobId, SessionDbClient client) {
try {
client.deleteJob(sessionId, jobId);
assertEquals(true, false);
} catch (RestException e) {
assertEquals(expected, e.getResponse().getStatus());
}
}
}
| |
package com.iteye.weimingtom.fastfire.port.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import com.iteye.weimingtom.fastfire.port.window.FFFWindow;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Debug;
import android.os.Environment;
public class FFFResource {
public final static boolean USE_CACHE = true;
private final static String ZIP_FILENAME = "data.zip";
private final static String DATA_PATH = "data";
private final static String CGDATA_PATH = "cgdata";
private final static String RULE_PATH = "rule";
private String WORKPATH = "./";
private String ZIPFILE = WORKPATH + ZIP_FILENAME;
public Map<String, Bitmap> imageMap = new Hashtable<String, Bitmap>();
public Map<String, ByteBuffer> dataMap = new Hashtable<String, ByteBuffer>();
public Map<String, String> textMap = new HashMap<String, String>();
public Map<String, String> imagePathMap = new Hashtable<String, String>();
/**
* FIXME:create directory failed?
*/
public void init(FFFWindow win) {
FFFLog.trace("FFFResource::init()");
if (win != null) {
Context ctx = win.getContext();
if (ctx != null) {
String root = Environment.getExternalStorageDirectory() + "/Android/data/" + ctx.getPackageName();
File path = new File(root);
File pathData = new File(root + File.separator + DATA_PATH);
File pathCGData = new File(root + File.separator + CGDATA_PATH);
File pathRule = new File(root + File.separator + RULE_PATH);
File zipfile = new File(path, ZIP_FILENAME);
WORKPATH = path.getAbsolutePath();
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (mExternalStorageAvailable && mExternalStorageWriteable) {
path.mkdirs();
pathData.mkdirs();
pathCGData.mkdirs();
pathRule.mkdirs();
ZIPFILE = zipfile.getAbsolutePath();
} else {
ZIPFILE = null;
}
AssetManager am = ctx.getAssets();
if (am != null) {
InputStream inputStream = null;
BufferedInputStream istr = null;
OutputStream outputStream = null;
BufferedOutputStream ostr = null;
try {
ArrayList<String> fileAssets = new ArrayList<String>();
String[] filesRoot = am.list("");
if (false) {
FFFLog.trace("init start:" + filesRoot.length);
for (int i = 0; filesRoot != null && i < filesRoot.length; i++) {
FFFLog.trace("init start:" + filesRoot[i]);
if (filesRoot[i] != null && filesRoot[i].equals(ZIP_FILENAME)) {
fileAssets.add(ZIP_FILENAME);
}
}
} else {
fileAssets.add(ZIP_FILENAME);
}
{
String[] filesData = am.list(DATA_PATH);
for (int i = 0; filesData != null && i < filesData.length; i++) {
fileAssets.add(DATA_PATH + File.separator + filesData[i]);
}
}
{
String[] filesCGData = am.list(CGDATA_PATH);
for (int i = 0; filesCGData != null && i < filesCGData.length; i++) {
fileAssets.add(CGDATA_PATH + File.separator + filesCGData[i]);
}
}
{
String[] filesRule = am.list(RULE_PATH);
for (int i = 0; filesRule != null && i < filesRule.length; i++) {
fileAssets.add(RULE_PATH + File.separator + filesRule[i]);
}
}
for (int i = 0; i < fileAssets.size(); i++) {
FFFLog.trace("FFFResource::init() copying assets..." + fileAssets.get(i));
inputStream = am.open(fileAssets.get(i));
istr = new BufferedInputStream(inputStream);
outputStream = new FileOutputStream(WORKPATH + File.separator + fileAssets.get(i));
ostr = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[2048];
int size = 0;
while (true) {
size = istr.read(bytes);
if (size >= 0) {
ostr.write(bytes, 0, size);
ostr.flush();
} else {
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ostr != null) {
try {
ostr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (istr != null) {
try {
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
public void loadClassText(String name, Class<?> cls, String resName) {
String str = null;
InputStream input = cls.getResourceAsStream(resName);
if (input != null) {
try {
byte[] bytes = new byte[input.available()];
input.read(bytes);
str = new String(bytes, "UTF8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
textMap.put(name, str);
}
public void loadText(String name, String path) {
InputStream instr = null;
ZipFile zipFile = null;
try {
File file = new File(ZIPFILE);
if (file.exists() && file.canRead()) {
zipFile = new ZipFile(ZIPFILE);
ZipEntry entry = zipFile.getEntry(path);
if (entry != null) {
instr = zipFile.getInputStream(entry);
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
byte[] bytes = null;
bytes = new byte[instr.available()];
instr.read(bytes);
String str = new String(bytes, "UTF8");
textMap.put(name, str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (instr != null) {
try {
instr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void loadClassImage(String name, Class<?> cls) {
imageMap.put(name, BitmapFactory.decodeStream(cls.getResourceAsStream(name)));
}
public Bitmap loadImageNoCache(String name) {
String path = imagePathMap.get(name);
if (path != null) {
InputStream instr = null;
ZipFile zipFile = null;
try {
File file = new File(ZIPFILE);
if (file.exists() && file.canRead()) {
zipFile = new ZipFile(ZIPFILE);
ZipEntry entry = zipFile.getEntry(path);
if (entry != null) {
instr = zipFile.getInputStream(entry);
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
//imageMap.put(name, BitmapFactory.decodeStream(instr));
FFFLog.traceMemory("FFFResource.loadImage " + name);
return BitmapFactory.decodeStream(instr);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (instr != null) {
try {
instr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
public void loadImage(String name, String path) {
imagePathMap.put(name, path);
if (USE_CACHE) {
imageMap.put(name, loadImageNoCache(name));
}
}
public void loadClassData(String name, Class<?> cls) {
InputStream instr = cls.getResourceAsStream(name);
byte[] bytes = null;
try {
bytes = new byte[instr.available()];
instr.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
dataMap.put(name, ByteBuffer.wrap(bytes));
FFFLog.traceMemory("FFFResource.loadClassData " + name);
}
public void loadData(String name, String path) {
InputStream instr = null;
ZipFile zipFile = null;
try {
File file = new File(ZIPFILE);
if (file.exists() && file.canRead()) {
zipFile = new ZipFile(ZIPFILE);
ZipEntry entry = zipFile.getEntry(path);
if (entry != null) {
instr = zipFile.getInputStream(entry);
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
} else {
instr = new FileInputStream(WORKPATH + File.separator + path);
}
byte[] bytes = null;
try {
bytes = new byte[instr.available()];
instr.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
dataMap.put(name, ByteBuffer.wrap(bytes));
FFFLog.traceMemory("FFFResource.loadData " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (instr != null) {
try {
instr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void loadBytes(String name, ByteBuffer bytes) {
dataMap.put(name, bytes);
FFFLog.traceMemory("FFFResource.loadBytes " + name);
}
public void unloadAll() {
for (Map.Entry<String, Bitmap> entry : imageMap.entrySet()) {
if (entry != null && entry.getValue() != null && !entry.getValue().isRecycled()) {
entry.getValue().recycle();
FFFLog.traceMemory("unloadAll recycle " + entry.getKey());
} else {
FFFLog.traceMemory("unloadAll warning!!! " + entry.getKey());
}
}
imageMap.clear();
dataMap.clear();
textMap.clear();
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
/*
* Changes for SnappyData distributed computational and data platform.
*
* Portions Copyright (c) 2017-2019 TIBCO Software Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.sql.execute;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import com.gemstone.gemfire.cache.IsolationLevel;
import com.gemstone.gemfire.internal.cache.CachedDeserializableFactory;
import com.gemstone.gemfire.internal.cache.ExternalTableMetaData;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.TXManagerImpl;
import com.gemstone.gemfire.internal.cache.TXStateInterface;
import com.gemstone.gemfire.internal.cache.VMIdAdvisor;
import com.gemstone.gemfire.internal.shared.SystemProperties;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.engine.GemFireXDQueryObserver;
import com.pivotal.gemfirexd.internal.engine.GemFireXDQueryObserverHolder;
import com.pivotal.gemfirexd.internal.engine.access.GemFireTransaction;
import com.pivotal.gemfirexd.internal.engine.access.MemConglomerate;
import com.pivotal.gemfirexd.internal.engine.access.index.GfxdIndexManager;
import com.pivotal.gemfirexd.internal.engine.distributed.GfxdQueryResultCollector;
import com.pivotal.gemfirexd.internal.engine.distributed.GfxdQueryStreamingResultCollector;
import com.pivotal.gemfirexd.internal.engine.distributed.GfxdResultCollector;
import com.pivotal.gemfirexd.internal.engine.distributed.execution.LeadNodeExecutionObject;
import com.pivotal.gemfirexd.internal.engine.distributed.execution.SampleInsertExecutionObject;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.engine.sql.catalog.ExtraTableInfo;
import com.pivotal.gemfirexd.internal.engine.sql.conn.GfxdHeapThresholdListener;
import com.pivotal.gemfirexd.internal.engine.store.AbstractCompactExecRow;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.engine.store.GemFireStore;
import com.pivotal.gemfirexd.internal.engine.store.RowEncoder;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.reference.SQLState;
import com.pivotal.gemfirexd.internal.iapi.services.cache.ClassSize;
import com.pivotal.gemfirexd.internal.iapi.services.loader.GeneratedMethod;
import com.pivotal.gemfirexd.internal.iapi.sql.Activation;
import com.pivotal.gemfirexd.internal.iapi.sql.ParameterValueSet;
import com.pivotal.gemfirexd.internal.iapi.sql.ResultSet;
import com.pivotal.gemfirexd.internal.iapi.sql.conn.LanguageConnectionContext;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ColumnDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.NoPutResultSet;
import com.pivotal.gemfirexd.internal.iapi.store.raw.ContainerHandle;
import com.pivotal.gemfirexd.internal.iapi.types.DataTypeDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.impl.sql.execute.InsertConstantAction;
import com.pivotal.gemfirexd.internal.impl.sql.execute.ResultSetStatisticsVisitor;
import com.pivotal.gemfirexd.internal.impl.sql.execute.TriggerEvent;
import com.pivotal.gemfirexd.internal.impl.sql.execute.xplain.XPLAINUtil;
import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds;
import com.pivotal.gemfirexd.internal.shared.common.sanity.SanityManager;
/**
* An instance of this class is generated to inserts rows into the base table.
* No triggers or constraints are evaluated here.
*
* @author rdubey
* @author ymahajan
*/
public final class GemFireInsertResultSet extends AbstractGemFireResultSet {
private final NoPutResultSet sourceResultSet;
private final GeneratedMethod checkGM;
private final GemFireContainer gfContainer;
private final RowEncoder.PreProcessRow processor;
private final boolean hasSerialAEQorWAN;
private boolean isPreparedBatch;
private boolean isPutDML;
/**
* @return the isPreparedBatch
*/
public boolean isPreparedBatch() {
return isPreparedBatch;
}
private boolean batchLockTaken;
private ArrayList<Object> batchRows;
private long batchSize;
private final GfxdHeapThresholdListener thresholdListener;
private int rowCount;
private int numOpens;
private int[] autoGeneratedColumns;
private AutogenKeysResultSet autoGeneratedKeysResultSet;
private boolean hasDependentSampleTable;
private ArrayList<DataValueDescriptor []> batchRowsForByteStore;
public GemFireInsertResultSet(final NoPutResultSet source,
final GeneratedMethod checkGM, final Activation activation)
throws StandardException {
super(activation);
this.sourceResultSet = source;
this.checkGM = checkGM;
final InsertConstantAction constants = (InsertConstantAction)activation
.getConstantAction();
long heapConglom = constants.getConglomerateId();
final MemConglomerate conglom = this.tran
.findExistingConglomerate(heapConglom);
this.gfContainer = conglom.getGemFireContainer();
RowEncoder encoder = this.gfContainer.getRowEncoder();
this.processor = encoder != null
? encoder.getPreProcessorForRows(this.gfContainer) : null;
this.hasSerialAEQorWAN = this.gfContainer.getRegion().isSerialWanEnabled();
this.thresholdListener = Misc.getMemStore().thresholdListener();
this.isPutDML = activation.isPutDML();
final boolean isColumnTable = gfContainer.isRowBuffer();
final LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
if (isColumnTable && !Misc.routeQuery(lcc) && !lcc.isSnappyInternalConnection()) {
throw StandardException.newException(SQLState.SNAPPY_OP_DISALLOWED_ON_COLUMN_TABLES);
}
}
@Override
public void open() throws StandardException {
if (!this.isClosed) {
return;
}
this.hasDependentSampleTable = !this.lcc.isSnappyInternalConnection() &&
Misc.getMemStore().isSnappyStore() && this.gfContainer.hasDependentSampleTables();
final long beginTime = statisticsTimingOn ? XPLAINUtil
.recordTiming(openTime = -1) : 0;
long restOfOpenTime = 0;
final LocalRegion reg = this.gfContainer.getRegion();
final GfxdIndexManager sqim = (GfxdIndexManager)(reg != null ? reg
.getIndexUpdater() : null);
final LanguageConnectionContext lcc = this.activation
.getLanguageConnectionContext();
TXStateInterface tx = this.gfContainer.getActiveTXState(this.tran);
// TOOD: decide on autocommit or this flag: Discuss
if (tx == null && (this.gfContainer.isRowBuffer() || reg.getCache().snapshotEnabledForTest())) {
this.tran.getTransactionManager().begin(IsolationLevel.SNAPSHOT, null);
((GemFireTransaction)lcc.getTransactionExecute()).setActiveTXState(TXManagerImpl.getCurrentTXState(), false);
this.tran.setImplicitSnapshotTxStarted(true);
}
tx = this.gfContainer.getActiveTXState(this.tran);
if (sqim != null && !this.isPutDML) {
sqim.fireStatementTriggers(TriggerEvent.BEFORE_INSERT, lcc, this.tran, tx);
}
super.open();
if (beginTime != 0) {
nextTime = XPLAINUtil.nanoTime();
openTime = nextTime - beginTime;
}
ExecRow row;
boolean usingPutAll = this.isPreparedBatch;
if (usingPutAll) {
if (this.batchRows == null) {
this.batchRows = new ArrayList<Object>();
this.batchSize = 0;
if (this.hasDependentSampleTable && this.gfContainer.isByteArrayStore()) {
this.batchRowsForByteStore = new ArrayList<DataValueDescriptor[]>();
}
}
while ((row = this.sourceResultSet.getNextRowCore()) != null) {
// Evaluate any check constraints on the row
evaluateCheckConstraints();
// insert any auto-generated keys into the row holder
handleAutoGeneratedColumns(row);
// Get gemfire container and directly do an insert into the
// container.
handleBatchInserts(row);
}
}
else if (this.sourceResultSet.getEstimatedRowCount() > 1) {
handleMultipleInserts();
usingPutAll = true;
}
else {
while ((row = this.sourceResultSet.getNextRowCore()) != null) {
// Evaluate any check constraints on the row
evaluateCheckConstraints();
// insert any auto-generated keys into the row holder
handleAutoGeneratedColumns(row);
DataValueDescriptor[] rowArray = row.getRowArray();
if (this.processor != null) {
rowArray = this.processor.preProcess(rowArray);
}
this.gfContainer.insertRow(rowArray, this.tran, tx, lcc,
this.isPutDML);
this.rowCount++;
}
}
if (beginTime != 0) {
restOfOpenTime = XPLAINUtil.nanoTime();
nextTime = restOfOpenTime - nextTime;
}
// for tx inserts, the distribution will be done by handle* methods
// Suranjan: This needs to be avoided for Parallel DBSync or Parallel WAN
if (!usingPutAll && tx != null) {
if (this.hasSerialAEQorWAN) {
ParameterValueSet pvs = this.activation.getParameterValueSet();
this.activation.distributeBulkOpToDBSynchronizer(
this.gfContainer.getRegion(), pvs != null
&& pvs.getParameterCount() > 0, this.tran, lcc.isSkipListeners(),
null);
}
}
if (sqim != null && !this.isPutDML) {
sqim.fireStatementTriggers(TriggerEvent.AFTER_INSERT, lcc, this.tran, tx);
}
if (beginTime != 0) {
openTime += XPLAINUtil.recordTiming(restOfOpenTime);
}
}
private void handleBatchInserts(final ExecRow row) throws StandardException {
// if we reached the max batch size or eviction/criticalUp then flush
if (this.batchSize > GemFireXDUtils.DML_MAX_CHUNK_SIZE
|| (this.thresholdListener != null && (this.thresholdListener
.isEviction() || this.thresholdListener.isCritical()))) {
flushBatch();
}
this.batchSize += addRow(this.batchRows, row);
this.rowCount++;
}
private void handleMultipleInserts() throws StandardException {
ExecRow row;
ArrayList<Object> rows = new ArrayList<Object>();
final LanguageConnectionContext lcc = this.activation
.getLanguageConnectionContext();
final TXStateInterface tx = this.gfContainer.getActiveTXState(this.tran);
try {
while ((row = this.sourceResultSet.getNextRowCore()) != null) {
// Evaluate any check constraints on the row
evaluateCheckConstraints();
// insert any auto-generated keys into the row holder
handleAutoGeneratedColumns(row);
// if we reached the max batch size or eviction/criticalUp then flush
if ((this.batchSize > GemFireXDUtils.DML_MAX_CHUNK_SIZE
|| (this.thresholdListener != null && (this.thresholdListener
.isEviction() || this.thresholdListener.isCritical())))
&& rows.size() > 0) {
// now always publish this as a separate batch event to the queue
this.gfContainer.insertMultipleRows(rows, tx, lcc, false,
this.isPutDML);
if (this.hasSerialAEQorWAN) {
this.activation.distributeBulkOpToDBSynchronizer(
this.gfContainer.getRegion(), true, this.tran,
lcc.isSkipListeners(), rows);
}
rows.clear();
this.batchSize = 0;
}
this.batchSize += addRow(rows, row);
this.sourceResultSet.releasePreviousByteSource();
this.rowCount++;
}
} finally {
if (rows.size() > 0) {
// now always publish this as a separate batch event to the queue
this.gfContainer
.insertMultipleRows(rows, tx, lcc, false, this.isPutDML);
if (this.hasSerialAEQorWAN) {
this.activation.distributeBulkOpToDBSynchronizer(
this.gfContainer.getRegion(), true, this.tran,
lcc.isSkipListeners(), rows);
}
}
this.batchSize = 0;
}
}
private long addRow(final ArrayList<Object> rows, final ExecRow row)
throws StandardException {
// optimize for byte[] store
if (this.gfContainer.isByteArrayStore()) {
//Since we are obtaining raw row value, it is ok
// to release the offheap byte source
if (this.hasDependentSampleTable) {
this.batchRowsForByteStore.add(row.getRowArrayClone());
}
Object rawRow = row.getRawRowValue(false);
if (rawRow instanceof DataValueDescriptor[]) {
final DataValueDescriptor[] dvds = (DataValueDescriptor[])rawRow;
rawRow = this.gfContainer.getCurrentRowFormatter()
.generateRowData(dvds);
}
rows.add(rawRow);
return AbstractCompactExecRow.getRawRowSize(rawRow);
}
else {
DataValueDescriptor[] rowArray = row.getClone().getRowArray();
if (this.processor != null) {
rowArray = this.processor.preProcess(rowArray);
}
rows.add(rowArray);
return row.estimateRowSize();
}
}
@Override
public final void flushBatch() throws StandardException {
final ArrayList<Object> rows = this.batchRows;
if (rows != null && rows.size() > 0) {
final TXStateInterface tx = this.gfContainer.getActiveTXState(this.tran);
try {
final Activation act = this.activation;
// now always publish this as a separate batch event to the queue
this.gfContainer.insertMultipleRows(rows, tx,
act.getLanguageConnectionContext(), false, this.isPutDML);
if (act.isQueryCancelled()) {
act.checkCancellationFlag();
}
if (this.hasSerialAEQorWAN) {
act.distributeBulkOpToDBSynchronizer(this.gfContainer.getRegion(),
true, this.tran, lcc.isSkipListeners(), rows);
}
if (this.hasDependentSampleTable) {
ArrayList batchRows = null;
if (this.gfContainer.isByteArrayStore()) {
batchRows = this.batchRowsForByteStore;
} else {
batchRows = this.batchRows;
}
boolean enableStreaming = this.lcc.streamingEnabled();
SnappyUpdateDeletePutResultSet rs = new SnappyUpdateDeletePutResultSet(this.activation, false);
final GfxdResultCollector<Object> rc;
rc = new GfxdQueryResultCollector();
rs.setupRC(rc);
LeadNodeExecutionObject execObj = new SampleInsertExecutionObject(
this.gfContainer.getQualifiedTableName(), batchRows);
SnappyActivation.executeOnLeadNode(rs,rc, false, this.activation,
this.lcc, execObj);
}
} finally {
rows.clear();
if (this.hasDependentSampleTable && this.gfContainer.isByteArrayStore()) {
this.batchRowsForByteStore.clear();
}
this.batchSize = 0;
}
}
}
@Override
public final void closeBatch() throws StandardException {
assert this.isPreparedBatch;
//assert this.batchLockTaken;
releaseLocks();
if(this.tran != null) {
this.tran.release();
}
}
@Override
protected void openCore() throws StandardException {
// reset row count and batch size
this.rowCount = 0;
this.batchSize = 0;
if (this.numOpens++ == 0) {
this.sourceResultSet.openCore();
}
else {
this.sourceResultSet.reopenCore();
}
this.isPreparedBatch = this.activation.isPreparedBatch();
if (!this.isPreparedBatch || !this.batchLockTaken) {
takeLocks();
}
// open the row holder for generated keys
if (this.autoGeneratedKeysResultSet == null
&& this.activation.getAutoGeneratedKeysResultsetMode()) {
final ExtraTableInfo tableInfo = this.gfContainer.getExtraTableInfo();
int[] cols = this.activation.getAutoGeneratedKeysColumnIndexes();
String[] colNames = this.activation.getAutoGeneratedKeysColumnNames();
// check for any invalid column indexes/names provided by user
if (cols != null) {
for (int pos : cols) {
if (tableInfo.getAutoGeneratedColumn(pos) == null) {
throw StandardException.newException(
SQLState.LANG_INVALID_AUTOGEN_COLUMN_POSITION,
Integer.valueOf(pos), this.gfContainer.getQualifiedTableName());
}
}
}
else if (colNames != null) {
ColumnDescriptor cd;
cols = new int[colNames.length];
for (int index = 0; index < colNames.length; ++index) {
if ((cd = tableInfo.getAutoGeneratedColumn(colNames[index])) != null) {
cols[index] = cd.getPosition();
}
else {
throw StandardException.newException(
SQLState.LANG_INVALID_AUTOGEN_COLUMN_NAME, colNames[index],
this.gfContainer.getQualifiedTableName());
}
}
}
else {
// nothing provided by user so return all auto-gen columns
cols = tableInfo.getAutoGeneratedColumns();
}
if (cols != null && cols.length > 0) {
Arrays.sort(cols);
// set in activation to avoid dealing with names again
this.activation.setAutoGeneratedKeysResultsetInfo(cols, null);
this.autoGeneratedColumns = cols;
final Properties props = new Properties();
this.gfContainer.getContainerProperties(props);
this.autoGeneratedKeysResultSet = new AutogenKeysResultSet(
this.activation, cols, tableInfo);
}
}
}
/**
* Run the check constraints against the current row. Raise an error if a
* check constraint is violated.
*
* @exception StandardException
* thrown on error
*/
private void evaluateCheckConstraints() throws StandardException {
if (this.checkGM != null) {
// Evaluate the check constraints. The expression evaluation
// will throw an exception if there is a violation, so there
// is no need to check the result of the expression.
this.checkGM.invoke(this.activation);
}
}
@Override
public void finishResultSet(final boolean cleanupOnError) throws StandardException {
try {
if (this.sourceResultSet != null) {
this.sourceResultSet.close(cleanupOnError);
}
if (!this.isPreparedBatch) {
releaseLocks();
}
this.numOpens = 0;
} finally {
if(this.tran != null) {
this.tran.release();
}
}
}
private void takeLocks() throws StandardException {
this.gfContainer.open(this.tran, ContainerHandle.MODE_READONLY);
// also get the locks on the fk child tables
openOrCloseFKContainers(this.gfContainer, this.tran, false, true);
if (this.isPreparedBatch) {
this.batchLockTaken = true;
}
}
private void releaseLocks() throws StandardException {
// release the locks on the fk child tables
openOrCloseFKContainers(this.gfContainer, this.tran, true, true);
this.gfContainer.closeForEndTransaction(this.tran, true);
if (this.isPreparedBatch) {
this.batchLockTaken = false;
}
}
@Override
public int modifiedRowCount() {
return this.rowCount;
}
@Override
public boolean returnsRows() {
return false;
}
@Override
public void accept(ResultSetStatisticsVisitor visitor) {
visitor.setNumberOfChildren(0);
visitor.visit(this);
}
public DataValueDescriptor getNextUUIDValue(final int columnPosition)
throws StandardException {
final ExtraTableInfo tabInfo = this.gfContainer.getExtraTableInfo();
final ColumnDescriptor cd = tabInfo.getRowFormatter().getColumnDescriptor(
columnPosition - 1);
final DataTypeDescriptor dtd = cd.getType();
final DataValueDescriptor dvd = dtd.getNull();
final LanguageConnectionContext lcc = this.activation
.getLanguageConnectionContext();
// check if int or bigint
try {
final LocalRegion region = this.gfContainer.getRegion();
final long incStart = cd.getAutoincStart();
if (dtd.getTypeId().getTypeFormatId() == StoredFormatIds.LONGINT_TYPE_ID) {
long uuid = region.newUUID(true);
if (uuid < incStart) {
// need to reset the underlying VMId and local unique ID
uuid = region.resetUUID(incStart);
}
final GemFireXDQueryObserver observer = GemFireXDQueryObserverHolder
.getInstance();
if (observer != null) {
final int[] pkColumns = tabInfo.getPrimaryKeyColumns();
final boolean forRegionKey = (pkColumns != null
&& pkColumns.length > 0 && pkColumns[0] == columnPosition);
uuid = observer.overrideUniqueID(uuid, forRegionKey);
}
dvd.setValue(uuid);
lcc.setIdentityValue(uuid);
return dvd;
}
else {
int shortUUID = region.newShortUUID();
if (shortUUID < incStart) {
if (incStart < 0 || incStart > Integer.MAX_VALUE) {
SanityManager
.THROWASSERT("unexpected value for autoincrement start "
+ incStart + " column " + cd);
}
// need to reset the underlying VMId and local unique ID
shortUUID = region
.resetShortUUID((int)(incStart & VMIdAdvisor.UINT_MASK));
}
dvd.setValue(shortUUID);
lcc.setIdentityValue(shortUUID);
return dvd;
}
} catch (IllegalStateException ise) { // check for overflow
throw StandardException.newException(SQLState.LANG_AI_OVERFLOW, ise,
this.gfContainer.getQualifiedTableName(), cd.getColumnName());
}
}
public DataValueDescriptor getMaxIdentityValue(final int columnPosition)
throws StandardException {
final ColumnDescriptor cd = this.gfContainer.getCurrentRowFormatter()
.getColumnDescriptor(columnPosition - 1);
final DataTypeDescriptor dtd = cd.getType();
final DataValueDescriptor dvd = dtd.getNull();
GemFireStore store = Misc.getMemStore();
LocalRegion identityRgn = store.getIdentityRegion();
assert identityRgn != null;
final String key = this.gfContainer.getUUID();
// we don't want to lock out a new generator node (when current one fails)
// in retrieval and put else it can cause a deadlock (new generator node
// waiting on this node to initialize, and this node sends the generation
// message to the new generator node itself which will keep waiting for it
// to initialize)
final long increment = cd.getAutoincInc();
long result;
while (true) {
IdentityValueManager.GetIdentityValueMessage msg =
new IdentityValueManager.GetIdentityValueMessage(identityRgn, key,
cd.getAutoincStart(), increment, getLanguageConnectionContext());
final Object res;
try {
res = msg.executeFunction();
} catch (SQLException sqle) {
throw Misc.wrapSQLException(sqle, sqle);
}
assert res != null: "Expected one result for targeted function "
+ "execution of GetIdentityValueMessage";
result = ((Long)res).longValue();
// now record the generated value checking if any new generator node has
// read the value in the meantime
if (IdentityValueManager.getInstance().setGeneratedValue(key, result,
increment, msg.getTarget())) {
break;
}
}
if (dtd.getTypeId().getTypeFormatId() == StoredFormatIds.LONGINT_TYPE_ID) {
dvd.setValue(result);
lcc.setIdentityValue(result);
return dvd;
}
else {
// check for overflow
if (result >= Integer.MIN_VALUE && result <= Integer.MAX_VALUE) {
dvd.setValue((int)result);
lcc.setIdentityValue((int)result);
return dvd;
}
else {
throw StandardException.newException(SQLState.LANG_AI_OVERFLOW,
this.gfContainer.getQualifiedTableName(), cd.getColumnName());
}
}
}
@Override
public ResultSet getAutoGeneratedKeysResultset() {
// the value in LCC must also have been set for clients to work correctly
if (SanityManager.DEBUG) {
if (this.autoGeneratedKeysResultSet != null) {
SanityManager.ASSERT(this.activation.getLanguageConnectionContext()
.getIdentityVal() != 0);
}
}
return this.autoGeneratedKeysResultSet;
}
/**
* @see ResultSet#hasAutoGeneratedKeysResultSet
*/
@Override
public boolean hasAutoGeneratedKeysResultSet() {
return (this.autoGeneratedKeysResultSet != null);
}
private void handleAutoGeneratedColumns(final ExecRow row)
throws StandardException {
// insert any auto-generated keys into the row holder
if (this.autoGeneratedKeysResultSet != null) {
this.autoGeneratedKeysResultSet.insertRow(row, this.autoGeneratedColumns);
}
}
@Override
public long estimateMemoryUsage() throws StandardException {
long memory = 0L;
if (this.autoGeneratedKeysResultSet != null) {
memory += this.autoGeneratedColumns.length * 4
+ ClassSize.estimateArrayOverhead();
memory += this.autoGeneratedKeysResultSet.estimateMemoryUsage();
}
if (this.batchRows != null) {
memory += ClassSize.estimateArrayOverhead();
for (Object row : this.batchRows) {
if (row instanceof DataValueDescriptor[]) {
memory += ClassSize.estimateArrayOverhead();
for (DataValueDescriptor dvd : (DataValueDescriptor[])row) {
memory += dvd.estimateMemoryUsage();
}
}
else {
memory += CachedDeserializableFactory.calcMemSize(row);
}
}
}
return memory;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.tribes.transport.nio;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.catalina.tribes.Channel;
import org.apache.catalina.tribes.ChannelException;
import org.apache.catalina.tribes.ChannelMessage;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.UniqueId;
import org.apache.catalina.tribes.io.ChannelData;
import org.apache.catalina.tribes.io.XByteBuffer;
import org.apache.catalina.tribes.transport.AbstractSender;
import org.apache.catalina.tribes.transport.MultiPointSender;
import org.apache.catalina.tribes.transport.SenderState;
import org.apache.catalina.tribes.util.Logs;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class ParallelNioSender extends AbstractSender implements MultiPointSender {
private static final Log log = LogFactory.getLog(ParallelNioSender.class);
protected final long selectTimeout = 5000; //default 5 seconds, same as send timeout
protected final Selector selector;
protected final HashMap<Member, NioSender> nioSenders = new HashMap<>();
public ParallelNioSender() throws IOException {
synchronized (Selector.class) {
// Selector.open() isn't thread safe
// http://bugs.sun.com/view_bug.do?bug_id=6427854
// Affects 1.6.0_29, fixed in 1.7.0_01
selector = Selector.open();
}
setConnected(true);
}
@Override
public synchronized void sendMessage(Member[] destination, ChannelMessage msg)
throws ChannelException {
long start = System.currentTimeMillis();
this.setUdpBased((msg.getOptions()&Channel.SEND_OPTIONS_UDP) == Channel.SEND_OPTIONS_UDP);
byte[] data = XByteBuffer.createDataPackage((ChannelData)msg);
NioSender[] senders = setupForSend(destination);
connect(senders);
setData(senders,data);
int remaining = senders.length;
ChannelException cx = null;
try {
//loop until complete, an error happens, or we timeout
long delta = System.currentTimeMillis() - start;
boolean waitForAck = (Channel.SEND_OPTIONS_USE_ACK &
msg.getOptions()) == Channel.SEND_OPTIONS_USE_ACK;
while ( (remaining>0) && (delta<getTimeout()) ) {
try {
remaining -= doLoop(selectTimeout, getMaxRetryAttempts(),waitForAck,msg);
} catch (Exception x ) {
if (log.isTraceEnabled()) log.trace("Error sending message", x);
int faulty = (cx == null)?0:cx.getFaultyMembers().length;
if ( cx == null ) {
if ( x instanceof ChannelException ) cx = (ChannelException)x;
else cx = new ChannelException("Parallel NIO send failed.", x);
} else {
if (x instanceof ChannelException) {
cx.addFaultyMember(((ChannelException) x).getFaultyMembers());
}
}
//count down the remaining on an error
if (faulty < cx.getFaultyMembers().length) {
remaining -= (cx.getFaultyMembers().length - faulty);
}
}
//bail out if all remaining senders are failing
if ( cx != null && cx.getFaultyMembers().length == remaining ) throw cx;
delta = System.currentTimeMillis() - start;
}
if ( remaining > 0 ) {
//timeout has occurred
ChannelException cxtimeout = new ChannelException(
"Operation has timed out(" + getTimeout() + " ms.).");
if ( cx==null ) cx = new ChannelException(
"Operation has timed out(" + getTimeout() + " ms.).");
for (int i=0; i<senders.length; i++ ) {
if (!senders[i].isComplete()) {
cx.addFaultyMember(senders[i].getDestination(),cxtimeout);
}
}
throw cx;
} else if ( cx != null ) {
//there was an error
throw cx;
}
} catch (Exception x ) {
try { this.disconnect(); } catch (Exception e) {/*Ignore*/}
if ( x instanceof ChannelException ) throw (ChannelException)x;
else throw new ChannelException(x);
}
}
private int doLoop(long selectTimeOut, int maxAttempts, boolean waitForAck, ChannelMessage msg)
throws IOException, ChannelException {
int completed = 0;
int selectedKeys = selector.select(selectTimeOut);
if (selectedKeys == 0) {
return 0;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = it.next();
it.remove();
int readyOps = sk.readyOps();
sk.interestOps(sk.interestOps() & ~readyOps);
NioSender sender = (NioSender) sk.attachment();
try {
if (sender.process(sk,waitForAck)) {
completed++;
sender.setComplete(true);
if ( Logs.MESSAGES.isTraceEnabled() ) {
Logs.MESSAGES.trace("ParallelNioSender - Sent msg:" +
new UniqueId(msg.getUniqueId()) + " at " +
new java.sql.Timestamp(System.currentTimeMillis()) + " to " +
sender.getDestination().getName());
}
SenderState.getSenderState(sender.getDestination()).setReady();
}//end if
} catch (Exception x) {
if (log.isTraceEnabled()) {
log.trace("Error while processing send to " + sender.getDestination().getName(),
x);
}
SenderState state = SenderState.getSenderState(sender.getDestination());
int attempt = sender.getAttempt()+1;
boolean retry = (sender.getAttempt() <= maxAttempts && maxAttempts>0);
synchronized (state) {
//sk.cancel();
if (state.isSuspect()) state.setFailing();
if (state.isReady()) {
state.setSuspect();
if ( retry )
log.warn("Member send is failing for:" +
sender.getDestination().getName() +
" ; Setting to suspect and retrying.");
else
log.warn("Member send is failing for:" +
sender.getDestination().getName() +
" ; Setting to suspect.", x);
}
}
if ( !isConnected() ) {
log.warn("Not retrying send for:" + sender.getDestination().getName() +
"; Sender is disconnected.");
ChannelException cx = new ChannelException(
"Send failed, and sender is disconnected. Not retrying.", x);
cx.addFaultyMember(sender.getDestination(),x);
throw cx;
}
byte[] data = sender.getMessage();
if ( retry ) {
try {
sender.disconnect();
sender.connect();
sender.setAttempt(attempt);
sender.setMessage(data);
}catch ( Exception ignore){
state.setFailing();
}
} else {
ChannelException cx = new ChannelException(
"Send failed, attempt:" + sender.getAttempt() + " max:" + maxAttempts,
x);
cx.addFaultyMember(sender.getDestination(),x);
throw cx;
}//end if
}
}
return completed;
}
private void connect(NioSender[] senders) throws ChannelException {
ChannelException x = null;
for (int i=0; i<senders.length; i++ ) {
try {
senders[i].connect();
}catch ( IOException io ) {
if ( x==null ) x = new ChannelException(io);
x.addFaultyMember(senders[i].getDestination(),io);
}
}
if ( x != null ) throw x;
}
private void setData(NioSender[] senders, byte[] data) throws ChannelException {
ChannelException x = null;
for (int i=0; i<senders.length; i++ ) {
try {
senders[i].setMessage(data);
}catch ( IOException io ) {
if ( x==null ) x = new ChannelException(io);
x.addFaultyMember(senders[i].getDestination(),io);
}
}
if ( x != null ) throw x;
}
private NioSender[] setupForSend(Member[] destination) throws ChannelException {
ChannelException cx = null;
NioSender[] result = new NioSender[destination.length];
for ( int i=0; i<destination.length; i++ ) {
NioSender sender = nioSenders.get(destination[i]);
try {
if (sender == null) {
sender = new NioSender();
AbstractSender.transferProperties(this, sender);
nioSenders.put(destination[i], sender);
}
sender.reset();
sender.setDestination(destination[i]);
sender.setSelector(selector);
sender.setUdpBased(isUdpBased());
result[i] = sender;
}catch ( UnknownHostException x ) {
if (cx == null) cx = new ChannelException("Unable to setup NioSender.", x);
cx.addFaultyMember(destination[i], x);
}
}
if ( cx != null ) throw cx;
else return result;
}
@Override
public void connect() {
//do nothing, we connect on demand
setConnected(true);
}
private synchronized void close() throws ChannelException {
ChannelException x = null;
Object[] members = nioSenders.keySet().toArray();
for (int i=0; i<members.length; i++ ) {
Member mbr = (Member)members[i];
try {
NioSender sender = nioSenders.get(mbr);
sender.disconnect();
}catch ( Exception e ) {
if ( x == null ) x = new ChannelException(e);
x.addFaultyMember(mbr,e);
}
nioSenders.remove(mbr);
}
if ( x != null ) throw x;
}
@Override
public void add(Member member) {
// NOOP
}
@Override
public void remove(Member member) {
//disconnect senders
NioSender sender = nioSenders.remove(member);
if ( sender != null ) sender.disconnect();
}
@Override
public synchronized void disconnect() {
setConnected(false);
try {close(); }catch (Exception x){/*Ignore*/}
}
@Override
public void finalize() {
try {disconnect(); }catch ( Exception e){/*Ignore*/}
try {
selector.close();
}catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Failed to close selector", e);
}
}
}
@Override
public boolean keepalive() {
boolean result = false;
for (Iterator<Entry<Member,NioSender>> i = nioSenders.entrySet().iterator(); i.hasNext();) {
Map.Entry<Member, NioSender> entry = i.next();
NioSender sender = entry.getValue();
if ( sender.keepalive() ) {
//nioSenders.remove(entry.getKey());
i.remove();
result = true;
} else {
try {
sender.read();
}catch ( IOException x ) {
sender.disconnect();
sender.reset();
//nioSenders.remove(entry.getKey());
i.remove();
result = true;
}catch ( Exception x ) {
log.warn("Error during keepalive test for sender:"+sender,x);
}
}
}
//clean up any cancelled keys
if ( result ) try { selector.selectNow(); }catch (Exception e){/*Ignore*/}
return result;
}
}
| |
package com.thayer.idsservice.ids.expedia.beans;
import java.util.ArrayList;
public class ExpediaResv {
private ArrayList remarkLst = null;
private String mailRates = "";
private String title = "";
private String channelDesc = "";
private String dateBooked = "";
private String propId = "";
private String propName = "";
private String cnfNum = "";
private String cxlNum = "";
private String status = "";
private String firstName = "";
private String lastName = "";
private String guestAddressLine1 = "";
private String guestPhone = "";
private String guestEmail = "";
private String iata = "";
private String iataName = "";
private String iataPhone = "";
private String iataEmail = "";
private String remarks = "";
private String inDate = "";
private String outDate = "";
private String nights = "";
private String rooms = "";
private String roomtype = "";
private String paln = "";
private String adults = "";
private String children = "";
private String guaRule = "";
private String cxlRule = "";
private String gds = "";
private String ccType = "";
private String ccName = "";
private String ccNumber = "";
private String ccExpiration = "";
private String totalRevenue = "";
private String bookedRates = "";
private String modHist = "";
private String guestCity = "";
private String guestCountry = "";
private String amountTax = "";
private String amountSerFee = "";
public String getAmountSerFee() {
return amountSerFee;
}
public void setAmountSerFee(String amountSerFee) {
this.amountSerFee = amountSerFee;
}
public String getAmountTax() {
return amountTax;
}
public void setAmountTax(String amountTax) {
this.amountTax = amountTax;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAdults() {
return adults;
}
public void setAdults(String adults) {
this.adults = adults;
}
public String getBookedRates() {
return bookedRates;
}
public void setBookedRates(String bookedRates) {
this.bookedRates = bookedRates;
}
public String getCcExpiration() {
return ccExpiration;
}
public void setCcExpiration(String ccExpiration) {
this.ccExpiration = ccExpiration;
}
public String getCcName() {
return ccName;
}
public void setCcName(String ccName) {
this.ccName = ccName;
}
public String getCcNumber() {
return ccNumber;
}
public void setCcNumber(String ccNumber) {
this.ccNumber = ccNumber;
}
public String getCcType() {
return ccType;
}
public void setCcType(String ccType) {
this.ccType = ccType;
}
public String getChannelDesc() {
return channelDesc;
}
public void setChannelDesc(String channelDesc) {
this.channelDesc = channelDesc;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getCnfNum() {
return cnfNum;
}
public void setCnfNum(String cnfNum) {
this.cnfNum = cnfNum;
}
public String getCxlNum() {
return cxlNum;
}
public void setCxlNum(String cxlNum) {
this.cxlNum = cxlNum;
}
public String getCxlRule() {
return cxlRule;
}
public void setCxlRule(String cxlRule) {
this.cxlRule = cxlRule;
}
public String getDateBooked() {
return dateBooked;
}
public void setDateBooked(String dateBooked) {
this.dateBooked = dateBooked;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGds() {
return gds;
}
public void setGds(String gds) {
this.gds = gds;
}
public String getGuaRule() {
return guaRule;
}
public void setGuaRule(String guaRule) {
this.guaRule = guaRule;
}
public String getGuestAddressLine1() {
return guestAddressLine1;
}
public void setGuestAddressLine1(String guestAddressLine1) {
this.guestAddressLine1 = guestAddressLine1;
}
public String getGuestEmail() {
return guestEmail;
}
public void setGuestEmail(String guestEmail) {
this.guestEmail = guestEmail;
}
public String getGuestPhone() {
return guestPhone;
}
public void setGuestPhone(String guestPhone) {
this.guestPhone = guestPhone;
}
public String getIata() {
return iata;
}
public void setIata(String iata) {
this.iata = iata;
}
public String getIataEmail() {
return iataEmail;
}
public void setIataEmail(String iataEmail) {
this.iataEmail = iataEmail;
}
public String getIataName() {
return iataName;
}
public void setIataName(String iataName) {
this.iataName = iataName;
}
public String getIataPhone() {
return iataPhone;
}
public void setIataPhone(String iataPhone) {
this.iataPhone = iataPhone;
}
public String getInDate() {
return inDate;
}
public void setInDate(String inDate) {
this.inDate = inDate;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getModHist() {
return modHist;
}
public void setModHist(String modHist) {
this.modHist = modHist;
}
public String getNights() {
return nights;
}
public void setNights(String nights) {
this.nights = nights;
}
public String getOutDate() {
return outDate;
}
public void setOutDate(String outDate) {
this.outDate = outDate;
}
public String getPaln() {
return paln;
}
public void setPaln(String paln) {
this.paln = paln;
}
public String getPropId() {
return propId;
}
public void setPropId(String propId) {
this.propId = propId;
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRooms() {
return rooms;
}
public void setRooms(String rooms) {
this.rooms = rooms;
}
public String getRoomtype() {
return roomtype;
}
public void setRoomtype(String roomtype) {
this.roomtype = roomtype;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTotalRevenue() {
return totalRevenue;
}
public void setTotalRevenue(String totalRevenue) {
this.totalRevenue = totalRevenue;
}
public String getGuestCity() {
return guestCity;
}
public void setGuestCity(String guestCity) {
this.guestCity = guestCity;
}
public String getGuestCountry() {
return guestCountry;
}
public void setGuestCountry(String guestCountry) {
this.guestCountry = guestCountry;
}
public ArrayList getRemarkLst() {
return remarkLst;
}
public void setRemarkLst(ArrayList remarkLst) {
this.remarkLst = remarkLst;
}
public String getMailRates() {
return mailRates;
}
public void setMailRates(String mailRates) {
this.mailRates = mailRates;
}
}
| |
/*
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.numeric;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.ConstantExpressionUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
public class ConstantMathCallInspection extends BaseInspection {
@SuppressWarnings("StaticCollection")
@NonNls static final Set<String> constantMathCall =
new HashSet<String>(23);
static {
constantMathCall.add("abs");
constantMathCall.add("acos");
constantMathCall.add("asin");
constantMathCall.add("atan");
constantMathCall.add("cbrt");
constantMathCall.add("ceil");
constantMathCall.add("cos");
constantMathCall.add("cosh");
constantMathCall.add("exp");
constantMathCall.add("expm1");
constantMathCall.add("floor");
constantMathCall.add("log");
constantMathCall.add("log10");
constantMathCall.add("log1p");
constantMathCall.add("rint");
constantMathCall.add("round");
constantMathCall.add("sin");
constantMathCall.add("sinh");
constantMathCall.add("sqrt");
constantMathCall.add("tan");
constantMathCall.add("tanh");
constantMathCall.add("toDegrees");
constantMathCall.add("toRadians");
}
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"constant.math.call.display.name");
}
@Override
@NotNull
public String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"constant.math.call.problem.descriptor");
}
@Override
public InspectionGadgetsFix buildFix(Object... infos) {
return new MakeStrictFix();
}
private static class MakeStrictFix extends InspectionGadgetsFix {
@Override
@NotNull
public String getName() {
return InspectionGadgetsBundle.message(
"constant.conditional.expression.simplify.quickfix");
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor)
throws IncorrectOperationException {
final PsiIdentifier nameIdentifier =
(PsiIdentifier)descriptor.getPsiElement();
final PsiReferenceExpression reference =
(PsiReferenceExpression)nameIdentifier.getParent();
assert reference != null;
final PsiMethodCallExpression call =
(PsiMethodCallExpression)reference.getParent();
assert call != null;
final PsiExpressionList argumentList = call.getArgumentList();
final PsiExpression[] arguments = argumentList.getExpressions();
final String methodName = reference.getReferenceName();
final PsiExpression argument = arguments[0];
final PsiMethod method = call.resolveMethod();
if (method == null) {
return;
}
final PsiParameterList parameterList = method.getParameterList();
final PsiParameter[] parameters = parameterList.getParameters();
if (parameters.length != 1) {
return;
}
final PsiType type = parameters[0].getType();
final Object argumentValue =
ConstantExpressionUtil.computeCastTo(argument, type);
final String newExpression;
if (argumentValue instanceof Float ||
argumentValue instanceof Double) {
final Number number = (Number)argumentValue;
newExpression = createValueString(methodName,
number.doubleValue());
}
else {
final Number number = (Number)argumentValue;
newExpression = createValueString(methodName,
number.longValue());
}
if (newExpression == null) {
return;
}
if (PsiType.LONG.equals(type)) {
replaceExpressionAndShorten(call, newExpression + 'L');
}
else {
replaceExpressionAndShorten(call, newExpression);
}
}
}
@SuppressWarnings({"NestedMethodCall", "FloatingPointEquality"})
@Nullable
@NonNls
static String createValueString(@NonNls String name, double value) {
if ("abs".equals(name)) {
return Double.toString(Math.abs(value));
}
else if ("floor".equals(name)) {
return Double.toString(Math.floor(value));
}
else if ("ceil".equals(name)) {
return Double.toString(Math.ceil(value));
}
else if ("toDegrees".equals(name)) {
return Double.toString(Math.toDegrees(value));
}
else if ("toRadians".equals(name)) {
return Double.toString(Math.toRadians(value));
}
else if ("sqrt".equals(name)) {
return Double.toString(Math.sqrt(value));
}
else if ("cbrt".equals(name)) {
return Double.toString(Math.pow(value, 1.0 / 3.0));
}
else if ("round".equals(name)) {
return Long.toString(Math.round(value));
}
else if ("rint".equals(name)) {
return Double.toString(Math.rint(value));
}
else if ("log".equals(name)) {
if (value == 1.0) {
return "0.0";
}
else {
return null;
}
}
else if ("log10".equals(name)) {
if (value == 1.0) {
return "0.0";
}
else {
return null;
}
}
else if ("log1p".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
else if ("exp".equals(name)) {
if (value == 0.0) {
return "1.0";
}
else if (value == 1.0) {
return "Math.E";
}
else {
return null;
}
}
else if ("expm1".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
else if ("cos".equals(name) || "cosh".equals(name)) {
if (value == 0.0) {
return "1.0";
}
else {
return null;
}
}
else if ("acos".equals(name)) {
if (value == 1.0) {
return "0.0";
}
else if (value == 0.0) {
return "(Math.PI/2.0)";
}
else {
return null;
}
}
else if ("acosh".equals(name)) {
if (value == 1.0) {
return "0.0";
}
else {
return null;
}
}
else if ("sin".equals(name) || "sinh".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
else if ("asin".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else if (value == 1.0) {
return "(Math.PI/2.0)";
}
else {
return null;
}
}
else if ("asinh".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
else if ("tan".equals(name) || "tanh".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
else if ("atan".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else if (value == 1.0) {
return "(Math.PI/4.0)";
}
else {
return null;
}
}
else if ("atanh".equals(name)) {
if (value == 0.0) {
return "0.0";
}
else {
return null;
}
}
return null;
}
@Nullable
@NonNls
static String createValueString(@NonNls String name, long value) {
if ("abs".equals(name)) {
return Long.toString(Math.abs(value));
}
return null;
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new ConstantMathCallVisitor();
}
private static class ConstantMathCallVisitor extends BaseInspectionVisitor {
@Override
public void visitMethodCallExpression(
@NotNull PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
final PsiReferenceExpression methodExpression =
expression.getMethodExpression();
final String methodName = methodExpression.getReferenceName();
if (!constantMathCall.contains(methodName)) {
return;
}
final PsiExpressionList argumentList = expression.getArgumentList();
final PsiExpression[] arguments = argumentList.getExpressions();
if (arguments.length == 0) {
return;
}
final PsiExpression argument = arguments[0];
final Object argumentValue =
ConstantExpressionUtil.computeCastTo(argument, PsiType.DOUBLE);
if (!(argumentValue instanceof Double)) {
return;
}
final double doubleValue = ((Double)argumentValue).doubleValue();
final String valueString = createValueString(methodName,
doubleValue);
if (valueString == null) {
return;
}
final PsiMethod method = expression.resolveMethod();
if (method == null) {
return;
}
final PsiClass referencedClass = method.getContainingClass();
if (referencedClass == null) {
return;
}
final String className = referencedClass.getQualifiedName();
if (!"java.lang.Math".equals(className)
&& !"java.lang.StrictMath".equals(className)) {
return;
}
registerMethodCallError(expression);
}
}
}
| |
/*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.lldp.impl;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.Ethernet;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cluster.ClusterMetadataService;
import org.onosproject.cluster.ClusterService;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.mastership.MastershipEvent;
import org.onosproject.mastership.MastershipListener;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.LinkKey;
import org.onosproject.net.Port;
import org.onosproject.net.config.ConfigFactory;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistry;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceEvent.Type;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkService;
import org.onosproject.net.link.ProbedLinkProvider;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.provider.lldpcommon.LinkDiscovery;
import org.onosproject.provider.lldpcommon.LinkDiscoveryContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.onlab.packet.Ethernet.TYPE_BSN;
import static org.onlab.packet.Ethernet.TYPE_LLDP;
import static org.onlab.util.Tools.get;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Link.Type.DIRECT;
import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
import static org.onosproject.net.config.basics.SubjectFactories.CONNECT_POINT_SUBJECT_FACTORY;
import static org.onosproject.net.config.basics.SubjectFactories.DEVICE_SUBJECT_FACTORY;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider which uses LLDP and BDDP packets to detect network infrastructure links.
*/
@Component(immediate = true)
public class LldpLinkProvider extends AbstractProvider implements ProbedLinkProvider {
private static final String PROVIDER_NAME = "org.onosproject.provider.lldp";
private static final String FORMAT =
"Settings: enabled={}, useBDDP={}, probeRate={}, " +
"staleLinkAge={}";
// When a Device/Port has this annotation, do not send out LLDP/BDDP
public static final String NO_LLDP = "no-lldp";
private static final int MAX_RETRIES = 5;
private static final int RETRY_DELAY = 1_000; // millis
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LinkProviderRegistry providerRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LinkService linkService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected PacketService packetService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected MastershipService masterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ComponentConfigService cfgService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigRegistry cfgRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterMetadataService clusterMetadataService;
private LinkProviderService providerService;
private ScheduledExecutorService executor;
protected ExecutorService eventExecutor;
private boolean shuttingDown = false;
// TODO: Add sanity checking for the configurable params based on the delays
private static final long DEVICE_SYNC_DELAY = 5;
private static final long LINK_PRUNER_DELAY = 3;
private static final String PROP_ENABLED = "enabled";
@Property(name = PROP_ENABLED, boolValue = true,
label = "If false, link discovery is disabled")
private boolean enabled = false;
private static final String PROP_USE_BDDP = "useBDDP";
@Property(name = PROP_USE_BDDP, boolValue = true,
label = "Use BDDP for link discovery")
private boolean useBddp = true;
private static final String PROP_PROBE_RATE = "probeRate";
private static final int DEFAULT_PROBE_RATE = 3000;
@Property(name = PROP_PROBE_RATE, intValue = DEFAULT_PROBE_RATE,
label = "LLDP and BDDP probe rate specified in millis")
private int probeRate = DEFAULT_PROBE_RATE;
private static final String PROP_STALE_LINK_AGE = "staleLinkAge";
private static final int DEFAULT_STALE_LINK_AGE = 10000;
@Property(name = PROP_STALE_LINK_AGE, intValue = DEFAULT_STALE_LINK_AGE,
label = "Number of millis beyond which links will be considered stale")
private int staleLinkAge = DEFAULT_STALE_LINK_AGE;
private final LinkDiscoveryContext context = new InternalDiscoveryContext();
private final InternalRoleListener roleListener = new InternalRoleListener();
private final InternalDeviceListener deviceListener = new InternalDeviceListener();
private final InternalPacketProcessor packetProcessor = new InternalPacketProcessor();
// Device link discovery helpers.
protected final Map<DeviceId, LinkDiscovery> discoverers = new ConcurrentHashMap<>();
// Most recent time a tracked link was seen; links are tracked if their
// destination connection point is mastered by this controller instance.
private final Map<LinkKey, Long> linkTimes = Maps.newConcurrentMap();
private ApplicationId appId;
static final SuppressionRules DEFAULT_RULES
= new SuppressionRules(EnumSet.of(Device.Type.ROADM, Device.Type.FIBER_SWITCH, Device.Type.OTN),
ImmutableMap.of(NO_LLDP, SuppressionRules.ANY_VALUE));
private SuppressionRules rules = LldpLinkProvider.DEFAULT_RULES;
public static final String CONFIG_KEY = "suppression";
public static final String FEATURE_NAME = "linkDiscovery";
private final Set<ConfigFactory<?, ?>> factories = ImmutableSet.of(
new ConfigFactory<ApplicationId, SuppressionConfig>(APP_SUBJECT_FACTORY,
SuppressionConfig.class,
CONFIG_KEY) {
@Override
public SuppressionConfig createConfig() {
return new SuppressionConfig();
}
},
new ConfigFactory<DeviceId, LinkDiscoveryFromDevice>(DEVICE_SUBJECT_FACTORY,
LinkDiscoveryFromDevice.class, FEATURE_NAME) {
@Override
public LinkDiscoveryFromDevice createConfig() {
return new LinkDiscoveryFromDevice();
}
},
new ConfigFactory<ConnectPoint, LinkDiscoveryFromPort>(CONNECT_POINT_SUBJECT_FACTORY,
LinkDiscoveryFromPort.class, FEATURE_NAME) {
@Override
public LinkDiscoveryFromPort createConfig() {
return new LinkDiscoveryFromPort();
}
}
);
private final InternalConfigListener cfgListener = new InternalConfigListener();
/**
* Creates an OpenFlow link provider.
*/
public LldpLinkProvider() {
super(new ProviderId("lldp", PROVIDER_NAME));
}
private final String buildSrcMac() {
String srcMac = ProbedLinkProvider.fingerprintMac(clusterMetadataService.getClusterMetadata());
String defMac = ProbedLinkProvider.defaultMac();
if (srcMac.equals(defMac)) {
log.warn("Couldn't generate fingerprint. Using default value {}", defMac);
return defMac;
}
log.trace("Generated MAC address {}", srcMac);
return srcMac;
}
@Activate
public void activate(ComponentContext context) {
eventExecutor = newSingleThreadScheduledExecutor(groupedThreads("onos/linkevents", "events-%d", log));
shuttingDown = false;
cfgService.registerProperties(getClass());
appId = coreService.registerApplication(PROVIDER_NAME);
cfgRegistry.addListener(cfgListener);
factories.forEach(cfgRegistry::registerConfigFactory);
SuppressionConfig cfg = cfgRegistry.getConfig(appId, SuppressionConfig.class);
if (cfg == null) {
// If no configuration is found, register default.
cfg = this.setDefaultSuppressionConfig();
}
cfgListener.reconfigureSuppressionRules(cfg);
modified(context);
log.info("Started");
}
private SuppressionConfig setDefaultSuppressionConfig() {
SuppressionConfig cfg = cfgRegistry.addConfig(appId, SuppressionConfig.class);
cfg.deviceTypes(DEFAULT_RULES.getSuppressedDeviceType())
.annotation(DEFAULT_RULES.getSuppressedAnnotation())
.apply();
return cfg;
}
@Deactivate
public void deactivate() {
shuttingDown = true;
cfgRegistry.removeListener(cfgListener);
factories.forEach(cfgRegistry::unregisterConfigFactory);
cfgService.unregisterProperties(getClass(), false);
disable();
eventExecutor.shutdownNow();
eventExecutor = null;
log.info("Stopped");
}
@Modified
public void modified(ComponentContext context) {
Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
boolean newEnabled, newUseBddp;
int newProbeRate, newStaleLinkAge;
try {
String s = get(properties, PROP_ENABLED);
newEnabled = isNullOrEmpty(s) || Boolean.parseBoolean(s.trim());
s = get(properties, PROP_USE_BDDP);
newUseBddp = isNullOrEmpty(s) || Boolean.parseBoolean(s.trim());
s = get(properties, PROP_PROBE_RATE);
newProbeRate = isNullOrEmpty(s) ? probeRate : Integer.parseInt(s.trim());
s = get(properties, PROP_STALE_LINK_AGE);
newStaleLinkAge = isNullOrEmpty(s) ? staleLinkAge : Integer.parseInt(s.trim());
} catch (NumberFormatException e) {
log.warn("Component configuration had invalid values", e);
newEnabled = enabled;
newUseBddp = useBddp;
newProbeRate = probeRate;
newStaleLinkAge = staleLinkAge;
}
boolean wasEnabled = enabled;
enabled = newEnabled;
useBddp = newUseBddp;
probeRate = newProbeRate;
staleLinkAge = newStaleLinkAge;
if (!wasEnabled && enabled) {
enable();
} else if (wasEnabled && !enabled) {
disable();
} else {
if (enabled) {
// update all discovery helper state
loadDevices();
}
}
log.info(FORMAT, enabled, useBddp, probeRate, staleLinkAge);
}
/**
* Enables link discovery processing.
*/
private void enable() {
providerService = providerRegistry.register(this);
masterService.addListener(roleListener);
deviceService.addListener(deviceListener);
packetService.addProcessor(packetProcessor, PacketProcessor.advisor(0));
loadDevices();
executor = newSingleThreadScheduledExecutor(groupedThreads("onos/link", "discovery-%d", log));
executor.scheduleAtFixedRate(new SyncDeviceInfoTask(),
DEVICE_SYNC_DELAY, DEVICE_SYNC_DELAY, SECONDS);
executor.scheduleAtFixedRate(new LinkPrunerTask(),
LINK_PRUNER_DELAY, LINK_PRUNER_DELAY, SECONDS);
requestIntercepts();
}
/**
* Disables link discovery processing.
*/
private void disable() {
withdrawIntercepts();
providerRegistry.unregister(this);
masterService.removeListener(roleListener);
deviceService.removeListener(deviceListener);
packetService.removeProcessor(packetProcessor);
if (executor != null) {
executor.shutdownNow();
}
discoverers.values().forEach(LinkDiscovery::stop);
discoverers.clear();
providerService = null;
}
/**
* Loads available devices and registers their ports to be probed.
*/
private void loadDevices() {
if (!enabled) {
return;
}
deviceService.getAvailableDevices()
.forEach(d -> updateDevice(d)
.ifPresent(ld -> updatePorts(ld, d.id())));
}
private boolean isBlacklisted(DeviceId did) {
LinkDiscoveryFromDevice cfg = cfgRegistry.getConfig(did, LinkDiscoveryFromDevice.class);
if (cfg == null) {
return false;
}
return !cfg.enabled();
}
private boolean isBlacklisted(ConnectPoint cp) {
// if parent device is blacklisted, so is the port
if (isBlacklisted(cp.deviceId())) {
return true;
}
LinkDiscoveryFromPort cfg = cfgRegistry.getConfig(cp, LinkDiscoveryFromPort.class);
if (cfg == null) {
return false;
}
return !cfg.enabled();
}
private boolean isBlacklisted(Port port) {
return isBlacklisted(new ConnectPoint(port.element().id(), port.number()));
}
/**
* Updates discovery helper for specified device.
*
* Adds and starts a discovery helper for specified device if enabled,
* calls {@link #removeDevice(DeviceId)} otherwise.
*
* @param device device to add
* @return discovery helper if discovery is enabled for the device
*/
private Optional<LinkDiscovery> updateDevice(Device device) {
if (device == null) {
return Optional.empty();
}
if (rules.isSuppressed(device) || isBlacklisted(device.id())) {
log.trace("LinkDiscovery from {} disabled by configuration", device.id());
removeDevice(device.id());
return Optional.empty();
}
LinkDiscovery ld = discoverers.computeIfAbsent(device.id(),
did -> new LinkDiscovery(device, context));
if (ld.isStopped()) {
ld.start();
}
return Optional.of(ld);
}
/**
* Removes after stopping discovery helper for specified device.
* @param deviceId device to remove
*/
private void removeDevice(final DeviceId deviceId) {
discoverers.computeIfPresent(deviceId, (did, ld) -> {
ld.stop();
return null;
});
}
/**
* Updates ports of the specified device to the specified discovery helper.
*/
private void updatePorts(LinkDiscovery discoverer, DeviceId deviceId) {
deviceService.getPorts(deviceId).forEach(p -> updatePort(discoverer, p));
}
/**
* Updates discovery helper state of the specified port.
*
* Adds a port to the discovery helper if up and discovery is enabled,
* or calls {@link #removePort(Port)} otherwise.
*/
private void updatePort(LinkDiscovery discoverer, Port port) {
if (port == null) {
return;
}
if (port.number().isLogical()) {
// silently ignore logical ports
return;
}
if (rules.isSuppressed(port) || isBlacklisted(port)) {
log.trace("LinkDiscovery from {} disabled by configuration", port);
removePort(port);
return;
}
// check if enabled and turn off discovery?
if (!port.isEnabled()) {
removePort(port);
return;
}
discoverer.addPort(port);
}
/**
* Removes a port from the specified discovery helper.
* @param port the port
*/
private void removePort(Port port) {
if (port.element() instanceof Device) {
Device d = (Device) port.element();
LinkDiscovery ld = discoverers.get(d.id());
if (ld != null) {
ld.removePort(port.number());
}
} else {
log.warn("Attempted to remove non-Device port", port);
}
}
/**
* Requests packet intercepts.
*/
private void requestIntercepts() {
TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
selector.matchEthType(TYPE_LLDP);
packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId);
selector.matchEthType(TYPE_BSN);
if (useBddp) {
packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId);
} else {
packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
}
}
/**
* Withdraws packet intercepts.
*/
private void withdrawIntercepts() {
TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
selector.matchEthType(TYPE_LLDP);
packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
selector.matchEthType(TYPE_BSN);
packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
}
protected SuppressionRules rules() {
return rules;
}
protected void updateRules(SuppressionRules newRules) {
if (!rules.equals(newRules)) {
rules = newRules;
loadDevices();
}
}
/**
* Processes device mastership role changes.
*/
private class InternalRoleListener implements MastershipListener {
@Override
public void event(MastershipEvent event) {
if (MastershipEvent.Type.BACKUPS_CHANGED.equals(event.type())) {
// only need new master events
return;
}
eventExecutor.execute(() -> {
DeviceId deviceId = event.subject();
Device device = deviceService.getDevice(deviceId);
if (device == null) {
log.debug("Device {} doesn't exist, or isn't there yet", deviceId);
return;
}
if (clusterService.getLocalNode().id().equals(event.roleInfo().master())) {
updateDevice(device).ifPresent(ld -> updatePorts(ld, device.id()));
}
});
}
}
private class DeviceEventProcessor implements Runnable {
DeviceEvent event;
DeviceEventProcessor(DeviceEvent event) {
this.event = event;
}
@Override
public void run() {
Device device = event.subject();
Port port = event.port();
if (device == null) {
log.error("Device is null.");
return;
}
log.trace("{} {} {}", event.type(), event.subject(), event);
final DeviceId deviceId = device.id();
switch (event.type()) {
case DEVICE_ADDED:
case DEVICE_UPDATED:
updateDevice(device).ifPresent(ld -> updatePorts(ld, deviceId));
break;
case PORT_ADDED:
case PORT_UPDATED:
if (port.isEnabled()) {
updateDevice(device).ifPresent(ld -> updatePort(ld, port));
} else {
log.debug("Port down {}", port);
removePort(port);
providerService.linksVanished(new ConnectPoint(port.element().id(),
port.number()));
}
break;
case PORT_REMOVED:
log.debug("Port removed {}", port);
removePort(port);
providerService.linksVanished(new ConnectPoint(port.element().id(),
port.number()));
break;
case DEVICE_REMOVED:
case DEVICE_SUSPENDED:
log.debug("Device removed {}", deviceId);
removeDevice(deviceId);
providerService.linksVanished(deviceId);
break;
case DEVICE_AVAILABILITY_CHANGED:
if (deviceService.isAvailable(deviceId)) {
log.debug("Device up {}", deviceId);
updateDevice(device).ifPresent(ld -> updatePorts(ld, deviceId));
} else {
log.debug("Device down {}", deviceId);
removeDevice(deviceId);
providerService.linksVanished(deviceId);
}
break;
case PORT_STATS_UPDATED:
break;
default:
log.debug("Unknown event {}", event);
}
}
}
/**
* Processes device events.
*/
private class InternalDeviceListener implements DeviceListener {
@Override
public void event(DeviceEvent event) {
if (event.type() == Type.PORT_STATS_UPDATED) {
return;
}
Runnable deviceEventProcessor = new DeviceEventProcessor(event);
eventExecutor.execute(deviceEventProcessor);
}
}
/**
* Processes incoming packets.
*/
private class InternalPacketProcessor implements PacketProcessor {
@Override
public void process(PacketContext context) {
if (context == null || context.isHandled()) {
return;
}
Ethernet eth = context.inPacket().parsed();
if (eth == null || (eth.getEtherType() != TYPE_LLDP && eth.getEtherType() != TYPE_BSN)) {
return;
}
LinkDiscovery ld = discoverers.get(context.inPacket().receivedFrom().deviceId());
if (ld == null) {
return;
}
if (ld.handleLldp(context)) {
context.block();
}
}
}
/**
* Auxiliary task to keep device ports up to date.
*/
private final class SyncDeviceInfoTask implements Runnable {
@Override
public void run() {
if (Thread.currentThread().isInterrupted()) {
log.info("Interrupted, quitting");
return;
}
// check what deviceService sees, to see if we are missing anything
try {
loadDevices();
} catch (Exception e) {
// Catch all exceptions to avoid task being suppressed
log.error("Exception thrown during synchronization process", e);
}
}
}
/**
* Auxiliary task for pruning stale links.
*/
private class LinkPrunerTask implements Runnable {
@Override
public void run() {
if (Thread.currentThread().isInterrupted()) {
log.info("Interrupted, quitting");
return;
}
try {
// TODO: There is still a slight possibility of mastership
// change occurring right with link going stale. This will
// result in the stale link not being pruned.
Maps.filterEntries(linkTimes, e -> {
if (!masterService.isLocalMaster(e.getKey().dst().deviceId())) {
return true;
}
if (isStale(e.getValue())) {
providerService.linkVanished(new DefaultLinkDescription(e.getKey().src(),
e.getKey().dst(),
DIRECT));
return true;
}
return false;
}).clear();
} catch (Exception e) {
// Catch all exceptions to avoid task being suppressed
if (!shuttingDown) {
// Error condition
log.error("Exception thrown during link pruning process", e);
} else {
// Provider is shutting down, the error can be ignored
log.trace("Shutting down, ignoring error", e);
}
}
}
private boolean isStale(long lastSeen) {
return lastSeen < System.currentTimeMillis() - staleLinkAge;
}
}
/**
* Provides processing context for the device link discovery helpers.
*/
private class InternalDiscoveryContext implements LinkDiscoveryContext {
@Override
public MastershipService mastershipService() {
return masterService;
}
@Override
public LinkProviderService providerService() {
return providerService;
}
@Override
public PacketService packetService() {
return packetService;
}
@Override
public long probeRate() {
return probeRate;
}
@Override
public boolean useBddp() {
return useBddp;
}
@Override
public void touchLink(LinkKey key) {
linkTimes.put(key, System.currentTimeMillis());
}
@Override
public DeviceService deviceService() {
return deviceService;
}
@Override
public String fingerprint() {
return buildSrcMac();
}
}
static final EnumSet<NetworkConfigEvent.Type> CONFIG_CHANGED
= EnumSet.of(NetworkConfigEvent.Type.CONFIG_ADDED,
NetworkConfigEvent.Type.CONFIG_UPDATED,
NetworkConfigEvent.Type.CONFIG_REMOVED);
private class InternalConfigListener implements NetworkConfigListener {
private synchronized void reconfigureSuppressionRules(SuppressionConfig cfg) {
if (cfg == null) {
log.debug("Suppression Config is null.");
return;
}
SuppressionRules newRules = new SuppressionRules(cfg.deviceTypes(),
cfg.annotation());
updateRules(newRules);
}
@Override
public void event(NetworkConfigEvent event) {
eventExecutor.execute(() -> {
if (event.configClass() == LinkDiscoveryFromDevice.class &&
CONFIG_CHANGED.contains(event.type())) {
if (event.subject() instanceof DeviceId) {
final DeviceId did = (DeviceId) event.subject();
Device device = deviceService.getDevice(did);
updateDevice(device).ifPresent(ld -> updatePorts(ld, did));
}
} else if (event.configClass() == LinkDiscoveryFromPort.class &&
CONFIG_CHANGED.contains(event.type())) {
if (event.subject() instanceof ConnectPoint) {
ConnectPoint cp = (ConnectPoint) event.subject();
if (cp.elementId() instanceof DeviceId) {
final DeviceId did = (DeviceId) cp.elementId();
Device device = deviceService.getDevice(did);
Port port = deviceService.getPort(did, cp.port());
updateDevice(device).ifPresent(ld -> updatePort(ld, port));
}
}
} else if (event.configClass().equals(SuppressionConfig.class) &&
(event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)) {
SuppressionConfig cfg = cfgRegistry.getConfig(appId, SuppressionConfig.class);
reconfigureSuppressionRules(cfg);
log.trace("Network config reconfigured");
}
});
}
}
}
| |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.routing;
import gnu.trove.map.hash.TObjectIntHashMap;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import java.util.*;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
/**
*
*/
public class RoutingNodes implements Iterable<RoutingNode> {
private final MetaData metaData;
private final ClusterBlocks blocks;
private final RoutingTable routingTable;
private final Map<String, RoutingNode> nodesToShards = newHashMap();
private final List<MutableShardRouting> unassigned = newArrayList();
private final List<MutableShardRouting> ignoredUnassigned = newArrayList();
private final Map<String, TObjectIntHashMap<String>> nodesPerAttributeNames = new HashMap<String, TObjectIntHashMap<String>>();
public RoutingNodes(ClusterState clusterState) {
this.metaData = clusterState.metaData();
this.blocks = clusterState.blocks();
this.routingTable = clusterState.routingTable();
Map<String, List<MutableShardRouting>> nodesToShards = newHashMap();
// fill in the nodeToShards with the "live" nodes
for (DiscoveryNode node : clusterState.nodes().dataNodes().values()) {
nodesToShards.put(node.id(), new ArrayList<MutableShardRouting>());
}
// fill in the inverse of node -> shards allocated
for (IndexRoutingTable indexRoutingTable : routingTable.indicesRouting().values()) {
for (IndexShardRoutingTable indexShard : indexRoutingTable) {
for (ShardRouting shard : indexShard) {
if (shard.assignedToNode()) {
List<MutableShardRouting> entries = nodesToShards.get(shard.currentNodeId());
if (entries == null) {
entries = newArrayList();
nodesToShards.put(shard.currentNodeId(), entries);
}
entries.add(new MutableShardRouting(shard));
if (shard.relocating()) {
entries = nodesToShards.get(shard.relocatingNodeId());
if (entries == null) {
entries = newArrayList();
nodesToShards.put(shard.relocatingNodeId(), entries);
}
// add the counterpart shard with relocatingNodeId reflecting the source from which
// it's relocating from.
entries.add(new MutableShardRouting(shard.index(), shard.id(), shard.relocatingNodeId(),
shard.currentNodeId(), shard.primary(), ShardRoutingState.INITIALIZING, shard.version()));
}
} else {
unassigned.add(new MutableShardRouting(shard));
}
}
}
}
for (Map.Entry<String, List<MutableShardRouting>> entry : nodesToShards.entrySet()) {
String nodeId = entry.getKey();
this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue()));
}
}
public Iterator<RoutingNode> iterator() {
return nodesToShards.values().iterator();
}
public RoutingTable routingTable() {
return routingTable;
}
public RoutingTable getRoutingTable() {
return routingTable();
}
public MetaData metaData() {
return this.metaData;
}
public MetaData getMetaData() {
return metaData();
}
public ClusterBlocks blocks() {
return this.blocks;
}
public ClusterBlocks getBlocks() {
return this.blocks;
}
public int requiredAverageNumberOfShardsPerNode() {
int totalNumberOfShards = 0;
// we need to recompute to take closed shards into account
for (IndexMetaData indexMetaData : metaData.indices().values()) {
if (indexMetaData.state() == IndexMetaData.State.OPEN) {
totalNumberOfShards += indexMetaData.totalNumberOfShards();
}
}
return totalNumberOfShards / nodesToShards.size();
}
public boolean hasUnassigned() {
return !unassigned.isEmpty();
}
public List<MutableShardRouting> ignoredUnassigned() {
return this.ignoredUnassigned;
}
public List<MutableShardRouting> unassigned() {
return this.unassigned;
}
public List<MutableShardRouting> getUnassigned() {
return unassigned();
}
public Map<String, RoutingNode> nodesToShards() {
return nodesToShards;
}
public Map<String, RoutingNode> getNodesToShards() {
return nodesToShards();
}
public RoutingNode node(String nodeId) {
return nodesToShards.get(nodeId);
}
public TObjectIntHashMap<String> nodesPerAttributesCounts(String attributeName) {
TObjectIntHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName);
if (nodesPerAttributesCounts != null) {
return nodesPerAttributesCounts;
}
nodesPerAttributesCounts = new TObjectIntHashMap<String>();
for (RoutingNode routingNode : this) {
String attrValue = routingNode.node().attributes().get(attributeName);
nodesPerAttributesCounts.adjustOrPutValue(attrValue, 1, 1);
}
nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts);
return nodesPerAttributesCounts;
}
public MutableShardRouting findPrimaryForReplica(ShardRouting shard) {
assert !shard.primary();
for (RoutingNode routingNode : nodesToShards.values()) {
List<MutableShardRouting> shards = routingNode.shards();
for (int i = 0; i < shards.size(); i++) {
MutableShardRouting shardRouting = shards.get(i);
if (shardRouting.shardId().equals(shard.shardId()) && shardRouting.primary()) {
return shardRouting;
}
}
}
return null;
}
public List<MutableShardRouting> shardsRoutingFor(ShardRouting shardRouting) {
return shardsRoutingFor(shardRouting.index(), shardRouting.id());
}
public List<MutableShardRouting> shardsRoutingFor(String index, int shardId) {
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
List<MutableShardRouting> nShards = routingNode.shards();
for (int i = 0; i < nShards.size(); i++) {
MutableShardRouting shardRouting = nShards.get(i);
if (shardRouting.index().equals(index) && shardRouting.id() == shardId) {
shards.add(shardRouting);
}
}
}
for (int i = 0; i < unassigned.size(); i++) {
MutableShardRouting shardRouting = unassigned.get(i);
if (shardRouting.index().equals(index) && shardRouting.id() == shardId) {
shards.add(shardRouting);
}
}
return shards;
}
public int numberOfShardsOfType(ShardRoutingState state) {
int count = 0;
for (RoutingNode routingNode : this) {
count += routingNode.numberOfShardsWithState(state);
}
return count;
}
public List<MutableShardRouting> shardsWithState(ShardRoutingState... state) {
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(state));
}
return shards;
}
public List<MutableShardRouting> shardsWithState(String index, ShardRoutingState... state) {
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(index, state));
}
return shards;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder("routing_nodes:\n");
for (RoutingNode routingNode : this) {
sb.append(routingNode.prettyPrint());
}
sb.append("---- unassigned\n");
for (MutableShardRouting shardEntry : unassigned) {
sb.append("--------").append(shardEntry.shortSummary()).append('\n');
}
return sb.toString();
}
}
| |
//
// This file was pubmed.openAccess.jaxb.generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.06.04 at 07:58:30 PM BST
//
package elsevier.jaxb.math.mathml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* <p>Java class for mtable.type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="mtable.type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <group ref="{http://www.w3.org/1998/Math/MathML}mtable.content" maxOccurs="unbounded"/>
* <attGroup ref="{http://www.w3.org/1998/Math/MathML}mtable.attlist"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "mtable.type", propOrder = {
"mtrsAndMlabeledtrs"
})
@XmlRootElement(name = "mtable")
public class Mtable {
@XmlElements({
@XmlElement(name = "mlabeledtr", type = Mlabeledtr.class),
@XmlElement(name = "mtr", type = Mtr.class)
})
protected List<Object> mtrsAndMlabeledtrs;
@XmlAttribute
protected String align;
@XmlAttribute
protected String alignmentscope;
@XmlAttribute
protected String columnwidth;
@XmlAttribute
protected String width;
@XmlAttribute
protected String rowspacing;
@XmlAttribute
protected String columnspacing;
@XmlAttribute
protected String rowlines;
@XmlAttribute
protected String columnlines;
@XmlAttribute
protected String frame;
@XmlAttribute
protected String framespacing;
@XmlAttribute
protected Boolean equalrows;
@XmlAttribute
protected Boolean equalcolumns;
@XmlAttribute
protected Boolean displaystyle;
@XmlAttribute
protected String side;
@XmlAttribute
protected String minlabelspacing;
@XmlAttribute
protected String rowalign;
@XmlAttribute
protected String columnalign;
@XmlAttribute
protected String groupalign;
@XmlAttribute(name = "class")
@XmlSchemaType(name = "NMTOKENS")
protected List<String> clazzs;
@XmlAttribute
protected String style;
@XmlAttribute
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object xref;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the mtrsAndMlabeledtrs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the mtrsAndMlabeledtrs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMtrsAndMlabeledtrs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Mlabeledtr }
* {@link Mtr }
*
*
*/
public List<Object> getMtrsAndMlabeledtrs() {
if (mtrsAndMlabeledtrs == null) {
mtrsAndMlabeledtrs = new ArrayList<Object>();
}
return this.mtrsAndMlabeledtrs;
}
/**
* Gets the value of the align property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlign() {
if (align == null) {
return "axis";
} else {
return align;
}
}
/**
* Sets the value of the align property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlign(String value) {
this.align = value;
}
/**
* Gets the value of the alignmentscope property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlignmentscope() {
if (alignmentscope == null) {
return "true";
} else {
return alignmentscope;
}
}
/**
* Sets the value of the alignmentscope property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlignmentscope(String value) {
this.alignmentscope = value;
}
/**
* Gets the value of the columnwidth property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getColumnwidth() {
if (columnwidth == null) {
return "auto";
} else {
return columnwidth;
}
}
/**
* Sets the value of the columnwidth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setColumnwidth(String value) {
this.columnwidth = value;
}
/**
* Gets the value of the width property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWidth() {
if (width == null) {
return "auto";
} else {
return width;
}
}
/**
* Sets the value of the width property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWidth(String value) {
this.width = value;
}
/**
* Gets the value of the rowspacing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRowspacing() {
if (rowspacing == null) {
return "1.0ex";
} else {
return rowspacing;
}
}
/**
* Sets the value of the rowspacing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRowspacing(String value) {
this.rowspacing = value;
}
/**
* Gets the value of the columnspacing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getColumnspacing() {
if (columnspacing == null) {
return "0.8em";
} else {
return columnspacing;
}
}
/**
* Sets the value of the columnspacing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setColumnspacing(String value) {
this.columnspacing = value;
}
/**
* Gets the value of the rowlines property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRowlines() {
if (rowlines == null) {
return "none";
} else {
return rowlines;
}
}
/**
* Sets the value of the rowlines property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRowlines(String value) {
this.rowlines = value;
}
/**
* Gets the value of the columnlines property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getColumnlines() {
if (columnlines == null) {
return "none";
} else {
return columnlines;
}
}
/**
* Sets the value of the columnlines property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setColumnlines(String value) {
this.columnlines = value;
}
/**
* Gets the value of the frame property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFrame() {
if (frame == null) {
return "none";
} else {
return frame;
}
}
/**
* Sets the value of the frame property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFrame(String value) {
this.frame = value;
}
/**
* Gets the value of the framespacing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFramespacing() {
if (framespacing == null) {
return "0.4em 0.5ex";
} else {
return framespacing;
}
}
/**
* Sets the value of the framespacing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFramespacing(String value) {
this.framespacing = value;
}
/**
* Gets the value of the equalrows property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isEqualrows() {
if (equalrows == null) {
return false;
} else {
return equalrows;
}
}
/**
* Sets the value of the equalrows property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setEqualrows(Boolean value) {
this.equalrows = value;
}
/**
* Gets the value of the equalcolumns property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isEqualcolumns() {
if (equalcolumns == null) {
return false;
} else {
return equalcolumns;
}
}
/**
* Sets the value of the equalcolumns property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setEqualcolumns(Boolean value) {
this.equalcolumns = value;
}
/**
* Gets the value of the displaystyle property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isDisplaystyle() {
if (displaystyle == null) {
return false;
} else {
return displaystyle;
}
}
/**
* Sets the value of the displaystyle property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDisplaystyle(Boolean value) {
this.displaystyle = value;
}
/**
* Gets the value of the side property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSide() {
if (side == null) {
return "right";
} else {
return side;
}
}
/**
* Sets the value of the side property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSide(String value) {
this.side = value;
}
/**
* Gets the value of the minlabelspacing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMinlabelspacing() {
if (minlabelspacing == null) {
return "0.8em";
} else {
return minlabelspacing;
}
}
/**
* Sets the value of the minlabelspacing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMinlabelspacing(String value) {
this.minlabelspacing = value;
}
/**
* Gets the value of the rowalign property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRowalign() {
if (rowalign == null) {
return "baseline";
} else {
return rowalign;
}
}
/**
* Sets the value of the rowalign property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRowalign(String value) {
this.rowalign = value;
}
/**
* Gets the value of the columnalign property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getColumnalign() {
if (columnalign == null) {
return "center";
} else {
return columnalign;
}
}
/**
* Sets the value of the columnalign property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setColumnalign(String value) {
this.columnalign = value;
}
/**
* Gets the value of the groupalign property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGroupalign() {
return groupalign;
}
/**
* Sets the value of the groupalign property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGroupalign(String value) {
this.groupalign = value;
}
/**
* Gets the value of the clazzs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clazzs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClazzs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getClazzs() {
if (clazzs == null) {
clazzs = new ArrayList<String>();
}
return this.clazzs;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the xref property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getXref() {
return xref;
}
/**
* Sets the value of the xref property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setXref(Object value) {
this.xref = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| |
package com.search.core;
import com.google.gson.Gson;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.search.core.objectStructure.Business;
import it.cnr.jatecs.classification.ClassificationScoreDB;
import it.cnr.jatecs.classification.ClassifierRangeWithScore;
import it.cnr.jatecs.classification.interfaces.IClassifier;
import it.cnr.jatecs.classification.module.Classifier;
import it.cnr.jatecs.classification.svm.SvmLearner;
import it.cnr.jatecs.classification.svm.SvmLearnerCustomizer;
import it.cnr.jatecs.indexes.DB.interfaces.ICategoryDB;
import it.cnr.jatecs.indexes.DB.interfaces.IIndex;
import it.cnr.jatecs.indexes.DB.troveCompact.*;
import it.cnr.jatecs.indexing.corpus.BagOfWordsFeatureExtractor;
import it.cnr.jatecs.io.FileSystemStorageManager;
import libsvm.svm_parameter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.util.*;
/**
* Created by murugesm on 10/12/2016.
*/
public class SVMVersion implements Runnable
{
public SVMVersion(DBCursor cursor, DB db, String method)
{
this.cursor = cursor;
this.db = db;
this.method = method;
}
static final String CLEAR = "CLEAR";
static final String EXCEPTION = "EXCEPTION";
static final String CLASSIFY = "CLASSIFY";
static final String LEARN = "LEARN";
static final String INDEX = "INDEX";
static final String INIT = "INIT";
static final String EXIT = "EXIT";
static final String SEPARATOR = " ";
static final String TRAIN = "TRAIN";
static final String TEST = "TEST";
static final String[] STRING_ARRAY = new String[0];
static final String LABEL_SEPARATOR = "|";
static final String NAIVE_BAYES = "NB";
static final String OK = "OK";
static HashSet<String> exhaustiveList = new HashSet<String>();
static BagOfWordsFeatureExtractor extractor = new BagOfWordsFeatureExtractor();
static TroveMainIndexBuilder mainIndexBuilder = null;
static IIndex training = null;
static ICategoryDB categoryDB = null;
static TroveCategoryDBBuilder categoryDBBuilder = new TroveCategoryDBBuilder();
static IClassifier classifier = null;
static TroveDependentIndexBuilder testIndexBuilder = null;
static TroveContentDBType contentDBType = TroveContentDBType.IL;
static TroveClassificationDBType classificationDBType = TroveClassificationDBType.IL;
DBCursor cursor;
DB db;
String method;
public static void main(String[] args) throws IOException, InterruptedException
{
getJSON();
}
public void run()
{
String json = null;
if(method == "train")
{
while (cursor.hasNext())
{
json = cursor.next().toString();
json = json.replaceAll("_", "");
json = json.replaceAll("-", "");
Gson gson = new Gson();
Business business1 = gson.fromJson(json, Business.class);
String[] categories = business1.getCategories();
ArrayList<String> mainCategories = new ArrayList<String>();
for (String category : categories)
{
if (exhaustiveList.contains(category))
{
mainCategories.add(category);
}
}
String reviewData = null;
try
{
reviewData = getReviewData.getReviews(db, business1.getBusinessid());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
extractFeatures(mainIndexBuilder, mainCategories, business1.getName(), reviewData);
writeLine("Finished Training " + business1.getName());
}
}
else
{
while(cursor.hasNext())
{
json = cursor.next().toString();
json = json.replaceAll("_","");
json = json.replaceAll("-","");
Gson gson = new Gson();
Business business1 = gson.fromJson(json, Business.class);
String[] categories = business1.getCategories();
ArrayList<String> mainCategories = new ArrayList<String>();
for(String category: categories)
{
if(exhaustiveList.contains(category))
{
mainCategories.add(category);
}
}
String reviewData = null;
try
{
reviewData = getReviewData.getReviews(db, business1.getBusinessid());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
extractFeaturesTest(testIndexBuilder, mainCategories, business1.getName(), reviewData);
writeLine("Testing " + business1.getName());
}
}
}
public static void getJSON() throws IOException, InterruptedException
{
exhaustiveList.add("Restaurants");
exhaustiveList.add("Nightlife");
exhaustiveList.add("Active Life");
exhaustiveList.add("Automotive");
exhaustiveList.add("Home Services");
exhaustiveList.add("Pets");
exhaustiveList.add("Public Services & Government");
exhaustiveList.add("Food");
exhaustiveList.add("Local Services");
exhaustiveList.add("Hotels & Travel");
exhaustiveList.add("Event Planning & Services");
exhaustiveList.add("Health & Medical");
exhaustiveList.add("Shopping");
exhaustiveList.add("Beauty & Spas");
exhaustiveList.add("Arts & Entertainment");
exhaustiveList.add("Education");
exhaustiveList.add("Financial Services");
exhaustiveList.add("Religious Organizations");
exhaustiveList.add("Professional Services");
exhaustiveList.add("Mass Media");
exhaustiveList.add("Local Flavor");
String[] labels = {"Restaurants", "Nightlife", "Active Life", "Restaurants", "Automotive", "Home Services", "Pets", "Public Services & Government", "Food", "Local Services", "Hotels & Travel", "Event Planning & Services", "Health & Medical", "Shopping", "Beauty & Spas", "Arts & Entertainment", "Education", "Financial Services", "Religious Organizations", "Professional Services", "Mass Media", "Local Flavor"};
for (String label : labels)
{
categoryDBBuilder.addCategory(label);
}
categoryDB = categoryDBBuilder.getCategoryDB();
mainIndexBuilder = new TroveMainIndexBuilder(categoryDB);
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("yelp_dataset");
DBCollection business = db.getCollection("business");
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int totalBusinesses = business.find().count();
int totalTrain = (int) (totalBusinesses * 0.8 );
int window = (int) (totalTrain/ numOfProcessors);
DBCursor[] cursors = new DBCursor[numOfProcessors];
Thread[] threads = new Thread[numOfProcessors];
for(int p=0; p < numOfProcessors; p++)
{
cursors[p] = business.find().limit(window).skip(window * p);
com.search.core.SVMVersion objClass = new com.search.core.SVMVersion(cursors[p], db, "train");
threads[p] = new Thread(objClass, p + "");
threads[p].start();
}
for(int p=0; p < numOfProcessors; p++)
{
try
{
threads[p].join();
}
catch (Exception e)
{
writeLine(e.toString());
}
}
FileSystemStorageManager storageManager = new FileSystemStorageManager("/Users/murugesm/Sem 3/Search/project", false);
storageManager.open();
training = TroveReadWriteHelper.generateIndex(storageManager, mainIndexBuilder.getIndex(), contentDBType, classificationDBType);
testIndexBuilder = new TroveDependentIndexBuilder(training.getDomainDB());
storageManager.close();
int totalTests = totalBusinesses - totalTrain;
window = (int) (totalTests/ numOfProcessors);
DBCursor[] cursorsTest = new DBCursor[numOfProcessors];
Thread[] threadsTest = new Thread[numOfProcessors];
for(int p=0; p < numOfProcessors; p++)
{
cursorsTest[p] = business.find().limit(window).skip(window * p);
// cursors[p] = business.find().limit((totalTests) - (window * p)).skip(window * p);
com.search.core.SVMVersion objClass = new com.search.core.SVMVersion(cursorsTest[p], db, "test");
threadsTest[p] = new Thread(objClass, p + "");
threadsTest[p].start();
}
for(int p=0; p < numOfProcessors; p++)
{
try
{
threadsTest[p].join();
}
catch (Exception e)
{
writeLine(e.toString());
}
}
System.out.print("Done Multithreading");
IIndex testIndex = testIndexBuilder.getIndex();
SvmLearner svmLearner = new SvmLearner();
double smooth = 1.0;
SvmLearnerCustomizer svmCustomizer = new SvmLearnerCustomizer();
svmCustomizer.getSVMParameter().svm_type = svm_parameter.C_SVC;
svmCustomizer.getSVMParameter().kernel_type = svm_parameter.LINEAR;
svmCustomizer.setSoftMarginDefaultCost(1.0);
svmLearner.setRuntimeCustomizer(svmCustomizer);
classifier = svmLearner.build(training);
Classifier classifierModule = new Classifier(testIndex, classifier, true);
classifierModule.exec();
ClassificationScoreDB confidences = classifierModule.getConfidences();
int numDoc = testIndex.getDocumentDB().getDocumentsCount();
writeLine(numDoc + " " + categoryDB.getCategoriesCount());
PrintWriter writer = new PrintWriter("output-svm.txt", "UTF-8");
for (int docID = 0; docID < numDoc; ++docID)
{
String docName = testIndex.getDocumentDB().getDocumentName(docID);
Set<Map.Entry<Short, ClassifierRangeWithScore>> entries = confidences.getDocumentScoresAsSet(docID);
Iterator<Map.Entry<Short, ClassifierRangeWithScore>> iterator = entries.iterator();
HashMap<String, Double> map = new HashMap<String, Double>();
while (iterator.hasNext())
{
Map.Entry<Short, ClassifierRangeWithScore> next = iterator.next();
ClassifierRangeWithScore value = next.getValue();
map.put(categoryDB.getCategoryName(next.getKey()), value.score);
//writeLine(docName + " " + categoryDB.getCategoryName(next.getKey()) + " " + value.score);
}
writer.print("'"+docName+"'");
writeLine("The top 3 possibility of category for the business "+docName+ " are :");
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator()
{
public int compare(Object o1, Object o2)
{
return ((Map.Entry<String, Double>) o2).getValue().compareTo(((Map.Entry<String, Double>) o1).getValue());
}
});
int count = 0;
for (Object e : a)
{
writer.print(" '"+((Map.Entry<String, Double>) e).getKey()+"'");
System.out.println(((Map.Entry<String, Double>) e).getKey() + " : " + ((Map.Entry<String, Double>) e).getValue());
count++;
if(count>2)
{
break;
}
}
writer.println();
writeLine("------------------------------------------------------------------------");
}
writer.close();
}
public static void extractFeatures(TroveMainIndexBuilder mainIndexBuilder, ArrayList<String> categories, String businessName, String text)
{
List<String> labels1 = new Vector<String>();
for(String category: categories)
{
labels1.add(category);
}
List<String> features = extractor.extractFeatures(text);
try
{
mainIndexBuilder.addDocument(businessName, features.toArray(STRING_ARRAY), labels1.toArray(STRING_ARRAY));
}
catch (Exception e)
{
writeLine("Exception found for document "+businessName+" : "+ e.toString());
}
}
public static void extractFeaturesTest(TroveDependentIndexBuilder testIndexBuilder, ArrayList<String> categories, String businessName, String text)
{
List<String> labels1 = new Vector<String>();
for(String category: categories)
{
labels1.add(category);
}
List<String> features = extractor.extractFeatures(text);
try
{
testIndexBuilder.addDocument(businessName, features.toArray(STRING_ARRAY), labels1.toArray(STRING_ARRAY));
}
catch (Exception e)
{
writeLine("Exception found for document "+businessName+" : "+ e.toString());
}
}
private static void writeLine(String line)
{
System.out.println(line);
}
}
| |
/*
* Copyright 2002-2004 Jeremias Maerki.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.krysalis.barcode4j;
import org.krysalis.barcode4j.compat.Rectangle2D;
/**
* This class provides information on the dimensions of a barcode. It makes a
* distinction between the dimensions with and without quiet zone.
*
* @author Jeremias Maerki
* @version $Id$
*/
public class BarcodeDimension {
private double width;
private double height;
private double widthPlusQuiet;
private double heightPlusQuiet;
private double xOffset;
private double yOffset;
/**
* Creates a new BarcodeDimension object. No quiet-zone is respected.
* @param w width of the barcode in millimeters (mm).
* @param h height of the barcode in millimeters (mm).
*/
public BarcodeDimension(double w, double h) {
this.width = w;
this.height = h;
this.widthPlusQuiet = this.width;
this.heightPlusQuiet = this.height;
this.xOffset = 0.0;
this.yOffset = 0.0;
}
/**
* Creates a new BarcodeDimension object.
* @param w width of the raw barcode (without quiet-zone) in millimeters (mm).
* @param h height of the raw barcode (without quiet-zone) in millimeters (mm).
* @param wpq width of the barcode (quiet-zone included) in millimeters (mm).
* @param hpq height of the barcode (quiet-zone included) in millimeters (mm).
* @param xoffset x-offset if the upper-left corner of the barcode within
* the extended barcode area.
* @param yoffset y-offset if the upper-left corner of the barcode within
* the extended barcode area.
*/
public BarcodeDimension(double w, double h,
double wpq, double hpq,
double xoffset, double yoffset) {
this.width = w;
this.height = h;
this.widthPlusQuiet = wpq;
this.heightPlusQuiet = hpq;
this.xOffset = xoffset;
this.yOffset = yoffset;
}
/**
* Returns the height of the barcode (ignores quiet-zone).
* @return height in millimeters (mm)
*/
public double getHeight() {
return height;
}
public double getHeight(int orientation) {
orientation = normalizeOrientation(orientation);
if (orientation % 180 != 0) {
return getWidth();
} else {
return getHeight();
}
}
/**
* Returns the height of the barcode (quiet-zone included).
* @return height in millimeters (mm)
*/
public double getHeightPlusQuiet() {
return heightPlusQuiet;
}
public double getHeightPlusQuiet(int orientation) {
orientation = normalizeOrientation(orientation);
if (orientation % 180 != 0) {
return getWidthPlusQuiet();
} else {
return getHeightPlusQuiet();
}
}
/**
* Returns the width of the barcode (ignores quiet-zone).
* @return width in millimeters (mm)
*/
public double getWidth() {
return width;
}
public static int normalizeOrientation(int orientation) {
switch (orientation) {
case 0:
return 0;
case 90:
case -270:
return 90;
case 180:
case -180:
return 180;
case 270:
case -90:
return 270;
default:
throw new IllegalArgumentException(
"Orientation must be 0, 90, 180, 270, -90, -180 or -270");
}
}
public double getWidth(int orientation) {
orientation = normalizeOrientation(orientation);
if (orientation % 180 != 0) {
return getHeight();
} else {
return getWidth();
}
}
/**
* Returns the width of the barcode (quiet-zone included).
* @return width in millimeters (mm)
*/
public double getWidthPlusQuiet() {
return widthPlusQuiet;
}
public double getWidthPlusQuiet(int orientation) {
orientation = normalizeOrientation(orientation);
if (orientation % 180 != 0) {
return getHeightPlusQuiet();
} else {
return getWidthPlusQuiet();
}
}
/**
* Returns the x-offset of the upper-left corner of the barcode within the
* extended barcode area.
* @return double x-offset in millimeters (mm)
*/
public double getXOffset() {
return xOffset;
}
/**
* Returns the y-offset of the upper-left corner of the barcode within the
* extended barcode area.
* @return double y-offset in millimeters (mm)
*/
public double getYOffset() {
return yOffset;
}
/** @return a bounding rectangle (including quiet zone if applicable) */
public Rectangle2D getBoundingRect() {
Rectangle2D.Double r = new Rectangle2D.Double(
0, 0, getWidthPlusQuiet(), getHeightPlusQuiet());
return r;
}
/** @return a content rectangle (excluding quiet zone) */
public Rectangle2D getContentRect() {
Rectangle2D.Double r = new Rectangle2D.Double(
getXOffset(), getYOffset(), getWidth(), getHeight());
return r;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer sb = new StringBuffer(super.toString());
sb.append("[width=");
sb.append(getWidth());
sb.append("(");
sb.append(getWidthPlusQuiet());
sb.append("),height=");
sb.append(getHeight());
sb.append("(");
sb.append(getHeightPlusQuiet());
sb.append(")]");
return sb.toString();
}
}
| |
/**
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.core;
import org.bitcoinj.script.*;
import org.slf4j.*;
import javax.annotation.*;
import java.io.*;
import java.util.*;
import static com.google.common.base.Preconditions.*;
/**
* A TransactionOutput message contains a scriptPubKey that controls who is able to spend its value. It is a sub-part
* of the Transaction message.
*/
public class TransactionOutput extends ChildMessage implements Serializable {
private static final Logger log = LoggerFactory.getLogger(TransactionOutput.class);
private static final long serialVersionUID = -590332479859256824L;
// The output's value is kept as a native type in order to save class instances.
private long value;
// A transaction output has a script used for authenticating that the redeemer is allowed to spend
// this output.
private byte[] scriptBytes;
// The script bytes are parsed and turned into a Script on demand.
private transient Script scriptPubKey;
// These fields are Java serialized but not Bitcoin serialized. They are used for tracking purposes in our wallet
// only. If set to true, this output is counted towards our balance. If false and spentBy is null the tx output
// was owned by us and was sent to somebody else. If false and spentBy is set it means this output was owned by
// us and used in one of our own transactions (eg, because it is a change output).
private boolean availableForSpending;
@Nullable private TransactionInput spentBy;
private transient int scriptLen;
/**
* Deserializes a transaction output message. This is usually part of a transaction message.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload,
int offset) throws ProtocolException {
super(params, payload, offset);
setParent(parent);
availableForSpending = true;
}
/**
* Deserializes a transaction output message. This is usually part of a transaction message.
*
* @param params NetworkParameters object.
* @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @throws ProtocolException
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset,
boolean parseLazy, boolean parseRetain) throws ProtocolException {
super(params, payload, offset, parent, parseLazy, parseRetain, UNKNOWN_LENGTH);
availableForSpending = true;
}
/**
* Creates an output that sends 'value' to the given address (public key hash). The amount should be created with
* something like {@link Coin#valueOf(int, int)}. Typically you would use
* {@link Transaction#addOutput(Coin, Address)} instead of creating a TransactionOutput directly.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to) {
this(params, parent, value, ScriptBuilder.createOutputScript(to).getProgram());
}
/**
* Creates an output that sends 'value' to the given public key using a simple CHECKSIG script (no addresses). The
* amount should be created with something like {@link Coin#valueOf(int, int)}. Typically you would use
* {@link Transaction#addOutput(Coin, ECKey)} instead of creating an output directly.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to) {
this(params, parent, value, ScriptBuilder.createOutputScript(to).getProgram());
}
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes) {
super(params);
// Negative values obviously make no sense, except for -1 which is used as a sentinel value when calculating
// SIGHASH_SINGLE signatures, so unfortunately we have to allow that here.
checkArgument(value.signum() >= 0 || value.equals(Coin.NEGATIVE_SATOSHI), "Negative values not allowed");
checkArgument(value.compareTo(NetworkParameters.MAX_MONEY) < 0, "Values larger than MAX_MONEY not allowed");
this.value = value.value;
this.scriptBytes = scriptBytes;
setParent(parent);
availableForSpending = true;
length = 8 + VarInt.sizeOf(scriptBytes.length) + scriptBytes.length;
}
public Script getScriptPubKey() throws ScriptException {
if (scriptPubKey == null) {
maybeParse();
scriptPubKey = new Script(scriptBytes);
}
return scriptPubKey;
}
/**
* <p>If the output script pays to an address as in <a href="https://bitcoin.org/en/developer-guide#term-p2pkh">
* P2PKH</a>, return the address of the receiver, i.e., a base58 encoded hash of the public key in the script. </p>
*
* @param networkParameters needed to specify an address
* @return null, if the output script is not the form <i>OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG</i>,
* i.e., not P2PKH
* @return an address made out of the public key hash
*/
@Nullable
public Address getAddressFromP2PKHScript(NetworkParameters networkParameters) throws ScriptException{
if (getScriptPubKey().isSentToAddress())
return getScriptPubKey().getToAddress(networkParameters);
return null;
}
/**
* <p>If the output script pays to a redeem script, return the address of the redeem script as described by,
* i.e., a base58 encoding of [one-byte version][20-byte hash][4-byte checksum], where the 20-byte hash refers to
* the redeem script.</p>
*
* <p>P2SH is described by <a href="https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki">BIP 16</a> and
* <a href="https://bitcoin.org/en/developer-guide#p2sh-scripts">documented in the Bitcoin Developer Guide</a>.</p>
*
* @param networkParameters needed to specify an address
* @return null if the output script does not pay to a script hash
* @return an address that belongs to the redeem script
*/
@Nullable
public Address getAddressFromP2SH(NetworkParameters networkParameters) throws ScriptException{
if (getScriptPubKey().isPayToScriptHash())
return getScriptPubKey().getToAddress(networkParameters);
return null;
}
@Override
protected void parseLite() throws ProtocolException {
value = readInt64();
scriptLen = (int) readVarInt();
length = cursor - offset + scriptLen;
}
@Override
void parse() throws ProtocolException {
scriptBytes = readBytes(scriptLen);
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
checkNotNull(scriptBytes);
maybeParse();
Utils.int64ToByteStreamLE(value, stream);
// TODO: Move script serialization into the Script class, where it belongs.
stream.write(new VarInt(scriptBytes.length).encode());
stream.write(scriptBytes);
}
/**
* Returns the value of this output. This is the amount of currency that the destination address
* receives.
*/
public Coin getValue() {
maybeParse();
try {
return Coin.valueOf(value);
} catch (IllegalArgumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* Sets the value of this output.
*/
public void setValue(Coin value) {
checkNotNull(value);
unCache();
this.value = value.value;
}
/**
* Gets the index of this output in the parent transaction, or throws if this output is free standing. Iterates
* over the parents list to discover this.
*/
public int getIndex() {
List<TransactionOutput> outputs = getParentTransaction().getOutputs();
for (int i = 0; i < outputs.size(); i++) {
if (outputs.get(i) == this)
return i;
}
throw new IllegalStateException("Output linked to wrong parent transaction?");
}
/**
* <p>Gets the minimum value for a txout of this size to be considered non-dust by a reference client
* (and thus relayed). See: CTxOut::IsDust() in the reference client. The assumption is that any output that would
* consume more than a third of its value in fees is not something the Bitcoin system wants to deal with right now,
* so we call them "dust outputs" and they're made non standard. The choice of one third is somewhat arbitrary and
* may change in future.</p>
*
* <p>You probably should use {@link org.bitcoinj.core.TransactionOutput#getMinNonDustValue()} which uses
* a safe fee-per-kb by default.</p>
*
* @param feePerKbRequired The fee required per kilobyte. Note that this is the same as the reference client's -minrelaytxfee * 3
* If you want a safe default, use {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}*3
*/
public Coin getMinNonDustValue(Coin feePerKbRequired) {
// A typical output is 33 bytes (pubkey hash + opcodes) and requires an input of 148 bytes to spend so we add
// that together to find out the total amount of data used to transfer this amount of value. Note that this
// formula is wrong for anything that's not a pay-to-address output, unfortunately, we must follow the reference
// clients wrongness in order to ensure we're considered standard. A better formula would either estimate the
// size of data needed to satisfy all different script types, or just hard code 33 below.
if (!CoinDefinition.useFairPay) {
//todo
return null;
} else {
final long size = this.bitcoinSerialize().length + 148;
Coin[] nonDustAndRemainder = feePerKbRequired.multiply(size).divideAndRemainder(1000);
return nonDustAndRemainder[1].equals(Coin.ZERO) ? nonDustAndRemainder[0] : nonDustAndRemainder[0].add(Coin.SATOSHI);
}
}
/**
* Returns the minimum value for this output to be considered "not dust", i.e. the transaction will be relayable
* and mined by default miners. For normal pay to address outputs, this is 546 satoshis, the same as
* {@link Transaction#MIN_NONDUST_OUTPUT}.
*/
public Coin getMinNonDustValue() {
return getMinNonDustValue(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(3));
}
/**
* Sets this objects availableForSpending flag to false and the spentBy pointer to the given input.
* If the input is null, it means this output was signed over to somebody else rather than one of our own keys.
* @throws IllegalStateException if the transaction was already marked as spent.
*/
public void markAsSpent(TransactionInput input) {
checkState(availableForSpending);
availableForSpending = false;
spentBy = input;
if (parent != null)
if (log.isDebugEnabled()) log.debug("Marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), input);
else
if (log.isDebugEnabled()) log.debug("Marked floating output as spent by {}", input);
}
/**
* Resets the spent pointer / availableForSpending flag to null.
*/
public void markAsUnspent() {
if (parent != null)
if (log.isDebugEnabled()) log.debug("Un-marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), spentBy);
else
if (log.isDebugEnabled()) log.debug("Un-marked floating output as spent by {}", spentBy);
availableForSpending = true;
spentBy = null;
}
/**
* Returns whether {@link TransactionOutput#markAsSpent(TransactionInput)} has been called on this class. A
* {@link Wallet} will mark a transaction output as spent once it sees a transaction input that is connected to it.
* Note that this flag can be false when an output has in fact been spent according to the rest of the network if
* the spending transaction wasn't downloaded yet, and it can be marked as spent when in reality the rest of the
* network believes it to be unspent if the signature or script connecting to it was not actually valid.
*/
public boolean isAvailableForSpending() {
return availableForSpending;
}
/**
* The backing script bytes which can be turned into a Script object.
* @return the scriptBytes
*/
public byte[] getScriptBytes() {
maybeParse();
return scriptBytes;
}
/**
* Returns true if this output is to a key in the wallet or to an address/script we are watching.
*/
public boolean isMineOrWatched(TransactionBag transactionBag) {
return isMine(transactionBag) || isWatched(transactionBag);
}
/**
* Returns true if this output is to a key, or an address we have the keys for, in the wallet.
*/
public boolean isWatched(TransactionBag transactionBag) {
try {
Script script = getScriptPubKey();
return transactionBag.isWatchedScript(script);
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.debug("Could not parse tx output script: {}", e.toString());
return false;
}
}
/**
* Returns true if this output is to a key, or an address we have the keys for, in the wallet.
*/
public boolean isMine(TransactionBag transactionBag) {
try {
Script script = getScriptPubKey();
if (script.isSentToRawPubKey()) {
byte[] pubkey = script.getPubKey();
return transactionBag.isPubKeyMine(pubkey);
} if (script.isPayToScriptHash()) {
return transactionBag.isPayToScriptHashMine(script.getPubKeyHash());
} else {
byte[] pubkeyHash = script.getPubKeyHash();
return transactionBag.isPubKeyHashMine(pubkeyHash);
}
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.debug("Could not parse tx output script: {}", e.toString());
return false;
}
}
/**
* Returns a human readable debug string.
*/
@Override
public String toString() {
try {
Script script = getScriptPubKey();
StringBuilder buf = new StringBuilder("TxOut of ");
buf.append(Coin.valueOf(value).toFriendlyString());
if (script.isSentToAddress() || script.isPayToScriptHash())
buf.append(" to ").append(script.getToAddress(params));
else if (script.isSentToRawPubKey())
buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey()));
else if (script.isSentToMultiSig())
buf.append(" to multisig");
else
buf.append(" (unknown type)");
buf.append(" script:").append(script);
return buf.toString();
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the connected input.
*/
@Nullable
public TransactionInput getSpentBy() {
return spentBy;
}
/**
* Returns the transaction that owns this output.
*/
@Nullable
public Transaction getParentTransaction() {
return (Transaction)parent;
}
/**
* Returns the transaction hash that owns this output.
*/
@Nullable
public Sha256Hash getParentTransactionHash() {
return parent == null ? null : parent.getHash();
}
/**
* Returns the depth in blocks of the parent tx.
*
* <p>If the transaction appears in the top block, the depth is one. If it's anything else (pending, dead, unknown)
* then -1.</p>
* @return The tx depth or -1.
*/
public int getParentTransactionDepthInBlocks() {
if (getParentTransaction() != null) {
TransactionConfidence confidence = getParentTransaction().getConfidence();
if (confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
return confidence.getDepthInBlocks();
}
}
return -1;
}
/**
* Ensure object is fully parsed before invoking java serialization. The backing byte array
* is transient so if the object has parseLazy = true and hasn't invoked checkParse yet
* then data will be lost during serialization.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
maybeParse();
out.defaultWriteObject();
}
/**
* Returns a new {@link TransactionOutPoint}, which is essentially a structure pointing to this output.
* Requires that this output is not detached.
*/
public TransactionOutPoint getOutPointFor() {
return new TransactionOutPoint(params, getIndex(), getParentTransaction());
}
/** Returns a copy of the output detached from its containing transaction, if need be. */
public TransactionOutput duplicateDetached() {
return new TransactionOutput(params, null, Coin.valueOf(value), org.spongycastle.util.Arrays.clone(scriptBytes));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransactionOutput other = (TransactionOutput) o;
if (!Arrays.equals(scriptBytes, other.scriptBytes)) return false;
if (value != other.value) return false;
if (parent != null && parent != other.parent) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (value ^ (value >>> 32));
result = 31 * result + Arrays.hashCode(scriptBytes);
if (parent != null)
result *= parent.getHash().hashCode() + getIndex();
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.